[LRUG] Comparable Null Objects

Andrew Premdas apremdas at gmail.com
Thu Jul 16 00:48:20 PDT 2015


On 15 July 2015 at 16:34, Duncan Stuart <dgmstuart at gmail.com> wrote:

> Thanks everyone - that was really interesting. Here's the approach I've
> decided on:
>
> class NoExpectedDate
>   include Comparable
>   def to_s(format)
>     "Unknown"
>   end
>   def <=>(other)
>     1 # Treat it as after every other date
>   end
>   def coerce(other)
>     [other, Float::INFINITY]
>   end
> end
>
> I like it because it has just enough behaviour to quack like a Date where
> required.
>

I think this solution lacks one really important thing, a comment. Now I
know that comments seem to be somewhat out of fashion nowadays, but here
you have a bit of non-obvious code that makes something work. The fact that
this code is in a seperate class, and not in Events is a good thing.
However if someone does have to get to this code in the future you need to
explain what is going on, and why its important, as this is very hard to
infer from just the implementation.

Another thing you could think about is the name of this class. The
NoExpected part of the name is actually all about Events. You've let that
domain pollute this class. I think NullDate would be a better name. After
all there is no reason why NullDates could not be used in other situations.
This name will also help event in revealing just enough of the
implementation (i.e. that you are using null object) so that you don't have
to dig down

class Event
  def expected_date
     @expected_date ||= NullDate.new

vs

  def expected_date
    @expected_date ||= NoExpectedDate.new

With NoExpectedDate I feel I have to go an look at this to work out what is
going on. With NullDate, I am being told that we are using the NullObject
pattern.

All best

Andrew



-- 
------------------------
Andrew Premdas
blog.andrew.premdas.org
-------------- next part --------------
An HTML attachment was scrubbed...
URL: <http://lists.lrug.org/pipermail/chat-lrug.org/attachments/20150716/79d25823/attachment-0003.html>


More information about the Chat mailing list