Liskov substitution principle (LSP)

The commands for quit, help, and get inventory do not require parameters, while the AddInventory and UpdateQuantityCommand do. There are several ways to handle this and the team decided to introduce an interface to identify those commands as follows:

public interface IParameterisedCommand
{
bool GetParameters();
}

By applying the Liskov substitution principle (LSP), only those commands that require parameters should implement the GetParameters() method. For example, on the AddInventory command, the IParameterisedCommand is implemented using a method defined on the base InventoryCommand:

public class AddInventoryCommand : InventoryCommand, IParameterisedCommand
{
public string InventoryName { get; private set; }

/// <summary>
/// AddInventoryCommand requires name
/// </summary>
/// <returns></returns>
public bool GetParameters()
{
if (string.IsNullOrWhiteSpace(InventoryName))
InventoryName = GetParameter("name");

return !string.IsNullOrWhiteSpace(InventoryName);
}
}

The GetParameter method on the InventoryCommand class simply uses the ConsoleUserInterface to read a value from the console. The method will be shown later in this chapter. In C#, there is handy syntax that shows well how LSP can be used to apply functionality to only objects of a specific interface. On the first line of the RunCommand method, the is keyword is used to both test whether the current object implements the IParameterisedCommand interface as well as cast the object as a new object: parameterisedCommand. This is shown in bold in the following code snippet:

public (bool wasSuccessful, bool shouldQuit) RunCommand()
{
if (this is IParameterisedCommand parameterisedCommand)
{
var allParametersCompleted = false;

while (allParametersCompleted == false)
{
allParametersCompleted = parameterisedCommand.GetParameters();
}
}

return (InternalCommand(), _isTerminatingCommand);
}
..................Content has been hidden....................

You can't read the all page of ebook, please click here login for view all page.
Reset
3.129.210.17