Strategy

AKA: Policy

When you need your program to behave a certain way in response to events, you usually use configuration to set the behaviour and branching in the code to act as specified. A spell checker might check words and fragments for spelling and grammar errors but needs to know which language to check against. So, you set a variable for which language and when it comes to spell checking, you load the correct dictionary and check the spelling.

However, when you add new languages, you must add new code switches. Not all languages have the same types of word sequences to verify. Sometimes, words are not separated by spaces but by other characters. Sometimes words might not be in a dictionary, but simple rules might guide regular constructions such as the hyphenated-sequence, or neologisms, such as malamanteau1.

Just storing a variable for which dictionary to load is no longer sufficient. You need to select a language-appropriate processor. With each language there is now a chance you need to add another case to your switch on languages for how to check spellings.

Instead of a switch statement, you can use a strategy or policy object to encapsulate the checking algorithm. You must define the API upfront but not much more. This way, the checking algorithm can change as per the switch but the checker no longer needs to know about the checking algorithm or even what checking algorithms are available at compile time.

To add a new language with new rules, create a new class which implements the checking algorithm. You can provide an object of that type to the checker as necessary. A plugin would, upon registration, create and supply a checking algorithm object (potentially as a stateless Singleton) to the spell-checker. The spell-checker can store these in a dictionary, as every implementation follows a standard interface.

In essence, Strategy suggests you use an object to define behaviour. The object can perform an algorithm on the context passed to it, meaning a strategy operates on a context, not on that holding the strategy object.

Beware of performance problems caused by last-minute decision-making as the more objects you have behaving like a Strategy, the less predictable your program and the less work can be done ahead of time.

“You’ve told me what to do, but I’ll do it my way, thanks.”

1

I believe this joke word originated from XKCD https://xkcd.com/739, but the point is that there are rules for how neologisms come about, and why not spell-check them as if they already existed?