Programming principles and design · Lesson 38 of 60 · Concept lesson · Optional
Interfaces and contracts
An interface lists what something can do, and a contract is the promise about how it behaves.
Code that relies on the interface works with any part that keeps the promise.
The inside of a part can change safely as long as the contract stays the same.
Picture it
Code example
class Square {
constructor(side) {
this.side = side;
}
area() {
return this.side * this.side;
}
}
class Rectangle {
constructor(width, height) {
this.width = width;
this.height = height;
}
area() {
return this.width * this.height;
}
}
for (const shape of [new Square(3), new Rectangle(3, 4)]) {
console.log(shape.area());
}Output:
9 12
The loop only relies on every shape having an area method. It works for any new shape that keeps that promise.
class Square:
def __init__(self, side):
self.side = side
def area(self):
return self.side * self.side
class Rectangle:
def __init__(self, width, height):
self.width = width
self.height = height
def area(self):
return self.width * self.height
for shape in [Square(3), Rectangle(3, 4)]:
print(shape.area())Output:
9 12
The loop only relies on every shape having an area method. It works for any new shape that keeps that promise.
Check yourself
Pick an answer for each question. You can retry as many times as you like.
Loading the questions…