private methods are stupid

posted on December 08, 2008 - tagged as: oop

Today at work in a unit-testing-brown-bag-lunch-session, I spouted off about private methods, claiming that they are stupid.  I stand by my statement; private methods are definitely stupid.  However, my true feelings are a bit more nuanced.

If we assume we are associating a specific chunk of functionality with every method we write, then there is an overarching hubris associated with declaring a method to be private.  When we declare such a method to be private, we  predict the future, saying “only I, the privileged creator of this spectacular class will ever need this functionality.”

But, wait, aren’t there legitimate reasons to declare a private method?  What if a particular method leaves an object in an inconsistent state, debilitating all subsequent calls to “public” methods?  Should this dangerous method be marked private?  Perhaps.  Leaving aside arguments about the necessity to create such a method, there are other ways around the problem.  Convention, not language level constructs solve the issue nicely.  Python, for example, uses a leading underscore for “private” methods, and Smalltalk programmers sometimes place these methods in the “private” protocol.  And while I am not interested in metaphysical debates about what makes a system “object oriented” (I mean really, I think CLOS is perhaps the best OO system out there), with the examples of Smalltalk and Python, it is clear that private methods are not necessary for OO systems.

The argument that private methods are necessary to “protect” code is even sillier.  If we’re afraid of how other programmers might use our classes, then we shouldn’t bother programming.  Not only do these fears foster a sense of mistrust among programmers, but also, they are not easily eliminated.  In the most straightforward cases, users of our classes with access to the code may go through and mark useful methods public (note that loosening protection introduces no bugs in non-reflective code), or worse, copy and paste this functionality into another method entirely.   In more severe cases, the “nefarious” programmer will resort to introspection or disassemblers.

We programmers are tinkerers, and we should be willing to let ourselves tinker.  Sleep easy, and declare your methods to be public!

Comments !

social

tags