You can not close
a file unless it's open
. How should the close method react when executed in the wrong state? Should it return a failure, or throw an exception. That depends upon the language and programming style you are following.
Weather or not the Bird can fly or not is a representation of it's internal state. The same as a file resource, and as such you would follow the same design patterns. Treating the Bird as having an internal state the the developer needs to control.
class Bird {
boolean canFly();
void teach();
void fly();
}
try
{
if(!b.canFly()) { b.teach(); }
b.fly();
} catch (e) { ... }
Having the perspective, that a method is order dependant upon another method doesn't follow my understanding of OOP design. The object has an internal state. The object manages it's own internal state, and outside source code shouldn't be responsible for management of that state (if possible). If you have to tell the developers to execute the methods in a given order, then you've designed the object wrong.
Instead of teaching and flying. You should initialize the bird, and make handling of the Bird's internal state an internal matter of the object. This way, you will not break other people's source code when you have to revise the design of Bird.
class Bird {
private boolean taught = false;
private boolean flying = false;
private void teach() {...}
protected void init() {
if(!this->taught) { this->teach(); }
}
public void startFlying() { this->init(); this->flying = true; }
public void stopFlying() { this->init(); this->flying = false; }
}
Learn()
method return a result (what was learned) that is then passed to theFly()
method as a parameter.