Lazycoder

16May/040

Handleless doors and OOP

Udi Dahan – The Software Simplist: Solutions with OO

Udi writes about an OO system with “Doors” that have “Handles”. One problem that one of his readers found was that if you want to use the handle of a door that does not have a handle, you have to check to see if the handle is null every time you want to use it.

public void foo(Door d)
{
  if (d.Handle != null)
    if (d.Handle.Status == Status.New)
       // do something
}

My solution would be a little different. IDoor.

public interface IDoor
{
    public bool IsWood;
}

public class DoorWithHandle : IDoor
{
    public bool IsWood = true;
    public Handle DoorHandle = new Handle();
}

public class DoorWithoutHandle : IDoor
{
    public bool IsWood = true;
}

Now this doesn’t really solve the problem of null checking, you still have to check the type of the IDoor you’re working with and ensure that you have an instance of a DoorWithHandle class before you try to use the handle.

public void ManipulateHandle(IDoor door)
{
    if(door is DoorWithHandle)
    {
        Handle handle = door.Handle;
        handle.Turn();
    }
}

But you’ll get a different error depending on whether or not you are controlling the type of IDoor descendant that you are passed in your code. If you create a method that accepts types of only DoorWithHandle when you know you want to manipulate the handle you’ll be OK. Anyone, including you, who tries to pass in a DoorWithoutHandle type will get a compile time error.

public void ManipulateHandle(DoorWithHandle door)
{
    Handle handle = door.Handle;
    handle.Turn();
}
Share and Enjoy:
  • del.icio.us
  • DotNetKicks
  • DZone
  • Reddit
  • Digg
  • StumbleUpon
  • LinkedIn
  • Facebook
  • FriendFeed
  • HackerNews
  • Netvibes
  • Posterous
  • Tumblr
  • Twitter
Comments (0) Trackbacks (0)

No comments yet.


Leave a comment


No trackbacks yet.