patkua@work

Sprouting inner classses

Since returning to a more hands-on technical role, I’ve noticed a few habits that I didn’t realise I had, or have more recently acquired. One of these particular habits is (credit to Michael Feathers for the pattern name) is my tendency to sprout tiny classes.

Perhaps it’s my aversion to writing too much procedural code in an object-oriented language or it’s my preference to write small, well encapsulated objects. So far, my general approach seems to be:

I first notice a particular class’ responsibility has grown too much. An easy temptation is to move it to a function, and if I need to share it, might even be tempted to make it static. Instead, I sprout a static inner class who now owns that responsibility. I move any state needed for that responsibility to the class, keeping the tell, don’t ask principle in tact as much as possible. As I interact with the object more, I refine the class name, seeking to understand its responsibilities in different contexts. I might push more responsibilities into it, or move some responsibilities away from it.

I like to try to keep the class private until I’m happy that the class makes sense and all the responsibilities relate to each other in some logical manner. When I’m confident that the class is mature enough, I elevate it to a top level class.

What approaches do other people tend to favour? What can be improved? What doesn’t make sense?

Exit mobile version