Czytam Obiekty PHP, Wzorce i Praktykę . Autor próbuje modelować lekcję na uczelni. Celem jest przedstawienie rodzaju lekcji (wykładu lub seminarium) oraz opłat za lekcję w zależności od tego, czy jest to lekcja godzinowa, czy stała. Tak więc wynik powinien być
Lesson charge 20. Charge type: hourly rate. Lesson type: seminar.
Lesson charge 30. Charge type: fixed rate. Lesson type: lecture.
gdy dane wejściowe są następujące:
$lessons[] = new Lesson('hourly rate', 4, 'seminar');
$lessons[] = new Lesson('fixed rate', null, 'lecture');
Ja to napisałem:
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 />";
}
Ale zgodnie z książką się mylę (jestem pewien, że też). Zamiast tego autor podał dużą hierarchię klas jako rozwiązanie. W poprzednim rozdziale autor podał następujące „cztery drogowskazy” jako czas, w którym powinienem rozważyć zmianę struktury mojej klasy:
- Duplikacja kodu
- Klasa, która za dużo wiedziała o jej kontekście
- Gniazdem wszystkich branż - zajęcia, które starają się robić wiele rzeczy
- Instrukcje warunkowe
Jedyny problem, jaki widzę, to stwierdzenia warunkowe, i to również w niejasny sposób - więc po co to refaktoryzować? Jak myślisz, jakie problemy mogą pojawić się w przyszłości, których nie przewidziałem?
Aktualizacja : zapomniałem wspomnieć - jest to struktura klas, którą autor przedstawił jako rozwiązanie - wzorzec strategii :