Is one better than the other?
Is that even a valid question?
I’ve been advised recently that the MyObject.DoSomething() is quite dated and the service way of doing it is preferred. Is that right?
Example:
public class Policy : ICancellable
{
public void Cancel()
{
// Code to cancel working with 'this'.
}
}
vs
public class PolicyCancellationService
{
public void Cancel(Policy policy)
{
// Code to cancel working with 'policy'.
}
}
If the service way of doing it is used – can the object be responsible for any functionality or should it just be dumb?
Both ways are valid; you should choose whichever leads to high cohesion and low coupling.
As a rule of thumb, you should begin by trying to put it in the class itself, i.e.
MyObject.DoSomething().You should only use a separate (service) class if:
DoSomethingdoes not directly relate to the responsibility ofMyObject. If you put an unrelated method intoMyObject, it leads to low cohesion.MyObjectdoes not have all the information required to performDoSomething. If you give this additional information toMyObject, it leads to high coupling.In your example, if cancellation is an important feature of a policy and the policy has all the required information to perform this operation, you should keep it in the
Policyclass.Quite the contrary: you should keep as much functionality as possible in the domain objects themselves. Services should be limited to coordinating activities between multiple domain objects; they should preferably not contain any business logic.