1

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?

user1578653
  • 329
  • 2
  • 7
  • 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 Jan 30 '15 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 Jan 30 '15 at 16:23
  • Makes more sense, yes. I'll leave it to somebody else to answer the full question. – Ben Aaronson Jan 30 '15 at 16:25
  • related: [Derive from a base class but not include a condition in the base class's method](http://programmers.stackexchange.com/a/271458/31260) – gnat Jan 30 '15 at 16:25

1 Answers1

1
  1. Yes, that is the template method pattern

  2. 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.

Doc Brown
  • 199,015
  • 33
  • 367
  • 565