Identifying Development Patterns


Super-power your development skills and write code that is reusable, maintainable and modifiable.


By William Patton
www.pattonwebz.com
Twitter: @will_patton_88

What Kind of Patterns Exist in Software Development?

Each Role in Software Development has it’s own grouping of Patterns

  • Development/Design Patterns
  • Architectural Patterns
  • Project Management Patterns

Why do I need to know design patterns?

You don’t!

But they can help!

(you probably already use some of them)

How knowing design patterns can help?

Knowing more code is always a benefit when that code can be applied to a problem you are facing. Understanding and applying different development patterns can skill up a developer.

They allow you to:

  • onboard easier to new projects
  • work faster within a project
  • use time smarter in a crunch

So What Exactly Are Development Patterns?


A reusable solution that can be implemented to solve a specific problem.

They don’t dictate how the implementation is done at all. They outline a set of ideas that someone can apply to their current situation.

Why are Patterns useful?


They create reusable, recognizable & robust solutions that are easier to maintain and quicker to iterate upon.

  • Tested in the field by many developers over many years.
  • Saves time because many problems have existing solutions.
  • Reduces long-term tech debt in your code by encouraging good development practices.

All good software shares the same basic traits.


It is always:

  • Simple to understand.
  • Simple to maintain.
  • Simple to modify.
  • Simple to use.

It is simple!

Simple is good

Complexity is the enemy

If the code isn’t simple that is a code smell.

A code smell is an indicator of a deeper problem than the actual written code.


It could be a sign of overengineering or lack of thoughtful analysis before writing the code.

The cause could be:

  • Frequently changing requirements
  • Lacking vital information from the outset
  • Reluctance to refactor

DRY & SOLID Principals

The basis of many existing development patterns.

DRY Code


Don’t Repeat Yourself

  • It applies to the functionality of code rather than the actual code itself.
  • Repeating the same functionality in more than two places creates a maintenance nightmare.
  • When you need to update this code you have to update it many places.

The SOLID Principals


  • Single-responsibility principle
  • Open-closed principle
  • Liskov substitution principle
  • Interface segregation principle
  • Dependency inversion principle

Some ideas to keep in mind


  • Encapsulate what varies
  • Program to an interface
  • Abstract away complexity
  • Strive for loose coupling

Simply keeping these statements in mind as you work can help to avoid introducing code smells and avoid expensive maintenance.

An Example of Encapsulate What Varies


Conditional statements are one example of something that varies or needs updated often. Encapsulation can improve the readability of your code by abstracting away the parts that are unimportant for the functionality of the code.

It also:

  • Makes the conditions a single responsibility function.
  • Helps to keep the function using the conditions open to extension but closed to modification.

An Example of Encapsulate What Varies


function add_css_class_for_landing_page($classes) {
     if (
         is_singluar( 'landing-page' ) ||
         is_page_template( 'templates/landing-page.php' ) ||
         in_array( get_the_ID(), [
             25, 85, 126, 345, 658, 1007
         ] )
     ) {
         $classes[] = 'a-landing-page';
     }
     return $classes;
 }
add_filter( 'body_class', 'add_css_class_for_landing_page' );
function is_a_landing_page() {
     return (
         is_singluar( 'landing-page' ) ||
         is_page_template( 'templates/landing-page.php' ) ||
         in_array( get_the_ID(), [
            25, 85, 126, 345, 658, 1007
         ] )
    );
}

function add_css_class_for_landing_page($classes) {
     if ( is_a_landing_page() ) {
         $classes[] = 'a-landing-page';
     }
     return $classes;
}
add_filter( 'body_class', 'add_css_class_for_landing_page' );

What are the most common patterns?


In WordPress, the most commonly seen patterns are the Singleton, the Observer and the Facade.

By far the most talked-about pattern is the Singleton.

Where do patterns come from?

This is a question that doesn’t really have a single answer.

  • Patterns are formed over time
  • Created when the same problem needs to be solved over and over.
  • Eventually, someone puts a name to it.

The most well-referenced source of patterns is found in a book written in 1994 by a group of 4 software engineers. The ‘Gang of Four’ as they have come to be know.

The Gang of Four Patterns


The book: Design Patterns: Elements of Reusable Object-Oriented Software contains 2 parts. The first part is a holistic view of building software. The 2nd part is the catalogue of patterns. This catalogue is collected based on common patterns that the authors had seen in their work building software.

Written by:

  • Erich Gamma
  • Richard Helm
  • Ralph Johnson
  • John Vlissides

The Catalogue


Creational

  • Factory Method
  • Abstract Factory
  • Builder
  • Prototype
  • Singleton

Structural

  • Adapter
  • Bridge
  • Composite
  • Decorator
  • Facade
  • Flyweight
  • Proxy

The Catalogue


Behavioural

  • Chain of Responsibility
  • Command
  • Interperator
  • Iterator
  • Mediator
  • Memento
  • Observer
  • State
  • Strategy
  • Template Method
  • Visitor

The Singleton


