According to Explanation on how "Tell, Don't Ask" is considered good OO, I know the following is bad:
if(a.isX){
a.doY();
}
public class A{
public boolean isX;
public void doY(){
}
}
which I should modify it to
a.doYWhenX();
public class A{
private boolean isX;
public void doYWhenX(){
if(this.isX){
this.doY();
}
}
public void doY(){
}
}
to obey "tell, don't ask" rule. But what if the situation that needs 2 objects? eg:
if(a.isX && b.isP){
a.doY();
b.doQ();
}
public class A{
public boolean isX;
public void doY(){
}
}
public class B{
public boolean isP;
public void doQ(){
}
}
How should I refactor it to obey "Tell, don't ask" rule? I tried:
a.doYWhenX(b);
public class A{
private boolean isX;
public void doYWhenX(b){
if(this.isX && b.isP){
this.doY();
b.doQ();
}
}
public void doY(){
}
}
public class B{
public boolean isP;
public void doQ(){
}
}
but A is still asking the state of B, which is not "pure tell,don't ask".
Note: In real code, A and B are some components (eg:Timer, Notice board) which the isX and doY() is not easy to move them into 2 separate classes, and A and B are not easy to combine into one class because some other classes may just use A individually instead of B, for example (which simulates an Page based app, Page1 uses both A and B, but Page2 uses A only):
public static void main(String args[]){
this.a=new A();
this.b=new B();
Page1 page1=new Page1(this.a,this.b);
this.view.addSubview(page1);
Page2 page2=new Page1(this.a);
this.view.addSubview(page2);
}
public class Page1 extends View{
private A a;
private B b;
public Page1(A a,B b){
if(a.isX && b.isP){
a.doY();
b.doQ();
}
}
}
public class Page2 extends View{
private A a;
public Page2(A a){
this.a=a;
}
public void onButtonPressed(){
a.doX();
}
}
A
/B
example any longer.if(a.isX && b.isP){ a.doY(); b.doQ(); }
anda.doYWhenX(); b.doQWhenP()
. You can't do "tell, don't ask" without somebody coordinating activity among unrelated classes.a.isX
asa.issubclass(X)
(or in Java,a instanceof X
), which isn't indicated in the original question — thea.isX
andb.isP
booleans represent some condition within the respective objects being true, but there's no indication that those checks are questions of class hierarchy/membership.