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

2

6

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?

Abnaki answered 2/4, 2011 at 5:59 Comment(0)
R
13

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.

Reeva answered 2/4, 2011 at 6:10 Comment(0)
S
4

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

Stockist answered 2/4, 2011 at 6:10 Comment(0)

© 2022 - 2024 — McMap. All rights reserved.