Say I have a Car
, that owns a SpeedBooster
that whenever is active
and the car has to move, it will add an extra - configurable - speed to that moving action.
I was thinking about how to design-implement this using OOP, and I ended up doubting between two different solutions:
Solution 1
The Car is the one that checks if the Booster is ON
and itself calculates that extra distance that will be added to the final move.
SpeedBooster Class
class SpeedBooster {
private active: boolean;
private speedIncrement: number;
constructor(speedIncrement: number, active = false) {
this.active = active;
this.speedIncrement = speedIncrement;
}
public activate(): void {
this.active = true;
}
public deactivate(): void {
this.active = false;
}
public isActive(): boolean {
return this.active;
}
public getSpeedIncrement(): number {
return this.speedIncrement;
}
}
Car Class
class Car {
private position: number;
private speedBooster: SpeedBooster;
constructor(speedBooster: SpeedBooster) {
this.position = 0;
this.speedBooster = speedBooster;
}
public move(distance: number): void {
if (this.speedBooster.isActive()) {
let extraDistance = this.speedBooster.getSpeedIncrement() * distance;
let totalDistance = extraDistance + distance;
this.position =+ totalDistance;
} else {
this.position =+ distance;
}
}
// etc...
}
Solution 2
The Car just asks the Booster about that extra distance it will have to add to the final move. The Booster knows it's state (ON
/OFF
) and returns the extra distance or 0.
SpeedBooster Class
class SpeedBooster {
private active: boolean;
private speedIncrement: number;
constructor(speedIncrement: number, active = false) {
this.active = active;
this.speedIncrement = speedIncrement;
}
public activate(): void {
this.active = true;
}
public deactivate(): void {
this.active = false;
}
public calculateExtraDistance(distance) {
if (this.active) {
return this.speedIncrement * distance;
} else {
return 0;
}
}
}
Car Class
class Car {
private position: number;
private speedBooster: SpeedBooster;
constructor(speedBooster: SpeedBooster) {
this.position = 0;
this.speedBooster = speedBooster;
}
public move(distance: number): void {
let extraDistance = speedBooster.calculateExtraDistance(distance);
this.position =+ distance + extraDistance;
}
// etc...
}
I am not too experienced in OOP, and I haven't decided which solution I would go for yet... anyone dares to share their opinions?