Strategy Pattern

Introduces the Strategy Design Pattern and shows its potential in keeping your code base S.O.L.I.D. and clean. An example implementation of the pattern is provided in TypeScript.

The Strategy Pattern is one of those design patterns that are remarkably simple in style yet efficient in function. Quite a few developers, when first getting in contact with a formal description of the pattern, realize they have been using it all along.

In this article I will introduce the strategy pattern and show its great potential for keeping your code base S.O.L.I.D. and clean. The code examples presented are implemented in TypeScript.

Implementing a Course Management System (First Approach)

Imagine you are tasked with implementing a course management system for a college or university. More specifically, your current job is to list the registered students of a certain course (student enrollment) and print it out in some form. Let's quickly glance at the key players involved here:

The classes could look as follows:

class Course
{
    constructor(public readonly nr: number,
                public readonly name: string,
                public readonly participants: Student[]) {}
}

class Student
{
    constructor(public readonly nr: number, 
                public readonly firstName: string, 
                public readonly lastName: string,
                public readonly satScore: number) {}
}

So far, there's nothing remarkable going on there: Courses have an identifying nr, name and a list of participants. Students have attributes such as an identifying nr, firstName, lastName and a satScore(see SAT score).

Now, printing the list of participants to an output device (we will stick with the Console here to keep things simple) is a task that should be delegated to some sort of View component. Let's create a CourseView component and have it print out sample data through a printParticipants() method:

class CourseView
{
    constructor(public readonly course: Course) {}

    public printParticipants(): void {
        console.log(`\n\n==== ${this.course.name.toUpperCase()} ====`);
        console.log(`Nr\tFirst Name\tLast Name\tSAT Score`);

        this.course.participants.forEach(p => {
            console.log(`${p.nr}\t${p.firstName}\t\t${p.lastName}\t\t${p.satScore}`);
        })
    }
}

We will quickly run our sample app and check the results.

// create sample students
const students: Array<Student> = [
    new Student(46279, "John",      "Doe",      13.8),
    new Student(12345, "Jane",      "Doe",      16.4),
    new Student(15623, "Alex",      "Sanchez",   9.5),
    new Student(98745, "Vanessa",   "Miller",   19.1)
];

// create sample course and view
const cs101 = new Course(101, "Computer Science 101", students);
const cs101View = new CourseView(cs101Course);

// print
cs101View.printParticipants();

This will give us the following output:

==== COMPUTER SCIENCE 101 ====
Nr	    First Name	Last Name	    SAT Score
46279	  John		    Doe		        13.8
12345	  Jane		    Doe		        16.4
15623	  Alex		    Sanchez		     9.5
98745	  Vanessa     Miller		    19.1

Great, the basics are in place and working. Printing the list of participants is still very rudimentary as it just returns the order of participants given in the sample data at design time. Usually any person viewing these lists has a certain informational need. In short, they would very much want the list to be sorted according to some criteria before it gets printed.

Feature Request I: Sorting the List of Participants by Last Names

Let's modify the CourseView class and have it sort the participants by their lastName (in ascending order) before printing out the results:

class CourseView
{
    constructor(public readonly course: Course) {}

    public printParticipants(): void {
        console.log(`\n\n==== ${this.course.name?.toUpperCase()} ====`);
        console.log(`Nr\tFirst Name\tLast Name\tSAT Score`);

        // sort and loop over participants
        this.course.participants.sort(this.compareByLastNameAscending).forEach(p => {
            console.log(`${p.nr}\t${p.firstName}\t\t${p.lastName}\t\t${p.satScore}`);
        });
    }

    private compareByLastNameAscending(a: Student, b: Student): number {
        if(a.lastName < b.lastName)
        {
            return -1;
        }
        else if(a.lastName > b.lastName)
        { 
            return 1; 
        }
        else    // must be equal
        {
            return 0;
        }
    }
}

