When you do decide it is worth the hassle, there is a refactoring for this that follows tell don't ask. Yes, even with two classes. Yes, without encapsulation destroying accessors. Getters be damnedNo getters required.
What you need is multiple dispatch. Something which many languages don't directly support. Including Java.
You can simulate multiple dispatch in Java using a little thing called the visitor pattern:
class A {
private boolean isX;
public void accept(B b) {
if (this.isX) {
b.accept(A::doY);
}
}
public void doY(){
}
}
Do it this way and you need no accessors. A
decides what to do based on it's own state. B
decides what to do based on it's own state. And nothing is done until both states have had their say.
Oh sure, it's ugly. It always is when simulating a feature your language doesn't have. But if real encapsulation is important to you, done with no stupid getters, where only A
knows isX
exists, then this works.
There are slicker solutions that might be viable where A
and B
don't even know each other exist. See Predicates. See also: Groovy. See also getThis() trick.