Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

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:

  • does some stuff with the first dependency,
  • constructs a new TransactionDetails() object and sets various things on it,
  • calls myPaymentDetails.setTransactionDetails( td );
  • returns something to say which page in the wizard follows next

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:

  • it will limit the ability to re-use the service class
  • it is not possible to understand what the real dependencies are by reading the method signatures

My question is:

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

like image 925
WW. Avatar asked Apr 02 '11 05:04

WW.


2 Answers

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.

like image 98
WhiteFang34 Avatar answered Nov 15 '22 03:11

WhiteFang34


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

like image 4
Jochen Bedersdorfer Avatar answered Nov 15 '22 01:11

Jochen Bedersdorfer