We use cookies to enhance your experience on the site
CodeWorlds

Best Practices

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:

1// Bad:
2function setIncubatorTemperature(temperature) {
3  incubator.temperature = temperature;
4  // What if temperature is too high? Or a string instead of a number?
5}
6
7// Good:
8function setIncubatorTemperature(temperature) {
9  // Check that temperature is a number
10  if (typeof temperature !== 'number') {
11    throw new Error('Temperature must be a number');
12  }
13
14  // Check temperature is in the safe range
15  if (temperature < 20 || temperature > 40) {
16    throw new Error('Temperature outside safe range (20-40°C)');
17  }
18
19  incubator.temperature = temperature;
20}

2. Write Automated Tests

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

Solution:

1// Unit test for the fence control system
2describe('FenceControlSystem', () => {
3  it('should activate the fence when threat is detected', () => {
4    const fenceSystem = new FenceControlSystem();
5    fenceSystem.detectThreat({ level: 'HIGH', sector: 'B2' });
6    expect(fenceSystem.getStatus('B2')).toBe('ACTIVE');
7  });
8
9  it('should alert if fence voltage is too low', () => {
10    const fenceSystem = new FenceControlSystem();
11    const alert = fenceSystem.checkVoltage(5000); // below minimum
12    expect(alert.type).toBe('VOLTAGE_WARNING');
13  });
14});

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:

1// Bad — one class doing too much
2class JurassicParkSystem {
3  monitorDinosaurs() { /* ... */ }
4  controlFences() { /* ... */ }
5  manageVisitors() { /* ... */ }
6  processPayments() { /* ... */ }
7  generateReports() { /* ... */ }
8}
9
10// Good — separate, focused classes
11class DinosaurMonitor {
12  trackLocation(id) { /* ... */ }
13  checkHealth(id) { /* ... */ }
14}
15
16class FenceController {
17  activate(sector) { /* ... */ }
18  checkVoltage(sector) { /* ... */ }
19}
20
21class VisitorManager {
22  checkIn(visitorId) { /* ... */ }
23  evacuate(sector) { /* ... */ }
24}

4. Always Handle Errors

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

Solution:

1// Bad:
2async function checkDinosaurStatus(id) {
3  const dino = await getDinosaur(id);
4  return dino.status; // What if getDinosaur throws?
5}
6
7// Good:
8async function checkDinosaurStatus(id) {
9  try {
10    const dino = await getDinosaur(id);
11    return dino.status;
12  } catch (error) {
13    if (error instanceof DinoNotFoundError) {
14      console.warn(`Dinosaur ${id} not found — may have been transferred`);
15      return 'unknown';
16    }
17    // Unknown error — re-throw for the caller
18    throw new SystemError(`Failed to check dinosaur status: ${error.message}`);
19  }
20}

5. Document Your Code

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

Solution:

1/**
2 * Verifies an employee's access level to park zones.
3 *
4 * @param {Object} employee - Object containing employee data
5 * @param {string} employee.id - Unique employee identifier
6 * @param {string} employee.firstName - Employee's first name
7 * @param {string} employee.lastName - Employee's last name
8 * @param {number} employee.accessLevel - Employee's access level (1-5)
9 * @param {string} zone - Identifier of the zone the employee is trying to access
10 * @returns {boolean} - Returns true if the employee has access, false otherwise
11 *
12 * @example
13 * // Check if Dr. Wu has access to the lab
14 * const drWu = { id: '001', firstName: 'Henry', lastName: 'Wu', accessLevel: 5 };
15 * const access = checkAccess(drWu, 'laboratory');
16 * console.log(access); // true
17 */
18function checkAccess(employee, zone) {
19  // Map of required access levels for different zones
20  const requiredLevel = {
21    'public': 1,
22    'administration': 2,
23    'herbivore enclosures': 3,
24    'predators': 4,
25    'laboratory': 5
26  };
27
28  // Check if zone exists
29  if (!requiredLevel.hasOwnProperty(zone)) {
30    console.warn(`Unknown zone: ${zone}`);
31    return false;
32  }
33
34  // Compare employee's access level with the zone requirement
35  return employee.accessLevel >= requiredLevel[zone];
36}

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:

