I am beginner in object oriented programming and I have one simple question. What is difference between:
public class Calculation
{
private _externalObject = new ExternalClass();
public int FirstParameter {get;set;}
public int SecondParameter {get;set;}
public int ThirdParameter {get;set;}
public int FourthParameter
{
get
{
_externalObject.Calculate(FirstParameter, SecondParameter, ThirdParameter);
}
}
}
and
public class Calculation
{
private _externalObject;
public Calculation()
{
_externalObject = new ExternalClass();
}
public int FirstParameter {get;set;}
public int SecondParameter {get;set;}
public int ThirdParameter {get;set;}
public int FourthParameter
{
get
{
_externalObject.Calculate(FirstParameter, SecondParameter, ThirdParameter);
}
}
}
I want to learn how should I write optimal code.
In this particular case, there isn't any measurable difference.
If, however, you had more than one constructor, you would have to initialize the field in each constructor if you didn't do it directly in the field declaration.
It is more a matter of personal style than anything.
Note on class design and integration - if you have an external dependency like that, good OOP would require you to use DI (Dependency Injection) instead of instantiating the value within the class directly. Constructor injection is a good choice:
private ExternalClass _externalObject;
public Calculation(ExternalClass externalClass)
{
_externalObject = externalClass;
}
The above allows for modification of behaviour without changing the actual class and makes the class more testable.
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With