design patterns - The Tell, don't ask principle - should I apply it here? -


lets have sort of graphical animation code have 2 classes: sprite , spriteanimator. spriteanimator responsible moving sprites @ regular intervals. sprite has property can lock movement though.

i first implemented use case 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 remembered tell-don't ask principle, , feel i'm asking state, making decision , tell them - principle forbids me. recode this:

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 better code? i'm not sure how feel method names containg word "if".

there third option - controller takes ownership of locked-states of sprites. this:

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 has performance impact o(n^2) loop.

so guys think? time pragmatic , choose option #1 feel best violates tell-don't-ask-principle?

based on principle, looks second option way go.

tell object want. let figure out how it.

don't worry function's name, better yet, if you're afraid of not remembering how function works, comment function maintainable you, or else.


Comments

Popular posts from this blog

delphi - How to convert bitmaps to video? -

jasper reports - Fixed header in Excel using JasperReports -

python - ('The SQL contains 0 parameter markers, but 50 parameters were supplied', 'HY000') or TypeError: 'tuple' object is not callable -