PHP Design Patterns – Behavioural

These are just the Behavioural patterns. See the previous posts for Creational patterns and Structural patterns

Chain of responsibility

A method called in one object will move up the chain of objects until one is found that can properly handle the call.

abstract class AbstractExperiment {
    abstract function getExperiment();
    abstract function getTitle();
}
 
class Experiment extends AbstractExperiment {
    private $experiment;
    private $tissue;
    function __construct($experiment_in) {
        $this->experiment = $experiment_in;
        $this->tissue = NULL;
    }
    function getExperiment() {
        return $this->experiment;
    }
    //this is the end of the chain - returns title or says there is none
    function getTissue() {
      if (NULL != $this->tissue) {
        return $this->tissue;
      } else {
        return 'there is no tissue applied';
      }
    }
}

class SubExperiment extends AbstractExperiment {
    private $experiment;
    private $parentExperiment;
    private $tissue;
    function __construct($experiment_in, Experiment $parentExperiment_in) {
      $this->experiment = $experiment_in;
      $this->parentExperiment = $parentExperiment_in;
      $this->tissue = NULL;
    }
    function getExperiment() {
      return $this->experiment;
    }
    function getParentExperiment() {
      return $this->parentExperiment;
    }   
    function getTissue() {
      if (NULL != $this->tissue) {
        return $this->tissue;
      } else {
        return $this->parentExperiment->getTissue();
      }
    }
}

