I don't see a refactoring opportunity here, as such.
I see the need for a factory. Look up the "factory" design pattern.
And I see code all over the place like... (followed by a conditional wherein a specific instance is created)_ is a huge tip-off.
Basically, what you want to do it push all the ugliness of deciding which class to instantiate into one place. First, in your example, A and B should share a superclass or better yet implement an interface in which public C createC()
is defined.
The factory is nothing more than a class with a static method that makes the decision on which A or B to instantiate.
public class SomeFactory {
public static YourInterface make(int someNumber) {
switch (someNumber) {
case 1: return new A();
case 2: return new B();
default:
throw new RuntimeException("unknown type");
}
}
}
So what you do is:
YourInterface yi = SomeFactory.make(1);
C c = yi.createC();
Or
C c = SomeFactory.make(1).createC();
And now your code is pretty clean. Create a new implementation of SomeInterface? No problem, add its creation to the factory and your code still works. If for your application make()
is costly, no problem, just make one and use it repeatedly.