Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

What is the preferred way to handle this in java

Let's say I have the following classes:

public interface X {
...
}

public class A implements X {
...
}

public class B implements X {
...
}

Now let's say I have a method somewhere that takes an object of type X, and must handle each implementation of X differently. The naïve approach is:

public void doSomething(X x) {
  if(x instanceof A)
    doSomethingA((A) x);
  else if(x instanceof B)
    doSomethingB((B) x);
}

...but this seems particularly ugly and not polymorphic. What is the clean way of handling such a situation in general?

EDIT: Sure, it would be easy if I could push the implementation of doSomething() to classes A and B, but what about in situations where that doesn't make sense? i.e. doSomething() is defined on a class C and the implementation is highly dependent on C's internal state.

like image 937
Kricket Avatar asked Nov 30 '25 02:11

Kricket


1 Answers

It's easy:

public interface X {
  int doSomething();
}

public class A implements X {
  public int doSomething() {
    // implementation in A
  }  
}

public class B implements X {
  public int doSomething() {
    // implementation in B
  }  

}

UPDATE: Ok, seems here we have some algorithm in C which dependants on C's state as well as on A/B differences. Then I would try to split that algorithm so that C class has only a common implementation for both A and B, and A-/B-dependent parts should go to an appropriate class as a particular implementation of the same method which is invoked in C. If possible, C's state can partially be passed to A's and B's doSomething

like image 120
Wizart Avatar answered Dec 02 '25 14:12

Wizart