Your Resolution this year should be:
If you aren’t sure, make it public... and make everything virtual (or overridable, depending on your language) by default.
Of course this primarily applies to those folks building frameworks for statically typed languages... <cough> Microsoft <cough>, but it also holds weight for the rest of us. After all, we all want other people to use our code - even if other people is your customers, your team, or yourself. The point is, we want our code to be (re)used.
And I don’t know about you, but I’d much rather use code that enabled me rather than code that was constantly getting in my way.
Sorry for the tangent, I seem to be doing that a lot lately. Darn, there I go again. Let’s get back on track...
Why public and virtual?
I think a short story explains it best... and Eilon Lipton, lead developer on the mvc.net offering, has just such a story. (emphasis mine)
Several weeks ago we invited several customers for a top secret sneak preview of the CTP, including the MVC framework. Jeffrey Palermo was attending and trying to build some samples with the MVC framework. [...] I sat with Jeffrey for about half an hour and we managed to use many of the extensibility points in the framework to work around the bugs he encountered. The whole time I kept thinking (and probably saying aloud) that I was so glad I made those methods public or virtual or whatever! Without them Jeffrey would have been stuck.
The moral of the story: If you aren’t sure, make it public. If we have to use a method, chances are, someone else does too.
Marking methods as public and virtual helps other help themselves when working with, or working around, your code. Don’t make the classic mistake of assuming you know every possible way in which your code will be used, because you don’t. You can’t!
Don’t forget testing
I’m a rabid fan of Rhino.Mocks and the power it brings my unit tests. And while being able to dynamically mock am interface is awesome in its own right, I think one of the nicest features of Rhino.Mocks is the ability to do partial mocking.
Partial mocks are useful when you want to mock a part of a class. This allows you to test abstract methods in isolation, for instance.
Distilled, that it means that you can mock individual methods of a real, concrete, class while letting the other methods use their actual implementation. The only caveat is that it can only mock publicly available abstract or virtual methods.
So, as long as an object’s methods are marked as public and virtual you can dynamically override them in your unit tests. Doing so allows you to narrow the focus of your tests to just the behavior under test. This also often leads to shorter, more cohesive tests. :)
So remember, enable others to use your code by enabling your code from the start. Public and virtual are your friends... use them when you can. ;)