The author's example code appears to be doing the same thing, but iterating using Ruby's block syntax:
data_source.person(id) do |person|
person.phone_number = phone_number
data_source.update_person person
end
I'm assuming data_source.person(id) would return 0 or more Person objects.Ruby's block syntax is essentially a method of passing an anonymous function as an argument to a method call. It is used by the standard libraries iteration method (e.g., Enumerable#each), but its use here is not iteration (though the teller could be implemented with iteration under the covers.)
data_source.person(...) appears to be a method that takes an id, attempts to retrieve the person with the ID, and, if such a person object exists, yields the person object to the block. From the code, it doesn't look like it is designed to be a collection (it could be implemented on top of a finder that returned a collection, or a finder that returned either a record or nil.)
class DataSource
def person(id)
p = find_person(id)
p && yield p
end
endIt's not iterating.
Conceptually, they both say "update this field for every entry having this ID" and at a quick glance the code for each language looks almost the same.
To an extent yes. I'd fully expect the Ruby version to run more code after the block has been executed, the Python version much less so (even though it is possible) for instance.
And the context manager can't handle this case, as it's not able to skip the block body.
Since it's a nasty dirty hack that tends to misbehave on bad data instead of failing cleanly, I generally restrict it to experimental/throwaway code. Seeing it recommended as a good idea is a bit WTF.
I was simply pointing out that the technique is available in other languages without using lambda and/or blocks.
This assumes that an empty result set of a finder is "bad data"; there are times when this is true (in which case, the basic "teller" idiom as illustrated here isn't a good choice), but there are lots of times where it isn't, too.
> Many codebases are littered with them [null checks] and,
> as a result they [codebases] are often very hard to understand.
I wager they're referring to null checks complicating the codebase (introducing uncertainty into method signatures and argument values down the chain).And that's what creates a ripe environment for such bugs and vulnerabilities that you mention.
Anyways, my big a-ha moment in programming was when I started thinking in terms of data-structures and mapping functions/transformations across them.
(map update-phone (filter ... users))
And the author doesn't seem familiar with many programming languages. Using his "finders and tellers" idiom isn't as special as he thinks, and doesn't require lambdas or blocks. Here's a similar idea in Python, not using its lambdas:
C++ has had similar functionality in the STL using iterators since before C++98.Lambdas and blocks are convenient and nice features to have, but they're not required for this.