We are using the Array.sort([compareFunction]) function for sorting, which is part of the ECMAScript Language Specficiation 5.1. It accepts as an argument a universal compareFunctionthat defines the general sort order and that itself accepts two elements A and B and returns a negative number if A < B (i.e. A sorted before B), 0 if A == B (i.e. A and B equal) and a positive number if A > B (i.e. A sorted after B). In our case, such comparing is delegated to the compareByLastNameAscending(a: Student, b: Student): number method, which does exactly as it says: It compares the Students by their lastName in ascending order.

This gives us:

==== COMPUTER SCIENCE 101 ====
Nr	    First Name	Last Name	    SAT Score
46279	  John		    Doe		        13.8
12345   Jane		    Doe		        16.4
98745	  Vanessa     Miller		    19.1
15623	  Alex        Sanchez		     9.5

Feature Request II: Sorting the List of Participants Dynamically by Two Criteria

Next, a new requirement request is thrown at you: The user now needs to sort the list dynamically according to two criteria:

  • lastName, and

  • nr (student number)

Dynamically here means that the user can pick at runtime which criterion to sort by. Ok, you think, no problem. You have sorted by one criterion, so now you simply sort by another. To allow the user to switch between the two, you will just have to add a switching mechanism that tells your view which sorting specifics to apply.

Let's get to it: Add a property sortByLastName: boolean to the CourseView class, which will act as a switch for the sorting criterion to apply. We will also add a new compare method private compareByScore(a: Student, b: Student): number to compare students by their scores. In our printParticipants() method we will then have to pick the proper compare method ( as selected by our switch) and pass it to the Array.sort() method:

class CourseView
{
    // ...

    // our new switch to define which criterion to sort by
    public sortByLastName: boolean = false;

    public printParticipants(): void {
        // ... (nothing new here)

        // pick the compare method according to switch
        var compareMethod =   this.sortByLastName 
                            ? this.compareByLastName 
                            : this.compareBySatScore;

        // sort by the compare method selected
        this.course.participants.sort(compareMethod).forEach(p => {
            console.log(`${p.nr}\t${p.firstName}\t\t${p.lastName}\t\t${p.satScore}`);
        })
    }

    private compareByLastName(a: Student, b: Student): number {
        // ... (nothing new here)
    }

    private compareBySatScore(a: Student, b: Student): number {
        if(a.satScore> b.satScore)
        {
            return -1;
        }
        else if(a.satScore< b.satScore)
        { 
            return 1; 
        }
        else    // must be equal
        {
            return 0;
        }
    }
}

Let's see how our app reacts when setting the sortByLastName switch to false and thus have our participants sorted by satScore:

==== COMPUTER SCIENCE 101 ====
Nr    First Name	Last Name	    SAT Score
98745	Vanessa     Miller		    19.1
12345	Jane        Doe		        16.4
46279	John        Doe		        13.8
15623	Alex        Sanchez		     9.5

Fine, that works! But this begins to feel awkward. We have only added another minor feature and our CourseView class already beings to look bloated. If we keep adding more features, our class will soon burst at the seams. For now, it looks as though we might get away with this convoluted code arrangement.

But no! There we have it: a new feature request comes your way. This "getting away with" idea never really works out, does it?

Feature Request III: Sorting the List of Participants Dynamically by Three (or More) Criteria

The user now wants to sort the list of participants also by student nr. You're sensing a pattern here. We cannot just keep adding new switches and compare methods to accompany every new sorting feature. The sortByLastName switch is already a bad choice as it doesn't tell us anything about what happens if it is false. If we were to add another switch, our code base would disintegrate completely.

Moreover, all these compare methods bloat up our class. Certainly, our CourseView class is doing too many things at once and thus violating the Single Responsibility Principle (SRP). Now that you come to think about it, the class also doesn't adhere to the Open-Closed Principle (OCP): We cannot just add another sorting criterion without modifying the existing class structure. Our current code is definitely not closed to modification as the OCP demands.

If only there was a way to adhere to both SRP and OCP and be able to add custom sorting "strategies" without polluting our code! You think for a moment. Did you say "strategy"? You have an idea...

Strategy Pattern to the Rescue: Outsourcing the Sorting Methods

