Similar Questions
- When do you write a private method, versus protected?
- Best to use Private methods or Protected methods?
- Reasons to use private instead of protected for fields and methods
My Question
Many people agree that protected methods should be used only when you have a reason to use them. How does a test-driven development model way into this? (Especially with regard to faking objects.) I have a friend who is a big fan of TDD and now BDD and is a C# developer, and he told me he hardly ever uses the private
keyword. After he said that, I kept using it for fields but starting defaulting all of my methods to protected
. Some people on StackOverflow also agree that protected
should be used by default—could some of you please weigh in on this question? What is the best reason to use protected
by default (since the threads above explain reasons not to)?
Edit: per Oded's comment, what about using protected
by default and the Open-Closed Principle (a class should be open for extension and closed for modification)?
Here's what I consider a best practice, do with my developments and suggest to all of my clients:
- Start with your test (or specification, if you're into BDD). Production classes and methods that you pull from your tests should be public.
- Note: If you're developing in .NET, you may wish to consider using the internal keyword (and adding the InternalsVisibleTo assembly attribute to your production assembly, so that your test project can use the code) instead. Then you would make it public only if another production assembly depends on it.
- Any method that you create as part of the refactoring phase of your TDD should be made private.
- Make helper methods protected only when a derived production class needs them.
- Any method created in the refactoring phase (now private or protected), that you need in another production class should be extracted to a helper class and made public (or internal in .NET, and any language that supports the concept).
- If the helper class is needed in another assembly, then:
- If the other assembly already depends on the helper class' assembly, make the helper class public (if it isn't already).
- If the other assembly does not depend on the helper class' assembly, extract the helper class to a helper assembly (the best fit, or a new one) and make it public. Be sure to make the original assembly reference the new helper assembly, if it doesn't already.
This should pretty much cover all of your cases.
Hope this helps.