Three ways of coding
An example of turning on the light to set the color, using three encoding methods to achieve. They are scripted programming, procedural programming with functional thinking and object-oriented programming.
Scripted programming:
class Light {
status: string
color: string
}
function main() {
const light = new Light()
if (light.status === "on") {
throw new Error("The light is on")
}
light.status = "on"
light.color = "red"
}
Copy the code
Procedural programming with functional thinking:
class Light {
status: string
color: string
}
function open(light: Light) {
if (light.status === "on") {
throw new Error("The light is on")
}
light.status = "on"
}
function setColor(light: Light, color: string) {
if(light.status ! = ="on") {
throw new Error("The light is not on")
}
light.color = color
}
function main() {
const light = new Light()
open(light)
setColor(light, "red")}Copy the code
Object-oriented programming:
class Light {
#status: string
#color: string
public on() {
if (this.#status === "on") {
throw new Error("The light is on")}this.#status = "on"
}
public set color(color: string) {
if (this.#status ! = ="on") {
throw new Error("The light is not on")}this.#color = color
}
}
function main() {
const light = new Light()
light.on()
light.color = "red"
}
Copy the code
Light has so many implementations, you slowly taste… Which one do you usually use?