A singleton solves 2 problems at once:

  1. Ensures single existance.
  2. Provides single, global, access.

  • Enforce single access to a resource.
  • Allow easy access to the internals of your system.
  • Prevent instantiation actions running more than once.

How to spot a singleton

  • Uses a private static property to hold its instance
  • Has a private constructor method
  • Exposes a static getter method
<?php
class MySingleton {

    private static $instance;

    private function __construct() {
        // construction actions
    }

    public static function get_instance() {
        if ( null === self::$instance ) {
            self::$instance = new self();
        }
        return self::$instance;
    }

}

Factories

The Factory

Factory Method Or Simple Factory

  1. Accepts some input
  2. Decides what to make
  3. Returns the product
<?php
 class MyFactory {

     public function build_pizza($type) {

         switch ($type) {
             case 'pinapple':
                 $pizza = new PinapplePizza();
                 break;
             case 'pepperoni':
                 $pizza = new PepperoniPizza();
                 break;
             default:
                 $pizza = new CheesePizza();
         }

         return $pizza;
     }
 
}

The Adapter

You want to avoid modifying the client code as much as possible. It’s tested and stable.

Then your data provider changes the shape they send it to you in or how you retrieve it. It throws a spanner in your nicely tested code.

The solution is an adapter.

It sits between your client code and the provider and translates the calls between both parts of the system.

The Decorator


Decorators are powerful. They can add new functionality to existing objects in an interoperable way.

Decorators wrap existing objects with themselves to provide additional benefits to the base object.

When complexity is inevitable the Facade can save the day

The Facade

Somtimes called a wrapper.


Facades act as the front entrance to a complex system. The Facade is all that is exposed to the public. It might be more limited than the sum of all the parts of the system that it fronts – what is important is that it exposes what the client code needs.

Simple access and operation methods are placed in front of the complexity.

Complex setup or use cases are abstracted away. On the face of it, everything operates simply and efficiently.

The Observer


Also known as ‘Event-Subscriber’, ‘Publisher/Subscriber’ or ‘Listener’.

The Observer pattern watches another object or event for when it changes and may do something based on the change.

It relies on the system being observed emitting events to expose when it updates.

Spotting an Observer


WordPress includes a system that is basically an event driven architecture.

Actions and Filter hooks are events. When this event happens then do a thing.

In reality, there is no such thing as an action – they are abstractions.

All actions are really filters.

The code for add_action()

function add_action( $tag, $function_to_add, $priority = 10, $accepted_args = 1 ) {
    return add_filter( $tag, $function_to_add, $priority, $accepted_args );
}

Programming Pasta

Spaghetti Code

Code so twisted together and hard to follow it’s like a tangle of spaghetti.

An accident waiting to happen.

Ravioli Code

Nicely formed classes and objects that make sense on their own but as a whole program.

It is a messy plate of raviolli.

Lasanga Code

Neatly arranged layers of code on top of each other.

To change one layer you have to adjust the layers either below or above it.

Anti-Patterns

Lava Flow/Dead Code

// You may think this code does nothing. You 
// would be right. But when we remove this
// code the app crashes. We don't know why.

Code that has existed so long, probably not documented, that nobody remembers what it does or why it exists.

The longer this kind of thing exists in your code the more solidified, and harder to remove, it becomes.

At a certain point it is just part of your codebase – unchanging and ever present.

Gold Plating


  • Gold plating is in direct competition against YAGNI – You ain’t gonna need it.
  • YAGNI forces you into the mindset of ‘Do the simplest thing that could possibly work’.

  • Building things in case you need them later means that it becomes very hard to follow development processes that use continuous refactoring, unit testing, and continuous integration.

Signs of Gold Plating


  • Something got built because we might need this in the future.
  • Building with the anticipation of a possible future change does nothing right now. The result is unnecessary complexity.
  • More time is spent on nice-to-haves than functional requirements.
  • If code review is slow going, with lots of churn, it can be an indicator that things are being gold plated.

The God Class – or The Blob


The biggest signs of The Blob is when one thing:

  • is too powerful
  • holds too many cards
  • does too many things

The Golden Hammer


“We always use the Golden Hammer as a solution”

This can be considered the opposite of using the best tool for the job.

Your favorite tool becomes the Golden Hammer. It is used for all problems even when it’s not the best fit.

Reinventing the Wheel

Never assume:

  • your problem is unique.
  • existing solutions are too rigid.
  • that alternatives don’t fit.
  • you can do it better.

Prove it!

Remember before you try to reinvent the wheel that you don’t know everything.

Most code is written by one person and most packages are maintained by very small teams. You do not know all the code that is out there.

Anytime you run into a problem you have not solved before it is worth your time to do some investigations into what is available and if it can fit your need.

Credits

  • “Gavel” by walknboston is licensed with CC BY 2.0. To view a copy of this license, visit https://creativecommons.org/licenses/by/2.0/
  • “Gold tiles 1” by M0les is licensed with CC BY 2.0. To view a copy of this license, visit https://creativecommons.org/licenses/by/2.0/
  • By Wm335td – Own work, CC BY-SA 4.0, https://commons.wikimedia.org/w/index.php?curid=85901120