Assigning Responsibilities Duh!
In object design a big dilemma is where to assign responsibilities, thumb rule is to keep behavior with data i.e. to define methods in the class that has the data. This rule has is always not correct even when data is in the class. Look at this simple example, An application need to store Order object(s) containing set of Order Items, Customer who ordered it. These objects need to be saved to a database. Order, OrderLineItem and Customer classes and relation ship among them are identified. Dilemma is where should save responsibility(methods) live and why it need to be there. To be specific, Is there a need to have a new class like DataStore, or have save method be part of Order object (it is the object that has data).
public class Order
{
void save();
}
// or
class DataStore
{
void save(Order anOrder);
}
If it is a method in order, then
- Order object needs knowledge of api like JDBC. It is not a real part of Order object.
- Similarly save method should be in each domain object.
- If need be, How to handle bulk saves(saving a collections of Orders) in a single transaction?
In this application Order need to be priced also. Price of an Order is sum of it’s OrderLineItem’s price. Where does price responsibility belong?
public class Order
{
double price();
}
// or
class Pricer
{
double price(Order anOrder);
}
Here Order's price does not depend on any external data, keeping price calculation in Order makes more sense. (there may be a method in OrderLineItem also to calculate its individual price). What if price of a order is dependent on current interest rates (external data), and need to price set of orders with same set of interest rates, then clearly in other Pricer class.
When adding a responsibility to a class, ask why not move it to it's new (or other) class. Questions like
- can the same responsibility/behavior be applied to collection of objects in single operation? (transaction, data set etc).
- is same/similar responsibility need to be there in classes?
- is needed data (to fulfill responsibility) noisy?
- Is needed data (to fulfill responsibility) external?
can help in idenitifying the responsibility's location. If all things equal, add it to class with data - its the norm.
Duh!.
1 Comments:
good one. Quite tricky deciding during implementation which way to go. May be DAO helps to an extent.
Pricer could be a strategy.
Post a Comment
<< Home