The value of being explicit….
So I had to explain some code I wrote a year or so ago to the colleague who was maintaing it and it looked something like this:
public CollaboratorA doSomething() {
final Set data = new HashSet();
// .. populate the data
return new CollaboratorA {
boolean isThisTrueForSomeCriteria(final Object o) {
return data.contains(o);
}
}
}
which is all perfectly valid; but not at all intuitive. In particular; what was the lifetime of Set data?
I then rewrote this and moved the inner class into it's explicit class:
public CollaboratorA doSomething() {
final Set data = new HashSet();
// .. populate the data
return new SetBackedCollaboratorA(data);
}
class SetBackedCollaboratorA implements CollaboratorA {
private final Set data;
SetBackedCollaboratorA(final Set theData) {
this.data = theData;
}
boolean isThisTrueForSomeCriteria(final Object o) {
return data.contains(o);
}
}
and this was found to be much easier to understand even though under the hood there is absolutely no difference. I am not entirely sure whether the byte code would even be any different, but the intuitiveness or readability was improved; so it was a win :)
To be clear; it was not the use an an inner class that was confusing; it was the fact that an inner class was referencing a variable defined in the method, outside of the method that created the inner class and the data.
Lesson for the day (because I keep needing to learn it again ;)); code that is functional is not as valuable as code that is intuitively functional.
Loading…
Chris May
Steve McConnel (In 'writing solid code' I think) makes the point that he'd rather have comprehensible-but-broken code than incomprehensible-but-working, because the former can be fixed and subsequently changed, whereas the latter will probably have to be re-written when a change is required.
03 Feb 2006, 12:49
The interesting point is that "comprehensible" is relative :)
03 Feb 2006, 13:30
Add a comment
You are not allowed to comment on this entry as it has restricted commenting permissions.