DEV Community

Discussion on: Null Object Pattern

Collapse
 
dainbrump profile image
Mark Litchfield • Edited

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.

Collapse
 
craigbrad profile image
Craig Bradley

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.