My PUMP can (inflate) my BALLOON. No problem! But when I try to use my PUMP to (pop) the BALLOON, it really doesn’t work very well. I can keep using my PUMP and, eventually, it will (pop) the balloon, but my arm is getting really tired, and I want to (pop) it now. So, instead, I get my POINTY STICK and (pop)! Of course, my POINT STICK is even less effective at (inflate)ing my BALLOON, than the PUMP is at (pop)ing it.
Class Balloon
{
Private int _volume = 0;
Private bool _popped = false;
Public Balloon() { }
//Restrict calling to only a PUMP object
Internal Inflate()
{
if (_popped) return;
_volume += 1;
if (volume > 10) this.Pop();
}
//Restrict calling to only a POINTY STICK object
Internal Pop()
{
if (!_popped) _popped = true;
}
Public string GirlHappiness
{ get
{
if (!_popped)
{
if (_volume < 3)
return "......";
if (_volume < 6)
return "Ooohhh";
else
return "Ahhhh! Yay!";
}
else
return "WaAaAaAaHhHhHh";
}
}
Public string BoyHappiness
{ get
{
if (!_popped)
{
if (_volume < 3)
return "zzzzzz";
if (_volume < 6)
return "zzzzzz";
else
return "zzzzzz";
}
else
return "Ahahaha YAY!";
}
}
}
So, is there any way to achieve this? I cannot achieve the desired result via separating assemblies, and the other method I’ve explored, using reflection and tracing the stack, is unreliable outside of debugging. What to do?!
Two ways that pop up in my mind: Use explicit interface implementation or events.
With explicit interfaces, you hide the implementation for those who do not threat the instance ‘as is’. Example:
Note that the Pump and Pop implementations can be marked private. They are only visible when you threat the balloon as IPumpable or IPoppable respectively.