Best Practices: Protected or Private Methods by Default and Test-Driven Development

Related questions

My question

Many people agree that protected methods should only be used when you have a reason to use them. How is this a test-based development model? (Especially with regard to falsifying objects.) I have a friend who is a big fan of TDD, and now BDD is a C # developer, and he told me that he hardly ever uses the private keyword. After he said this, I continued to use it for fields, but began to default all my methods to protected . Some people at StackOverflow also agree that protected should be used by default and - could some of you be balanced on this issue? What is the best reason to use protected by default (since the above threads explain the reasons for not)?

Edit : one Oded comment, what about using protected by default and the principle of open closing (the class must be open for extension and closed for modification)?

+4
source share
1 answer

Here is what I consider the best practice, I do with my developments and offer it to all my clients:

  • Start with your test (or spec if you are in the BDD). The production classes and methods that you derive from your tests must be publicly available .
    • Note. If you work in .NET, you may want to use the keyword inside (and add the InternalsVisibleTo assembly attribute to your production assembly, so your test project can use code). Then you will make it publicly available only if another production assembly depends on it .
  • Any method that you create as part of the refactoring phase of your TDD must be made private .
  • Make helper methods secure only when the required production class needs them.
  • Any method created during the refactoring phase (now closed or protected) that you need in another production class must be extracted to the helper class and made public (or internal in .NET, as well as any language that supports the concept).
  • If a helper class is needed in another assembly , then:
    • If another assembly already depends on the assembly of the helper class, make the helper class public (if it has not already been).
    • If the other assembly is independent of the assembly of the helper class, retrieve the helper class in the helper assembly (best suited or new) and make it public . Be sure to link to the original assembly with a new auxiliary assembly, if one is not already specified.

This should pretty much cover all your affairs.
Hope this helps.

+10
source

All Articles