Brad Abrams and extension methods to the rescue..

Currently i am implementing Sokoban and i was pondering which methods i should add to my Cell class:

  • bool HoldsWall
  • bool HoldsBox
  • bool HoldsPlayer

Or

  • bool HoldsPieceOfType(Type type)

Which option should i choose? With the aid of extension methods (in the same namespace) i can have them both:

namespace Sokoban.Domain
{
 public static class ExtensionMethods
 {
  public static bool HoldsBox(this Cell cell)
  {
   return cell.HoldsPieceOfType(typeof(Box));
  }

  public static bool HoldsPlayer(this Cell cell)
  {
   return cell.HoldsPieceOfType(typeof(Player));
  }

  public static bool HoldsWall(this Cell cell)
  {
   return cell.HoldsPieceOfType(typeof(Wall));
  }
 }
}

In case you don’t like this solution, blame Brad Abrams who inspired me to implement it this way with his session at Visug yesterday.

Remark: Because the possible pieces in Sokoban are very well known (the game/requirements are not going to change) thus one should choose the first option (No extension methods required.)

  1. Did you consider the generic variant: Holds.

    I think you’d like to limit your type parameter to some base class maybe? Which would be possible with the generic approach.

    Your HoldsPieceOfType allows any type and some just don’t make sense.

  2. @Stijn: You are absolutely right.

    bool Holds<T>() where T : Piece

    Seems like a viable solution :)

Leave a Comment


NOTE - You can use these HTML tags and attributes:
<a href="" title=""> <abbr title=""> <acronym title=""> <b> <blockquote cite=""> <cite> <code> <del datetime=""> <em> <i> <q cite=""> <strike> <strong>