Can't we just delegate the entire sorting logic to a separate class, some kind of "strategy" that the user could pick and the view would adhere to? We could even go a step further and make it a class hierarchy so as to host an entire armada of different strategies for sorting. OurCourseView class could then receive a property that references the current sorting strategy.

This setup would serve two purposes: First, the user could switch between different sorting methods as per their preferred sort criterion. Second, by decoupling the sorting logic from the view logic, we could implement new sorting methods in the future without having to touch our view class. SRP and OCP would both be satisfied, and our code would look much cleaner!

This very idea is exactly what the Strategy Design Pattern is all about: Separate the execution of some business logic from the entity that makes use of it and give this entity a way of switching between different forms of the logic. Thus, the currently selected concrete implementation of said business logic within the entity becomes a strategy that can be changed and swapped as need arises.

As a first step, we would have to create a common base class called SortingStrategy. It could be made an abstract class and would only handle the sorting logic according to an internal compare method, the implementation of which it would delegate to its sub types. Our players and their relationships could then look something like this:

Let's see how we would implement the abstract SortingStrategy base class:

abstract class SortingStrategy
{
    public sort (students: Array<Student>): Array<Student> {
        // create a copy of the student array
        // so as not to modify the existing array
        const copyOfStudents = students.slice(0);

        copyOfStudents.sort(this.compareStudents);
        return copyOfStudents;
    }

    protected abstract compareStudents(a: Student, b: Student): number;
}

One thing to note here is that within the sort logic we no longer operate on the original student array. Instead, we create a copy (Array.slice(0)) and operate on this one, so as not to have any permanent side-effects (operating on the original array would have it changed every time we call the sort method).

And now to the implementation of the different sorting strategies. We would need at least three types:

  • LastNameAscendingSortingStrategy: sorting by Student.lastName (ascending order)

  • StudentNrAscendingSortingStrategy: sorting by Student.nr (ascending order)

  • SatScoreDescendingSortingStrategy: sorting by Student.satScore (descending order)

Our classes would be implemented as follows:

class LastNameAscendingSortingStrategy extends SortingStrategy
{
    protected compareStudents(a: Student, b: Student): number {
        if(a.lastName < b.lastName)
        {
            return -1;
        }
        else if(a.lastName == b.lastName)
        { 
            return 0; 
        }
        else
        {
            return 1;
        }
    }
}

class StudentNrAscendingSortingStrategy extends SortingStrategy
{
    protected compareStudents(a: Student, b: Student): number {
        if(a.nr < b.nr)
        {
            return -1;
        }
        else if(a.nr == b.nr)
        {
            return 0; 
        }
        else
        {
            return 1;
        }
    }
}

class SatScoreDescendingSortingStrategy extends SortingStrategy
{
    protected compareStudents(a: Student, b: Student): number {
        if(a.satScore > b.satScore)
        {
            return -1;
        }
        else if(a.satScore == b.satScore)
        {
            return 0; 
        }
        else
        {
            return 1;
        }
    }
}

And our CourseView class would receive a sortingStrategy property, which would act as the new switch to give the client the ability to parameterize the desired sorting strategy. Also, the CourseView would have to sort the list of participants according the the strategy currently assigned.

class CourseView
{
    // ...
    
    // this is our new "switch"
    public sortingStrategy: SortingStrategy;

    public printParticipants(title: string): void {
        console.log(`\n\n==== ${this.course.name?.toUpperCase()} ====`);
        console.log(`==== ${title} ====`);
        console.log(`Nr\tFirst Name\tLast Name\tScore`);

        // retrieve the currently selected sorting strategy, 
        // then sort and iterate over participants
        this.sortParticipantsBySelectedStrategy().forEach(p => {
            console.log(`${p.nr}\t${p.firstName}\t\t${p.lastName}\t\t${p.satScore}`);
        })
    }

    private sortParticipantsBySelectedStrategy(): Student[] {
        if(!this.sortingStrategy)
        {
            return this.course.participants;
        }

        return this.sortingStrategy.sort(this.course.participants);
    }
}

