This is a low level design question. I am trying to get a grip on Object Oriented programming.
I am writing a Java class with a method that sets values of data members of a value object. These values are computed by my class according to some business logic. Finally my class is supposed to return the value object so populated. What is the most object oriented way of doing this?
One possible approach, where I seem to be headed is, creating compute() methods inside my Java class for each of the data members (of the VO) that I need to set. Each of these compute methods return the required value which I set using the respective setter method of the value object.
However, I think this approach is more procedural than object oriented as I am just calling these compute methods procedurally in a sequence and populating my value object.
So what design (…design patterns, maybe?) or best practices can I use / look at, so that this code becomes object oriented.
Representative code (what I have right now):
class Adapter { // this is my Java class
MyValueObject applyBusinessLogic(Input object)
{
MyValueObject vo = new MyValueObject();
vo.setA(computeA());
vo.setB(computeB());
vo.setC(computeC());
return vo;
}
String computeA() { ...some logic... return a;}
String computeB() { ...some logic... return b;}
String computeC() { ...some logic... return c;}
}
class MyValueObject {
String a;
String b;
String c;
public void setA(String a)
{
this.a = a;
}
public void setB(String b)
{
this.b = b;
}
public void setC(String c)
{
this.c = c;
}
}
IMHO, it really depends on the responsibilities and what the calculation methods do. You should keep in mind the SRP (http://en.wikipedia.org/wiki/Single_responsibility_principle) to do you OO design. Also high cohesion and loose coupling principles.
If computeA(), B and C are not related, then your Adapter class should be split. If they are related, then your Adapter class should be named differently to express what it really does. For instance: TaxCalculator.
Then you could create a new class receiving a TaxCalculator and a MyValueObject which does the apply. Or just leave the apply in the calculator (though it would be two responsibilities for one class, which is usually bad). In the latter case, perhaps you could call the class TaxCalculationsSetter or something similar, and make the compute methods private. Et voila, you would satisfy again the SRP. 😉
Always keep in mind that “what a responsibility” is, is a somewhat subjective thing.
I hope this has clarified something.