Ugo's Blog


5 Tips to Writing Better Code

5 Useful Tips That Help You To Improve The Way You Code

Author: Ugochukwu E. Nwachukwu
 Aug. 3, 2023    219 views  


The content of this blog post is for informational purposes only and should not be considered as professional advice or endorsement.




Writing code is good. But writing good, clean code is an art form that elevates programming to a new level.   Good code is beautiful to look at. It is easy to understand and debugging.

 

Here are 5 things you can do to make your code better:

 

 

1. Write Modular code

Modular code refers to a programming practice where a large and complex program is broken down into smaller, self-contained units of functionality, known as modules.

 

Each module serves a specific purpose and can be independently developed, tested, and maintained. These modules can then be combined to create the complete program, promoting code reusability, readability, and maintainability.

 

Each function needs to serve its unique purpose. Dividing a big task into smaller tasks and putting them into separate functions/methods makes it easy to understand.

 

 

2. Follow Consistent Naming Conventions.

Choose a specific naming style and stick to it throughout the codebase. In CamelCase, the first letter of each word is capitalized (e.g., firstName, totalAmount). In snake_case, words are separated by underscores and all lowercase (e.g., first_name, total_amount). Consistency in naming style helps developers identify variables and functions quickly.

 

Remember to use descriptive and meaningful names that convey the purpose or content of the variable, function, or class. Avoid cryptic abbreviations and opt for self-explanatory names, which improves the readability of the code.

 

Class names should represent a real-world object or entity, typically using nouns (e.g., User, Car, Invoice). Method names, on the other hand, should be descriptive verb phrases that indicate the action performed (e.g., calculate_total, send_email).

 

These are some tips for good consistent naming conventions.

 

 

3. Use whitespace to enhance code readability.

It is important to space out code. Give extra space in your code to prevent it from cluttering up. Clustered code is challenging to read and maintain.


Here is an example of some clustered Java code.

# clustered code
class Employee{
    public String name;
    public int age;
    public double salary;
    public Employee(String n,int a,double s){
        name=n;  age=a;
        salary=s;
    }
    public void displayDetails(){
        System.out.println("Name: "+name+", Age: "+age+", Salary: "+salary);
    }
}

 

Here is an example of some spaced out Java code.

class Employee {
    public String name;
    public int age;
    public double salary;

    public Employee(String n, int a, double s) {
        name = n;
        age = a;
        salary = s;
    }

    public void displayDetails() {
        System.out.println("Name: " + name + ", Age: " + age + ", Salary: " + salary);
    }
}

 

This also involves giving spaces in conditional statements.

// Clustered condition

if (firstNumber%2==0&&secondNumber%3==0){

    // do something cool

}

// Conditions with Whitespaces

if (firstNumber % 2 == 0  &&  secondNumber % 3 == 0){

    // do something cool

}

 

This makes it easy to follow, especially if you are working in a team.

 

 

4. Follow the DRY (Don't Repeat Yourself) principle.

The DRY (Don't Repeat Yourself) principle is a fundamental software development guideline that advocates avoiding duplication of code and promoting code reuse. The principle emphasizes that every piece of knowledge or logic within a codebase should have a single, unambiguous representation, reducing redundancy and improving maintainability.

 

We can summarize the core idea behind the DRY principle can as follows:

"Every piece of knowledge must have a single source of truth."

 

Suppose you have some process or activity that needs to be carried out multiple times throughout your code. In that case, it makes sense to put it in a method or function and call it when needed. Doing this beats typing out the process over and over again, as that makes your code tedious.

 

 

5. Comment your code to explain complex logic or algorithms

Imagine you are working on a team project and seeing one huge chunk of code. The code needs to be more straightforward and you have a deadline to meet. It would be a Herculean task to decipher its meaning and begin working on it. That's where comments come in.

 

Commenting code involves adding human-readable explanations within the source code to clarify complex logic, algorithms, or any sections that might be difficult to understand at first glance. Comments provide insights into the code's purpose, reasoning, or potential caveats, making it easier for other developers (and even yourself in the future) to comprehend the implementation.

 

Languages like Python and Java even go further by allowing you to provide documentation for methods and classes. This helps provide insight into methods and classes.

 

Here is an example in Python:
 

class Rectangle:
    """
    A class representing a rectangle.

    Attributes:
        length (float): The length of the rectangle.
        width (float): The width of the rectangle.
    """

    def __init__(self, length, width):
        """
        Constructor to initialize a Rectangle object.

        Parameters:
            length (float): The length of the rectangle.
            width (float): The width of the rectangle.
        """
        self.length = length
        self.width = width

    def calculate_area(self):
        """
        Calculate the area of the rectangle.

        Returns:
            float: The area of the rectangle (length * width).
        """

        return self.length * self.width

 

Here is an example in Java:

/**
 * This method calculates the area of a rectangle.
 * 
 * @param length The length of the rectangle.
 * @param width The width of the rectangle.
 * @return The area of the rectangle (length * width).
 * @throws IllegalArgumentException If length or width is negative.
 */
public double calculateArea(double length, double width) {
    if (length < 0 || width < 0) {
        throw new IllegalArgumentException("Length and width must be non-negative.");
    }
    return length * width;
}

 

 

Conclusion

Good code is not just functional; it's a masterpiece of elegance and clarity. It's beautiful to look at and a pleasure to work with, making debugging and maintenance effortless. In this article, we've explored five valuable tips that can help you refine your coding skills and create better code:

 

 

Happy coding!

 






Liked this post? Share it to others!










Check Profile