This seems like bad design to me. Why wouldn't you establish the defaults in the Car class, set a private variable speed in the class and just add a constructor that accepts a speed. Creating a second, unrelated class, just seems to be messy and more prone to the introduction of hard-to-trace bugs. Perhaps this was not the best example to use for demonstrating a Null Object Pattern.
class Car {
speed = 50;
constructor(speed) {
this.speed = speed || this.speed;
}
getSpeed() {
return this.speed;
}
}
const calculateSpeed = function (vehicle = new Car()) {
return vehicle.getSpeed();
}
const car1 = new Car(100);
console.log(calculateSpeed(car1)); // 100
console.log(calculateSpeed()); // 50
The code above solves the problem without potentially introducing new ones. Obviously, the constructor could be cleaned up to ensure we've received a number for speed and so on.
Yes, this solves the problem but doesn't really make it clear that we're dealing with null's in the constructor. I feel like the example in the post is not the best because it's just returning a value from the method. If the behaviour was more complex, then you might want to do something specific if the case where we have null. That's where the null object pattern really shines.
For further actions, you may consider blocking this person and/or reporting abuse
We're a place where coders share, stay up-to-date and grow their careers.
This seems like bad design to me. Why wouldn't you establish the defaults in the Car class, set a private variable
speed
in the class and just add a constructor that accepts a speed. Creating a second, unrelated class, just seems to be messy and more prone to the introduction of hard-to-trace bugs. Perhaps this was not the best example to use for demonstrating a Null Object Pattern.The code above solves the problem without potentially introducing new ones. Obviously, the constructor could be cleaned up to ensure we've received a number for
speed
and so on.Yes, this solves the problem but doesn't really make it clear that we're dealing with null's in the constructor. I feel like the example in the post is not the best because it's just returning a value from the method. If the behaviour was more complex, then you might want to do something specific if the case where we have
null
. That's where thenull object pattern
really shines.