Why is my class worse than the hierarchy of classes in the book (beginner OOP)?

Posted by aditya menon on Programmers See other posts from Programmers or by aditya menon
Published on 2012-04-05T11:03:45Z Indexed on 2012/04/05 11:41 UTC
Read the original article Hit count: 297

Filed under:
|
|

I am reading this book. The author is trying to model a lesson in a college. The goal is to output the Lesson Type (Lecture or Seminar), and the Charges for the lesson depending on whether it is a hourly or fixed price lesson. So the output should be:

lesson charge 20. Charge type: hourly rate. lesson type seminar.
lesson charge 30. Charge type: fixed rate. lesson type lecture.

When the input is as follows:

$lessons[] = new Lesson('hourly rate', 4, 'seminar');
$lessons[] = new Lesson('fixed rate', null, 'lecture');

I wrote this:

class Lesson {
    private $chargeType;
    private $duration;
private $lessonType;

public function __construct($chargeType, $duration, $lessonType) {
    $this->chargeType = $chargeType;
    $this->duration = $duration;
    $this->lessonType = $lessonType;
}

public function getChargeType() {
    return $this->getChargeType;
}

public function getLessonType() {
    return $this->getLessonType;
}

public function cost() {
    if($this->chargeType == 'fixed rate') {
        return "30";
    } else {
        return $this->duration * 5;
    }
}
}

$lessons[] = new Lesson('hourly rate', 4, 'seminar');
$lessons[] = new Lesson('fixed rate', null, 'lecture');

foreach($lessons as $lesson) {
    print "lesson charge {$lesson->cost()}.";
    print " Charge type: {$lesson->getChargeType()}.";
    print " lesson type {$lesson->getLessonType()}.";
    print "<br />";
}

But according to the book, I am wrong (I am pretty sure I am, too). The author gave a large hierarchy of classes as the solution instead. In a previous chapter, the author stated the following 'four signposts' as the time when I should consider changing my class structure:

  • Code Duplication
  • The Class Who Knew Too Much About His Context
  • The Jack of All Trades - Classes that try to do many things
  • Conditional Statements

The only problem I can see is Conditional Statements, and that too in a vague manner - so why refactor this? What problems do you think might arise in the future that I have not foreseen?

© Programmers or respective owner

Related posts about php

Related posts about object-oriented