Software Engineering Principles Every Frontend Developer Should Know
Tags: react, webdev, softwareengineering, frontend
Published: 2024-05-12 12:21:26

As frontend developers, we often focus on creating beautiful user interfaces. However, it's essential to remember that beauty also lies on the inside and the pixel-perfect approach should translate to our code organization and structure as well. In this article, we'll explore some fundamental software engineering principles that every frontend developer should know and apply in their projects.

## 1. DRY (Don't Repeat Yourself)

The DRY principle emphasizes the importance of code reusability and maintenance. Avoid duplicating code by extracting common functionalities into reusable components, functions, or modules. By adhering to the DRY principle, you can reduce code duplication, improve maintainability, and make your codebase more modular. React encourages a component-driven architecture where responsibilities are segregated for easy development and scalability in the future.

Let's take a products page from a simple E-Commerce application for example. We expect to see a list of products for sale. We can break down the page into smaller, reusable components.

Components:

1. ProductCard: Displays a single product with its name, price, and description.
2. ProductList: Displays a list of products.

```javascript
// ProductCard.js
import React from 'react';

const ProductCard = ({ product }) => {
  return (
    <div>
      <h2>{product.name}</h2>
      <p>Price: ${product.price}</p>
      <p>Description: {product.description}</p>
    </div>
  );
};

export default ProductCard;
```

```javascript
// ProductList.js
import React, { useState } from 'react';
import ProductCard from './ProductCard';

const ProductList = () => {
  const [products, setProducts] = useState([
    { id: 1, name: 'Product 1', price: 9.99, description: 'Description 1' },
    { id: 2, name: 'Product 2', price: 19.99, description: 'Description 2' },
    // ...
  ]);

  return (
    <div>
      {products.map((product) => (
        <ProductCard key={product.id} product={product} />
      ))}
    </div>
  );
};

export default ProductList;
```

In this example, we see that by segregating the logic concerning a product into the `ProductCard` component, we can re-use this in the `map` functionality in the `ProductList` component and avoid duplicated code for every product item in the List page.


## 2. SOLID Principles

SOLID is an acronym representing five key principles of object-oriented design:

- **S**ingle Responsibility Principle (SRP): Each module or class should have only one reason to change.
- **O**pen/Closed Principle (OCP): Software entities should be open for extension but closed for modification.
- **L**iskov Substitution Principle (LSP): Subtypes should be substitutable for their base types without altering the correctness of the program.
- **I**nterface Segregation Principle (ISP): Clients should not be forced to depend on interfaces they don't use.
- **D**ependency Inversion Principle (DIP): High-level modules should not depend on low-level modules. Both should depend on abstractions.

Let's take a look at how we can apply the Liskov Substitution Principle (LSP) in a React TypeScript component:

```typescript
// Vehicle.ts
interface Vehicle {
  drive(): void;
  name: string;
}

// Car.ts
class Car implements Vehicle {
  constructor(private name: string) {
    this.name = name;
  }

  drive(): void {
    console.log(`Driving a ${this.name}`);
  }
}

// Motorcycle.ts
class Motorcycle implements Vehicle {
  constructor(private name: string) {
    this.name = name;
  }

  drive(): void {
    console.log(`Riding a ${this.name}`);
  }
}

// App.tsx
import React from 'react';
import { Vehicle } from './Vehicle';
import Car from './Car';
import Motorcycle from './Motorcycle';

function VehicleComponent(props: { vehicle: Vehicle }) {
  props.vehicle.drive();
  return <div>Driving a {props.vehicle.name}</div>;
}

const App = () => {
  const car = new Car();
  const motorcycle = new Motorcycle();

  return (
    <div>
      <VehicleComponent vehicle={car} />
      <VehicleComponent vehicle={motorcycle} />
    </div>
  );
};

export default App;
```

In this example, we have a `Vehicle` interface that defines the `name` attribute and `drive` method. We then have two concrete implementations: `Car` and `Motorcycle`, which both implement the `Vehicle` interface.

In the App component, we create instances of `Car` and `Motorcycle` and pass them to the VehicleComponent. The `VehicleComponent` calls the drive method on the passed-in vehicle object.

The LSP ensures that we can substitute `Car` or `Motorcycle` for the `Vehicle` interface without altering the correctness of the program. The `VehicleComponent` works seamlessly with both `Car` and `Motorcycle` instances, demonstrating the substitutability of subtypes for their base types.


## 3. KISS (Keep It Simple, Stupid)

The KISS principle advocates for simplicity in design and implementation. Write code that is easy to understand, straightforward, and does one thing well. Avoid unnecessary complexity and over-engineering, as it can lead to confusion and maintenance challenges in the long run.

Let's look at 2 implementations of a `Counter` component.

```javascript
// Complex Counter
import React, { useState, useEffect } from 'react';
import { debounce } from 'lodash';

const ComplexCounter = () => {
  const [count, setCount] = useState(0);
  const [clicked, setClicked] = useState(false);
  const [error, setError] = useState(null);

useEffect(() => {
	if (clicked) {
		setCount(prev => prev + 1)
		setClicked(false)
	}
}, [clicked, setClicked]);

  const handleClick = (clicked: boolean) => {
    setClicked(!clicked);
  };

  return (
    <div>
      <p>Count: {count}</p>
      <button onClick={() => handleClick(clicked)}>Increment</button>
    </div>
  );
};

export default ComplexCounter;
```

```javascript
// Simple Counter
import React, { useState } from 'react';

const SimpleCounter = () => {
  const [count, setCount] = useState(0);

  const handleClick = () => {
    setCount(count + 1);
  };

  return (
    <div>
      <p>Count: {count}</p>
      <button onClick={handleClick}>Increment</button>
    </div>
  );
};

export default SimpleCounter;
```

We see that the `ComplexCounter` implementation is harder to understand and maintain and more prone to errors. 
It introduced an unnecessary state variable for `clicked` and a `useEffect` hook.
It's an example of how not to implement a React component.


## 4. YAGNI (You Aren't Gonna Need It)

YAGNI reminds us to avoid adding functionality prematurely based on speculative future requirements. Instead, focus on correctly implementing the features that are currently needed.  This becomes very important when you are building a very user-centric product. It would be best if you tried not to introduce new features on the assumption of what you think users might want. Utilize a proper user research framework and prototyping methods instead. 
By following YAGNI, you can prevent unnecessary complexity, reduce development time, and maintain a lean codebase.

## 5. Clean Code

Clean code is readable, understandable, and maintainable. Follow coding conventions and best practices, use meaningful variable names, and write self-explanatory code. Keep functions and classes small and focused, adhere to consistent formatting, and strive for clarity in your codebase.

Let's take a simple utility function used to conceal parts of a user's private information for Data Security purposes.

```typescript
const hashUsersPrivateInformation = (privateInformation: string): string => {
  // Calculate the length of the private info to determine how many characters to mask
  const maxLength = privateInformation.length > 4 ? privateInformation.length - 4 : privateInformation.length;
// Create a regular expression pattern to match the desired number of characters
  const regexPattern = `.{1,${maxLength}}`;
  const regex = new RegExp(regexPattern);

  return privateInformation.replace(regex, (match) => '*'.repeat(match.length));
};
```

We see that:
1. The function's name is self-descriptive
2. It includes useful comments to help other developers.
3. It has a primary purpose that is understandable. 

We should aim to structure our code similarly.

## Conclusion

Incorporating these software engineering principles into your front-end development workflow allows you to write better-quality code, improve collaboration with team members, and build robust and scalable applications. Software engineering is not just about writing code; it's about creating reliable, maintainable, and elegant solutions to complex problems.