JavaScript and TypeScript course Β· Module 5: Advanced JavaScript
Structuring Code in a Larger Project
In this lesson11
After going through all the most important JavaScript techniques, it's time to look at the bigger picture - how to organize code in larger projects. Poor code structure can lead to a disaster similar to what we experienced in Jurassic Park - chaos, errors, and difficulty managing the system.
Why Project Structure Matters
Imagine all of Jurassic Park's infrastructure managed by one massive system. All enclosure security, dinosaur health monitoring, visitor flow management, catering, genetics labs - everything in one monolithic program. Disaster is just around the corner, right?
A well-designed project structure ensures:
- Maintainability - easier to find and fix bugs
- Scalability - ability to add new features without breaking existing ones
- Testability - ability to test components in isolation
- Collaboration ease - multiple developers can work in parallel on different parts
- Readability - easier to understand how the system works
Folder and File Organization
There are many approaches to organizing code in larger JavaScript projects. Let's look at a few proven patterns that would work in a Jurassic Park management system.
1. Type-Based Structure
One popular structure, especially in smaller apps, groups files by their type:
jurassic-park-management/
βββ src/
β βββ components/ # UI components
β βββ services/ # API communication services
β βββ utils/ # Utility tools
β βββ models/ # Type and interface definitions
β βββ hooks/ # Custom hooks
β βββ constants/ # Application constants
β βββ assets/ # Images, fonts, etc.
β βββ styles/ # CSS/SCSS styles
β βββ tests/ # Tests
βββ package.json2. Feature-Based Structure
As the project grows, a feature-based structure is often better:
jurassic-park-management/
βββ src/
β βββ features/
β β βββ dinosaurs/
β β β βββ DinosaurList.jsx
β β β βββ DinosaurDetail.jsx
β β β βββ dinosaurService.js
β β β βββ dinosaurReducer.js
β β β βββ dinosaur.test.js
β β βββ security/
β β β βββ SecurityDashboard.jsx
β β β βββ securityService.js
β β β βββ security.test.js
β β βββ monitoring/
β β βββ MonitoringPanel.jsx
β β βββ monitoringService.js
β β βββ monitoring.test.js
β βββ shared/
β β βββ components/ # Shared components
β β βββ utils/ # Shared utilities
β β βββ hooks/ # Shared hooks
β βββ app/
β βββ store.js
β βββ router.js
βββ package.json3. Modular Structure (Domain-Driven)
For enterprise-level projects:
jurassic-park-management/
βββ modules/
β βββ DinosaurModule/
β β βββ domain/ # Business logic
β β βββ infrastructure/ # External communication
β β βββ presentation/ # UI
β β βββ index.js # Public API
β βββ SecurityModule/
β βββ MonitoringModule/
βββ shared/
βββ app/Application Architecture
MVC (Model-View-Controller)
// Model
class DinosaurModel {
constructor(data) {
this.id = data.id;
this.name = data.name;
this.species = data.species;
this.health = data.health;
}
isHealthy() { return this.health > 60; }
isDangerous() { return this.dangerLevel > 7; }
}
// View
class DinosaurView {
render(dinosaur) {
return `<div class="dino-card ${dinosaur.isHealthy() ? 'healthy' : 'sick'}">
<h3>${dinosaur.name}</h3>
<p>${dinosaur.species}</p>
<p>Health: ${dinosaur.health}%</p>
</div>`;
}
}
// Controller
class DinosaurController {
constructor(model, view, service) {
this.model = model;
this.view = view;
this.service = service;
}
async loadAndDisplay(id) {
const data = await this.service.getDinosaur(id);
const dinosaur = new this.model(data);
return this.view.render(dinosaur);
}
}Code Modularization
Regardless of folder structure and architecture, the key is to properly split code into smaller, cohesive modules.
1. Modularization by Responsibility
Each module should have a clear, single responsibility:
// dinosaurHealthMonitor.js - responsible only for monitoring dinosaur health
export function checkVitalSigns(dinosaurId) {
//
}
export function alertHealthIssue(dinosaurId, issue) {
//
}
// enclosureSecurity.js - responsible only for enclosure security
export function checkEnclosureSecurity(enclosureId) {
//
}
export function activateEmergencyProtocol(enclosureId) {
//
}2. Clean Interfaces Between Modules
Modules should communicate through clean, well-defined interfaces:
// Higher-level module uses lower-level module interfaces
import { checkVitalSigns } from './dinosaurHealthMonitor';
import { checkEnclosureSecurity } from './enclosureSecurity';
// parkSafetySystem.js
export async function performSafetyCheck() {
const dinosaurs = await fetchAllDinosaurs();
const enclosures = await fetchAllEnclosures();
// Use other module interfaces
const healthIssues = dinosaurs.map(checkVitalSigns);
const securityIssues = enclosures.map(checkEnclosureSecurity);
return {
healthIssues: healthIssues.filter(issue => issue !== null),
securityIssues: securityIssues.filter(issue => issue !== null)
};
}3. Dependency Injection
Dependency injection is a technique that allows reversing dependencies between modules, making testing and changes easier:
// Without DI
function DinosaurMonitor() {
// Direct dependency
const vitalSignsMonitor = new VitalSignsMonitor();
return {
checkDinosaur(dinosaur) {
return vitalSignsMonitor.check(dinosaur);
}
};
}
// With DI
function DinosaurMonitor(vitalSignsMonitor) {
return {
checkDinosaur(dinosaur) {
return vitalSignsMonitor.check(dinosaur);
}
};
}
// Now we can inject different implementations
const realMonitor = DinosaurMonitor(new VitalSignsMonitor());
const testMonitor = DinosaurMonitor(new MockVitalSignsMonitor());Managing Imports
In large projects, managing imports can become problematic. Here are some techniques that help keep them organized:
1. Barrel Exports
Index files that re-export all public elements from a given directory:
// dinosaurMonitoring/index.js
export * from './vitalSigns';
export * from './behaviorAnalysis';
export * from './healthAlerts';
// In another module
import { checkVitalSigns, analyzeBehavior } from './dinosaurMonitoring';
// Instead of
import { checkVitalSigns } from './dinosaurMonitoring/vitalSigns';
import { analyzeBehavior } from './dinosaurMonitoring/behaviorAnalysis';2. Import Aliases
Many bundling tools (like webpack, Vite) allow defining aliases for import paths:
// webpack.config.js
module.exports = {
resolve: {
alias: {
'@core': path.resolve(__dirname, 'src/core'),
'@features': path.resolve(__dirname, 'src/features'),
'@shared': path.resolve(__dirname, 'src/shared'),
}
}
};
// In code
import { activateProtocol } from '@core/security';
import { DinosaurCard } from '@features/dinosaurs/components';This eliminates the problem of relative paths (../../..) and makes imports more readable.
State Management
In larger applications, state management becomes a key challenge. Here are several approaches:
1. Centralized State Management (Redux, MobX)
Storing the entire application state in one place:
// Redux actions for dinosaur monitoring system
const UPDATE_DINOSAUR_HEALTH = 'UPDATE_DINOSAUR_HEALTH';
const ALERT_HEALTH_ISSUE = 'ALERT_HEALTH_ISSUE';
// Reducer
function dinosaurHealthReducer(state = initialState, action) {
switch (action.type) {
case UPDATE_DINOSAUR_HEALTH:
return {
...state,
dinosaurs: state.dinosaurs.map(dino =>
dino.id === action.payload.id
? { ...dino, health: action.payload.health }
: dino
)
};
case ALERT_HEALTH_ISSUE:
return {
...state,
alerts: [...state.alerts, action.payload]
};
default:
return state;
}
}2. Modularized State (Redux Toolkit, Zustand)
Splitting state into smaller, independent "slices":
// State slice responsible for dinosaurs
const dinosaurSlice = createSlice({
name: 'dinosaurs',
initialState: { list: [], loading: false, error: null },
reducers: {
fetchStart: (state) => {
state.loading = true;
},
fetchSuccess: (state, action) => {
state.list = action.payload;
state.loading = false;
},
updateHealth: (state, action) => {
const { id, health } = action.payload;
const dinosaur = state.list.find(d => d.id === id);
if (dinosaur) dinosaur.health = health;
}
}
});
// State slice responsible for enclosures
const enclosureSlice = createSlice({
name: 'enclosures',
initialState: { list: [], securityStatus: {} },
reducers: {
//
}
});3. Server State vs. Client State
Distinguishing between data coming from the server and UI state:
// Server data - handled by React Query
const { data: dinosaurs, isLoading, error } = useQuery(
'dinosaurs',
() => fetchDinosaurs()
);
// UI state - handled locally
const [selectedDinosaurId, setSelectedDinosaurId] = useState(null);Managing Side Effects
In large applications, managing side effects (API requests, I/O operations, etc.) becomes complex. Here are several approaches:
1. Centralized Management (Redux Saga, Redux Thunk)
// Redux Saga for dinosaur health monitoring
function* monitorDinosaurHealthSaga() {
while (true) {
try {
// Fetch all dinosaurs
const dinosaurs = yield call(api.fetchAllDinosaurs);
// Check health of each dinosaur
for (const dinosaur of dinosaurs) {
const healthData = yield call(api.fetchDinosaurHealth, dinosaur.id);
// Update state
yield put(updateDinosaurHealth(dinosaur.id, healthData));
// If health is critical, report alert
if (healthData.status === 'critical') {
yield put(alertHealthIssue(dinosaur.id, healthData));
}
}
// Wait 5 minutes before next check
yield delay(5 * 60 * 1000);
} catch (error) {
console.error('Health monitoring error:', error);
yield put(monitoringError(error));
// Wait 1 minute before retrying
yield delay(60 * 1000);
}
}
}2. Effect Hooks (React Query, SWR)
// React Query hook for managing dinosaur health data
function useDinosaurHealth(dinosaurId) {
return useQuery(
['dinosaurHealth', dinosaurId],
() => api.fetchDinosaurHealth(dinosaurId),
{
// Refresh data every 1 minute
refetchInterval: 60 * 1000,
// React to health changes
onSuccess: (data) => {
if (data.status === 'critical') {
notifyHealthIssue(dinosaurId, data);
}
}
}
);
}
// In a component
function DinosaurMonitor({ dinosaurId }) {
const { data, isLoading, error } = useDinosaurHealth(dinosaurId);
if (isLoading) return <Loading />;
if (error) return <Error message={error.message} />;
return (
<div className={`health-status ${data.status}`}>
<h2>Dinosaur health: {data.status}</h2>
<div>Temperature: {data.temperature}Β°C</div>
<div>Heart rate: {data.heartRate} BPM</div>
<div>Updated: {formatTime(data.timestamp)}</div>
</div>
);
}Testing Large Applications
In large projects, comprehensive testing is crucial. Here are the levels of testing to consider:
1. Unit Tests
Testing individual modules in isolation:
// Testing the checkVitalSigns function from dinosaurHealthMonitor
describe('dinosaurHealthMonitor', () => {
describe('checkVitalSigns', () => {
it('should correctly identify healthy dinosaurs', () => {
const healthyDino = {
id: 'trex1',
temperature: 38,
heartRate: 70,
bloodOxygen: 95
};
const result = checkVitalSigns(healthyDino);
expect(result.status).toBe('healthy');
expect(result.issues).toHaveLength(0);
});
it('should detect high temperature', () => {
const feverishDino = {
id: 'trex1',
temperature: 42, // Too high
heartRate: 70,
bloodOxygen: 95
};
const result = checkVitalSigns(feverishDino);
expect(result.status).toBe('issue');
expect(result.issues).toContain('high temperature');
});
});
});2. Integration Tests
Testing cooperation between modules:
// Testing cooperation between health module and alert module
describe('Health monitoring integration', () => {
it('should generate alerts for health issues', async () => {
// Prepare mocks
const mockAlertSystem = {
sendAlert: jest.fn()
};
const mockDinosaurData = {
id: 'raptor2',
temperature: 43, // Critically high
heartRate: 120, // Elevated
bloodOxygen: 85 // Low oxygen level
};
// Create monitoring system with mocked alert system
const healthMonitor = createHealthMonitor(mockAlertSystem);
// Call monitoring function
await healthMonitor.checkAndAlert(mockDinosaurData);
// Check if alert was sent
expect(mockAlertSystem.sendAlert).toHaveBeenCalledWith(
expect.objectContaining({
dinosaurId: 'raptor2',
severity: 'critical',
issues: expect.arrayContaining([
expect.stringMatching(/temperature/i),
expect.stringMatching(/heart rate/i),
expect.stringMatching(/oxygen/i)
])
})
);
});
});3. End-to-End Tests (E2E)
Testing complete user paths:
// E2E test of enclosure breach response process
describe('Enclosure breach response', () => {
it('should activate emergency protocol on fence failure', async () => {
// Log in as system administrator
await login('admin', 'password');
// Navigate to enclosure management panel
await navigateTo('enclosures');
// Simulate fence failure
await simulateFenceFailure('enclosure-b12');
// Check if alarm was activated
const alarmStatus = await getElement('.alarm-status');
expect(alarmStatus).toHaveClass('active');
// Check if emergency protocol was launched
const protocolStatus = await getElement('.emergency-protocol');
expect(protocolStatus.textContent).toContain('Active');
// Check if notifications were sent
const notifications = await getElements('.notification');
expect(notifications).toHaveLength(2); // To security team and management
// Simulate fence repair
await repairFence('enclosure-b12');
// Check if alarm was deactivated
const updatedAlarmStatus = await getElement('.alarm-status');
expect(updatedAlarmStatus).not.toHaveClass('active');
});
});Code Documentation
In large projects, documentation becomes essential. Here are different levels of documentation to consider:
1. Code Documentation (Comments, JSDoc)
/**
* Checks the health status of a dinosaur.
* @param {string} dinoId - The unique dinosaur identifier
* @param {Object} [options] - Additional options
* @param {boolean} [options.detailed=false] - Return detailed report
* @returns {Promise<HealthStatus>} Health status object
* @throws {DinoNotFoundError} When the dinosaur is not found
* @example
* const status = await checkHealth('TRX-001', { detailed: true });
*/
async function checkHealth(dinoId, options = {}) {
const dino = await getDinosaurById(dinoId);
if (!dino) throw new DinoNotFoundError(dinoId);
return {
healthy: dino.health > 60,
level: dino.health,
lastChecked: new Date().toISOString()
};
}2. Module Documentation (README.md)
Each module should have its own README.md file describing its functionality, interface, and usage:
# Dinosaur Health Monitoring Module
This module is responsible for monitoring and assessing the health status of dinosaurs in Jurassic Park.
## Features
- Regular checking of dinosaur vital signs
- Detecting health issues and generating alerts
- Historical health status tracking and trends
- Automatic veterinary staff notifications
## API
### `checkVitalSigns(dinosaur)`
Checks dinosaur health based on vital signs.
### `monitorHealth(dinosaurId, interval)`
Starts periodic dinosaur health monitoring.
### `stopMonitoring(dinosaurId)`
Stops dinosaur health monitoring.
## Usage Examples
~~~js
// One-time health check
const healthStatus = checkVitalSigns(dinosaur);
// Start continuous monitoring
const stopMonitoring = monitorHealth('trex1', 60000); // every minute
// Stop monitoring
stopMonitoring();Integration with Other Modules
This module uses:
- Sensor system APIs (src/modules/sensors)
- Alert system (src/modules/alerts)
Used by:
- Park management dashboard (src/modules/dashboard)
- Security system (src/modules/security)
### 3. Architecture Documentation (Diagrams, ADR)
Documenting architectural decisions is crucial for understanding why the system was designed a certain way. Helpful tools include:
- **Architecture diagrams** (C4, UML)
- **Architecture Decision Records (ADR)** - documents describing important architectural decisions, their context, and consequences
~~~text
# ADR 001: Choosing Redux as the State Management System
## Context
The Jurassic Park management application needs a state management mechanism that handles:
- Complex global state (dinosaur data, enclosures, visitors)
- Asynchronous operations (communication with park systems)
- State change history tracking (security audit)
## Decision
We decided to use Redux with Redux Toolkit and Redux Saga as the main state management mechanism.
## Rationale
- **Predictability**: Redux ensures unidirectional data flow
- **Middleware**: Redux Saga simplifies managing complex async operations
- **DevTools**: Redux developer tools facilitate debugging
- **Ecosystem**: Rich ecosystem of libraries and tools
- **Time Travel Debugging**: Ability to track state change history
## Consequences
### Positive
- Clear data flow in the application
- Easier debugging of state issues
- Ability to audit user actions
### Negative
- Increased amount of code (actions, reducers, selectors)
- Higher learning curve for new team members
- Potential performance overhead if used improperlyBest Practices for Large JavaScript Projects
1. Establish Coding Standards
Define and enforce coding standards using tools like ESLint, Prettier:
// .eslintrc.json
{
"extends": [
"eslint:recommended",
"plugin:react/recommended"
],
"rules": {
"react/prop-types": "error",
"no-unused-vars": "error",
"no-console": ["warn", { "allow": ["warn", "error"] }],
"prefer-const": "error"
}
}2. Use Typing (TypeScript, PropTypes)
// typescript
interface DinosaurVitalSigns {
id: string;
temperature: number;
heartRate: number;
bloodOxygen: number;
}
interface HealthAssessment {
status: 'healthy' | 'issue' | 'critical';
issues: string[];
lastChecked: Date;
}
function checkVitalSigns(dinosaur: DinosaurVitalSigns): HealthAssessment {
// implementation...
}3. Automate Tests and Deployments (CI/CD)
Set up CI/CD pipelines that automatically run tests, static code analysis, and deploy the application:
# .github/workflows/ci.yml
name: CI/CD
on:
push:
branches: [ main, develop ]
pull_request:
branches: [ main, develop ]
jobs:
test:
runs-on: ubuntu-latest
steps:
- uses: actions/checkout@v2
- name: Set up Node.js
uses: actions/setup-node@v2
with:
node-version: '14'
- name: Install dependencies
run: npm ci
- name: Run tests
run: npm test
- name: Run linting
run: npm run lint
- name: Build
run: npm run build
deploy:
needs: test
if: github.ref == 'refs/heads/main'
runs-on: ubuntu-latest
steps:
- uses: actions/checkout@v2
# ... deployment steps4. Use Code Reviews
Establish a Code Review process that ensures code is reviewed by at least one other developer before merging into the main branch.
5. Monitor Performance
Implement application performance monitoring to quickly detect and fix issues:
// Example custom performance monitoring tool configuration
const performanceMonitor = {
eventTiming: {},
startTiming(eventName) {
this.eventTiming[eventName] = {
start: performance.now()
};
},
endTiming(eventName) {
if (this.eventTiming[eventName]) {
const start = this.eventTiming[eventName].start;
const duration = performance.now() - start;
// Log to monitoring server
logPerformanceMetric(eventName, duration);
// Generate alert if operation took too long
if (duration > performanceThresholds[eventName]) {
alertPerformanceIssue(eventName, duration);
}
delete this.eventTiming[eventName];
}
}
};
// Usage
function loadDinosaurData(id) {
performanceMonitor.startTiming('loadDinosaurData');
return fetchDinosaurData(id)
.then(data => {
performanceMonitor.endTiming('loadDinosaurData');
return data;
})
.catch(error => {
performanceMonitor.endTiming('loadDinosaurData');
throw error;
});
}Summary
Structuring code in larger JavaScript projects is a complex topic requiring a thoughtful approach. Key aspects are:
- Folder/file organization - choosing the right structure depending on project size and nature
- Application architecture - defining how different parts of the application interact
- Code modularization - splitting code into smaller, cohesive modules with clear responsibilities
- Import management - maintaining readable and efficient imports
- State management - choosing the right approach for managing state
- Side effect management - organizing async operations and other side effects
- Testing - implementing a comprehensive testing strategy
- Documentation - ensuring well-documented code and architecture
By following these principles, you can avoid the chaos that might lead to a "catastrophe" in your JavaScript project - just as proper organization and management would have helped avoid the catastrophe in Jurassic Park!
Code for this lesson: main.js
// ES Modules in the browser - Jurassic Park
console.log("ES Modules in the Browser\n");
// Demo of <script type="module">
console.log("=== HTML Example ===\n");
console.log(`<!DOCTYPE html>
<html>
<head>
<title>Jurassic Park</title>
</head>
<body>
<!-- ES Module in the browser -->
<script type="module">
import { Dinosaur } from './dinosaur.js';
const rex = new Dinosaur('Rex');
console.log(rex);
</script>
<!-- Fallback for old browsers -->
<script nomodule>
console.log('Your browser does not support ES Modules');
</script>
</body>
</html>`);
// Dynamic import in the browser
console.log("\n=== Dynamic Import ===\n");
async function loadDinosaurModule() {
try {
console.log("β³ Loading module...");
// Simulated dynamic import
const module = {
Dinosaur: class {
constructor(name) {
this.name = name;
}
}
};
console.log("Module loaded!");
const dino = new module.Dinosaur('Blue');
console.log("Created:", dino);
} catch (error) {
console.error("Loading error:", error);
}
}
loadDinosaurModule();
// Import maps
console.log("\n=== Import Maps ===\n");
console.log(`<script type="importmap">
{
"imports": {
"dinosaurs": "/modules/dinosaurs.js",
"security": "/modules/security.js",
"lodash": "https://cdn.skypack.dev/lodash"
}
}
</script>
<script type="module">
// Now we can use aliases
import { Dinosaur } from 'dinosaurs';
import { Security } from 'security';
import _ from 'lodash';
</script>`);
console.log("\nES Modules in the browser:");
console.log("Native support (no bundler)");
console.log("Automatic defer");
console.log("Strict mode by default");
console.log("Import maps for aliases");
console.log("\nModern browsers = native modules!");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. What is the difference between type-based and feature-based project organization?
Hands-on tasks in the game
- Code editor
Create a modular structure with separation of concerns and a clear API for each module.