JavaScript and TypeScript course Β· Module 5: Advanced JavaScript

Best Practices

8 min read Β·
In this lesson3

This time Dr. Ian Malcolm together with the entire Jurassic Park team has prepared a critical briefing for you. After several park incidents, including the infamous system failure and dinosaur escape, the team has developed a set of programming best practices that could prevent similar catastrophes in the future.

Principles That Could Have Saved Jurassic Park

1. Validate All Input Data

Park problem: The system didn't properly check incubator temperature data for dinosaur eggs, leading to uncontrolled Velociraptor breeding.

Solution:

// Bad:
function setIncubatorTemperature(temperature) {
  incubator.temperature = temperature;
  // What if temperature is too high? Or a string instead of a number?
}

// Good:
function setIncubatorTemperature(temperature) {
  // Check that temperature is a number
  if (typeof temperature !== 'number') {
    throw new Error('Temperature must be a number');
  }

  // Check temperature is in the safe range
  if (temperature < 20 || temperature > 40) {
    throw new Error('Temperature outside safe range (20-40Β°C)');
  }

  incubator.temperature = temperature;
}

2. Write Automated Tests

Park problem: Changes to the security system introduced bugs that weren't caught before going live.

Solution:

// Unit test for the fence control system
describe('FenceControlSystem', () => {
  it('should activate the fence when threat is detected', () => {
    const fenceSystem = new FenceControlSystem();
    fenceSystem.detectThreat({ level: 'HIGH', sector: 'B2' });
    expect(fenceSystem.getStatus('B2')).toBe('ACTIVE');
  });

  it('should alert if fence voltage is too low', () => {
    const fenceSystem = new FenceControlSystem();
    const alert = fenceSystem.checkVoltage(5000); // below minimum
    expect(alert.type).toBe('VOLTAGE_WARNING');
  });
});

3. Single Responsibility Principle (SRP)

Park problem: The main control system tried to do everything - monitor dinosaurs, control fences, manage visitors, handle payments. One bug could bring down the entire system.

Solution:

// Bad - one class doing too much
class JurassicParkSystem {
  monitorDinosaurs() { /* ... */ }
  controlFences() { /* ... */ }
  manageVisitors() { /* ... */ }
  processPayments() { /* ... */ }
  generateReports() { /* ... */ }
}

// Good - separate, focused classes
class DinosaurMonitor {
  trackLocation(id) { /* ... */ }
  checkHealth(id) { /* ... */ }
}

class FenceController {
  activate(sector) { /* ... */ }
  checkVoltage(sector) { /* ... */ }
}

class VisitorManager {
  checkIn(visitorId) { /* ... */ }
  evacuate(sector) { /* ... */ }
}

4. Always Handle Errors

Park problem: Unhandled errors caused the system to crash silently, without activating emergency protocols.

Solution:

// Bad:
async function checkDinosaurStatus(id) {
  const dino = await getDinosaur(id);
  return dino.status; // What if getDinosaur throws?
}

// Good:
async function checkDinosaurStatus(id) {
  try {
    const dino = await getDinosaur(id);
    return dino.status;
  } catch (error) {
    if (error instanceof DinoNotFoundError) {
      console.warn(`Dinosaur ${id} not found - may have been transferred`);
      return 'unknown';
    }
    // Unknown error - re-throw for the caller
    throw new SystemError(`Failed to check dinosaur status: ${error.message}`);
  }
}

5. Document Your Code

Park problem: After the lead engineer left, nobody knew exactly how the access control system worked.

Solution:

/**
 * Verifies an employee's access level to park zones.
 *
 * @param {Object} employee - Object containing employee data
 * @param {string} employee.id - Unique employee identifier
 * @param {string} employee.firstName - Employee's first name
 * @param {string} employee.lastName - Employee's last name
 * @param {number} employee.accessLevel - Employee's access level (1-5)
 * @param {string} zone - Identifier of the zone the employee is trying to access
 * @returns {boolean} - Returns true if the employee has access, false otherwise
 *
 * @example
 * // Check if Dr. Wu has access to the lab
 * const drWu = { id: '001', firstName: 'Henry', lastName: 'Wu', accessLevel: 5 };
 * const access = checkAccess(drWu, 'laboratory');
 * console.log(access); // true
 */
function checkAccess(employee, zone) {
  // Map of required access levels for different zones
  const requiredLevel = {
    'public': 1,
    'administration': 2,
    'herbivore enclosures': 3,
    'predators': 4,
    'laboratory': 5
  };

  // Check if zone exists
  if (!requiredLevel.hasOwnProperty(zone)) {
    console.warn(`Unknown zone: ${zone}`);
    return false;
  }

  // Compare employee's access level with the zone requirement
  return employee.accessLevel >= requiredLevel[zone];
}

6. Write Readable Code

Park problem: The genetic code written by Dr. Wu was so convoluted that nobody else understood exactly how hybrid dinosaurs were created.

Solution:

// Bad:
function ms(d,g,s) {
  const r = [];
  for(let i=0;i<d.length;i++) {
    if(d[i].g === g && d[i].t > s) {
      r.push(d[i]);
    }
  }
  return r;
}

