Could someone tell me whether the following is A) a good solution to the problem of repeating code and B) an example of the template method?
Let's say I have one table, named VEHICLES, which I use to store different types of vehicles (e.g. car, van, bus). I have a bunch of repository classes which should retrieve each type of vehicle:
class CarRepository{
public function getAll(){
$sql = "select * from vehicles where type='car'";
//some code to communicate with the database
}
}
class BusRepository{
public function getAll(){
$sql = "select * from vehicles where type='bus'";
//some code to communicate with the database
}
}
As you can see, each repo has almost the same code in the getAll method, which isn't very DRY. I was thinking a better solution might be to have a common base class for the repos, like this:
abstract class VehicleRepository{
final public function getAll(){
$sql = "select * from vehicles where type='".$this->getType()."'";
echo $sql;
//code to communicate with the database
}
abstract function getType();
}
And then each repo would just need to define the getType method:
class CarRepository extends VehicleRepository{
public function getType(){
return "car";
}
}
class BusRepository extends VehicleRepository{
public function getType(){
return "bus";
}
}
Does this seem reasonable? And is this what is meant by the template method pattern?
-
You don't seem to have reduced repetition? If you were going to take this approach, wouldn't you move everything but the "bus" and "car" strings into the common base class?Ben Aaronson– Ben Aaronson01/30/2015 16:21:39Commented Jan 30, 2015 at 16:21
-
@BenAaronson Yes I just noticed that I'd just moved the duplication, not eliminated it! I've updated the code - is that better?user1578653– user157865301/30/2015 16:23:21Commented Jan 30, 2015 at 16:23
-
Makes more sense, yes. I'll leave it to somebody else to answer the full question.Ben Aaronson– Ben Aaronson01/30/2015 16:25:24Commented Jan 30, 2015 at 16:25
-
related: Derive from a base class but not include a condition in the base class's methodgnat– gnat01/30/2015 16:25:43Commented Jan 30, 2015 at 16:25
1 Answer 1
Yes, that is the template method pattern
Currently there is no need to make the
getType
methods public, "protected" would be enough. If you actually need them outside of that class hierarchy, you can make them public, of course.
Explore related questions
See similar questions with these tags.