Layering Software Design

This is a quick-ish article about layering software design, and how to achieve layering in ways which are consistent and useful for the maintainability of your source code. I have seen it done badly I have also seen it done very well, but I thought it was worth covering. Throughout my career I have seen lots of software designs, great. Flow charts and diagrammatic representations of software designs. At this point I think “Great, I can follow this!” – and then I see the code, and the layering is impossible to decipher, and is seemingly only existent in the designer/architect’s head.

Consequently, I thought I would do a quick article on layering your software. I appreciate there are lots of articles around the SOLID principles, and various other related topics, and I urge you to read about spaghetti code and lasagne before reading this article.

This article is aimed at people who have a decent understanding of Object Oriented Programming, but who are in the process of learning about software design and separation of concerns. Alternatively, it may also help those who have large, unorganised code bases to manage, or large projects to design and build.

Quick notice: I’ll keep code samples to a minimum and as concise as possible for the purposes of readability, but said code will be in PHP

The Problem

What we are trying to do, when creating layers of software, is create manageable code, the concerns of which are as separated as possible. Often we are trying to achieve this by defining parts of our application, usually referred to as layers.

Then a professional of some description (software engineer, web developer, systems architect, etc) creates a drawing of the different components to the software and how they should interact with one another. “Excellent!” they exclaim, and off the various developers go to work on their layers. Unless you’re in a strict environment quite often the developers work in isolation, and agree on integration points (or these are predetermined, or predefined).

In my experience, what normally happens at this point is that we have a load of principles designed, and off the team go to carry out the development on the product itself begins. Let’s make the assumption we’re talking about a content management system.

Then the code happens, bug fixes, amendments, changes in specification, and then, eventually… The product is finished! And by this point the design and architecture are forgotten, balls! Nowhere to be seen throughout the codebase.

The Solution

If you’re already in this situation you have a slightly harder job, because you need to understand the intended layering first, and then where you need to get it to. In its simplest form, given these kinds of problems I would be creating layers as they’re required (ones that do not exist) or modifying all code within them, and its usages, to fit into layering practice.

An Example

Let us say that we have a CMS, which currently has a whole bunch of mail() (for non PHP-readers the mail function is documented here), PHP function calls; and we need to enhance the emailing functionality. The specification at the time of creation:

  • CMS must be able to send emails at appropriate times (fulfilled, it does send emails when it needs to)

The new specification:

  • CMS must be able to send emails at appropriate times (fulfilled)
  • We must take new GDPR regulations into account and only send emails to the users which they have approved
  • We must categorise emails at high or medium priority, medium priority messages must not be sent outside of 8pm and 7am, whereas high priority messages must be sent immediately

Likely future specification:

  • In the same instances, we may wish, based on user requirement, to send SMS instead

The way I would look to solve this problem:

  1. Create a Notifications layer through which all systems notifications are sent (end user code sample below), this notification will understand context, so that decisions can be made with regards to type of delivery
  2. Find every instance of mail() in the codebase, and replace it to use my new notifications layer

Userland Code Example

// Create an instance of the notification
$notification = new MessageReceivedNotification($currentUser);

// Set the message which the user has received
$notification->setMessage($theMessage);

// I would normally chain this on, but have not done so for the purposes of readability for those who do not write PHP 
$notification->send();

The Outcome

Now I have a layer in place for all notifications, the next thing to do is make sure that all developers working on the system are aware of this layer, that it is well documented, and everybody knows not to use the mail() function. All notifications now go through the new layer, and injecting new functionality into that section of functionality is a much easier process.

The Prevention

Ideally, you don’t want to end up in that situation in the first place. What you need for this is not only a design of how the layering works, but also a set of rules or standards which ensure that the layering is used in a way which prevents this issue in the first place.

We’ll take the example of a CMS again, with some examples of layers which are required:

  • Notification Service
  • Data Layer
  • Permissions Layer
  • Controllers

And here are some ways that you might introduce that layering, so that functionality can be easily implemented throughout your design.

Interface Facading

Particularly on the Permissions Layer you might want to use the facade design pattern to give a simple interface to interact with the Permissions Layer, this could be further facaded to use helper functions (code samples below). This means that all functionality relying on the facaded layer only ever need to worry about the facade, with no knowledge of how it works, but also that in order to check the permission status you will always use the layer, preventing the problem described above. You may decide that, for the purpose of this shared functionality, you want to make this layer interface through a singleton, particularly if the class itself is doing very little besides providing anaemic functionality to other classes.

class PermissionChecker
{
    public function checkPermission(string $permissionName) : bool
    {
        //  Return true/false based on whether or not this user can carry out this permission
    }
}

function checkPermission(string $permissionName) : bool
{
    $checker = new PermissionChecker();
    return $checker->checkPermission(string $permissionName);
}

Inheritance

Another common way of managing this layering is to ensure that all appropriate functionality extends a base class (inheritance), which encapsulates all the layers shared functionality, again this could facade through to a library of classes. A good example of this would be a Notification Service or Data Layer.

abstract class Model
{
    public static function find($recordId)
    {
        // At this point I am going to fetch a record based on its ID, I can choose to implement caching or other functionality here
    }
}

class Post extends Model
{
    // This class specifically represents the post records, if we're assuming the active record design pattern
}

Data layering is the most obvious to introduce, particularly as most frameworks will have already included this. The important part of the layering process is to understand what else needs to be layered, and consequently how this should occur.

How do I know what I need to layer?

This is impossible to answer really, as you could be programming a blog, or the software behind the next space shuttle launch! The following are not hard and fast rules, but a guideline which you could choose to follow. I personally would consider layering if:

Don’t forget, layers can exist within layers. Your data layer may have layers for caching and database transactions, for example.

  1. When the functionality is reusable (like models)
  2. When the functionality could require modification, which would need to affect everything within its remit (like notifications and adding user preference functionality)
  3. When the functionality is grouped, and might need modification or replacement later (like cart calculations functionality in a commerce system)

How should I invoke my layering?

That very much depends on your use case, personally I tend to consider it like this:

  1. I use inheritance when each instance makes sense to be its own entity (such as a notification, or a record in the model)
  2. I use facading when I am hiding a library of functionality (access permissions works in this case, as you may have a number of functionalities in here, such as super-admin-detection, permissions grid management, IP whitelisting, and infinite possibilities in terms of security management)

Hard Fast Rules (which don’t exist)

Of course, hard fast rules do not exist and every use case has the potential to need to not follow these guides. However, I follow these rules to layer my code properly and ensure it is truly layered/modular.

  1. Do not directly interface with any class which is part of the package/library, that is not the interface or Facade itself
  2. If working within a modular system, never use code which belongs to one module within another (unless it is predefined that this module is dependent on the other)
  3. Particularly within modular systems, having code in separate repositories and IDE projects can help ensure you don’t accidentally use code which is within another module
  4. The moment you think “Gosh, I hope I don’t have to change this later!” you either need to reconsider your base design, or you need to introduce layering there
  5. Follow DRY (don’t repeat yourself) – if you’re copy and pasting code you could almost definitely do with encapsulation, at the very least, but potentially your code should be in its own layer with an interface to allow your modification

Summarised Points to Take Away

  1. If you draw a design, and you have a layer, ensure some kind of physical representation (base class, interface, facade, etc) of that layer exists
  2. Ensure if you’re using layers they’re well documented, and everybody knows they need to use your layer, and how
  3. Layers are important for injecting new functionality later, and preventing the duplication of code

Thank you for reading!

I'd love to hear your opinion on what I've written. Anecdotes are always welcome.

This site uses Akismet to reduce spam. Learn how your comment data is processed.