This question is inspired by Mike Nakis' answer to a question I asked earlier: Should a Calculator be a value type or an entity type?. Please see the code below:
public class Calculator
{
private readonly int Number1;
private readonly int Number2;
private readonly int Answer;
public Calculator(int _Number1, int _Number2)
{
Number1 = _Number1;
Number2 = _Number2;
Answer = Add();
}
private int Add()
{
return Number1 + Number2; //plus 30 lines of code
}
}
Notice that there are two instance variables called: Number 1 and Number 2. This would also work (where both numbers are local variables):
public class Calculator
{
public int Add(int Number1,int Number2)
{
return Number1 + Number2; //plus 30 lines of code
}
}
I understand the difference between instance variables and local variables i.e. stack and heap; scope etc.
When designing a system (UML) ; how do you decide whether to use a local variable or an instance variables. The factors I can think of are as follows:
1) Easier to make a call immutable
The reason I ask is because I read a lot of questions on here where I think an instance variable should be used; however a local variable is used. Is there a rule that I am not aware of similar to: "Use aggregation over inheritance".
I am talking strictly from a DDD and best practices point of view. I realise this does not always apply in the real world because of time constraints etc.