BlackWaspTM

This web site uses cookies. By using the site you accept the cookie policy.This message is for compliance with the UK ICO law.

Programming Concepts

Liskov Substitution Principle

The fourth article in the SOLID Principles series describes the Liskov Substitution Principle (LSP). The LSP specifies that functions that use pointers of references to base classes must be able to use objects of derived classes without knowing it.

Refactored Code

There are various ways in which the code can be refactored to comply with the LSP. One is shown below. Here the Project class has been modified to include two collections instead of one. One collection contains all of the files in the project and one holds references to writeable files only. The LoadAllFiles method loads data into all of the files in the AllFiles collection. As the files in the WriteableFiles collection will be a subset of the same references, the data will be visible via these also. The SaveAllFiles method has been replaced with a method that saves only the writeable files.

The ProjectFile class now contains only one method, which loads the file data. This method is required for both writeable and read-only files. The new WriteableFile class extends ProjectFile, adding a method that saves the file data. This reversal of the hierarchy means that the code now complies with the LSP.

The refactored code is as follows:

public class Project
{
    public Collection<ProjectFile> AllFiles { get; set; }
    public Collection<WriteableFile> WriteableFiles { get; set; }

    public void LoadAllFiles()
    {
        foreach (ProjectFile file in AllFiles)
        {
            file.LoadFileData();
        }
    }

    public void SaveAllWriteableFiles()
    {
        foreach (WriteableFile file in WriteableFiles)
        {
            file.SaveFileData();
        }
    }
}


public class ProjectFile
{
    public string FilePath { get; set; }

    public byte[] FileData { get; set; }

    public void LoadFileData()
    {
        // Retrieve FileData from disk
    }
}


public class WriteableFile : ProjectFile
{
    public void SaveFileData()
    {
        // Write FileData to disk
    }
}
11 January 2011