DZone
Thanks for visiting DZone today,
Edit Profile
  • Manage Email Subscriptions
  • How to Post to DZone
  • Article Submission Guidelines
Sign Out View Profile
  • Post an Article
  • Manage My Drafts
Over 2 million developers have joined DZone.
Log In / Join
Please enter at least three characters to search
Refcards Trend Reports
Events Video Library
Refcards
Trend Reports

Events

View Events Video Library

Zones

Culture and Methodologies Agile Career Development Methodologies Team Management
Data Engineering AI/ML Big Data Data Databases IoT
Software Design and Architecture Cloud Architecture Containers Integration Microservices Performance Security
Coding Frameworks Java JavaScript Languages Tools
Testing, Deployment, and Maintenance Deployment DevOps and CI/CD Maintenance Monitoring and Observability Testing, Tools, and Frameworks
Culture and Methodologies
Agile Career Development Methodologies Team Management
Data Engineering
AI/ML Big Data Data Databases IoT
Software Design and Architecture
Cloud Architecture Containers Integration Microservices Performance Security
Coding
Frameworks Java JavaScript Languages Tools
Testing, Deployment, and Maintenance
Deployment DevOps and CI/CD Maintenance Monitoring and Observability Testing, Tools, and Frameworks

The software you build is only as secure as the code that powers it. Learn how malicious code creeps into your software supply chain.

Apache Cassandra combines the benefits of major NoSQL databases to support data management needs not covered by traditional RDBMS vendors.

Generative AI has transformed nearly every industry. How can you leverage GenAI to improve your productivity and efficiency?

Modernize your data layer. Learn how to design cloud-native database architectures to meet the evolving demands of AI and GenAI workloads.

Related

  • TDD Typescript NestJS API Layers with Jest Part 1: Controller Unit Test
  • Chaos Mesh — A Solution for System Resiliency on Kubernetes
  • Clean Unit Testing
  • The Anatomy of Good Unit Testing

Trending

  • Automating Data Pipelines: Generating PySpark and SQL Jobs With LLMs in Cloudera
  • Detection and Mitigation of Lateral Movement in Cloud Networks
  • Docker Base Images Demystified: A Practical Guide
  • Beyond Code Coverage: A Risk-Driven Revolution in Software Testing With Machine Learning
  1. DZone
  2. Coding
  3. Languages
  4. Practical PHP Patterns: Special Case

Practical PHP Patterns: Special Case

By 
Giorgio Sironi user avatar
Giorgio Sironi
·
Oct. 07, 10 · Interview
Likes (0)
Comment
Save
Tweet
Share
2.7K Views

Join the DZone community and get the full member experience.

Join For Free

The Special Case pattern is a very simple base pattern that describes a subclass representing, as the name suggests, a special case of the computation made by your program. Don't think that the technical simplicity of the solution means that this pattern is very diffused.

If vs. polymorphism

The idea of the pattern is to implements two classes with the same interface or base superclass, and rely on polymorphism to target the special case, instead that inserting if and switch statements in the original class. The extracted piece of functionality can be a method to override (specialization in the Template Method pattern) or an independent collaborator injected into the client code (Strategy pattern and many others).

Dispatching a method call instead of inserting if statements is simpler to read and understand, as the code of the class has a lower cyclomatic complexity overall (few possible execution paths). If you ever tried to debug Doctrine 1 or a similar piece of software where the methods contain many nested ifs, you have been probably forced to insert echo statements to reveal the actually executed path, even when a single, isolated unit test was exercising the code.

The alternative to some ifs is to introduce a Special Case. A rule of thumb for discovering if the substitution is possible is to check if the condition of the if is based on a state that is longer lived with respect to the parameters of the method that it resides in. Ifs that depend only on the state of the object fields or on collaborators are the simplest to replace.

Null Object

The Null Object pattern is a specialized version of Special Case (what a pun), and probably the most famous one. Instead of returning false or null when a computation fails to provide a result, you return an object that as a matter of fact, does nothing:

  • an User subclass AnonymousUser with authorize() that always return false
  • an empty array (it can be thought of as a Null Object, even if it is a primitive value)
  • an empty ArrayObject.

