Command Pattern: Refactor Conditionals into Polymorphism

LinkedIn Tweet Facebook
Command Pattern: Refactor Conditionals into Polymorphism

Polymorphism

Command pattern is need to execute a command in polymorphic manner using Object oriented mechanism.

This pattern should be used to replace if-else ladder or conditional command statements.

Replace conditional statements with polymorphism

Implementation

The storeAndExecute function will invoke further command without creating new objects.

Example

We will take a simple example of two commands

The Switch class invokes both these components. Switch class will contain Objects. When the user wants to execute a command he will send the string to execute the command.

Using command pattern does not mean you can remove the if conditions but polymorphism will help you keep your code organised. Instead of writing the logic in if blocks. We write a code in dedicated command objects.

The abstract command defines the method of the command to be executed.

Cyclomatic COmplexiy

Cyclomatic commplexity (CC) is a measture of code-complexity

cc = edges-nodes+2