design patterns - Using a class to store constant values -


is there better approach storing values required per following example. im trying avoid possible errors when passing string factory method.

but, there issues this? testable, there better way achieve same thing etc.

abstract class types {     const car = 'car';     const boat = 'boat';     const bike = 'bike'; }  class vehiclefactory {      public function make($type)      {         if ($type === types::car) {             // create new car         }         if ($type === types::boat) {             // create new boat         }         if ($type === types::bike) {             // create new bike         }     } }  class client {     public function createacar()     {         $vehiclefactory = new vehiclefactory();         $car = $vehiclefactory->create(types::car)     } } 

this looks language agnostic question going assume advice use enum instead of abstract class won't work.

your approach of using constants represent type of object gets created correct. if had change anything, way client class uses vehiclefactory provide test doubles while unit testing code :

class client {      private $factory;      public function __construct($factory){         $this->factory = $factory;     }          public function createacar()     {         $car = $factory->create(types::car)     } } 

now can pass in subclass of vehiclefactory (say vehiclemockfactory) can create test doubles instead of creating actual objects :

class vehiclemockfactory extends vehiclefactory {      public function make($type)      {         if ($type === types::car) {             // create new testcar         }         if ($type === types::boat) {             // create new testboat         }         if ($type === types::bike) {             // create new testbike         }     } } 

while unit testing, can pass vehiclemockfactory client rather actual vehiclefactory.


Comments

Popular posts from this blog

powershell Start-Process exit code -1073741502 when used with Credential from a windows service environment -

twig - Using Twigbridge in a Laravel 5.1 Package -

c# - LINQ join Entities from HashSet's, Join vs Dictionary vs HashSet performance -