Lädt...


🔧 Software Engineering Principles Every Frontend Developer Should Know


Nachrichtenbereich: 🔧 Programmierung
🔗 Quelle: dev.to

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.
// 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;
// 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:

  • Single Responsibility Principle (SRP): Each module or class should have only one reason to change.
  • Open/Closed Principle (OCP): Software entities should be open for extension but closed for modification.
  • Liskov Substitution Principle (LSP): Subtypes should be substitutable for their base types without altering the correctness of the program.
  • Interface Segregation Principle (ISP): Clients should not be forced to depend on interfaces they don't use.
  • Dependency 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:

// 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.

// 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;
// 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.

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.

...

🔧 Software Engineering Principles Every Frontend Developer Should Know


📈 66.19 Punkte
🔧 Programmierung

🔧 Software Engineering Principles Every backend Developer Should Know


📈 54.79 Punkte
🔧 Programmierung

🔧 10 Microservices Design Principles That Every Developer Should Know


📈 42.46 Punkte
🔧 Programmierung

🔧 8 Design Principles that every Ruby Developer should know


📈 42.46 Punkte
🔧 Programmierung

🔧 CSS techniques every frontend developer should know in 2024


📈 40.37 Punkte
🔧 Programmierung

🔧 5 Chrome Extensions Every Frontend Developer Should Know About


📈 40.37 Punkte
🔧 Programmierung

🔧 The Principles and Laws of UX Design – Why Every Designer Should Know Them


📈 35.69 Punkte
🔧 Programmierung

📰 Protecting Customer Data: Key Principles Every Company Should Know


📈 35.69 Punkte
📰 IT Security Nachrichten

🎥 Engineering Empathy: Adapting Software Engineering Principles and Process to Security


📈 33.96 Punkte
🎥 IT Security Video

🔧 Amazing UI Libraries Every Frontend Developer Must Know


📈 33.81 Punkte
🔧 Programmierung

🔧 5 Best Practices Every Frontend Developer Should Follow


📈 33.64 Punkte
🔧 Programmierung

🔧 Essential Skills Every Aspiring Frontend Developer Should Learn


📈 33.64 Punkte
🔧 Programmierung

🔧 13 VS Code extensions that every Frontend developer should have


📈 33.64 Punkte
🔧 Programmierung

🔧 Legal Templates Every Software Developer Should Know


📈 33.17 Punkte
🔧 Programmierung

🔧 Top Data Engineering Tools Every Professional Should Know


📈 30.35 Punkte
🔧 Programmierung

🔧 Frontend Developer or Software Developer : which one to choose and why?🤔


📈 29.13 Punkte
🔧 Programmierung

🕵️ The Top Cybersecurity Principles Every Board Member Must Know


📈 29.13 Punkte
🕵️ Hacking

📰 NACD Publishes Five Cybersecurity Principles Every Board Director Needs to Know


📈 29.13 Punkte
📰 IT Security Nachrichten

🔧 Free and Paid API Resources Every Developer Should Know


📈 28.97 Punkte
🔧 Programmierung

🔧 JavaScript ES6 Features Every Developer Should Know


📈 28.97 Punkte
🔧 Programmierung

🔧 10 JavaScript Super Hacks Every Developer Should Know


📈 28.97 Punkte
🔧 Programmierung

🔧 Some Code Tricks Every Web Developer Should Know


📈 28.97 Punkte
🔧 Programmierung

🔧 7 Essential JavaScript Unit Testing Frameworks Every Developer Should Know ✅


📈 28.97 Punkte
🔧 Programmierung

🔧 JavaScript tricks 🤯 that every developer should know


📈 28.97 Punkte
🔧 Programmierung

🔧 Top 3 JavaScript Concepts Every Developer Should Know 🚀


📈 28.97 Punkte
🔧 Programmierung

🔧 Essential Git Commands Every Developer Should Know


📈 28.97 Punkte
🔧 Programmierung

🔧 Top 10 AI Tools Every Developer Should Know About


📈 28.97 Punkte
🔧 Programmierung

🔧 Top 10 Backend Frameworks Every Developer Should Know


📈 28.97 Punkte
🔧 Programmierung

🔧 Scripting vs. Programming Languages: Uncover the Key Differences Every Developer Should Know!


📈 28.97 Punkte
🔧 Programmierung

🔧 Mastering Python: 6 Sneaky Tips Every Developer Should Know


📈 28.97 Punkte
🔧 Programmierung

🔧 5 building blocks of blockchain every developer should know


📈 28.97 Punkte
🔧 Programmierung

🔧 🛠️ Streamline Your Workflow: 10 Essential Command-Line Tools Every Developer Should Know🚀💻


📈 28.97 Punkte
🔧 Programmierung

🔧 VS Code settings that every front-end developer should know


📈 28.97 Punkte
🔧 Programmierung

matomo