Suppose I have a definition for a door:
class Door
{
public void Lock()
{
// lock the door
}
}
This appeared to make sense to me, at least for awhile. But now, I'm not so sure. If I had a Person object that wanted to lock a Door, he would call aDoor.Lock(). But in real life, we do not lock doors by telling the door to lock itself.
It seems like a more accurate model of the situation would be the person being able to directly modify the state of aDoor, provided he has sufficient power to lock doors. For example, aCat should not be able to set aDoor.IsLocked = true. I could see how to do this with properties, if they supported parameters:
class Person
{
public void LockDoor(Door door)
{
door.IsLocked(this) = true;
}
}
class Door
{
bool isLocked;
public bool IsLocked(Person person)
{
set
{
if(person != null) // ensure there is a real person trying to lock the door
{
this.isLocked = value;
}
}
}
}
static void Main()
{
Person personFromThinAir = new Person();
Door doorFromThinAir = new Door();
personFromThinAir.LockDoor(doorFromThinAir);
}
Instead, what we can do is this:
class Person
{
public void LockDoor(Door door)
{
door.SetLocked(this, true);
}
}
class Door
{
bool isLocked;
public void SetLocked(Person person, bool locked)
{
if(person != null)
{
this.isLocked = locked;
}
}
}
Obviously these two classes are strongly coupled and both would probably have interfaces extracted in actual code, but that's not what I'm getting at. My question is, is this a better way to model the relationship between the two objects? Is there an even better way than this? The more I think about it, the less sense of aDoor.Lock() I can make; it seems to violate object-oriented design.