Tell me, don't ask the principle - should I apply it here?

Let's say I have some kind of graphical animation code where I have two classes: Sprite and SpriteAnimator. SpriteAnimator is responsible for moving sprites at regular intervals. Sprite has a property that can block it from moving.

I first applied this use case like this:

public class Sprite
{
    public bool Locked;
    public void MoveTo(int x, int y){}
}

public class SpriteAnimator
{
    private List<Sprite> Sprites;
    public void DoMovement()
    {     
        foreach (Sprite sprite in Sprites)
        {
            if (!sprite.Locked) MoveTo(newX, newY); 
        }
    }
}

      

... but then I remembered Tell-don't ask main , and I feel like I'm asking about the state by doing and then tell them what to do - just like the principle forbids me. So I am assigning:

public class Sprite
{
    private bool Locked;
    public void MoveIfNotLockedTo(int x, int y) { ... }
}


public class SpriteAnimator
{
      private List<Sprite> Sprites;
    public void DoMovement()
    {     
        foreach (Sprite sprite in Sprites)
        {
            MoveIfNotLockedTo(newX, newY);
        }
    }
}

      

.. but is this really the best code? I'm not sure how I feel about method names containing the word "If".

There is also a third option - where the Controller takes responsibility for the locked states of the sprites. Something like that:

public class Sprite
{
    public void Move(int x, int y) { ... }
}


public class SpriteAnimator
{
  private List<Sprite> Sprites;
  private List<Sprite> LockedSprites;

    public void DoMovement()
    {     
        foreach (Sprite sprite in Sprites)
        {
            if (!LockedSprites.Contains(sprite) MoveTo(newX, newY);
        }
    }
}

      

... but it has a performance impact as I get an O (N ^ 2) loop.

So what do you guys think? Is it time to be pragmatic and choose option # 1, which I think is the best, but violates the "not responding" principle?

+3


source to share


2 answers


Based on the principle, it looks like the second option is the way to go.

Tell the object what you want. Make it clear how to do this.



Don't worry too much about the function name, even better if you're afraid of not remembering how the function works, just comment out the function appropriately so that it is easily supported by you or someone else.

+4


source


Why does an animator need to care? Given the current logic, the blocked check should be done inside the method Sprite.move()

. It is the animators' responsibility to tell the sprite to move. It is up to the sprite to decide if it moves or not.



+6


source







All Articles