Search code examples
oopdesign-patternslanguage-agnostic

When to use private methods?


I understand what public/protected/private accessors mean in Java or PHP for instance. However, when would you choose whether to make a method private?

Imagine I have a class that handles configuration strings - they must conform to a particular regular expression, and if so, further logic is performed to make sure the strings are valid.

I currently have this code in a private method in a Configuration class. This class accepts configuration strings and then returns values to client code after validating the strings.

However, I want to unit test the validation code, so perhaps it should be in another class. I typically don't do this though unless I know that the code will be reused. If it will only be used by a single class as in this case, I normally just make the method private.

So, my question is - what design rules should inform a programmer that a particular method should be private compared to being moved into its own class?


Solution

  • The Single Responsibility Principle is what I usually have in mind. Also, consider if you really need the validation in this class or if it does not have anything to do with it (perhaps the validation should not be handled in the domain logic but another layer above it). Private methods, as you probably already know should not be tested in unit tests so if you really need to test this kind of functionality perhaps you should put it in its own validation class, responsible for validation only and then test it.