mariia
mariia

Reputation: 137

How to refactor two similar methods in one

There is one method. In one case I need to return variable with one type. In another case I need to return variable with another type. I created two methods. But I know that it is not a good idea because of duplication of code. How do I fix it and use one method?

public ClassA doSomething(String aString, String bString, String cString, String dString) {
    ClassA client;
    ClientFactory clientFactory = new ClientFactoryImpl();
    client = clientFactory.createNewClient(aString, bString);
    ClassB conn = clientFactory.connect(cString, dString);
    return client;
}

public ClassB doSomething(String aString, String bString, String cString, String dString) {
    ClassA client;
    ClientFactory clientFactory = new ClientFactoryImpl();
    client = clientFactory.createNewClient(aString, bString);
    ClassB conn = clientFactory.connect(cString, dString);
    return conn;
}

Upvotes: 1

Views: 418

Answers (1)

Dragan Bozanovic
Dragan Bozanovic

Reputation: 23552

In general case, when client and conn depend on each other:

class SomethingResult {
  ClassA client;
  ClassB conn;
  SomethingResult(ClassA client, ClassB conn) {
    this.client = client;
    this.conn = conn;
  }
  // Getters
}

public SomethingResult doSomething(String aString, String bString, String cString, String dString) {
    // Create client and conn and execute any other logic
    return new SomethingResult(client, conn);
}

Then, for example, to get client:

ClassA client = doSomething(aString, bString, cString, dString).getClient();

In your specific case there is no need for this; you can simply do:

public ClassA getClient(String aString, String bString) {
    ClientFactory clientFactory = new ClientFactoryImpl();
    return clientFactory.createNewClient(aString, bString);
}

public ClassB getConn(String cString, String dString) {
    ClientFactory clientFactory = new ClientFactoryImpl();
    return clientFactory.connect(cString, dString);
}

Upvotes: 1

Related Questions