WW.
WW.

Reputation: 24311

How to reduce coupling when one class calls only one method on another class that has many methods?

I have a class (let's call it MyService) that accepts two dependencies in it's constructor. The first one is not all that relevant to the question. The second one is PaymentDetails. PaymentDetails lives for longer than the MyService, which is created by a factory to process this particular request.

In MyService.process(), it:

PaymentDetails has by necessity many methods on it. It is an Entity style object into which information is built up as the user steps through a series of about 5 pages.

What is bothering me is that as written my service class depends on the whole of PaymentDetails but only calls one single method.

This bothers me because:

My question is:

What is the best way to fix this so that my service class has minimal dependencies?

Upvotes: 6

Views: 5524

Answers (2)

WhiteFang34
WhiteFang34

Reputation: 72059

You could create a simple interface:

public interface TransactionAcceptor {
    void setTransactionDetails(TransactionDetails td);
}

Have PaymentDetails declare that it implement the interface:

public class PaymentDetails implements TransactionAcceptor {
    ...
}

And of course it already implements the required method. Then MyService only needs to deal with the TransactionAcceptor interface and not be coupled with PaymentDetails.

Upvotes: 13

Jochen Bedersdorfer
Jochen Bedersdorfer

Reputation: 4122

Add an interface Transactionable or something and let PaymentDetails implement it. In MyService deal with 'Transactionables' only.

Upvotes: 4

Related Questions