But what about Unit testing then? If I want to to test a single method, I would need to fetch the property… So looking at the unit testing part, it makes more sense to return a value. I was thinking about that when I was out before I saw your answer.
I’m doing it to get a better overview. I have one main public method. If you read the code of that function, in theory you can see step by step was going on, and don’t have to go through layers of function. It makes the code more understandable when I would need to do an adjustment in a few months.
Unit testing should not execute private methods by themself. Instead, unit testing should set up different the initial public conditions so that the private methods end up being fully exercised.
Set up the initial environment
Exercise the code
Test for the expected outcome
If the code being exercised sets internal state variables, you shouldrun other code that is dependent on those internal state variables so that you can determine what their state is.
It is not advised to add code to expose private variables and functions purely for the sake of testing convenience.
The issue with exposing private methods is that they are then no longer private. They are now publicly accessible, so you then need to document the fact that these public methods are only used for testing, which is another way of saying that they’re back doors in to your code.
Another problem with exposing private methods is that you lose some of the benefits of being private. You should not need to know how private methods do their job. They can and they should remain as black boxes, that are called upon by the class to do the work that is required.
A more stable way to deal with classes is to consider each class as a unit in its own right, which contains public methods for access and manipulation. That’s all you should need to know about a class, and it’s all that a test should exercise, because in the end, the only way that the class is going to be used is via its public interface.