My first tactic is to avoid private methods. When behaviors are small enough, the need for private methods diminishes.
My second tactic is to promote them to public, but document that they aren't part of the API. This feels like a hack. A trick that's necessary because I've not thought about the design deep enough. I do this more than I like, honestly, because it's so quick and cheap to do.
Today, I thought of another approach that reinforces the first tactic. Maybe the apparent need for private methods is a signal that what I really want is a collaborator. Instead of privately doing a bit of work in furtherance of a class behavior goal, delegate that work to a first-class worker. Example? Sure!
Suppose I'm writing a class to model a web request. Part of web requests are MIME content type headers. These headers have specific formats for which a parser is needed. I could build parsing into my web request class, undoubtedly through several private methods that implement MIME content type parsing RFC 2045. These will be hard to test.
Instead of those private methods to parse the headers, I want to defer the parsing to a first class delegate. An actual, red-blooded class that knows only how to parse RFC 2045. Turns out, open source libraries already exist, and I don't have to do the work. A happy side effect.
0 comments:
Post a Comment
Share your thoughts!