// Good:
/**
 * Filters dinosaurs by species and minimum strength level
 */
function filterDinosaursBySpeciesAndStrength(dinosaurs, species, minStrength) {
  return dinosaurs.filter(dinosaur =>
    dinosaur.species === species && dinosaur.strength > minStrength
  );
}

7. Avoid Global State

Park problem: The climate control system used global variables to store settings, which allowed a bug in the ventilation module to affect the entire climate system.

Solution:

// Bad:
let globalTemperature = 22;
let globalHumidity = 70;

function setJungleTemperature() {
  // Modifies global variables
  globalTemperature = 28;
  globalHumidity = 90;
}

function setLabTemperature() {
  // Also modifies the same global variables!
  globalTemperature = 20;
  globalHumidity = 50;
}

// What happens if both functions are called close together in time?

// Good:
class ClimateController {
  constructor() {
    this.zones = new Map();
  }

  setZoneParameters(zoneId, temperature, humidity) {
    this.zones.set(zoneId, { temperature, humidity });
  }

  getZoneParameters(zoneId) {
    return this.zones.get(zoneId);
  }
}

const climateController = new ClimateController();

climateController.setZoneParameters('jungle', 28, 90);
climateController.setZoneParameters('laboratory', 20, 50);

// Now each zone has its own independent settings

