Wednesday, May 17, 2006

What Is Good Code?

I've noticed that it's somewhat easier to deal with poorly written procedural code than poorly written object-oriented code. The reason, I think, is that the procedural code is all together in large unwieldy functions full of repeated conditional logic. One can take that kind of code and break it up into smaller functions, and then organize those functions into classes. Then one can take duplicate code and just call the appropriate methods instead. It's not necessarily easy, true, but it tends to be easier than cleaning up a confusing bunch of objects and factories. Often the code duplication in object code is hidden so it takes quite a while to figure out how the code currently works, and where the duplications starts and ends; rather surprisingly, it's also more difficult to figure out how to refactor the code to a better model. I think one potential reason that object code becomes problematic is that developers who are less experienced with OO tend to try to make their code "object-oriented." The approach I would recommend focuses on function rather than form. Consider paying attention to two qualities:
  1. Is your code easy to follow?
  2. Do you have to make changes in several different places when modifying or extending your code?
Focusing on these items, making the code clear and removing duplication, ought to naturally lead to nice clean object-oriented code.

1 comment:

Jeff Perrin said...

I'd throw in a third item... Get to know the problem domain for the area of the code you're working in as much as possible. It's easy to write nice little functions, but putting that functionality where it belongs requires more knowledge.

I've been struggling with this the last few days. Methods like this: well.getWellMonthlyObservations().getWellMonthlyProducingHours(well); are driving me nuts.