[LRUG] Comparable Null Objects

Stephen Best bestie at gmail.com
Thu Jul 16 15:24:41 PDT 2015


I think the key question here is whether the ordering, by date or with
undated things last, is something intrinsic and invariant within the domain?

That being the case I then I think `Event` should be comparable. delegating
to its date perhaps, and to avoid type checks I'd do something like cast
the dates to floats but explicitly (all objects receive `#to_f`). Given
this scenario it's a real shame the coercion protocol is so opaque, I would
definitely entertain Mark Coleman's suggestion:

On 16 July 2015 at 16:51, Mark Coleman <m at rkcoleman.co.uk> wrote:

> How about creating your own class for representing dates


As dates are really dressed up numeric types, with quite a wide interface,
it would be quite neat to define an `Event::Date` class which composed of a
date primitive and perhaps compares nicely with a far future null date
subtype sort of thing.

I suspect however this sorting is not part of the domain and is probably a
display concern, in which case all of this is moot. The sorting will be
performed by an external object and type checks will be really difficult to
avoid. The first thoughts I had around this null object implementation was
what about when you need to put the undated events first? or at an
arbitrary point in time? or sort by something else entirely?

I'm obsessed with `Hash#fetch` and I think that's a really neat way to
encapsulate a nil check conditional such that you don't spray boolean logic
everywhere. You could implement something like

class Event
  def date(&block)
    @date || block && block.call
  end
end

# for undated events last
events.sort_by { |e|
  e.date { heat_death_of_the_universe }
}

This would give you the future flexibility to use a null object because you
can reimplement date (or override in subclass) such that it calls the block
for null objects rather than exclusively the two falsey ones.


Stephen Best

theaudaciouscodeexperiment.com
github.com/bestie
@thebestie
-------------- next part --------------
An HTML attachment was scrubbed...
URL: <http://lists.lrug.org/pipermail/chat-lrug.org/attachments/20150716/4ecbd24d/attachment-0003.html>


More information about the Chat mailing list