Tag Info

New answers tagged


Idiomatically, unless variable is preferable to if !variable. Negated if statements are often considered a code smell as it's easier to miss the negation when skimming. The bigger picture here is that doing nil checks like this is also a bit of a code smell. For proper OO, aim to use the null object pattern so that this sort of check is never needed. ...


Consider the following: response = responses.to_a.first This will return the first element of responses, or nil. Then because conditional statements treat nil as false we can write: response = responses.to_a.first if response # do something ('happy path') else # do something else end Which is more readable than: if response.nil? # do something ...


Not only is if variable.nil? read more like natural language, it also guards against a programmer accidentally assigning it a false value and falling into your if statement, since Ruby is a loosely typed language.


Write what you mean. Mean what you write. Lets take a different test. .vowel? if char == 'a' # do stuff end vs if char.vowel? # do stuff end Now, its obvious that these do not do the same thing. But if you're only expecting char to be a or b it will work. But it will confuse the next developer - the second block will be entered into for the ...


As I mentionned in an edit of the question, the try-object pattern is the best alternative to this problem.


One solution is to use Null Object Pattern in Module A. Instead of returning null, Module A will return another type that is a 'type-safe' representation of "Nothing".


You can return either a thing or nothing, so somehow B has to know. You can return a list with 0 or 1 element, and B could, for example, treat it uniformaly. In pseudo-code: // Inside one of B's method foreach(x : A.getThings()) { this.doAction(x); }

Top 50 recent answers are included