Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

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

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)?

like image 977
Keith Pinson Avatar asked Dec 28 '22 15:12

Keith Pinson


1 Answers

Here's what I consider a best practice, do with my developments and suggest to all of my clients:

  1. 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.
  2. Any method that you create as part of the refactoring phase of your TDD should be made private.
  3. Make helper methods protected only when a derived production class needs them.
  4. 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).
  5. 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.

like image 100
Assaf Stone Avatar answered Dec 30 '22 10:12

Assaf Stone