RSS Amplifier

ghack.dev · Jul 27, 2024

#SoftwareEngineeringHack - Clean Code Cheatsheet - S1E1

0
Sign in to vote or save

Galih Laras Prakoso · ghack.dev

Hello hackers! Today, I’m going to share with you one of the most valuable cheat sheets that you can reference every time you write your code to ensure you follow the principles of writing clean code.

Clean code makes your life easier. Writing clean code increases the readability of your code, making it easier to maintain, debug, and understand. New collaborators can contribute more easily, technical debt is reduced, and your productivity will significantly increase. There are many other benefits to writing cleaner code.

This content is based on “Clean Code: A Handbook of Agile Software Craftsmanship” by Robert C. Martin (Uncle Bob).

This cheat sheet is designed to be a simple reference that you can easily scan and implement. I hope it will serve as a quick guide to help you write cleaner code.

  • Use meaningful Names

    • Avoid misleading names.

    • Name should reveal the intent.

  • Avoid Disinformation

    • Avoid using names that could be misinterpreted.

  • Pronounceable Names

    • Use names that are easy to say.

  • Searchable Names

    • Use names that are easy to search for.

  • Avoid Encodings

    • Don’t include types in names (e.g `int` in `intValue`).

let d // What does 'd' stand for?
let daysUntilDeadline; // Clearly indicates the meaning
  • Small Functions

    • Functions should be small, ideally 5-10 lines.

  • Do One Thing

    • Each function should do one thing and do it well.

  • Descriptive Names

    • Function names should explain what they do.

  • Few Arguments

    • Aim for zero to two arguments; three is acceptable but avoid more.

  • Command Query Separation

    • Functions should either do something (command) or answer something (query), but not both.

function process() {
  // This function does many unrelated things
  fetchData();
  calculateResults();
  renderUI();
}
function fetchData() {
  // Fetch data from the server
}
function calculateResults() {
  // Perform calculations on the data
}
function renderUI() {
  // Render the user interface
}
  • Good Comments

    • Use comments to explain why something is done, not what is done.

    • Use comments to clarify the intent of the code.

  • Bad Comments

    • Avoid redundant comments.

    • Avoid misleading comments.

    • Avoid commented-out code.

// Increment i by 1
i = i + 1;
// Adjust the counter to account for the newly added item
i = i + 1;
  • Consistent Indentation

    • Use consistent indentation throughout the codebase.

  • Vertical Density

    • Group related lines of code together.

  • Horizontal Spacing

    • Use spaces to make code readable, e.g., around operators.

if (a){b();}
else if (c){d();}
else{e();}
if (a) {
    b();
} else if (c) {
    d();
} else {
    e();
}
  • Hide Implementation Details

    • Objects should hide their implementation details.

  • Data/Object Anti-Symmetry

    • Objects expose behavior, while data structures expose data.

  • Law of Demeter

    • A method should only call methods of:

      • The object itself.

      • Objects passed as arguments.

      • Objects it creates.

public class Rectangle {
    public int width;
    public int height;
}
public class Rectangle {
    private int width;
    private int height;
    public int getWidth() {
        return width;
    }
    public int getHeight() {
        return height;
    }
}
  • Use Exceptions

    • Prefer exceptions over error codes.

  • Define Exception Classes

    • Create specific exception classes for different error types.

  • Don’t Return Null

    • Avoid returning null from methods; use exceptions or special case objects instead.

if (result == -1) {
    // Handle error
}
try {
    process();
} catch (Exception e) {
    // Handle exception
}
  • Single Responsibility Principle (SRP)

    • A class should have only one reason to change.

  • Open/Closed Principle (OCP)

    • Classes should be open for extension but closed for modification.

  • Liskov Substitution Principle (LSP)

    • Subclasses should be substitutable for their base classes.

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

class Manager {
    void calculate() {
        // Logic for calculation
    }
    void printReport() {
        // Logic for printing report
    }
}
class Calculator {
    void calculate() {
        // Logic for calculation
    }
}
class ReportPrinter {
    void printReport() {
        // Logic for printing report
    }
}
  • Automate Tests

    • Write automated tests for your code.

  • Test-Driven Development (TDD)

    • Write tests before writing the code.

  • Clean Tests

    • Tests should be readable, maintainable, and fast.

def add(a, b):
    return a + b
assert add(2, 3) == 5  # This is a manual test, not part of an automated test suite
def add(a, b):
    return a + b
def test_add():
    assert add(2, 3) == 5  # This is part of an automated test suite
  • Keep It Simple (KISS)

    • Avoid over-engineering. Simple solutions are often better.

  • Separation of Concerns

    • Different concerns should be separated into different modules.

  • Dependency Injection

    • Use dependency injection to decouple components.

def process_data():
    # Open file, read data, process data, save file
def read_data_from_file():
    # Open and read file
def process_data():
    # Process data
def save_data_to_file():
    # Save data to file
  • Duplicated Code

    • Avoid code duplication.

  • Long Methods

    • Methods should be short.

  • Large Classes

    • Classes should be small.

  • Excessive Use of Primitives

    • Use meaningful abstractions instead of raw data types.

  • Switch Statements

    • Replace switch statements with polymorphism.

def calculate_total(price, tax, discount, shipping, handling):
    return price + tax - discount + shipping + handling
def calculate_total(price, tax, discount, shipping, handling):
    total = price + tax
    total -= discount
    total += shipping
    total += handling
    return total
  • YAGNI (You Aren’t Gonna Need It)

    • Don’t add functionality until it’s necessary.

  • DRY (Don’t Repeat Yourself)

    • Avoid duplication of code.

  • SOLID Principles

    • Follow SOLID principles for object-oriented design.

# Adding an unused feature 'just in case'
def calculate(x, y, z=None):
    if z:
        return x + y + z
    return x + y
# Only implement what is needed
def calculate(x, y):
    return x + y

Writing clean code is not just a best practice but a necessity for any developer aiming to produce maintainable, efficient, and high-quality software. By adhering to the principles outlined in this cheat sheet, you can improve the readability, maintainability, and overall quality of your code, making your development process smoother and more productive.

I hope you find this cheat sheet useful. Feel free to leave your thoughts, comments, and questions below. If you enjoyed this content and want to stay updated with more tips and guides, please like, comment, and subscribe to my Substack blog. Happy coding!

Read the original on ghackdev.substack.com

Comments

Nothing yet. Say the first thing.

    Sign in to join the conversation.