Recently I was reading through the book "clean code" by Robert Martin, and in chapter 7 there was a section where he said you should try to replace null checks using the special case design pattern. I thought this was a great idea but then I thought about the following instance.
foreach(thing in someCollection) {
value = getValue();
if(value == null) {
break;
}
value.doSomething();
}
You could make it so the object returned by getValue
is polymorphic, create an interface that has the doSomething()
method enforced and implement it for the object you wish to return, and "mock" class for the spcial case (if the value is null). This would eliminate the need for a gaurd clause as it doesn't really matter if doSomething()
is called on our "mock" object as it is an actual object which has the doSomething()
method:
function doSomething(){
return;
}
the only issue is, the loop doesn't break. As far as I can tell there is no way of breaking out of a loop using a polymorphic class if a "mock" object is returned, unless you have a check for the mock object but then that defeats the point.
My question is, is there a clean way of dealing with nulls that don't incur this computation penalty? Or am I misunderstanding something about what is said in chapter 7 around null checks?
Aucun commentaire:
Enregistrer un commentaire