1// Bad:
2function ms(d,g,s) {
3  const r = [];
4  for(let i=0;i<d.length;i++) {
5    if(d[i].g === g && d[i].t > s) {
6      r.push(d[i]);
7    }
8  }
9  return r;
10}
11
12// Good:
13/**
14 * Filters dinosaurs by species and minimum strength level
15 */
16function filterDinosaursBySpeciesAndStrength(dinosaurs, species, minStrength) {
17  return dinosaurs.filter(dinosaur =>
18    dinosaur.species === species && dinosaur.strength > minStrength
19  );
20}

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:

1// Bad:
2let globalTemperature = 22;
3let globalHumidity = 70;
4
5function setJungleTemperature() {
6  // Modifies global variables
7  globalTemperature = 28;
8  globalHumidity = 90;
9}
10
11function setLabTemperature() {
12  // Also modifies the same global variables!
13  globalTemperature = 20;
14  globalHumidity = 50;
15}
16
17// What happens if both functions are called close together in time?
18
19// Good:
20class ClimateController {
21  constructor() {
22    this.zones = new Map();
23  }
24
25  setZoneParameters(zoneId, temperature, humidity) {
26    this.zones.set(zoneId, { temperature, humidity });
27  }
28
29  getZoneParameters(zoneId) {
30    return this.zones.get(zoneId);
31  }
32}
33
34const climateController = new ClimateController();
35
36climateController.setZoneParameters('jungle', 28, 90);
37climateController.setZoneParameters('laboratory', 20, 50);
38
39// 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:

1// Bad:
2function checkThreatAtDoors() {
3  if (sensors.motion > 10 && sensors.sound > 80 && !isDaytime()) {
4    raiseAlarm('Suspicious activity at doors!');
5  }
6}
7
8function checkThreatAtFence() {
9  // The same logic is repeated!
10  if (sensors.motion > 10 && sensors.sound > 80 && !isDaytime()) {
11    raiseAlarm('Suspicious activity at fence!');
12  }
13}
14
15// Good:
16function detectSuspiciousActivity() {
17  return sensors.motion > 10 && sensors.sound > 80 && !isDaytime();
18}
19
20function checkThreatAtDoors() {
21  if (detectSuspiciousActivity()) {
22    raiseAlarm('Suspicious activity at doors!');
23  }
24}
25
26function checkThreatAtFence() {
27  if (detectSuspiciousActivity()) {
28    raiseAlarm('Suspicious activity at fence!');
29  }
30}

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:

1# Initialize a Git repository
2git init
3
4# Add files to the repository
5git add .
6
7# First commit
8git commit -m "Initial version of Jurassic Park system"
9
10# Create a new branch for developing a new feature
11git checkout -b new-feeding-system
12
13# Work on the feature...
14
15# Save changes
16git add modified-files
17git commit -m "Add automated feeding system for predators"
18
19# Merge changes into main branch after tests
20git checkout main
21git merge new-feeding-system
22
23# In case of problems, quickly revert to the previous version
24git 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:

1// Jurassic Park dinosaur monitoring system
2var dinos = [];
3var alarms = 0;
4
5function add(name, type, area, dangerLvl) {
6  dinos.push({n: name, t: type, a: area, d: dangerLvl, h: 100});
7  console.log('added: ' + name);
8}
9
10function check() {
11  for (var i=0; i<dinos.length; i++) {
12    if (dinos[i].h < 50) {
13      console.log('WARNING! Dinosaur ' + dinos[i].n + ' has low health!');
14      alarms = alarms + 1;
15    }
16
17    if (dinos[i].a != dinos[i].lockArea && dinos[i].d > 3) {
18      console.log('DANGER! Predator outside zone!');
19      alarms = alarms + 1;
20    }
21  }
22
23  if (alarms > 0) alert('We have problems...');
24}
25
26// Example usage
27add('Rex', 'T-Rex', 'B5', 5);
28add('Tri', 'Triceratops', 'A2', 2);
29dinos[0].h = 30;
30dinos[0].a = 'X3'; // Outside assigned zone!
31check();

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.

Go to CodeWorlds