88 points · by micaeloliveira · 11y ago · 82 comments
My argument for this is you should design for the most common use case first, and most commonly people will want '.?' behavior. You can still check explicitly for null in the other cases, or even introduce a more cumbersome non-safe navigation operator. The resulting code will overall need fewer checks, be more readable, you'll have fewer crashes and exceptions, and it will generally do the right thing.
I occasionally write toy languages and this is one behavior I think I got right recently. Along the same lines, but as a more extreme measure, I would argue that invoking a method call on a null object should return null instead of throwing an exception.
Wouldn't you prefer seeing:
foo .? bar . baz .? roo
To know that nil is not even a possibility for `bar`?Why not make the nil check (or error silencing) explicit when it is so cheap to do so?
The reasons that is defensible in message passing systems is because such systems are basically recapitulations of computer networks, and object nullity is equivalent to a network partition. That's the kind of failure mode that you handle in the policy layer, which is above the runtime layer in an application system just as it would be above the network layer in a distributed system.
<?php
$foo = array();
echo $foo['a']['b']['c']; // not an error echo $foo['a']['b'] ?? 'default_value'; $v = @first($var1, $var2, 'some-default');
which will simply return the first parameter that has a non-null, non-empty-string value. d = lambda {|hash,key| Hash.new(&d) }
foo = Hash.new(&d)
p foo['a']['b']['c']
The argument to "Hash.new" is the default value, or a on object that takes the hash object itself and the key, and returns the default value (and optionally stores it in the hash, which makes it great for memoization). In this case, whenever accessing a non-existent hash key, it returns another hash with the same closure as the default...Of course it's likely to blow up in all kinds of ways since anything trying to do "if foo['a']" to check of 'a' is present in foo will break, for example.
foo?.bar?('baz')
was quite nice. int? count = customers?[0]?.Orders?.Count();
I remember asking for it but it never came. I don't think Ruby's proposed .? syntax would work with indexes either unless they use [? ].Neither Java nor Groovy has the int? declaration shown which enforces the optionality. The C# version looks more versatile.
Back when Groovy was more popular, its backers also discussed a cascading ? on their mailing list but it never happened. If C# had cascading ? then the example above would be
int? count = customers?[0].Orders.Count();
because the first ? would ripple to the subsequent member accesses and index lookups.It's frustrating to have such useful features blocked by such seemingly small problems as ambiguous patterns of characters.
int? count = customers?[0]?.Orders?.Count();
So yes, it can definitely be chained as the following paragraph in the linked page explains.Why not just extend fetch or try e.g. -- .try(:profile, :thumbnails, :large)
Also, there your example or using try falls short if the methods require additional arguments to be passed in. "try" already handles this by requiring you to "try" each method.
Of cause there is a very good argument to be had that this pattern also breaks the law of demeter by allowing you to call methods on objects that you don't own a stake in.
So technically you can pass arguments to a try method by doing object.try {|o| o.method(args) }
Not trying to be pedantic, hopefully being helpful.
module Chainable
def chain(*kl)
k = kl.shift
if self.respond_to?(k)
v = self.public_send(k)
else
v = nil
end
return v if kl.empty?
unless v.respond_to? :chain
raise ArgumentError, "can't chain on `#{k.inspect} => #{v.inspect}:#{v.class}`"
end
return v.chain(*kl)
end
end
and then this: class Object
include Chainable
endIt being faster has nothing to do with the syntactical appearance of the operator. I think it's more pertinent to ask why does .chain_try or .tries or .fetches need a special operator than whether it's a convenient addition.
o.chain :foo, [1, 2, 3], :bar, :baz, {key: 'value'}
Here `foo` and `baz` accept arguments, but `bar` does not.Also, it shouldn't make any significant performance difference whether this was implemented as a syntactic sugar, an operator or a method (this doesn't mean it won't perform better than my example method).
It's essentially syntax sugar to save time when you want to do something iff the whole chain is filled in.
Using that operator a single time or whatnot seems handy, but chaining it like that just seems like poor practice to me.
In the article the 'problem' code is:
if u && u.profile && u.profile.thumbnails && u.profiles.thumbnails.large
do_something_with(u.profiles.thumbnails.large)
fi
which repeats u 5 times, and the entire u.profiles.thumbnails.large twice!which would be replaced by only asking once.
even worse (although somewhat clearer, perhaps) is what I've occasionally seen:
if u
if u.profile
if u.profile.thumbnails
if u.profile.thumbnails.large
do_something_with(u.profile.thumbnails.large)
end
end
end
end
And even the super verbose version there still can raise exceptions when you get slightly mad data - say you decode some JSON which has u.profile.thumbnails as "null" (a string) rather than actually a null. asking if u.profile.thumbnails
will be true - but when you request u.profile.thumbnails.large, you blow up.You can achieve similar effects using only exceptions, but there's a good argument for using exceptions only for exceptional circumstances.
begin
do_something_with(u.profile.thumbnails.large)
rescue NoMethodError #or similar
# oh no!
end
which (alas) also will catch all noMethodErrors in do_something_with. So you then end up with begin
tmp = u.profile.thumbnails.large
rescue
tmp = nil
end
if tmp
do_something(tmp)
end
which is super ugly.I may have got details wrong - not being a rubyist, but I think this is the general gist of where a nestable operator makes much much cleaner code, which catches more errors.
As far as I see the proposed version will work equivalent to assigning the result of each method invocation to a temporary, and doing the next check on that, which gets far more ugly if you have to write it out
The whole motivation of the operator is for chaining.
if posts.comments??.likes??
or if posts..comments..likes
instead of if posts.?comments.?likes
That would mirror the usage of ?? as the nil-coalescing operator in Swift.The name "elvis" was promoted by the then-project manager of Groovy in an attempt to change the origin meaning of "G-Strings", the name for interpolated strings in Groovy. It originally alluded to the item of clothing, but in an attempt to sanitize Groovy's image for marketing, he wanted it to have meant the string on Elvis's guitar, so he created an accompanying fun-name for the null coalescing operator.
Ruby can't use "?." operator.
Can we use ".?" syntax
Why couldn't Ruby use "?."? def foo?
Object.new
end
foo?.class
since "foo?" is a valid method it would conflict with "?."Edit: with ".?" looks like "foo?.?class"
Edit 2: side note, this would never pass a code review, the expectation of "foo?" is that it returns true/false.
95% of the time, yes. However, the "official" rule is simply that such methods must return a value that can be EVALUATED as true/false. There are plenty of methods in the ruby core/standard library which end in a "?" but do not return true/false, such as:
* File#size (http://ruby-doc.org/core-2.2.3/File.html#method-c-size-3F) returns Integer or nil.
* Integer#nonzero? (http://ruby-doc.org/core-2.2.0/Numeric.html#method-i-nonzero...) returns self or nil.
This misunderstanding of what "?" methods are allowed to return is an ongoing problem in the community, e.g. https://github.com/rails/rails/issues/20110
This means that something like foo.thing?.bar is potentially ambiguous.
>AFAIK the general practice is to use ! for methods that perform a mutation in-place The ! suffix is rather loosely defined as it just means the user should be cautious/the method might have "dangerous"/surprising behavior.
Your description is usually correct but only when a non-suffixed version exists and not even then the behavior has to match your description. There are also a lot unsuffixed mutating methods. See also Kernel#exit vs. Kernel#exit! (immediate exist/exit handlers aren't called) or Tempfile#close vs. Tempfile#close! (close and unlink).
That's not quite the usual statement of the rule: ! is for methods where there exists a "dangerous" version and a "less dangerous" version, to denote the more dangerous version. A common example of that is methods where one version returns a copy of the original object with some modification applied and the other version modifies the original object in place, but IIRCT that's not the only distinction it is used for in the standard library and, more importantly, in-place mutations that aren't paired with a "return-a-modified-copy" method don't get the !.
if u.profiles.thumbnails.large
instead of these successive checks?(Or, better, alter the method that you get the user that you are getting "u" back from to return an "nonexistent user" object that responds to "profile" with a "nonexistent profile" object that responds to "thumbnails" with a single-item list containing a "nonexistent thumbnail" object that responds to a "large" method with a "nonexistent image" (or whatever) object that has the right behavior when used where an image object is expected in the code.
This approach allows replacing more conditionals with method implementations, and is in that sense more "object oriented" on that null-coalescing which still often requires passing the result to a conditional to handle the null case, and still takes some tricks to distinguish between the terminal method returning nil and something along the chain returning nil, where that differs in the handling.
As for why this is a common problem, "u.profiles.thumbnails.large" is is probably a chain of Rails/ActiveRecord model associations[1], which generally map to table rows . If there the "profiles" table doesn't have any rows "WHERE profiles.user_id = users.id", then ActiveRecord will leave a nil[2] (or empty array) in user.profiles. This is true for all foreign key relationships, so you often end up having to do something to protect against null values (no rows) every time you move between models.
Sometimes it is possible to work around this by always creating the associated model when the parent object is created, that only works in a few cases. Note: I recommend against doing tricks to auto-build the associated model on first access: that kind of "clever" solution can lead to confusing bugs later on. (I learned that one the hard way)
[1] http://guides.rubyonrails.org/association_basics.html
[2] ibid, 4.1.1.1 "The association method returns the associated object, if any. If no associated object is found, it returns nil."
"nil" in Ruby is an instance of NilClass. NilClass has a few methods, but e.g. "thumbnail" is not amongst them, so Ruby looks for a "method_missing" method, doesn't find that either, and then throws an exception, just as if you'd called another non-existent method.
To answer a question you didn't ask, though, you can easily write classes to wrap your objects to get pretty much the effect you are asking about. E.g.:
class Maybe
attr_reader :value
def initialize value
@value = value
end
def method_missing *args
return self if @value.nil?
Maybe.new(@value.send(*args))
end
end
p Maybe.new(nil).i.can.call.anything.without.exceptions
p Maybe.new("Hello foo").gsub("foo","world").value
The first call to "p" will print a respresentation of a "Maybe" instance holding "nil" in "@value".The second will print "Hello world", as "gsub" will be called on "Hello foo" since the "Maybe" has a non-nil value.
There are any number of implementations of helper classes like this for Ruby, with various levels of popularity. The benefit of course is that you can easily customize the behaviour for your specific needs (e.g. you could create one that will return a default value instead of nil, or you can create one that short-circuits on other values than nil, or any number of alternatives)
The advantage of introducing .? as proposed, though, is that it is easier to optimize (no new class or lots of extra objects to create and destroy).
Nils will get into data structures and figuring out when and where they got there will become more work. You'd end up writing a lot more logic testing for nil and throwing an exception when it's found, to avoid the nil propagating further.