Articles NutritionCheckpoint Hangman Survey Says About Steven Cleary

Lazy Class

A Lazy Class is a code smell. This code smell maps to the Refactoring techniques Inline Class and Collapse Hierarchy. Imagine we wanted to build/model a Parking Lot. In designing this parking lot, we want to consider the different types of parking spots. There might be regular parking spots, large parking spots, or even small parking spots. In one solution, to handle this we could have an abstract class vehicle and then have different types of vehicles for each spot.

solutionOne

Then when giving out parking spots to different vehicles we can check which type of vehicle it is an instance of. This is the solution used here. However with this solution we are only using the class to tell what type of vehicle it is so we can give it a spot it will fit in. However, the subclasses are Lazy Classes. In this instance, they contain no info or functionality and in the future they are not likely to. So lets refactor the class.

            
class AbstractVehicle{
  constructor() {
    if (new.target === AbstractVehicle) {
      throw new TypeError("Tried to construct an Abstract Class");
    }
  }
}

class SmallCar extends AbstractVehicle{}

class RegularCar extends AbstractVehicle{}

class Large extends AbstractVehicle{}

function getParkingSpotLazy(vehicle){
  if( vehicle instanceof SmallCar){
    // find a spot for a small car
  }else if( vehicle instanceof RegularCar){
    // find a spot for a regular car
  }else if( vehicle instanceof LargeCar){
    // find a spot for a large car
  }
}
            
          
            
var carSizesEnum = {"small":0, "regular":1, "large":2}
Object.freeze(carSizesEnum);

class Vehicle{
  constructor(carSize){
    this.carSize = carSize;
  }
}

var parkingSpots = [[],[],[]];

function getParkingSpot(vehicle){
  if(parkingSpots[vehicle.carSize].length > 0){
    parkingSpots[vehicle.carSize].shift();
  }
}
            
          

As you can see in this case, getting rid of the Lazy Classes made the code shorter and somewhat more readable.