Code Tip #2: Isolate References to external classes

Imagine we have the following Vehicle class that has a dependency on the speed property of an Engine class.

class Engine {
  constructor(speed){
    this.speed = speed * 1.2;
  }
}

The Engine class accept a speed value and uses a factor to define the final speed. Its internals is not so important.

import Engine from './Engine';

class Vehicle {
  constructor(price, weight, speed){
    this.price = price;
    this.weight = weight;
    this.engine = new Engine(speed);
  }

  getAcceleration(){
    return this.engine.speed * this.weight;
  }

  getSpeedPerKilo(){
    return this.engine.speed / this.weight;
  }
}

What is important is the fact that Vehicle uses all over the place the property of the Engine class. Another issue is that even if we don’t use any of the getAccelaration or getSpeedPerKilo methods we create an instance of the Engine class since the class is instantiated in the constructor. It will be better to do the following:

class Vehicle {
  constructor(price, weight, speed){
    this.price = price;
    this.weight = weight;
    this.speed = speed;
  }

  getAcceleration(){
    return this.getSpeed() * this.weight;
  }

  getSpeedPerKilo(){
    return this.getSpeed() / this.weight;
  }

  getSpeed(){
    this.engine = this.engine || new Engine(this.speed);
    return this.engine.speed;
  }
}

That way we isolate the dependency to the Engine class in a single place, and we create it lazily. If the getAcceleration or getSpeedPerKilo classes are never called, the Engine wont need to be instantiated.

Leave a Reply

Your email address will not be published. Required fields are marked *