21 ms·
Another thought: Why doesn't Java make it easier to refer to a method and call it dynamically? For this example: List<Person> beerDrinkers = new ArrayLis
by jimbokun 17y ago
Another thought:
Why doesn't Java make it easier to refer to a method and call it dynamically?
For this example:
List<Person> beerDrinkers = new ArrayList<Person>();
for (Person p: persons) {
if (p.getAge() > 16) {
beerDrinkers.add(p);
}
}
If we had a legalAge method defined on Person returning true for any person over 16, then it would be nice to write the equivalent of
List<Person> beerDrinkers = filter(persons, legalAge);
which would call the legalAge method on each person and keep the ones returning true. Like most things with Java, you can do this, kind of, but it means getting the instance class, looking up the method for the method name and signature, then invoking on the instance, all of which makes it just not worth it. Objective C has the idea of selectors, which is an easy way to specify the message you want to send to an object, which probably comes from some similar concept in SmallTalk.
This is arguably a more object oriented solution to this general problem. For one, it better follows Demeter's Law, as you do not need to expose the getAge property.
- scott_s 17y agoIn C++, the way you would do this involves boost::men_fn (http://www.boost.org/doc/libs/1_39_0/libs/bind/mem_fn.html http://www.boost.org/doc/libs/1_39_0/libs/bind/mem_fn.html): list<Person> beerDrinkers = filter(persons, boost::mem_fn(&Person::legalAge)); Where filter looks something like: template <class Sequence, class Pred> Sequence filter(const Sequence& in, Pred p) { Sequence out; for (typename Sequence::const_iterator i = in.begin(); i != in.end(); ++i) { if (p(*i)) { out.insert(out.end(), *i); } } return out; } We can even use this style if legalAge is something that takes a parameter, like ageCheck(age) using boost::bind (http://www.boost.org/doc/libs/1_39_0/libs/bind/bind.html http://www.boost.org/doc/libs/1_39_0/libs/bind/bind.html): list<Person> beerDrinkers = filter(persons, boost::bind(&Person::ageCheck, 21, _1));