Skip to main content
edited title
Link
wcminipgasker2023
  • 2.7k
  • 1
  • 14
  • 29

How to "Tell, don't ask" when both2 objects involves in the condition and action involves 2 objectsthe decision at the same time?

Became Hot Network Question
Source Link
wcminipgasker2023
  • 2.7k
  • 1
  • 14
  • 29

How to "Tell, don't ask" when both the condition and action involves 2 objects?

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();
    }
}