Sign Up

Sign Up to our social questions and Answers Engine to ask questions, answer people’s questions, and connect with other people.

Have an account? Sign In

Have an account? Sign In Now

Sign In

Login to our social questions & Answers Engine to ask questions answer people’s questions & connect with other people.

Sign Up Here

Forgot Password?

Don't have account, Sign Up Here

Forgot Password

Lost your password? Please enter your email address. You will receive a link and will create a new password via email.

Have an account? Sign In Now

Sorry, you do not have permission to ask a question, You must login to ask a question.

Forgot Password?

Need An Account, Sign Up Here

Please type your username.

Please type your E-Mail.

Please choose an appropriate title for the post.

Please choose the appropriate section so your post can be easily searched.

Please choose suitable Keywords Ex: post, video.

Browse

Need An Account, Sign Up Here

Please briefly explain why you feel this question should be reported.

Please briefly explain why you feel this answer should be reported.

Please briefly explain why you feel this user should be reported.

Sign InSign Up

Querify Question Shop: Explore Expert Solutions and Unique Q&A Merchandise

Querify Question Shop: Explore Expert Solutions and Unique Q&A Merchandise Logo Querify Question Shop: Explore Expert Solutions and Unique Q&A Merchandise Logo

Querify Question Shop: Explore Expert Solutions and Unique Q&A Merchandise Navigation

  • Home
  • About Us
  • Contact Us
Search
Ask A Question

Mobile menu

Close
Ask a Question
  • Home
  • About Us
  • Contact Us
Home/ Questions/Q 2497

Querify Question Shop: Explore Expert Solutions and Unique Q&A Merchandise Latest Questions

Author
  • 61k
Author
Asked: November 26, 20242024-11-26T05:57:07+00:00 2024-11-26T05:57:07+00:00

Software Engineering Principles Every Frontend Developer Should Know

  • 61k

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; 
Enter fullscreen mode Exit fullscreen mode

// 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; 
Enter fullscreen mode Exit fullscreen mode

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; 
Enter fullscreen mode Exit fullscreen mode

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; 
Enter fullscreen mode Exit fullscreen mode

// 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; 
Enter fullscreen mode Exit fullscreen mode

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)); }; 
Enter fullscreen mode Exit fullscreen mode

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.

frontendreactsoftwareengineeringwebdev
  • 0 0 Answers
  • 0 Views
  • 0 Followers
  • 0
Share
  • Facebook
  • Report

Leave an answer
Cancel reply

You must login to add an answer.

Forgot Password?

Need An Account, Sign Up Here

Sidebar

Ask A Question

Stats

  • Questions 4k
  • Answers 0
  • Best Answers 0
  • Users 2k
  • Popular
  • Answers
  • Author

    Insights into Forms in Flask

    • 0 Answers
  • Author

    Kick Start Your Next Project With Holo Theme

    • 0 Answers
  • Author

    Refactoring for Efficiency: Tackling Performance Issues in Data-Heavy Pages

    • 0 Answers

Top Members

Samantha Carter

Samantha Carter

  • 0 Questions
  • 20 Points
Begginer
Ella Lewis

Ella Lewis

  • 0 Questions
  • 20 Points
Begginer
Isaac Anderson

Isaac Anderson

  • 0 Questions
  • 20 Points
Begginer

Explore

  • Home
  • Add group
  • Groups page
  • Communities
  • Questions
    • New Questions
    • Trending Questions
    • Must read Questions
    • Hot Questions
  • Polls
  • Tags
  • Badges
  • Users
  • Help

Footer

Querify Question Shop: Explore Expert Solutions and Unique Q&A Merchandise

Querify Question Shop: Explore, ask, and connect. Join our vibrant Q&A community today!

About Us

  • About Us
  • Contact Us
  • All Users

Legal Stuff

  • Terms of Use
  • Privacy Policy
  • Cookie Policy

Help

  • Knowledge Base
  • Support

Follow

© 2022 Querify Question. All Rights Reserved

Insert/edit link

Enter the destination URL

Or link to existing content

    No search term specified. Showing recent items. Search or use up and down arrow keys to select an item.