Should class methods accept parameters or use class properties

encapsulation, oop, unit-testing

Solution

If you use a real-world example the answer becomes clearer.

public class person
{
    public string firstName { get; set; }
    public string lastName { get; set; }

    public string getFullName()
    {
        return firstName + " " + lastName;
    }
}

The point of an entity object is that it contains information about an entity, and can do the operations that the entity needs to do (based on the information it contains). So yes, there are situations in which certain operations won't work properly because the entity hasn't been fully initialized, but that's not a failure of design. If, in the real world, I ask you for the full name of a newborn baby who hasn't been named yet, that will fail also.

If certain properties are essential to an entity doing its job, they can be initialized in a constructor. Another approach is to have a boolean that checks whether the entity is in a state where a given method can be called:

while (person.hasAnotherQuestion()) {
  person.answerNextQuestion();
}

Problem

Consider the following class ``` public class Class1 { public int A { get; set; } public int B { get; set; } public int GetComplexResult() { return A + B; } } ``` In order to use `GetComplexResult`, a consumer of this class would have to know to set `A` and `B` before calling the method. If `GetComplexResult` accesses many properties to calculate its result, this can lead to wrong return values if the consumer doesn't set all the appropriate properties first. So you might write this class like this instead ``` public class Class2 { public int A { get; set; } public int B { get; set; } public int GetComplexResult(int a, int b) { return a + b; } } ``` This way, a caller to `GetComplexResult` is forced to pass in all the required values, ensuring the expected return value is correctly calculated. But if there are many required values, the parameter list grows as well and this doesn't seem like good design either. It also seems to break the point of encapsulating `A`, `B` and `GetComplexResult` in a single class. I might even be tempted to make `GetComplexResult` static since it doesn't require an instance of the class to do its work. I don't want to go around making a bunch of static methods. Are there terms to describe these 2 different ways of creating classes? They both seem to have pros and cons - is there something I'm not understanding that should tell me that one way is better than the other? How does unit testing influence this choice?

Original source