That's it. Very nice! We have cleaned up our code base and separated the sorting logic into its own class hierarchy. This is a code base now that can easily be maintained and extended without touching existing class hierarchies.

Now let's see our final work in action:

// create sample students and course view
const students: Array<Student> = [
    new Student(46279, "John",      "Doe",      13.8),
    new Student(12345, "Jane",      "Doe",      16.4),
    new Student(15623, "Alex",      "Sanchez",   9.5),
    new Student(98745, "Vanessa",   "Miller",   19.1)
];
const cs101 = new Course(101, "Computer Science 101", students);
const cs101View = new CourseView(cs101);

// print "unsorted" state
cs101View.printParticipants("UNSORTED");

// sort by last name, then print
cs101View.sortingStrategy = new LastNameAscendingSortingStrategy();
cs101View.printParticipants("SORTED BY LAST NAME ASCENDING");

// sort by SAT score, then print
cs101View.sortingStrategy = new SatScoreDescendingSortingStrategy();
cs101View.printParticipants("SORTED BY SAT SCORE DESCENDING");

// sort by nr, then print
cs101View.sortingStrategy = new StudentNrAscendingSortingStrategy();
cs101View.printParticipants("SORTED BY STUDENT NR ASCENDING");

And our console would read:

==== COMPUTER SCIENCE 101 ====
==== UNSORTED ====
Nr	    First Name	    Last Name	    SAT Score
46279	  John		        Doe		        13.8
12345	  Jane		        Doe		        16.4
15623   Alex		        Sanchez		     9.5
98745   Vanessa		      Miller		    19.1

==== COMPUTER SCIENCE 101 ====
==== SORTED BY LAST NAME ASCENDING ====
Nr       First Name	    Last Name	    SAT Score
46279    John		        Doe		        13.8
12345    Jane		        Doe		        16.4
98745    Vanessa		    Miller		    19.1
15623    Alex		        Sanchez		     9.5

==== COMPUTER SCIENCE 101 ====
==== SORTED BY SAT SCORE DESCENDING ====
Nr        First Name	    Last Name	  SAT Score
98745     Vanessa		      Miller      19.1
12345     Jane		        Doe         16.4
46279     John		        Doe         13.8
15623     Alex		        Sanchez	     9.5

==== COMPUTER SCIENCE 101 ====
==== SORTED BY STUDENT NR ASCENDING ====
Nr	     First Name	    Last Name	    SAT Score
12345    Jane           Doe           16.4
15623    Alex           Sanchez        9.5
46279    John           Doe           13.8
98745    Vanessa        Miller        19.1

That looks good. Our view and sorting strategies are working as expected.

One More Thing...

One more thing to make our code even more readable: Look again at the compareStudents(a: Student, b: Student): number method in our base class SortingStrategy. The number returned really isn't up to any good. All it does is tell us how to sort two Student instances: a < b (returns -1 or any negative number), a == b (returns 0) or a > b (returns 1 or any positive number). Let's try to make this a bit less subtle and more explicit. After all, TypeScript allows us to define number-based enums. We could define our own enum type and have it return those numbers behind more expressive names:

enum ComparisonResult
{
    FirstBeforeSecond = -1,
    Equal = 0,
    SecondBeforeFirst = 1
}

Our compareStudents(...) method would then have to return the new ComparisonResult enum type instead of a number directly (here only exemplified using the SatScoreDescendingSortingStrategy class):

class SatScoreDescendingSortingStrategy extends SortingStrategy
{
    protected compareStudents(a: Student, b: Student): ComparisonResult {
        if(a.satScore > b.satScore)
        {
            return ComparisonResult.FirstBeforeSecond;
        }
        else if(a.satScore == b.satScore)
        {
            return ComparisonResult.Equal; 
        }
        else
        {
            return ComparisonResult.SecondBeforeFirst;
        }
    }
}

Now, this change wraps it up perfectly! Your code base is now clean, readable and easily extendable. Great work! The Strategy Pattern has helped you a great deal in dealing with different ways of sorting the participants list.

Last updated