New classes for improved readability

In general design decisions are driven by either implementation problems or desire to improve readability. Interestingly I have found that for me the latter often drives refactorings inside existing classes but rarely creation of new classes. However creating new class to make important domain constraints or business rules explicit can be much more expressive than just introducing some new local variable or method.

For example we have sales application and for certain orders we want to provide possibility to pay only half price when placing the order.
One option is to add all logic related to payment types to Order class.

class Order {

boolean isPartialPaymentAccepted() {
}

void payPartially() {
}

void payFully() {
}
}

The problem of this design is that in order to find out when and what payment options are supported one has to dig into the Order class and find all the dispersed methods dealing with payment from the whole list of other methods. Alternative design is to make supported payment options explicit:

Refactored Groovy code:

class Order {

}

class PartialPaymentStrategy {
boolean isAccepted(order) {
}

def execute(order) {
}

}

class FullPaymentStrategy {
boolean isAccepted(order) {
}

def execute(order) {
}

}

Now it will be clear what payments are supported by only looking at the list of classes. In addition we have been able to simplify Order class and made payment related logic more cohesive.

Leave a comment