The Liskov Substitution Principle states that "in a computer program, if S is a subtype of T, then objects of type T may be replaced with objects of type S (i.e., objects of type S may substitute objects of type T) without altering any of the desirable properties of that program (correctness, task performed, etc.)"
This tutorial will show you how to create an class which will substitute text for the S and T in the example, so the concept is easier to understand, for example, replacing S with "Car" and T with "Vehicle" (as Car could be a subtype of vehicle), it will render the following paragraph:
If Car is a subtype of Vehicle, then objects of type Vehicle may be replaced with objects of type Car (i.e., objects of type Car may substitute objects of type Vehicle) without altering any of the desirable properties of that program (correctness, task performed, etc.)class LiskovPhraseMaker {
}
//class properties
var type = "T"
var subtype = "S"
This will create two string variables, with default text of S and Tfunc modifiedLiskovPhrase() -> String{
return "If \(subtype) is a subtype of \(type), then objects of type \(type) may be replaced with objects of type \(subtype) (i.e., objects of type \(subtype) may substitute objects of type \(type)) without altering any of the desirable properties of that program (correctness, task performed, etc.)"
}
import
statement, replace the existing code with that shown below, to make a new instance of the LiskovPhraseMaker class, and call the modifiedLiskovPhrase method:var phraseMaker = LiskovPhraseMaker()
print(phraseMaker.modifiedLiskovPhrase())
type
and subtype
variables, before calling the modifiedLiskovPhrase methodvar phraseMaker = LiskovPhraseMaker()
phraseMaker.type = "Feline"
phraseMaker.subtype = "Lion"
print(phraseMaker.modifiedLiskovPhrase())
At present it is possible to set just the type or subtype, and not the other, which could lead to some incorrect phrases, for example if S is a subtype of Feline, in order to avoid this, we could create a method which requires both the type and subtype to be set at the same time, and then make the type
and subtype
properties private, so they cannot be set separately
func set(type:String, subtype:String){
self.type = type
self.subtype = subtype
}
You will notice that the parameters the method takes (type and subtype) have the same names as the properties we created earlier. In order to differentiate between them in the method body, we prefix the properties with the self
keywordprivate
before each of the properties:
private var type = "T"
private var subtype = "S"
phraseMaker.set(type: "Canine", subtype: "Dog")