Tips for writing clean code

by Posted on January 22, 2024

Descriptive naming: Use meaningful names for variables, functions, and classes that convey their purpose. Avoid single-letter names or abbreviations that aren’t obvious.

// Bad
const x = getData();
const y = processIt(x);

// Good
const userData = fetchUserInformation();
const processedUser = generateUserReport(userData);


Whitespace and formatting: Use whitespace (spaces, tabs, newlines) to visually organize code and improve readability. Follow consistent indentation and formatting conventions for your language.

// Bad
if(condition){doSomething(x);}else{doSomethingElse(y);}

// Good
if (condition) {
  doSomething(x);
} else {
  doSomethingElse(y);
}


Comments: Explain non-obvious logic, complex algorithms, or unusual code constructs. Use comments to clarify intent, not to restate what the code already says.

// Bad

// This function does stuff
function doStuff() {
  // More stuff here
  return something;
}

// Good

// Calculates the average of a list of numbers
function calculateAverage(numbers) {
  // Sum all the numbers
  const sum = numbers.reduce((acc, num) => acc + num, 0);

  // Divide the sum by the number of elements
  return sum / numbers.length;
}



Small functions: Break down large functions into smaller, more manageable ones that each perform a single, well-defined task.

// Bad
function processAndDisplayData(data) {
  const processedData = filterData(data);
  const formattedData = formatData(processedData);
  displayData(formattedData);
}

// Good
function filterData(data) {
  // ... filtering logic ...
  return filteredData;
}

function formatData(data) {
  // ... formatting logic ...
  return formattedData;
}

function displayData(data) {
  // ... display logic ...
}

processAndDisplayData(data);



Single Responsibility Principle: Each function or class should have a single, clear responsibility. Avoid functions that do multiple unrelated things.

Coding style: Follow consistent coding conventions for naming, formatting, indentation, and commenting. This makes code more predictable and easier to read for both you and others.

Simple expressions: Favor simple, straightforward expressions over overly complex or clever ones. Avoid excessive nesting of conditional statements and loops.

Early returns: Exit functions as soon as possible if certain conditions are met, rather than nesting multiple conditional blocks.

// Bad
if (error) {
  console.error('Error:', error);
  return undefined;
}

// More code here

// Good
if (error) {
  console.error('Error:', error);
  return;
}

// More code here



Write unit tests: Write unit tests to verify the correctness of individual code units and catch bugs early in the development process.

Improve existing code: Regularly refactor your code to improve its readability, maintainability, and performance. Focus on simplifying logic, removing redundant code, and optimizing algorithms.

Plan before coding: Think about the overall structure of your code before starting to write. This can help you avoid complex logic and make your code more modular.

Use version control: Use a version control system like Git to track changes to your code and revert to previous versions if necessary.
Seek feedback: Get feedback from other developers on your code to identify areas for improvement.

Remember: Clean code is not just about aesthetics—it’s about making code easier to understand, maintain, and extend. By following these tips, you can write code that is more readable, efficient, and less prone to errors.