Location>code7788 >text

The Wisdom Behind the Code: 20 Programming Insights

Popularity:953 ℃/2024-11-09 01:29:13

Hi everyone, I'm Brother Muwan; at the
More than 10 years of work experience makes me deeply appreciate that program development is not only writing code, but also a systematic process. I have summarized 20 programming insights, covering code specification, design principles, testing methods and delivery processes. These lessons not only improve my code quality, but also promote teamwork and project management. Following the code specification makes the code more readable and maintainable; reasonable design can effectively respond to changes in requirements; comprehensive testing ensures the reliability of the product; and a good delivery process improves the development efficiency. I hope these insights can provide reference for more programmers and help you to make progress on the road of programming.

1. Clear naming

● Principle: Code should be easy to read and understand; e.g., names of variables, functions, and classes should clearly convey their intent;

● Example.

// Explicitly indicate the number of students
int numberOfStudents = 30;

/**
 * Calculating the area of a circle
 * @param radius radius
 * @return area (of a floor, piece of land etc)
 */
public double calculateAreaOfCircle(double radius) {
    return * radius * radius;
}

2. Use of notes

● Principle: Add comments to complex or important code segments to help others understand;

● Example:

/**
 * Calculate the average of the given list
 *
 * @param numbers A list of numbers to be calculated.
 * @return Returns the average of the numbers, or 0 if the list is empty.
 */
public static double calculateAverage(List<Double> numbers) {
    if (numbers == null || ()) {
        { if (numbers == null || ()) { return 0;
    }

    double sum = 0.0; // holds the sum of the numbers
    int count = 0; // the number of valid numbers to keep

    // Iterate through each number in the list and calculate the sum
    // [Note]: check if each element in the list is null, need to be filtered
    for (Double num : numbers) {
        if (num ! = null) {
            sum += num; count++; { if (num != null) { if (num != null)
            count++;
        }
    }

    if (count == 0) {
        return 0; }
    }
    double average = sum / count; return average; return 0; }
    return average; }
}

3. Consistent coding style

● Principle: Follow the team's coding standards and maintain a consistent code style;

● Example: Use uniform indentation and curly brace placement. For example, IDEs such as IDEA configure a uniform CodeStyle: Alibaba-CodeStyle, Google-CodeStyle, and so on;

4. Code modularization

● Principle: Decompose functions into small modules to increase reusability;

● Example:

public class Calculator {
    /**
     * plus
     * @param a
     * @param b
     * @return
     */
    public int add(int a, int b) {
        return a + b;
    }

    /**
     * diminish
     * @param a
     * @param b
     * @return
     */
    public int subtract(int a, int b) {
        return a - b;
    }
}

5. Avoidance of duplicate code

● Principle: Follow the DRY principle (Don't Repeat Yourself);

● Example:

//Bad practice.:repeatable
public class Calculator {
    public void addAndPrint(int a, int b) {
        int result = a + b;
        ("Result: " + result);
    }

    public void addAndPrintAnother(int x, int y) {
        int result = x + y;
        ("Result: " + result);
    }
}

//Good practice.:We can extract a public method to followDRYformula:
public class Calculator {

    public void addAndPrint(int a, int b) {
        printResult(add(a, b));
    }

    public int add(int a, int b) {
        return a + b;
    }

    private void printResult(int result) {
        ("Result: " + result);
    }
}

6. Relying on interfaces rather than specific implementations

● Principle: rely on interfaces rather than concrete implementations to enhance flexibility;

● Example:


public interface Shape {
    double area();
}

public class Circle implements Shape {
    private double radius;

    public Circle(double radius) {
         = radius;
    }

    @Override
    public double area() {
        return * radius * radius;
    }
}

public class Square implements Shape {
    private double sideLength;

    public Square(double sideLength) {
         = sideLength;
    }

    @Override
    public double area() {
        return sideLength * sideLength;
    }
}

//Relying on interfaces rather than concrete implementations
void printf(Shape shape);

7. Avoiding magic numbers

● Principle: Use constants instead of magic numbers;

● Example:


final double FIXED_RATE = 3
double area = FIXED_NO * radius

8. Simplification of conditional statements

● Principle: Avoid complex conditional logic. Use quick return to minimize if nesting levels;

● Example:


//not recommended:too deeply nested
public void checkUser(User user) {
    if (user != null) {
        if (() > 18) {
            if (()) {
                // Access
                ("Access granted");
            } else {
                ("User is not active");
            }
        } else {
            ("User is underage");
        }
    } else {
        ("User is null");
    }
}

//testimonials:Fast Failure Return
public void checkUser(User user) {
    if (user == null) {
        ("User is null");
        return;
    }
    
    if (() <= 18) {
        ("User is underage");
        return;
    }

    if (!()) {
        ("User is not active");
        return;
    }

    // Access
    ("Access granted");
}

9. Exception handling

● Principle: Improve program robustness through appropriate exception handling;

● Example:


//Exception
try {
    int result = 10 / 0;
} catch (ArithmeticException e) {
    ("Illegal parameter, not divisible by zero");
}

// fuse
try (Entry entry = ("resourceName")) {
    // your business logic
} catch (BlockException ex) {
    // Handle blocked requests
}

10. Standardized error log processing

:: Principle: Harmonize error handling and logging. Convenient log collection and alarm configuration;

● Example:


public void logError(String message) {
    ("ERROR|Trace:{0}|Msg:{1} " (), message);
}

11. Method parameters should not be too long

● Principle: method parameters should be as few as possible to avoid confusion, more than 3 recommended to be encapsulated into a model;

● Example:


//not recommended
void createUser(String name,int age,String email);


//testimonials
public class UserService {
    public void createUser(User user) {
        
    }
}

class User {
    private String name;
    private int age;
    private String email;

    public User(String name, int age, String email) {
         = name;
         = age;
         = email;
    }

    // Getters and Setters
}

12. Use of existing toolkits to streamline operations

:: Principle: Prioritize the use of existing tools such asto simplify operations

● Example:


("");
()

13. Use invariant variables wherever possible

:: Principle: usefinalkeyword declares immutable variables to improve code reliability;

● Example:


final int MAX_VALUE = 100;
();

14. Test-driven development (TDD)

● Principle: Write tests before writing code to ensure testability of code;

● Example:


@Test
public void testAdd() {
    Calculator calculator = new Calculator();
    assertEquals(5, (2, 3));
}

15. Avoiding over-optimization

● Principle: Prioritize code readability, optimization is usually done after identifying performance problems;

16. Use of version control

● Principle: Use version control tools (git) to manage code changes;

17. Emphasis on documentation

● Principles:

○ Before development, consider clearly why you want to do the requirement. From the background and current situation analysis - > why do (why) - > to do what (what) - > how to do (how) systematic thinking;

○ And then from the business use case analysis - > system dependency analysis - > domain model analysis - > architectural design analysis - > timing diagram analysis, etc. to land the final system points;

18. Emphasize code reviews

● Principle: Conduct regular code reviews to improve code quality and team R&D awareness;

19. Valuing every delivery

● Principles:

○ Target resources in advance, with upstream and downstream agreement and a clear milestone plan;

○ In the matter of on-demand promotion, weekly synchronization of project progress, and timely communication of risk;

○ Organizational review after the fact and focus on business data (focus on value)

20. Focus on quality of delivery

:: Principle: new features need more consideration of gray-scale validation

○Backend service: gray scale validation by grouping (gray grouping->default grouping)

○Client: After a small-scale upgrade to verify that there are no problems, gradually release the upgrade;

put at the end

Welcome to follow my public number: Programming Apocalypse to get the latest news first;

microsoft public number
image image