Share 3 principles for writing better code for front-end beginners

6e1faebb20b1919949fa424d4ac0626a.jpeg

As a beginner, you probably don't think much about coding style. Adopting the following three principles can immediately improve the quality of your code.

de1ac3905c07048c06955587f97c0eab.jpeg

Over the past few months, I've had the opportunity to mentor a group of talented new web developers who are enrolled in TechLabs' Digital Shapers program.

It was so interesting to watch the learning process of this team from scratch to finally release the application. When I review their code, it reminds me of my first few years as a developer. Especially when you are self-taught without any formal educational background, you just keep trying. You cannot perceive good or bad coding practices. You'll be happy with anything that works.

Which brings me to the question: "What are the coding principles I wish I had known earlier?" Here they are!

You can implement these simple tips into your coding practice in no time. While simple, they have had a huge impact on the way I write code.

Note: Although the title clearly states "Front-End Developer," these principles apply to all areas of programming.

1. Use "early return" instead of nested conditional statements

In web development, you will come across many situations where you need to check whether a certain condition is met.

As an example, suppose you have an API route that authenticates requests and returns a user object:

export const handler = async (req, res) => {
 if (req.method === "POST" || req.method === "OPTIONS") {
  const email = validateEmail(req.body.email);
  if (email) {
   const user = getUserByEmail(email);
   if (user) {
    return res.status(200).json({ user });
   } else {
    return res.status(404).json({ message: 'No user found' });
   }
  } else {
   return res.status(422).json({ message: 'Missing email' });
  }
 } else {
  return res.status(405).json({ message: 'Unsupported message' });
 }
}

While there isn't much logic encapsulation in this function, it already looks a bit disorganized. Specifically, this code has the following two problems:

  • It's hard to keep track of code flow. We need to read code from left to right instead of top to bottom (arrow anti-pattern).

  • It's hard to find an else statement for each if. They are separated by the bulk of the if statement.

A simple trick to improve this code is to use the Return-Early-Pattern. The "early return" mode terminates the execution of the function when the condition is not met, so that the expected result of the function always comes last. If we re-write the above API route, it will look like this:

export const handler = async (req, res) => {
 if (req.method !== "POST" && !req.method !== "OPTIONS") {
  return res.status(405).json({ message: 'Unsupported message' });
 }

 const email = validateEmail(req.body.email);
 if (!email) {
  return res.status(422).json({ message: 'Missing email' });
 }

 const user = getUserByEmail(email);
 if (!user) {
  return res.status(404).json({ message: 'No user found' });
 }

 return res.status(200).json({ user });
}

After using the "early return" pattern, we can easily trace code execution from top to bottom. Since we assume all goes well and only check for missing values, this avoids nesting too many conditions.

Finally, we can see at a glance the expected result of the function, which is at the very bottom.

2. Writing code for humans

Distilling the content of the previous tip, we get to the second principle: write code that is easy for other people to read, not for machines.

It sounds mundane, but at first it completely changed the way I thought. When I started programming, I always saw it as a way to communicate with the computer. We tell the computer what to do. But the code we write is read and understood by colleagues, not machines.

Our colleagues are people who need to read and understand code. Ultimately, the computer converts everything to 0s and 1s and doesn't care about readability. Let's take the groupBy function as an example:

const groupBy = (arr, groupFn) =>
  arr.reduce(
    (grouped, obj) => ({
      ...grouped,
      [groupFn(obj)]: [...(grouped[groupFn(obj)] || []), obj],
    }),
    {}
  );

We clearly show how to write complex one-line functions to perform a simple operation: grouping an array.

While this might make you feel more professional, it does make things more difficult for anyone who needs to review the code. In contrast, consider the following implementation:

const groupBy = (arr, groupFn) => {
  const grouped = {};
  for (const obj of arr) {
    const groupName = groupFn(obj);
    if (!grouped[groupName]) {
      grouped[groupName] = [];
    }
    grouped[groupName].push(obj);
  }
  return grouped;
};

We can read this code from top to bottom and immediately understand what each line of code does.

While this may not look as cool as the previous implementation, anyone who needs to revisit this code in the future will thank you for the easy-to-read implementation.

3. Hide information behind functions

As a junior developer, one final thought for improving your code style is to hide irrelevant information behind functions. This also helps with code readability.

If you're familiar with React, Hooks are a great example of this principle:

import React, { useState, useEffect } from 'react';

function FriendListItem(props) {
  const [isOnline, setIsOnline] = useState(null);

  useEffect(() => {
    function handleStatusChange(status) {
      setIsOnline(status.isOnline);
    }
    
  ChatAPI.subscribeToFriendStatus(props.friend.id, handleStatusChange);
  return () => {
      ChatAPI.unsubscribeFromFriendStatus(props.friend.id, handleStatusChange);
    };
  });

  return (
    <li style={
    
    { color: isOnline ? 'green' : 'black' }}>
      {props.friend.name}
    </li>
  );
}

Here we have a component that outputs a list item with a dynamic state color. While this code works fine, it encapsulates logic that is not directly related to the purpose of the FriendListItem component.

If we extract that logic and create a custom Hook called useFriendStatus, we can simplify the component as follows:

import React, { useState, useEffect } from 'react';

function FriendListItem(props) {
  const isOnline = useFriendStatus(props.friend.id);

  return (
    <li style={
    
    { color: isOnline ? 'green' : 'black' }}>
      {props.friend.name}
    </li>
  );
}

This has two advantages:

  • We can reuse the logic of useFriendStatus.

  • We reduce components to the essence of their functionality.

More generally, the principle of hiding information is to encapsulate irrelevant information behind abstract functions.

Therefore, we don't need to care about what happens inside the abstract function (implementation detail) - we can focus more on its purpose, which is the name of the function (problem domain level).

Summarize

I hope these little tips are helpful to you! In essence, writing better code is often just making it easier to read and understand, both for yourself and for others.

Original:
https://konstantinmuenster.medium.com/3-tips-to-write-better-code-as-a-beginner-frontend-developer-ea0fe9b3492c

作地:Konstantin Münster

Indirect translation, some self-adapted and added parts, the translation level is limited, it is inevitable that there are omissions, welcome to correct

Guess you like

Origin blog.csdn.net/Ed7zgeE9X/article/details/130023019