Reputation: 340
For years now I have been writing (on and off) at an office-management app. I need to rewrite it, because the code has become unmaintainable, so I will choose a PHP-framework and rewrite the business logic into classes.
Now I am stuck with this fundamentamental question: do I still need to return the result and if yes, how do I capture that result? Some pseudocode to make my question clear:
function a( $1, $2, $3 ) {
doThis( if ... return TRUE; if ... return FALSE; );
if ( doThis() != TRUE ) { return; }
doThat();
}
vs
class example {
private $1;
private $2;
private $3;
public function go() { $this->doThis(); $this->doThat(); }
private function doThis(){}
private function doThat(){}
}
$a = new example;
$a->go();
How can I stop the execution of the go()-method if the doThis()-method does not perform as expected? I presume I should not go about returning booleans and checking inside every method if a certain property is set to false? Or do I simply throw an Exception if something went wrong and don't do anything if everything is ok?
This is pretty basic, I know...
Thx!
Upvotes: 0
Views: 86
Reputation: 10666
Exceptions are for exceptional behaviour
, so don't throw exceptions just because your code isn't in a preferred state. When it comes to writing OOP, some people still manage to write procedural while using a object oriented framework, obviously you'd want to avoid that, a simple rule of thumb is to not write God-objects.
Now what I'm guessing that you want to do is to call two functions that should be called in a specific order, and there are several ways to do this, and it actually boils down to, what kind of class you have. Lets say you have an object of the type Person
then you might want to call different methods on that person from somewhere else:
$john = new Person();
$john->tryToWakeUp();
if($john->isAwake) {
$john->brushTeeth();
} else {
echo "John is still sleeping!";
}
On the other hand you might have an object of the type Engine
which might want to do several stuff internally for certain actions, like start:
class Engine {
public function start() {
$this->checkFuel();
if($this->hasFuel()) {
try {
$this->initializeSomethingThatHasToDoWithEngineStartUp();
} catch (EngineException $ee) {
$this->engineState = BAD_ENGINE;
Logger::log("Engine did not start");
}
}
}
}
I'd recommend you to read up on object oriented design and play around with it before you try to convert all of your business rules, because It's likely that half way through you'll realize that you've designed everything wrong. Object Oriented Design is not easy, but it does make sense EDIT:( It should make sense ).
Upvotes: 1