When a Null Object is returned, it effectively removes the checks for the null value or empty result from the client code. The client class object can call methods on the return value without worrying (calling methods on NULL is a fatal error in PHP and would crash a test suite). Or it can execute foreach() over a returned array and skip the cycle altogether if the array is empty.

Since null can be dispatched, we may in fact use it as a Test Double in our test code to ensure a collaborator is never called in a particular scenario. If you have a method that shouldn't refer to a collaborator, you can inject null in the constructor or via a setter. PHP is different from Java in the type hinting behavior: in Java you can pass null to this constructor:

public MyClass(Collaborator c) { ...

while in PHP you have to resort to this:

public function __construct(Collaborator $c = null) { ...

Implementation

The Special Case can be a Flyweight or an object with, since it has usually no internal state: the behavior depending on state is encapsulate in the code itself.

You can also have more than one Special Case for each superclass or interface: Fowler makes the example of a MissingCustomer and AnonymousCustomer as special cases for the Customer class. By the way, every method of a Null Object should return a plain scalar value or another Special Case object.

Note that with more than one level of Special Case objects, you may be violating the Law of Demeter: your client code access the first Special Case and then the other contained one, navigating the object graph instead of asking for its dependencies or sending a message.

Examples

In this example we apply the pattern to go from this situation:

<?php
/**
 * Very basic example, but for more complex ones see the specializations:
 * Template Method, Strategy, State...
 */
class Car
{
    private $speed = 0;
    private $type;

    public function __construct($type)
    {
        $this->type = $type;
    }

    /**
     * This if() is based only on the object state
     * and can probably be modelled differently.
     * You'll need two tests for this method.
     */
    public function accelerate()
    {
        if ($this->type == 'Ferrari') {
            $this->speed += 2;
        } else {
            $this->speed++;
        }
    }

    public function brake()
    {
        $this->speed--;
    }

    public function __toString()
    {
        return $this->type;
    }
}

// client code
$car = new Car('Fiat');
$ferrari = new Car('Ferrari');
$car->accelerate();
$ferrari->accelerate();
var_dump($car, $ferrari);

to this one:

<?php
/**
 * The base class.
 */
abstract class Car
{
    protected $speed = 0;
    protected $type;

    public abstract function accelerate();

    public function brake()
    {
        $this->speed--;
    }

    public function __toString()
    {
        return $this->type;
    }
}

/**
 * One Special Case: a car with $type parametrized in the constructor
 * and ordinary acceleration properties.
 */
class OrdinaryCar extends Car
{
    public function __construct($type)
    {
        $this->type = $type;
    }

    public function accelerate()
    {
        $this->speed++;
    }
}

/**
 * Another Special Case: a car with fixed $type and greater acceleration.
 */
class FerrariCar extends Car
{
    /**
     * This is state encapsulate in code: you don't have to set up 
     * it in tests or with configuration, only to instantiate this class.
     */
    protected $type = 'Ferrari';

    public function accelerate()
    {
        $this->speed += 2;
    }
}

// client code
$car = new OrdinaryCar('Fiat');
$ferrari = new FerrariCar();
$car->accelerate();
$ferrari->accelerate();
var_dump($car, $ferrari);
PHP Object (computer science) unit test

Opinions expressed by DZone contributors are their own.

Related

  • TDD Typescript NestJS API Layers with Jest Part 1: Controller Unit Test
  • Chaos Mesh — A Solution for System Resiliency on Kubernetes
  • Clean Unit Testing
  • The Anatomy of Good Unit Testing

Partner Resources

×

Comments
Oops! Something Went Wrong

The likes didn't load as expected. Please refresh the page and try again.

ABOUT US

  • About DZone
  • Support and feedback
  • Community research
  • Sitemap

ADVERTISE

  • Advertise with DZone

CONTRIBUTE ON DZONE

  • Article Submission Guidelines
  • Become a Contributor
  • Core Program
  • Visit the Writers' Zone

LEGAL

  • Terms of Service
  • Privacy Policy

CONTACT US

  • 3343 Perimeter Hill Drive
  • Suite 100
  • Nashville, TN 37211
  • support@dzone.com

Let's be friends:

Likes
There are no likes...yet! 👀
Be the first to like this post!
It looks like you're not logged in.
Sign in to see who liked this post!