//This class and all further sub classes work in the same way as SubExperiment above
class SubSubExperiment extends AbstractExperiment {
    private $experiment;
    private $parentExperiment;
    private $tissue;
    function __construct($experiment_in, Experiment $parentExperiment_in) { //as above }
    function getExperiment() { //same as above }
    function getParentExperiment() { //same as above }   
    function getTissue() { //same as above }
}

Command

Object will encapsulate everything needed to execute a method in another object. Eg. One class will contain all the functions needed inside. Other classes will then extend it and just execute the functions they need. The example below has functions to change the Experiment name to swap spaces for underscores and vice versa. The method is done in the Comandee and the function is executed in the Command.

class ExperimentCommandee {
    private $experiment;
    function __construct($experiment_in) {
        $this->setExperiment($experiment_in);
    }
    function getExperiment() {
        return $this->experiment;
    }
    function setExperiment($experiment_in) {
        $this->experiment = $experiment_in;
    }
    function setUnderscoresOn() {
        $this->setExperiment(Str_replace(' ','_',$this->getExperiment ()));
    }
    function setUnderscoresOff() {
        $this->setExperiment(Str_replace('_',' ',$this->getExperiment()));
    }
}

abstract class ExperimentCommand {
    protected $experimentCommandee;
    function __construct($experimentCommandee_in) {
        $this->experimentCommandee = $experimentCommandee_in;
    }
    abstract function execute();
}

class ExperimentUnderscoresOnCommand extends ExperimentCommand {
    function execute() {
        $this->experimentCommandee->setUnderscoresOn();
    }
}

class ExperimentUnderscoresOffCommand extends ExperimentCommand {
    function execute() {
        $this->experimentCommandee->setUnderscoresOff();
    }
}

Interpreter

Define a language and syntax, parse requests in that language and then assign the appropriate classes and methods to handle the requests. Eg. The output must be in a set format.

class Interpreter {  
    private $experimentList;
    public function __construct($experimentList_In) {
        $this->experimentList = $experimentList_In;
    }
    public function interpret(array $string) {      
        $string = $this->postarray;
        switch (array_pop($this->postarray)) {
            case 'vivo' :
                $value = new vivoExpt();
                return $value;
             case 'vitro' :
                $value = new vitroExpt();
                return $value;
        //switch case continues setting $value
}

class Client {
    private $experiments = array();
    public function __construct() { }
    public function vivoExpt() { //code for vivo experiment function }
    public function vitroExpt() { //code for vitro experiment function }
    //other functions called in the interpreter switch case here 
}

Iterator

A class can traverse the elements of another class. Eg. An ExperimentIterator class could traverse the ExperimentList class and return each Experiment in the order that they were added to the list. You could also make one which could iterate the list in reverse sequential order or all odd numbered elements etc.

class Experiment {
    private $experiment;
    function __construct($experiment_in) { $this->experiment = $experiment_in; }
    function getExperiment() { return $this->experiment; }
}

class ExperimentList {
    private $experiments = array();
    private $experimentCount = 0;
    public function __construct() {  }
    public function getExperimentCount() {
      return $this->experimentCount;
    }
    private function setBookCount($newCount) {
      $this->bookCount = $newCount;
    }
    public function getExperiment($exptNumberToGet) {
      if ((is_numeric($exptNumberToGet)) && ($exptNumberToGet <= $this->getexperimentCount())) { 
           return $this->experiments[$exptNumberToGet];
         } else {
           return NULL;
         }
    }
}

class ExperimentListIterator {
    protected $experimentList;
    protected $currentExperiment = 0;
    public function __construct(ExperimentList $experimentList_in) {
      $this->experimentList = $experimentList_in;
    }
    public function getCurrentExperiment() {
      if (($this->currentExperiment > 0) && 
            ($this->experimentList->getexperimentCount() >= $this->currentexperiment)) {
        return $this->experimentList->getExperiment($this->currentExperiment);
      }
    }
    public function getNextExperiment() {
      if ($this->hasNextExperiment()) {
        return $this->experimentList->getExperiment(++$this->currentExperiment);
      } else {
        return NULL;
      }
    }
    public function hasNextExperiment() {
      if ($this->experimentList->getExperimentCount() > $this->currentExperiment) {
        return TRUE;
      } else {
        return FALSE;
      }
    }
}

Mediator

An object distributes communication between two or more objects. Eg. A MediatorClass could be listening to two other classes to see when one of them changes the tissue. When one of them does so the mediator gets the other class to also change its tissue. Example just has one function to upper case but could have multiple to change the tissue in different ways.

class Mediator {
    private $tissue;
    function __construct($experiment_in) { 
        $this->tissue = new TissueExperiment($tissue_in,$this);
    }
    function getTissue() { return $this->tissue; }
    function change(Experiment $change) {}
}

abstract class Experiment {
    private $mediator;
    function __construct($mediator_in) { $this->mediator = $mediator_in; }
    function getMediator() { return $this->mediator; }
    function changed($change) { getMediator()->tissueChanged($change); }
}

class TissueExperiment extends Experiment {
    private $tissue;
    private $state;
    function __construct($tissue_in, $mediator_in) {
      $this->tissue = $tissue_in;
      parent::__construct($mediator_in);
    }
    function getTissue() { return $this->tissue; }
    function setTissue($tissue_in) { $this->tissue = $tissue_in; }
    function getState() { return $this->state; }
    function setState($state_in) { $this->state = $state_in; }
    function setTissueUpperCase() {
      $this->setTissue(strtoupper($this->getTissue()));
      $this->setState('upper');
      $this->getMediator()->change($this);
    }
}

Memento

One object stores another objects state. So a CaretakerClass could get the MementoClass to create, set or get the values for the OriginatorClass. The CartakerClass cannot directly access the OriginatorClass. MementoClass can only be instructed to do this.

class Originator {    
    private $experiment;   
    function __construct($experiment_in) {
      $this->setExperiment($experiment_in);
    }  
    public function getExperiment() {
      return $this->experiment;
    }      
    public function setExperiment($experiment_in) {
      $this->experiment = $experiment_in;
    }
}

class Memento {    
    private $experiment;    
    function __construct(Originator $originator) {
      $this->setExperiment($originator);      
    }  
    public function getExperiment(Originator $originator) {
      $originator->setExperiment ($this->experiment);
    }      
    public function setExperiment(Originator $originator) {
      $this->experiment = $originator->getExperiment();
    }    
}

//This would then be the Caretaker (client)
$originator = new Originator('In Vivo Micronucleus Assay');
$memento = new Memento($originator);

Observer

The subject object will notify other objects if its state has changed. The SubjectClass will use the attach method to link to the ObserverClass. For it to no longer be notified of changes it would need to be detached using detach method. Also called Publish/Subscribe where subject is publisher and observer subscriber. So when subject changes it calls the observers update method.

abstract class AbstractObserver {
    abstract function update(AbstractSubject $subject_in);
}

abstract class AbstractSubject {
    abstract function attach(AbstractObserver $observer_in);
    abstract function detach(AbstractObserver $observer_in);
    abstract function notify();
}

State

A class will change its behaviour when circumstances change. Eg. An object can alter its behaviour when an internal state changes so the object will appear to be a different class. For example a vending machine object can be a class that returns an item. If insufficient funds then it changes state to be like a class which returns money.

class StudyContext {
    private $experiment = NULL;
    private $experimentNameState = NULL; 
    public function __construct($experiment_in) {
      $this->experiment = $experiment_in;
      $this->setNameState(new ExperimentNameStateUnderscores());
    }
    public function getExperimentName() {
      return $this->experimentNameState->showExperiment($this);
    }  
    public function getExperiment() {
      return $this->experiment;
    }
    public function setNameState($experimentState_in) {
      $this->experimentNameState = $experimentState_in;
    }
}

interface ExperimentNameStateInterface {
    public function showName($context_in);
}
 
class ExperimentNameStateUnderscores implements ExperimentNameStateInterface {
    private $nameCount = 0; 
    public function showName($context_in) {
      $name = $context_in->getExperiment()->getName();
      $this->nameCount++;
      $context_in->setNameState(new ExperimentNameStateUnderscores());
      return Str_replace(' ','_',$name);
    }
}

class Experiment {
    private $name;
    function __construct($name_in) {
      $this->name = $name_in;
    }
    function getName() {return $this->name;}
}

Strategy

An object can choose which method it wants to call from the family of methods. Each method would be in its own class that calls a common base class. Eg. The Strategy class will be able to call from the three class methods StrategyOne(), StrategyTwo() and StrategyThree().

class Strategy {
    private $strategy = NULL;
    public function __construct {
        switch ($strategy) {
            case "A":
	        $this->strategy = new StrategyOne();
            break;
            case "B":
                $this->strategy = new StrategyTwo();
            break;
            case "C":
	        $this->strategy = new StrategyThree();
            break;
        }
    }
}

Template Method

An abstract class will define a method with an algorithm and methods which the algorithm will use; these methods can be optional or required. It is unusual in that the Parent class will have a lot of control. In the example both InVivo and InVitro classes extend Assays, they cannot override the first function as its ‘final’, have to override the second and the third is optional. So if they don’t use it, it will return NULL. This example is for making usable filenames for each experiment.

abstract class Assays {
    public final function showInfo($expt) {
	//The main function, this cannot be overridden (final) Will call other functions      inside it at some point
        $processedItem1 = $this->processItem1($expt1);
        $processedItem2 = $this->processItem2($expt2);
    }
    //function MUST be overridden by subclasses. Eg must always have at least one expt
    abstract function processItem1($expt1);
    //function can be overridden. Optional, if not used then set to NULL
    function processItem2($expt2) {
        return NULL;
    }
}
class InVitro extends Assays {
    function processItem1($expt1) {
        return 'VivoAssay-' . Str_replace(' ','_',$ expt1); 
    }
    function processItem2($expt2) {
        return 'VivoAssay-' . Str_replace(' ','_',$ expt2); 
    }
} 
class InVivo extends Assays {
    function processItem1($expt1) {
        return 'VitroAssay-' . Str_replace(' ','_',$ expt1); 
    }
}

Visitor

One class calls a function in another class that has the same method; the class has special functions for each class that can call it. In this example the ExperimentVisitee class can call the visitExperiment function in any function that extends Visitee. So Visitors that format ExperimentVisitee information can be added eithout changing ExperimentVisitee at all.

abstract class Visitor {
    abstract function visitExperiment(ExperimentVisitee $exptVisitee_In);
}

abstract class Visitee {
    abstract function accept(Visitor $visitorIn);
}

class ExperimentVisitee extends Visitee {
    //other variables and functions
    function accept(Visitor $visitorIn) {
        $visitorIn->visitExperiment($this);
    } 
}

This is for the Behavioural patterns – Creational patterns, Structural patterns

PHP Design Patterns – Structural

These are the Structural deisgn patterns. View other posts for Creational patterns and Behavioural patterns

Adapter

A class converts the interface of one class to be what another class expects. Eg. It extends another class, takes an object and then makes the object behave like the extended class.

Good if you want to use a class but it doesn’t exactly fit what you want. So you can adapt them slightly to your needs.

class Experiment {
    private $routine;
    private $tissue;
    function __construct($routine_in, $tissue_in) {
        $this->routine = $routine_in;
        $this->tissue  = $tissue_in;
    }
    function getRoutine() {
        return $this->routine;
    }
    function getTissue() {
        return $this->tissue;
    }
}

class ExperimentAdapter {
    private $experiment;
    function __construct(Experiment $experiment_in) {
        $this->experiment = $experiment_in;
    }
    function getRoutineAndTissue() {
        return $this->experiment->getTissue().' ('. $this->experiment->getRoutine().')';
    }
}

Bridge

The abstraction and implementation are decoupled into separate class hierarchies so they can work independently. Example will apply one of the two implementations (caps or lower) each time BridgeExperiment is instantiated.

abstract class BridgeExperiment {     
    private $experiment;
    private $implementation;
    function __construct($experiment_in, $choice_in) {
      $this->experiment = $experiment_in;
      if ('LOWER' == $choice_in) {
        $this->implementation = new BridgeExperimentLower();
      } else {
        $this->implementation = new BridgeExperimentCaps();
      }
    }    
    function showExperiment() {
      return $this->implementation->showExperiment($this->experiment);
    }
}
 
abstract class BridgeExperimentImp {    
    abstract function showExperiment($experiment);
}

class BridgeExperimentCapsImp extends BridgeExperimentImp {    
    function showExperiment($experiment_in) {
      return strtoupper($experiment_in); 
    }
}

class BridgeExperimentLowerImp extends BridgeExperimentImp {    
    function showExperiment($experiment_in) {
      return strtolower($experiment_in);
    }
}

Composite

An individual object or a group of an object will have similar behaviours. In the example SeveralExperiments is a group of zero or more OneExperiment objects. Both can return info about the tissue and routine (OneExperiment only about its self while SeveralExperiments will return them all). The addExperiment function will only work on SeveralExperiments though even though they both have the function.

//Experiment interface
interface ExperimentInterface {
    public function lockExperiment();
}

//single expt
class Experiment implements ExperimentInterface {
    public function lockExperiment() {
        //do something here
    }
}

//multiple expts
class CompositeExperiment implements ExperimentInterface {
    private $expts = array();
    public function add(Experiment $expt) {
        $this->expts[] = $expt;
    }
    public function lockExperiment() {
        foreach($this->expts as $expt) {
	  $expt->lockExperiment();
        }
    }
}

//doSomething to one experiment
$OneExpt = new Experiment();
doSomething($OneExpt);

//or add loads of expts and doSomething to them!
$expt1 = new Experiment();
$expt2 = new Experiment();
$expt3 = new Experiment();
$expt4 = new Experiment();
$multipleExpts = new CompositeExperiment();
$multipleExpts->add($expt1);
$multipleExpts->add($expt2);
$multipleExpts->add($expt3);
$multipleExpts->add($expt4);
doSomething($multipleExpts);

//now we can pass in single or multiple experiments without
//having to make changes to this function
function doSomething(ExperimentInterface $expt){
	$expt->lock();
}

Decorator

A class will add functionality to another class without changing the other classes’ structure. In the example we copy the experiments tissue in the decorator and change it for display, by adding brackets. It does this without changing the original object.

class Experiment {
    private $tissue;
    function __construct($tissue_in) {
        $this->tissue  = $tissue_in;
    }
    function getTissue() {
        return $this->tissue;
    }
}

class ExperimentTissueDecorator {
    protected $experiment;
    protected $tissue;
    public function __construct(Experiment $experiment_in) {
        $this->experiment = $experiment_in;
        $this->resetTissue();
    }   
    //doing this so original object is not altered
    function resetTissue() {
        $this->tissue = $this->experiment->getTissue();
    }
    function showTissue() {
        return $this->tissue;
    }
}

class ExperimentTissueBracketsDecorator extends ExperimentTissueDecorator {
    private $etd;
    public function __construct(ExperimentTissueDecorator $etd_in) {
        $this->etd = $etd_in;
    }
    function bracketsTissue() {
        $this->etd->tissue = "(" . $this->etd->tissue . ")";
    }
}

Façade

A class will hide a complex subsystem from the calling class. The complex subsystem will know nothing of the calling class. The example shows a class that creates experiment. If we wanted to make changes to the process we would only have to do so in the façade class rather than every place it was applied. Gateway Pattern is an example of Façade pattern.

class Facade {
    public $experiment = '';
    public function __construct($expt) {
        $this->experiment = $expt;
    }
    public function createExperiment() {
        $this->addTissue();
        $this->addRoutine();
    }
    private function addTissue() { //tissue code goes here }
    private function addRoutine() { //routine code goes here }
}

Flyweight

The variable and reusable elements of a class are broken into two classes to save resources. This is done when a large number of the exact same class would otherwise have been created. Not used much in PHP and is usually better to just use the prototype pattern instead.

 

Proxy

One class can control the creation and access of objects in another class. Like if a class is on a server or something that is memory intensive. Can be used to add additional access functionality such as recording the number of times the real subject is actually called.

abstract class AbstractExperiment {
    private $tissue;
    public function setTissue($tissue) {
        $this->tissue = $tissue;
    }
    public function getTissue() {
        return $this->tissue;
    }
}

class Experiment extends AbstractExperiment {
    public function __construct($tissue) {
        $this->setTissue($tissue);
    }
}

class ExperimentProxy extends AbstractExperiment {
    private $experimentName;
    public function __construct($tissue) {
        $this->tissue = $tissue;
    }
    public function () {
        if (NULL === $this-> experimentName) {
            $this-> experimentName = new Experiment($this->tissue);
        }
        return $this-> experimentName;
    }
}

$proxies = array();
for ($i = 0; $i < 10; $i++) {
    $proxies[$i] = new ExperimentProxy('Expt-' . $i);
}

These are just the Structural design patterns - Creational patterns, Behavioural patterns

PHP Design Patterns – Creational

These are the Creational design patterns. Behavioural patterns and Structural patterns appear in the next two following posts.

Abstract Factory

An interface for creating sets of related or dependant objects without specifying their concrete classes. There will be several classes (such as OutputFactory) which extend the AbstractFactory class which will in turn create new classes. This pattern is one of the most complicated patterns to learn and only really works and becomes useful with very complex systems.

abstract class AbstractFactory {
    abstract public function Experiment();
}

abstract class AbstractExperiment {
    abstract public function getExperiment();
}

class OutputFactory extends AbstractFactory {
    public function Experiment() {
        return new ExperimentOutput();
    }
}

class ExperimentOutput extends AbstractExperiment {
    public function getExperiment { 
        return 'Comet In Vivo Experiment 6'; 
    }
}

Builder

A director and a builder work together to build an object, the director controls what is built and how and the builder assembles it to the specification. In the example we see all the building blocks are available in the Builder class and the page is created in the Director class.

abstract class AbstractBuilder {
    abstract function getPage();
}

abstract class AbstractDirector {
    abstract function __construct(Builder $builder_in);
    abstract function buildPage();
    abstract function getPage();
}

class Page {
    private $page = NULL;
    private $page_text = NULL;
    function __construct() {}
    function showPage() {
        return $this->page;
    }
    function setText($text_in) {
        $this->page_text .= $text_in;
    }
    function formatPage() {
        $this->page = 'p' . $this->page_text . 'p';
    }
}

class Builder extends AbstractBuilder {
    private $page = NULL;
    function __construct() {
        $this->page = new Page();
    }
    function setText($text_in) {
        $this->page->setText($text_in);
    }
    function formatPage() {
        $this->page->formatPage();
    }
    function getPage() {
        return $this->page;
    }
}

class Director extends AbstractDirector {
    private $builder = NULL;
    public function __construct(AbstractBuilder $builder_in) {
        $this->builder = $builder_in;
    }
    public function buildPage() {
        $this->builder->setText('Test text for page!');
        $this->builder->formatPage();
    }
    public function getPage() {
        return $this->builder->getPage();
    }
}

 

Factory Method

Gives methods to make and return components of one object in various ways. Which subclass is created will depend on the parameter passed to the function. Can use interfacing or subclassing.

abstract class AbstractFactoryMethod {
    abstract function makeExperiment($param);
}

class InVivoFactoryMethod extends AbstractFactoryMethod {
    private $context = "In Vivo";  
    function makeExperiment($param) {
        $experiment = NULL;   
        switch ($param) {
            case "vivo":
                $experiment = new InVivoExperiment;
            break;
//more cases for in vitro etc.

class AbstractExperiment {}

//The actual class info for each class that is called in the switch statement
class InVivoExperiment {}

 

Monostate

An alternative to the singleton pattern so shares all its drawbacks and problems. Inflexible, makes testing difficult, poor thread safety, hidden dependencies and its global state makes it difficult to ensure it is correct. Doesn’t appear in many lists of patterns and usually bundled together under the Singleton heading. ‘Generally not a good idea’

We should not use a pattern without justification, only when it is simpler than a current implementation. So should be used more to refactor existing code than planned from the outset.

 

Multiton

Similar to singleton, and likewise should be avoided as it makes unit testing very difficult as it introduces a global state into an application. Can cause memory leaks, is not used in PHP often anyway. Does not appear in most lists of design patterns but more of a variation to singleton like monostate.

 

Prototype

Specify a Prototype object and create new objects by cloning the prototype. This avoids the cost of using the new keyword and avoids subclasses (like abstract factory).

abstract class Prototype {
    protected $experiment;
    abstract function __clone();
    function setExperiment($experiment) {
        $this->experiment = $experiment;
    }
}

class ExperimentPrototype extends Prototype {
    function __construct() {
        $this->experiment = 'In Vivo';
    }
    function __clone() {}    
}

$prototype = new ExperimentPrototype();
$clone1 = clone $prototype;
$clone1->setExperiment('In vitro');

 

Singleton

A class can only have one instance of its self and can globally distribute itself to other classes. Nearly every article and opinion I have read is that you should never need this and it is lazy. ‘If you think you have a time when Singleton pattern is needed. Check again because you’re probably wrong’, should use dependency injection instead.

 

That’s it for the Creational patterns – Behavioural patterns, Structural patterns

SOLID Principles – Part 2

Continued from – Part 1

Liskov Substitution Principle

Functions that use references to base classes must be able to use objects of derived classes without knowing it.

So a subclass should not break functionality from a client point of view when it overrides a parent class’ methods. A violation of LSP is a violation to OCP so like the first two all these principles connect to each other so your code is likely to be adhering to them all or breaking them all.

Our code must be loose and reusable and subject to change. So if the client has an abstract class of Study with subclasses of several assays (Comet, Micronucleus, Ames). If the object $myStudy changes from one subclass to the other (eg. Comet to Ames) it should continue to work without any problem and the change will be unknown to the client class. We will also be able to add new subclasses with no problem at all (eg. Chromosomal aberrations assay). All subclasses (derived class) must have functioning methods of the parent class.

The main importance of LSP over regular OOP is that because the client is unaware of the concrete class that the object may implement it makes the structure much more resilient. The structure can be updated, changed or reused without breaking anything.

We can use the Template Method design pattern when using LSP. The best example is that of the Square and Rectangle. A Square is considered a type or Rectangle that has all equal sides. So we would think that Square should be a subclass of Rectangle but Rectangle is a concrete class and this would mean changing the type. The better way to do it is have both Square and Rectangle classes be children of the abstract class Box. The Client can now be a single object of type Box that can create either a Square or Rectangle without the client knowing the difference.

abstract class Box {
    abstract protected function setData();  //Abstract method
    //Concrete method
    public function doBox() { 
        $this->setData();
        return $this->box; 
    } 
}

class Rectangle extends Box {
    public function __construct() { $this->doBox(); }  //Draw rectangle
    protected function setData() { //code for data }
} 

class Square extends Box {
    public function __construct() { $this->doBox(); }  //Draw square
    protected function setData() { //code for data }
}

class Client {
    private $object;
    public function __construct() { 
        $this->doRectangle;
        $this->doSquare;
    }
    public function doSquare() {
        $this->object = new Square();
        $this->boxWork($this->object);
    }
    public function doRectangle() {  
        $this->object = new Rectangle();
        $this->boxWork($this->object);
    }
    //Typehint ‘Box’ insures same parent class
    private function boxWork(Box $box) { echo $box->doBox(); }
}

TLDR: Never make a concrete base class / Don’t inherit from concrete classes (abstract classes and interfaces are the bees knees)

 

Interface Segregation Principle

Clients should not be forced to depend upon interfaces that they do not use.

There will always be some type of interface that the client will rely on either interface entities or classic objects using design patterns like Façade. This connects to SRP in that if a class depends on many implementations that it doesn’t even use it may also require changes if they change.

We will need several interfaces so that each client uses all the methods defined. So some clients may use several interfaces and some interfaces may contain duplication (this is only small as they only define the function name not any logic). An example would be:

class VitroAssay implements Study {
    function getCode() {}
    function getExperiments() {}
    function getMale() {}
    function getFemale() {}
    function numberOfTissues() {}
}

So here the VitroAssay would not need numberofTissues function as that is only for in vivo experiments. So this would break the principle. We would need two separate interfaces for in vivo and in vitro. Both would contain the getCode and getExperiments function name definitions but in vivo would contain the numberOfTissues function definition and in vitro would contain the getMale and getFemale function definitions as that’s only needed in in vitro experiments.

interface VivoStudy {
function getCode();
        function getExperiments();
        function numberOfTissues();
}

class VivoAssay implements Study {
    function getCode() { return $code; }
    function getExperiments() { return $expts; }
    function numberOfTissues() {return count($tissues); }
}

interface VitroStudy {
    function getCode();
    function getExperiments();
    function getMale();
    function getFemale();
}

class VivoAssay implements Study {
    function getCode() { return $code; }
    function getExperiments() { return $expts; }
    function getMale() { return $male; }
    function getFemale() { return $female; }
}

By keeping the interfaces segregated this will lead to loose coupling and easy testing.

 

Dependency Inversion Principle

A. High-level modules should not depend on low-level modules. Both should depend on abstractions.
B. Abstractions should not depend upon details. Details should depend on abstractions.

This is probably the most important of the principles and the one you should try to implement into your code first as it will solve most problems. Once DIP is applied it will make it easier to apply the other four principles.

So like in previous examples if we had a VivoStudy class with a Experiment class dependant on it that would be ok, but we want a Experiment class too so we change VivoStudy to just Study. Now we have a very specific type of experiment but a general Study class. No one can depend on a class like Experiment so we can use the most abstract module interface. Now we have:

interface Vivo { function thing(); }

class Study { function __construct(Vivo $expt) {} }

class Experiment implements Vivo { 
     function thing() { return $stuff; } 
}

We now have two dependencies instead of one. We will now be able to add a Vitro interface and a Experiment class that implements the Vitro interface. We could also expand further to have MicronucleusExperiment and CometExperiment classes that implement Vivo and others that implement Vitro.

This will help keep our code better designed to make it easier to read and understand for us. The optimal amount of information we can store easily in our mind at once is seven, plus or minus two. So functions with four lines maximum (five with definition), indentations not more than five deep, classes with no more than nine methods, design patterns with five to nine classes and five SOLID principles. The ideal number of programmers is five to nine and ideal number of teams in a company is also five to nine.

SOLID Principles – Part 1

The SOLID Principles were set out by Robert C. Martin in the early 2000’s. Its an acronym of acronyms: Single responsibility, Open-closed, Liskov substitution, Interface segregation and Dependency inversion. These are the basic principles for Object Orientated Programming and design.

I wrote a short document trying to condense each principle down to one page each with relevant code examples that applied to our business and the software we were going to be working with. So most classes are talking about experiments and studies and assays(medical tests) using either in vitro(tests on cells) and in vivo(tests on animals). This document was to help me and my co-workers understand it better and have a consolidated reference. I will share this with you over the next two posts.

Single Responsibility Principle

‘There should never be more than one reason for a class to change.’

Therefore an object should only have one responsibility. So for example a class for a bank account like this:

class BankAccount {
    public function Balance {}
    public function Deposit($amount) {}
    public function Withdraw($amount) {}
    public function AddInterest($amount) {}
    public function Transfer($amount, $toAccount) {}
}

If we used this class for current and savings accounts it would have more than one reason to change as savings accounts get interest and follow different rules to some current which often don’t get any interest. So we can change that to something like:

abstract class BankAccount {
    public function Balance() {}
    public function Deposit($amount) {}
    public function Withdraw($amount) {}
    public function Transfer($amount, $toAccount) {}
}

class CurrentAccount extends BankAccount {}

class SavingsAccount extends BankAccount {
    public function AddInterest($amount) {}
}

‘Responsibility can be a family of functions that serves one particular actor’ (eg an object does not need a role such as operator but rather a family such as operations). So as the needs of the actor changes so do the family of functions to accommodate the needs of the actor.

Presentation must be separated from business logic. For example:

class Study {
    function getStudyCode() { return $code; }
    function getExperiment() { return $expt; }
    function printData() { echo 'Here is the data: ' . $this->data; }
}

The printData function is presentation and not business logic so it needs to be taken out of the class and put elsewhere. This is not a single responsibility. Like Design Patterns SRP must not be overthought and over planned, too much can make our code overcomplicated and can make the design scattered with unclear responsibilities for classes or modules.

 

Open/Closed Principle

‘Software entities (classes, modules, functions, etc.) should be open for extension, but closed for modification.’

When new functionality is needed we should create new classes that extend our previous (working and fully tested) classes, not to go inside the existing class and change functions/methods. This principle fits very well with Single Responsibility in that having separate functions and classes will keep them from having multiple responsibilities.

The most appropriate solution to this is using the Strategy Pattern which uses an interface to define a contract between a client and server class.  Interfaces can only define behaviour so instead of using public variables we will have to use getters and setters.

In the example below we can use interface to have a file download with progress bar. By using the interface we could now extend the functionality to download music with a progress bar. Before in the Progress classes construct we would have asked for instance of File which of course would not work with an instance of music (Refused bequest: a class that overrides a method of a base class in such a way that the contract of the base class in not honoured by the derived class). Here is how it would now work:

interface Measurable {
    function getLength();
    function getSent();
}

class File implements Measurable {
    private $length;
    private $sent;
    public $filename;
    function setLength($length) { $this->length = $length; }
    function getLength() { return $this->length; }
    function setSent($sent) { $this->sent = $sent; }
    function getSent() { return $this->sent; }
    function getPath() { return dirname($this->filename); }
}

class Progress {
    private $content;
    function __construct(Measurable $content) { 
        $this->content = $content;
    }
    function getAsPercent() { 
        return $this->content->getSent() *100 / $this->content->getLength(); 
    }
}

We can also use the Template Method design pattern to use an abstract class instead of an interface. Better when we have a client very specific to our application, with reduced reusability and when the server classes have common behaviour.

Continued in Part 2

VBA – Custom user reports in Word

Using Visual Basic is a necessary evil. We need lots of functionality for users to create reports on all the stats and data they have collected within our software. All this data and information is useless without decent, clear and easy to create reports. For each report we are using several complicated Oracle queries that are in our own file type together with a .dotx file for the table layouts and a .dotm file to bring it all together and format the report. The .dotm allows for macros so we can insert Visual Basic code to help do any advanced formatting we could not do in either word or the Oracle queries (VBA is a powerful tool but if we can avoid it by adding another layer to our query we will).

Below are two of the main examples where we have been using Visual Basic in our reports. One for design and one for functionality.

This first script makes all rows of data in the table to have blank field under the treatment name if not the first item of the group (So it does not list ‘Chemical X’ under the treatment column ten times but just the first one – It looks nicer I promise) The second if statement also styles the average row at the end of each treatment group, making them bold, removing the word average for a ‘-‘ and adding a newline space below for better spacing. These are all design choices rather than functionality but makes the boring default table much nicer and easier to read. The reason the word ‘average’ is even there in the first place is to give an easy way to grab the correct row in Visual Basic to embolden and add spacing.

Sub CSMBeforeSave() 
' Generate report even if errors
On Error GoTo ErrHandler: 

Dim oTable As Table 
Dim oRow As Row 
Dim oCell As Cell 
Dim prevcode As String 
prevcode = "Yes" 

' Get the second table in the document
Set oTable = ActiveDocument.Tables(2) 
For i = 4 To oTable.Rows.Count 
    Set oRow = oTable.Rows(i)
    ' gets the treatment name
    txt = Mid(oRow.Cells(3).Range.Text, 1, Len(oRow.Cells(3).Range.Text) - 2) 
    If (prevcode <> "Yes") Then 
        ' change the treatment to nothing if second occurrence of the treatment
        oRow.Cells(1).Range.Text = "" 
    Else 
        prevcode = "No" 
    End If 
    If (txt = "Average") Then 
        If (i = oTable.Rows.Count - 1) Then 
            ' if last row just blank out average to be a dash
            oRow.Cells(3).Range.Text = "-" 
        Else 
            ' blank out word average and add a spacing below if not last row
            oRow.Cells(3).Range.Text = "-" + Chr(10) 
        End If 
        prevcode = "Yes" 
        For Each oCell In oRow.Cells 
            ' make "average" values bold 
            oCell.Range.Font.Bold = True 
        Next 
    End If 
Next 

ErrHandler: 
Exit Sub 

End Sub

This second script will find a paragraph that begins with <!IMG and gets the file path it contains. It then removes that path and replaces it with the image that path links to. This can be used for inserting any images into word but here I used it to get the png of the graph that was created using the language R.

Sub test() 
Dim img As InlineShape 

Dim firstTerm As String 
Dim secondTerm As String 
Dim myRange As Range 
Dim documentText As String 

Dim startPos As Long 
Dim stopPos As Long 
Dim nextPos As Long 

nextPosition = 1 

firstTerm = "<!IMG" secondTerm = "IMG!>" 

' replace file path for R graph with its image
For i = 1 To ActiveDocument.Paragraphs.Count 
    If InStr(ActiveDocument.Paragraphs(i).Range.Text, "<!IMG") <> 0 Then 
        ' find paragraph and remove IMG tags and anything else
        startPos = InStr(nextPosition, ActiveDocument.Paragraphs(i).Range.Text, firstTerm, vbTextCompare) 
        stopPos = InStr(startPos, ActiveDocument.Paragraphs(i).Range.Text, secondTerm, vbTextCompare) 
        answer = Mid$(ActiveDocument.Paragraphs(i).Range.Text, startPos + Len(firstTerm), stopPos - startPos - Len(secondTerm)) 
        ' remove text and then select position
        ActiveDocument.Paragraphs(i).Range.Text = "" 
        ActiveDocument.Paragraphs(i).Range.Select 
        Set img = Selection.InlineShapes.AddPicture(answer) 
        ' resize
        With img 
            .LockAspectRatio = msoTrue 
            .Width = CentimetersToPoints(9.23) 
            .Height = CentimetersToPoints(8.93) 
        End With 
    End If 
Next i 

End Sub

Abstract Class vs Interface – which to choose and when

Before we start a big new project we have been swatting up on UML diagrams, design patterns that we might need and the SOLID Principles. All of these use Object Oriented Programming at their core which means abstract classes and interfaces. So what is the difference and which one should you use and when?

Basic definition: In an abstract class you can define default functionality; in an interface you can only define functions.

We would use an abstract class over an interface if all the classes needed to perform the same function, we could then define this within the abstract class. Something like abstract class of vehicle with subclasses being cars and lorry’s that all need the same functions of ‘accelerate’ or ‘brake’. An interface is a list of functions where if a class implements it, it will have to have those functions defined within it.

An Interface would work better in an example of Accelerator which defines function of accelerate and stop. Then vehicles would implement this and would define the functions with cod about pushing down the pedals to accelerate or stop. A ball might then also implement accelerator and also define the two functions but would implement them in very different ways using gravity and force. So they would be performing the same functions, which is why they implement the same interface but define those functions in a completely different way.

Sublime Text 3 – And why its awesome

I’ve been using Sublime Text 3 for a while now and love it. Here is a quick list of things I like about it and ways it helps to speed up my workflow. It’s by no means a comprehensive list and there are probably lots I have not added or are yet to discover, but its stuff I use and have helped me.

There are lots of base themes and keyboard shortcuts that come with Sublime. A list of keyboard shortcuts are here.

Some highlights are:
Alt + ⇧ + 2 Split view into two columns
Ctrl + H Replace
Ctrl + R List classes
Ctrl + / Comment/un-comment current line
Ctrl + ] Indent current line(s)
Ctrl + ⇧ + M Select all contents of the current parentheses

Adding Package Control

In sublime text 3 press Ctrl+’ or View>Show Console. In the console paste the following python code to add the package manager. This way we can add awesome plugins.

import urllib.request,os,hashlib; h = '2915d1851351e5ee549c20394736b442' + '8bc59f460fa1548d1514676163dafc88'; pf = 'Package Control.sublime-package'; ipp = sublime.installed_packages_path(); urllib.request.install_opener( urllib.request.build_opener( urllib.request.ProxyHandler()) ); by = urllib.request.urlopen( 'http://packagecontrol.io/' + pf.replace(' ', '%20')).read(); dh = hashlib.sha256(by).hexdigest(); print('Error validating download (got %s instead of %s), please try manual install' % (dh, h)) if dh != h else open(os.path.join( ipp, pf), 'wb' ).write(by)

Once installed press ctrl+shift+p to open the command palette. You can now type ‘Package Control:’ to see all the commands. Selecting Install package means you can then add plugins from the default list of plugins. If you want another plugin you can ‘Package Control:Add Repository’ and then add the repo link. This plugin will now appear in the list when you enter ‘Package Control:Install Package’.

Colorsublime – theme colour schemes

Press ctrl+shift+p. Type inst to give you Package Control:Install package. Press enter. Now on the new drop down you can install any plugin. Type colorsublime and it installs. No reopen Sublime Text. Ctrl+shift+p and type ‘Colorsublime:Install Theme’ you can now scroll through all the themes (270+) using the up and down arrows. Once you find the right one press enter. You can now change easily at any time.

Im using ‘Birds of paradise’ currently. Try out ‘Hot dog stand’ if you’re brave.

ColorPicker

Ctrl+shift+p -> Package Control:Add Repository -> https://github.com/weslly/ColorPicker -> Package Control:Install Package -> Color Picker -> press enter.

Now you can press ctrl+shift+c to open the colorpicker and add colors straight into Sublime Text. Double click a color and ctrl+shift+c to easy replace.

Color Highlighter – Shows hex colours in editor

This plugin will underline any hex colours or colour names in the appropriate colour, highlighting them also does so in the correct colour. Its a default listed plugin so just press ctrl+shift+p to open command palette -> type “insta” and select Package Control: Install Package. Type ‘Color Highlighter’ and press enter on it to install. May need to close and re-open Sublime for it to work. Highlighting may not show until you save the file.

FileDiffs – Shows changes in file

This plugin can show any changes you have made toa file. You can choose to see changes since save or compare the file to either:
– Another file
– Clipboard
– Previous window
– An open tab
– The saved version

To add this press ctrl+shift+p -> Package Control:Install Package -> FileDiffs. Once installed ctrl+shift+p and type file -> select FileDiffs to open its menu and then choose how to compare the file. It will open a new untitled file showing the differences.

You could add a shortcut/keymap to open the FileDiffs menu in one go but editing the .sublime-keymap file.

Goto Documentation = Opens documentation

Ctrl+shift+p > Package Control:Install Package > Goto Documentation.
Then click Preferences > Package Settings > Goto Documentation > Keybindings User. Then you can set a shortcut so when your cursor is on a function you can press a key to open in the docs. So it basically is a shift-to-browser-select-url-search-in-google kind of deal.

{ "keys": ["f1"], "command": "goto_documentation" }

You can obviously set the hotkey to be whatever you want.

Debugging with Xdebug

Another thing to consider is using Xdebug for all your debugging needs. It works similar to how it is in PHPStorm and Netbeans. Too much to talk about here but its summed up well in this article and has good instructions for how to set it up.

Working with Python

I’ve been learning and working a lot with Python recently. It reminds me a lot of Matlab from my Uni days which was my favourite language I did there and is what I used for my dissertation on Text to Speech synthesis. Python is also very maths based, which was always my best subject at school, but it also feels like it takes the best parts of many other languages and is very intuitive to learn and read. Or maybe I have just reached that point of linguistics where its easier to learn new ones.

I have been building a small project with Python, an aggregator of news type site but mostly just to play with new ideas and use as a training ground. It may eventually become of something but likely will just be a mish mash of examples and unfinished ideas. Here is a function I created to take titles and capitalize all words with 3 or more letters, it also keeps whitespace eg. tabs. This is a good example of how python can be a very condensed line of code (often called one line list comprehensions) and still be fairly easily readable.

def capitalise(heading):
    return ' '.join([word.title() if len(word) > 2 else word for word in heading.split(' ')])

This could be done in a longer way that would probably be more readable. I have added comments to walk through each line and what it does:

def capitalise(heading): #defining the function taking heading as our argument
    out = [] #sets the empty list than will be our output
    for word in heading.split(' '): #A loop to iterate through each word in the split string
        if len(word) > 2: #if its longer than 2 letters
            letters = list(word.lower()) #make the whole word lowercase
            letters[0] = letters[0].upper() #make the first letter uppercase
            out.append("".join(letters)) #join the new word to our output
        else:
            out.append(word) #if it isnt longer than two letters add it to output as it is
    return " ".join(out) #return our output

Another function I made was to be able to shorten names to just be initials and the surname. I had to be careful here to account for people with lots of names:

def initials(name):
    names = name.split()
    return '.'.join(x[0].upper() for x in names) + names[-1][1:]