8. DRY (Don't Repeat Yourself)

Park problem: The threat detection code was duplicated across multiple systems, so a bug fix in one system was not applied to the others.

Solution:

// Bad:
function checkThreatAtDoors() {
  if (sensors.motion > 10 && sensors.sound > 80 && !isDaytime()) {
    raiseAlarm('Suspicious activity at doors!');
  }
}

function checkThreatAtFence() {
  // The same logic is repeated!
  if (sensors.motion > 10 && sensors.sound > 80 && !isDaytime()) {
    raiseAlarm('Suspicious activity at fence!');
  }
}

// Good:
function detectSuspiciousActivity() {
  return sensors.motion > 10 && sensors.sound > 80 && !isDaytime();
}

function checkThreatAtDoors() {
  if (detectSuspiciousActivity()) {
    raiseAlarm('Suspicious activity at doors!');
  }
}

function checkThreatAtFence() {
  if (detectSuspiciousActivity()) {
    raiseAlarm('Suspicious activity at fence!');
  }
}

9. Use Version Control

Park problem: The IT team did not use version control, so after introducing a new feature that turned out to contain bugs, there was no easy way to revert to the previous working version.

Solution:

# Initialize a Git repository
git init

# Add files to the repository
git add .

# First commit
git commit -m "Initial version of Jurassic Park system"

# Create a new branch for developing a new feature
git checkout -b new-feeding-system

# Work on the feature...

# Save changes
git add modified-files
git commit -m "Add automated feeding system for predators"

# Merge changes into main branch after tests
git checkout main
git merge new-feeding-system

# In case of problems, quickly revert to the previous version
git revert HEAD

10. Apply Code Review

Park problem: Dennis Nedry introduced a backdoor into the security system that nobody noticed because there was no code review process.

Team approach:

  1. Every change must be reviewed by at least one other developer
  2. Automated tests must pass before merging code
  3. Apply a checklist during reviews:
    • Does the code comply with standards?
    • Have potential security issues been addressed?
    • Has documentation been updated?
    • Do tests cover the new code?

The Cost of Ignoring Best Practices

As we know from Jurassic Park history, ignoring programming best practices can lead to catastrophic consequences:

  1. Data loss: Priceless dinosaur genetic material lost due to system bugs
  2. Security breaches: System failures leading to dangerous creature escapes
  3. Downtime: Park closure due to technical problems
  4. Development difficulties: Inability to quickly introduce new features
  5. Maintenance problems: Code that's hard to understand and fix

Exercise

Imagine you are the lead developer at Jurassic Park. Identify all potential problems in the code below and rewrite it according to best practices:

// Jurassic Park dinosaur monitoring system
var dinos = [];
var alarms = 0;

function add(name, type, area, dangerLvl) {
  dinos.push({n: name, t: type, a: area, d: dangerLvl, h: 100});
  console.log('added: ' + name);
}

function check() {
  for (var i=0; i<dinos.length; i++) {
    if (dinos[i].h < 50) {
      console.log('WARNING! Dinosaur ' + dinos[i].n + ' has low health!');
      alarms = alarms + 1;
    }

    if (dinos[i].a != dinos[i].lockArea && dinos[i].d > 3) {
      console.log('DANGER! Predator outside zone!');
      alarms = alarms + 1;
    }
  }

  if (alarms > 0) alert('We have problems...');
}

// Example usage
add('Rex', 'T-Rex', 'B5', 5);
add('Tri', 'Triceratops', 'A2', 2);
dinos[0].h = 30;
dinos[0].a = 'X3'; // Outside assigned zone!
check();

Remember, in the world of programming, just like in Jurassic Park - life always finds a way... to expose poorly thought-out solutions! That's why apply best practices to make your code safe, maintainable, and efficient.

Code for this lesson: main.js
// Best practices with modules - Jurassic Park
console.log("Best Practices with Modules\n");

// ===========================================
// 1. CLEAR FOLDER STRUCTURE
// ===========================================

console.log("=== 1. Project Structure ===\n");
console.log(`jurassic-park/
β”œβ”€β”€ src/
β”‚   β”œβ”€β”€ models/
β”‚   β”‚   β”œβ”€β”€ Dinosaur.js
β”‚   β”‚   β”œβ”€β”€ Enclosure.js
β”‚   β”‚   └── index.js
β”‚   β”œβ”€β”€ services/
β”‚   β”‚   β”œβ”€β”€ DinosaurService.js
β”‚   β”‚   β”œβ”€β”€ SecurityService.js
β”‚   β”‚   └── index.js
β”‚   β”œβ”€β”€ utils/
β”‚   β”‚   β”œβ”€β”€ validators.js
β”‚   β”‚   β”œβ”€β”€ formatters.js
β”‚   β”‚   └── index.js
β”‚   β”œβ”€β”€ config/
β”‚   β”‚   └── constants.js
β”‚   └── index.js
└── package.json`);

// ===========================================
// 2. SINGLE RESPONSIBILITY PER MODULE
// ===========================================

console.log("\n=== 2. Single Responsibility ===\n");

// GOOD - each module does one thing
const DinosaurValidator = {
  validate(data) {
    return data.name && data.species;
  }
};

const DinosaurFormatter = {
  format(dinosaur) {
    return `${dinosaur.name} - ${dinosaur.species}`;
  }
};

// BAD - one module does too much
const DinosaurEverything = {
  validate() {},
  format() {},
  save() {},
  load() {},
  update() {},
  delete() {}
};

console.log("Modules with single responsibility");
console.log("Avoid 'god objects'");

// ===========================================
// 3. NAMING
// ===========================================

console.log("\n=== 3. Naming Conventions ===\n");

console.log("GOOD:");
console.log("  DinosaurService.js - class/service");
console.log("  constants.js - constants");
console.log("  utils.js - utility functions");
console.log("  index.js - re-export");

console.log("\nBAD:");
console.log("  dino.js - unclear");
console.log("  stuff.js - too generic");
console.log("  temp.js - temporary files");

// ===========================================
// 4. DEPENDENCY INJECTION
// ===========================================

console.log("\n=== 4. Dependency Injection ===\n");

// GOOD - dependencies as parameters
class ParkManager {
  constructor(dinosaurService, securityService) {
    this.dinosaurService = dinosaurService;
    this.securityService = securityService;
  }
}

// BAD - hard-coded dependencies
class BadParkManager {
  constructor() {
    this.dinosaurService = new DinosaurService();
    this.securityService = new SecurityService();
  }
}

console.log("Pass dependencies");
console.log("Don't create dependencies inside");

// ===========================================
// 5. EXPORT ONLY WHAT IS NEEDED
// ===========================================

console.log("\n=== 5. Minimal API Surface ===\n");

// GOOD - export only the public API
const DinosaurModule = {
  // Public
  createDinosaur(name) {
    return _createInternal(name);
  },

  getDinosaur(id) {
    return _findById(id);
  }
};

// Private functions (not exported)
function _createInternal(name) {
  return { name, id: Math.random() };
}

function _findById(id) {
  return { id };
}

console.log("Minimal public surface");
console.log("Don't export internal helpers");

// ===========================================
// 6. DOCUMENTATION
// ===========================================

console.log("\n=== 6. Module Documentation ===\n");

/**
 * Dinosaur Service
 * Handles all dinosaur-related operations
 *
 * @module DinosaurService
 * @exports {Object} Service object with public methods
 *
 * @example
 * import DinosaurService from './DinosaurService';
 * const dino = DinosaurService.create('Rex');
 */
const DinosaurService = {
  /**
   * Creates a new dinosaur
   * @param {string} name - Dinosaur name
   * @returns {Object} Dinosaur object
   */
  create(name) {
    return { name };
  }
};

console.log("JSDoc for public APIs");
console.log("README for larger modules");

console.log("\n=== SUMMARY OF PRACTICES ===\n");
console.log("1. Clear folder structure");
console.log("2. Single responsibility per module");
console.log("3. Clear file names");
console.log("4. Dependency Injection");
console.log("5. Minimal exports");
console.log("6. Documentation");
console.log("7. Tests for each module");
console.log("8. Avoid circular dependencies");

console.log("\nClean modules = better code!");

Docs entries used in this lesson

Spotted a mistake in this lesson?

Check yourself

Answer the questions from this lesson. Pick an answer to see right away whether it is correct.

  1. 1. What does the Single Responsibility Principle mean?

  2. 2. Why is input data validation crucial in programming?

Hands-on tasks in the game

  • Vertical ordering

    Order the stages of creating reliable code from first to last:

  1. QuestionSingle Responsibility Principle
  2. QuestionInput Data Validation
  3. Put in orderStages of Writing Reliable Code

Useful articles