Skip to content

Instantly share code, notes, and snippets.

@mcansky
Created June 8, 2021 17:46
Show Gist options
  • Save mcansky/abd3e73013281b29076f87f1a2f2929c to your computer and use it in GitHub Desktop.
Save mcansky/abd3e73013281b29076f87f1a2f2929c to your computer and use it in GitHub Desktop.
&. operand vs nil object ?

What do we prefer ?

related : https://refactoring.guru/introduce-null-object

The question is : when should we go for NilObject classes : from the first method to unify the way to handle this kind of things in the code base or wait until you have something a bit complex to do it ?

Given

So let's say we have a Cup model that has tray_uuid and barcode attributes. In one case we want to get a Cup that is linked to a specific barcode and return the uuid of the tray it's stored on.

Of course, sometimes the barcode given doesn't find the related Cup (maybe we don't stock that one) so we want the method to fail nicely and the response to contain an empty string.

So, one way is to use &. operator with a to_s so we get empty string if there is no such Cup. The other would be to use a NilObject with a tray_uuid method that returns an empty string. Thus we have the default value, and everything is explicit and clear.

Yet, we traded a single line totally correct Ruby for an extra layer.

Which one would you pick and why ?

# nil class
class NilCup
def tray_uuid
''
end
end
# command code
def tray_uuid_for(barcode:)
cup = Cup.find_by(barcode: barcode) || NilCup.new
{ tray_uuid: cup.tray_uuid }
end
# command code
def tray_uuid_for(barcode:)
cup = Cup.find_by(barcode: barcode)
{ tray_uuid: cup&.tray_uuid.to_s }
end
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment