iTranslated by AI

The content below is an AI-generated translation. This is an experimental feature, and may contain errors. View original article
🔥

Bad Code Destroys Companies

に公開
2024/02/05

Introduction

The term "bad code" (often referred to as kuso-code in Japanese) is something frequently heard in the software development field. This term is slang for code that is inefficient, difficult to understand, and hard to maintain. Its existence goes beyond mere technical issues and can have a serious negative impact on a company's productivity and growth. In fact, bad code leads to project delays, increased costs, and decreased customer satisfaction, and in extreme cases, it can even lead to the downfall of a company. In this article, we will explore the definition and characteristics of bad code, analyze the cultural and organizational factors that cause it, and finally discuss how to overcome it. A deep understanding of and appropriate response to this issue are essential for a company to achieve sustainable growth.

Definition and Characteristics of Bad Code

Characteristics of Bad Code

Bad code possesses several typical characteristics. The most prominent is its lack of readability. Unclear variable names, redundant code blocks, repeated code, and ambiguous logic flows fall into this category. These features make the code difficult to understand, slow down the addition of new features and bug fixes, and ultimately cause project delays.

In addition, bad code is often inefficient and negatively affects system performance. Examples include algorithms that are not properly optimized or code that consumes more resources than necessary. These cause slow system response times and impair the user experience.

Furthermore, because bad code is difficult to maintain, it tends to create long-term technical debt. This makes updating or improving the system increasingly difficult over time, leading to higher costs and increased project risk.

Practical Examples of Bad Code

Inconsistent Handling of Date Data

In a certain API, within a specific entity class, the same date data is handled as both a Date type and a String type. This causes problems with data consistency, readability, and maintainability.

Entity Class Example (Java)

public class SampleEntity {
    private Date date;         // Date type for the date
    private String dateStr;    // Same date as a String type

    // Getter and setter for Date type
    public Date getDate() {
        return date;
    }

    public void setDate(Date date) {
        this.date = date;
    }

    // Getter and setter for String type
    public String getDateStr() {
        return dateStr;
    }

    public void setDateStr(String dateStr) {
        this.dateStr = dateStr;
    }
}


In this class, date and dateStr represent the same date data, but they are handled with different data types. This type of design has the following problems:

  1. Lack of Consistency: Since the same data is represented in different types, data consistency is compromised.

  2. Additional Conversion Logic: Conversion processes from one type to the other become necessary, making the code more complex.

  3. Potential for Bugs: The two different representations are not always guaranteed to be synchronized, which can be a source of bugs.

  4. Decreased Maintainability: Future developers will find it difficult to understand the intent behind this design, making maintenance difficult.

In this way, handling the same data with different types within the same entity can cause many problems and is a typical example of bad code.

Mapping Everything to the Object Type

As an example, here is a JPA mapping case.

The practice of using JPA to retrieve data from a database and mapping it to the Object type instead of a dedicated class should generally be avoided, as it compromises type safety and significantly reduces maintainability and readability.

import javax.persistence.EntityManager;
import javax.persistence.EntityManagerFactory;
import javax.persistence.Persistence;
import javax.persistence.Query;
import java.util.List;

public class BadMappingExample {
    public static void main(String[] args) {
        EntityManagerFactory emf = Persistence.createEntityManagerFactory("yourPersistenceUnit");
        EntityManager em = emf.createEntityManager();

        try {
            // Execute query
            Query query = em.createQuery("SELECT e.id, e.name, e.salary FROM Employee e", Object[].class);
            List<Object[]> result = query.getResultList();

            // Process results
            for (Object[] row : result) {
                // Type is unknown here, so treated as Object type
                Long id = (Long) row[0]; // ID
                String name = (String) row[1]; // Name
                Double salary = (Double) row[2]; // Salary

                System.out.println("ID: " + id + ", 名前: " + name + ", 給料: " + salary);
            }
        } finally {
            em.close();
            emf.close();
        }
    }
}

In this code, the ID, name, and salary are selected from the Employee entity, but instead of mapping the result to a specific class, it is mapped to Object[]. This causes the following issues:

  • Lack of type safety: Information about the types of these objects is lost at compile time, increasing the possibility of runtime errors.
  • Decreased readability and maintainability: If the entity changes in the future, this code becomes fragile. For example, if the order of the columns changes, casting will be performed on the wrong type, potentially causing a ClassCastException.

Generally, when using JPA, you can avoid these problems by mapping the results to your own dedicated classes or entity classes. This improves code readability, maintainability, and, above all, type safety.

Below is an example of mapping data retrieved from a database using JPA to an entity class. This approach ensures type safety and improves code readability and maintainability. In the following example, an Employee entity class exists and is used to map the query results.

First, define the Employee entity class:

import javax.persistence.Entity;
import javax.persistence.Id;

@Entity
public class Employee {
    @Id
    private Long id;
    private String name;
    private Double salary;

    // Constructor, getters, and setters omitted
    public Employee() {}

    // Getters and setters for id, name, and salary are also defined
}

Next, here is how to execute a query using the Employee entity and map the results:

import javax.persistence.EntityManager;
import javax.persistence.EntityManagerFactory;
import javax.persistence.Persistence;
import java.util.List;

public class GoodMappingExample {
    public static void main(String[] args) {
        EntityManagerFactory emf = Persistence.createEntityManagerFactory("yourPersistenceUnit");
        EntityManager em = emf.createEntityManager();

        try {
            // Query for mapping to an entity class
            List<Employee> employees = em.createQuery("SELECT e FROM Employee e", Employee.class).getResultList();

            // Process results
            for (Employee employee : employees) {
                System.out.println("ID: " + employee.getId() + ", 名前: " + employee.getName() + ", 給料: " + employee.getSalary());
            }
        } finally {
            em.close();
            emf.close();
        }
    }
}

This method maps the query results directly to instances of the Employee entity. This provides the following advantages:

  • Type safety: Errors can be detected at compile time, reducing the risk of runtime errors.

  • Improved readability: Using an entity class makes it clear what kind of data is being handled.

  • Improved maintainability: If the structure of the entity changes, the affected code is limited, making it easier to fix.

    Thus, when using JPA, mapping query results to entity classes can improve the quality of your application.

Exception Hiding

Exception hiding involves ignoring an exception without handling it appropriately or throwing a different exception without providing useful information to the user. This makes debugging difficult and can make diagnosing future problems nearly impossible. Below is a bad practice example of exception hiding.

public class ExceptionHidingExample {

    public static void main(String[] args) {
        try {
            // Attempt a dangerous operation
            int result = 10 / 0;
        } catch (ArithmeticException e) {
            // Catch and ignore the exception (Not recommended!)
            System.out.println("Something went wrong.");
        }

        try {
            // Another dangerous operation
            String text = null;
            System.out.println(text.length());
        } catch (NullPointerException e) {
            // Catch the exception and throw another one (Information is lost)
            throw new RuntimeException("Another error occurred.");
        }

        try {
            // Open a file and read content (Simulation)
            // Actually, code related to file operations would be here
            return "File content";
        } catch (Exception e) {
            // Catch the exception and return null
            return null;
        }
    }
}

In this code, the following problems exist:

  • In the first try-catch block, an ArithmeticException is caught, but the details of the exception are not logged, and only a generic message is output. As a result, clues about what the problem was and how to fix it are lost.
  • In the second try-catch block, a NullPointerException is caught and a new RuntimeException is thrown, but the stack trace and message of the original exception are lost. This hides information that is critical for tracing the cause of the exception.
  • In the third try-catch block, an Exception is caught and null is returned. If null is returned, the caller has no way of knowing why it failed.

    Returning null can also lead to a NullPointerException when the caller tries to use that value.

Code with Unclear Intent

As an example of code with unclear intent, consider a process using JPA to retrieve data from a database and taking only the first element from the resulting list. Such code can cause problems with readability and maintainability because the intent of the implementation is not clear.

import javax.persistence.EntityManager;
import javax.persistence.EntityManagerFactory;
import javax.persistence.Persistence;
import javax.persistence.Query;
import java.util.List;

public class AmbiguousCodeExample {
    public static void main(String[] args) {
        EntityManagerFactory emf = Persistence.createEntityManagerFactory("yourPersistenceUnit");
        EntityManager em = emf.createEntityManager();

        try {
            // Query execution with unclear intent
            Query query = em.createQuery("SELECT e FROM Employee e", Employee.class);
            List<Employee> employees = query.getResultList();

            // Retrieve only the first element, but the intent behind why only the first is needed is unclear
            if (!employees.isEmpty()) {
                Employee firstEmployee = employees.get(0);
            }
        } finally {
            em.close();
            emf.close();
        }
    }
}

In this code, the first element is retrieved from the list of Employee entities, but the business logic or intent behind this operation is not explained through comments or documentation, making it difficult for other developers to understand the code. Furthermore, such an implementation can lead to the following issues:

  • Lack of readability: There is insufficient information for the reader of the code to understand why only the first element is necessary.

  • Future errors: If the business logic changes, this part of the code might not be updated appropriately.

    In a proper implementation, it is recommended to clarify the business logic or intent behind specific operations using comments or documentation. This improves the readability and maintainability of the code.

Very Long Line Count Within a Single Loop

Designing a single loop to perform a vast number of processes is generally to be avoided, as it reduces code readability and makes maintenance difficult.

public class LongLoopExample {
    public static void main(String[] args) {
        boolean condition = true;
        int counter = 0;

        while (condition) {
            // Below is an example of performing many processes within a single loop
            System.out.println("Start of loop");

            // Process 1
            System.out.println("Process 1: Preparing data");

            // Process 2
            System.out.println("Process 2: Processing data");

            // Process 3
            System.out.println("Process 3: Validating processed data");

            // Process 4
            System.out.println("Process 4: Saving to database");

            // Process 5
            System.out.println("Process 5: Logging results");

            // Even more processes...
            // This design could be improved by splitting each process into appropriate methods

            // Loop termination condition (controlled by counter for demo)
            counter++;
            if (counter >= 1) { // In reality, a specific exit condition is needed
                condition = false;
            }

            System.out.println("End of loop");
        }
    }
}

This code executes multiple processing steps sequentially within a loop. In actual programs, rather than writing many processes inside a single loop like this, it is recommended to split each process into functions or methods to enhance code readability and reusability.

Improvement measures:

  • Split each step into independent methods and call these methods within the loop.
  • Provide appropriate comments or documentation to clarify the flow of processing.
  • For loops containing long processes, split them into the smallest possible units so that each part is easy to understand independently.

Such a design should be avoided as it adversely affects code readability and maintainability.

public class FunctionSeparationExample {
    public static void main(String[] args) {
        processData("Sample Data");

        // Assume there are many other processes here
        simulateManyLinesOfCode(); // Simulating many lines of code using this function

        // Finally, use the data
        useData();
    }

    // Function to process data
    private static void processData(String data) {
        System.out.println("Processing data: " + data);
        // Data processing logic...
    }

    // Function to simulate many lines of code
    private static void simulateManyLinesOfCode() {
        // Assume there is a lot of processing here in reality
        System.out.println("...Many lines of code...");
    }

    // Function to use data
    private static void useData() {
        // Data usage logic...
        System.out.println("Using data");
    }
}

The problem with this code is that the processData function and the useData function are too far apart in the code, making it difficult to understand the relationship between them at a glance. This problem becomes even more pronounced when there is a large amount of code or multiple functions intervening.

Improvement measures:

  • It is desirable to place related functions physically close to each other within the code. This clarifies the relationship between functions and makes tracing and understanding the code easier.
  • Designing classes or modules well to group related features is another way to improve code structure.
  • Utilizing comments and documentation to clearly separate code sections also helps improve readability in large projects.

Immediate Flag Usage

public class ImmediateFlagUsageExample {
    public static void main(String[] args) {
        boolean errorOccurred = false;

        // Start data processing
        System.out.println("Starting data processing...");

        // Data validation
        if (!errorOccurred) {
            System.out.println("Validating data...");
            // Simulate validation failure
            errorOccurred = true;
        }

        // Post-validation processing
        if (!errorOccurred) {
            System.out.println("Data validation successful, continuing process...");
        } else {
            System.out.println("Data validation failed, interrupting process...");
            return; // Terminate process immediately here
        }

        // Data processing
        if (!errorOccurred) {
            System.out.println("Processing data...");
            // Simulate processing failure
            errorOccurred = true;
        }

        // Post-processing
        if (!errorOccurred) {
            System.out.println("Data processing successful, continuing process...");
        } else {
            System.out.println("Data processing failed, interrupting process...");
            return; // Terminate process immediately due to processing failure
        }

        // Data storage
        if (!errorOccurred) {
            System.out.println("Saving data...");
            // Saving logic...
        }

        System.out.println("Ending data processing...");
    }
}

This code checks whether an error occurred at each stage and interrupts the process immediately if an error is found. While such immediate flag checking and process interruption might seem reasonable from an error-handling perspective at first glance, it has the following issues.

Decreased code readability: Excessive use of immediate conditional branching based on flags makes the flow of the code difficult to follow.

Improvement Plan:

  • Improve the code structure by dividing each stage of the process into independent methods and handling errors appropriately in each.

Deeply Nested Loops

Code with a large number of nested loops is a typical example of something that is difficult to understand and maintain. The following sample code uses multiple nested loops to perform a process that is difficult to understand at first glance. Such code structures should be avoided as they can cause performance degradation and bugs.

public class NestedLoopsExample {
    public static void main(String[] args) {
        // Outermost loop
        for (int i = 0; i < 3; i++) {
            System.out.println("Outermost loop: i = " + i);

            // Second layer loop
            for (int j = 0; j < 3; j++) {
                System.out.println("  Second layer loop: j = " + j);

                // Third layer loop
                for (int k = 0; k < 3; k++) {
                    System.out.println("    Third layer loop: k = " + k);

                    // Fourth layer loop
                    for (int l = 0; l < 3; l++) {
                        System.out.println("      Fourth layer loop: l = " + l);

                        // Further nested loop
                        for (int m = 0; m < 3; m++) {
                            System.out.println("        Further nested loop: m = " + m);
                            // Such deep nesting significantly impairs code readability and maintainability
                        }
                    }
                }
            }
        }
    }
}

This code example has five levels of nested loops, where each loop simply outputs numbers from 0 to 2. Such deep nesting significantly impairs code readability because it is impossible to understand what is being achieved at a glance.

Improvement measures:

  • Nested loops with complex logic should be divided into functions or methods as much as possible to make each part independent.
  • It is also effective to review the algorithm to reduce the nesting depth or consider a different approach.
  • By choosing appropriate data structures and algorithms for data processing, the need for deep nesting can be avoided.

The following example shows a version where the previous nested loop sample is divided into functions.

public class ImprovedNestedLoopsExample {

    public static void main(String[] args) {
        // Replace outermost loop with a function call
        outerLoop();
    }

    private static void outerLoop() {
        for (int i = 0; i < 3; i++) {
            System.out.println("Outermost loop: i = " + i);
            secondLayerLoop();
        }
    }

    private static void secondLayerLoop() {
        for (int j = 0; j < 3; j++) {
            System.out.println("  Second layer loop: j = " + j);
            thirdLayerLoop();
        }
    }

    private static void thirdLayerLoop() {
        for (int k = 0; k < 3; k++) {
            System.out.println("    Third layer loop: k = " + k);
            fourthLayerLoop();
        }
    }

    private static void fourthLayerLoop() {
        for (int l = 0; l < 3; l++) {
            System.out.println("      Fourth layer loop: l = " + l);
            moreNestedLoop();
        }
    }

    private static void moreNestedLoop() {
        for (int m = 0; m < 3; m++) {
            System.out.println("        Further nested loop: m = " + m);
            // Perform specific processing here
        }
    }
}

This code splits each loop into an independent method. This clarifies the responsibility of each method and makes the entire code easier to understand. Also, if future changes are required, it becomes easier to limit the scope of the impact and reduce the risk of introducing bugs.

The benefit of this approach also lies in improving code reusability and testability. Since each method can be tested individually, it is possible to build a more robust codebase.

Repeated Index Access Without Mapping to Local Variables

Code that repeatedly performs index access without mapping to a local variable can affect performance and readability. In the following example, values are repeatedly retrieved from an array by accessing the index each time.

public class RepeatedIndexAccessExample {
    public static void main(String[] args) {
        String[] data = {"Java", "Python", "C++", "JavaScript"};

        // Repeat index access many times
        System.out.println("First programming language: " + data[0]);
        System.out.println("Second programming language: " + data[1]);
        System.out.println("Third programming language: " + data[2]);
        System.out.println("Fourth programming language: " + data[3]);

        // When using data from the same index multiple times
        if (data[0].equals("Java")) {
            System.out.println(data[0] + " is a popular language.");
        }

        if (!data[1].isEmpty()) {
            System.out.println(data[1] + " is also widely used.");
        }
    }
}

This code accesses the same element from the data array multiple times, particularly for elements like data[0] and data[1], which are referenced repeatedly. Such an approach increases code redundancy and may lead to performance degradation, especially with data structures where access costs are high.

Improvement plan:
For improvement, it is recommended to map frequently accessed elements to local variables and access the data through those variables. This improves code readability and may improve performance.

public class ImprovedAccessExample {
    public static void main(String[] args) {
        String[] data = {"Java", "Python", "C++", "JavaScript"};

        // Map to local variables
        String firstLanguage = data[0];
        String secondLanguage = data[1];

        System.out.println("First programming language: " + firstLanguage);
        System.out.println("Second programming language: " + secondLanguage);
        // Remaining elements can be handled similarly

        if (firstLanguage.equals("Java")) {
            System.out.println(firstLanguage + " is a popular language.");
        }

        if (!secondLanguage.isEmpty()) {
            System.out.println(secondLanguage + " is also widely used.");
        }
    }
}

In this improved example, the first two elements of the data array are named using the local variables firstLanguage and secondLanguage. This makes the code more readable and reduces repeated access to the same data.

Habitual Null Checks

Habitual null checks refer to code that checks whether data is null out of habit or unconsciously. This is often seen in cases where nulls are likely to occur frequently or where handling nulls is indispensable. The following sample code shows an example where such null checks are performed excessively.

public class HabitualNullCheckExample {
    public static void main(String[] args) {
        String inputData = getInputData();

        // Habitual null check
        if (inputData != null) {
            System.out.println("Input data: " + inputData);
        } else {
            System.out.println("Input data is null.");
        }

        // Another null check in the middle of processing
        if (inputData != null) {
            String processedData = processData(inputData);
            if (processedData != null) {
                System.out.println("Processed data: " + processedData);
            } else {
                System.out.println("Processed data is null.");
            }
        }

        // Yet another null check in a different process
        if (inputData != null) {
            if (inputData.isEmpty()) {
                System.out.println("Input data is empty.");
            } else {
                System.out.println("Input data is not empty: " + inputData);
            }
        }
    }

    private static String getInputData() {
        // In a real application, assume data from user input or an external data source
        return "Test Data";
    }

    private static String processData(String data) {
        // Assume some kind of data processing
        return data.toUpperCase();
    }
}

In this code, inputData is checked for being null in multiple places. Such repeated null checks increase code redundancy and reduce readability, especially when the possibility of a null value is low or when a single check would suffice.

Improvement strategies:

  • Encapsulate processing that requires null checks into methods and perform the null check only once within those methods.
  • In Java 8 and later, use the Optional class to handle values that might be null, reducing the need for null checks.
  • Through Design by Contract, establish a contract to not pass nulls to functions.

Encapsulating processing that requires null checks into methods and performing the check only once within that method can improve code readability. The following sample code demonstrates this approach.

public class NullCheckEncapsulationExample {

    public static void main(String[] args) {
        String inputData = getInputData();

        // Method call for data processing
        printDataIfNotNull(inputData);

        // Another process
        String processedData = processDataIfNotNull(inputData);
        System.out.println("Processed data: " + processedData);
    }

    private static String getInputData() {
        // In a real application, assume data from user input or an external data source
        return "Test Data";
    }

    // Method that encapsulates the null check
    private static void printDataIfNotNull(String data) {
        if (data != null) {
            System.out.println("Input data: " + data);
        } else {
            System.out.println("Input data is null.");
        }
    }

    // Method that encapsulates the processing and the null check
    private static String processDataIfNotNull(String data) {
        if (data != null) {
            // Assume some kind of processing
            return data.toUpperCase();
        } else {
            return "Cannot process because data is null";
        }
    }
}

In this example, the null check is performed within the printDataIfNotNull and processDataIfNotNull methods. This encapsulates the logic requiring a null check within these methods, meaning other parts of the code, including the main method, do not need to be conscious of null checking. Encapsulating null checks in this way enhances code readability and avoids duplication of null checking logic.




Using the Optional class in Java 8 or later allows you to handle values that might be null and reduces the need for explicit null checks. Optional is a container object that can be used instead of null, and is useful when a value may or may not be present. The following sample code shows how to perform null checks using Optional.

import java.util.Optional;

public class OptionalExample {

    public static void main(String[] args) {
        Optional<String> inputData = getInputData();

        // Use Optional to check for existence and process only if a value is present
        inputData.ifPresent(data -> System.out.println("Input data: " + data));

        // Data processing
        String processedData = processData(inputData);
        System.out.println("Processed data: " + processedData);
    }

    private static Optional<String> getInputData() {
        // Use Optional.ofNullable to wrap a value that might be null
        // In a real application, assume data from user input or an external data source
        return Optional.ofNullable("Test Data");
    }

    // Encapsulate processing using Optional
    private static String processData(Optional<String> data) {
        // Use Optional.map to perform processing only if a value exists,
        // and use a default value otherwise
        return data.map(String::toUpperCase).orElse("Cannot process because data is null");
    }
}

In this example, the getInputData method returns an Optional<String>, explicitly representing that the returned value might be null. The ifPresent method defines a process to be executed only if the value inside the Optional exists, and the map method applies a function to the value if it exists. The orElse method provides a default value if the Optional is empty.

By using Optional, you can clarify the null check logic and express the program's intent more readably. It also helps prevent unintended NullPointerExceptions.

Why is Bad Code Born?

There are many causes for the emergence of bad code. One of them is deadline pressure. In the rush to meet project deadlines, developers often prioritize "moving fast" over "moving correctly" or "moving efficiently." This results in low-quality code that requires significant costs to fix later.

Furthermore, insufficient planning and unclear requirements are also factors. Requirements are often not clearly defined at the early stages of a project, and as they change during development, the codebase becomes complex and difficult to understand.

Inexperience and a lack of education are also critical factors. Developers who are not well-versed in programming best practices or design patterns tend to solve problems in inefficient ways. This is particularly noticeable in environments where education and mentoring are insufficient.

As described above, the problem of bad code is related not only to technical aspects but also deeply to organizational culture and project management issues. To solve this, an approach is required from the entire organization, rather than just focusing on technical skills.

Impact of Bad Code on the Company

Impact on the Development Process

Bad code has a significant negative impact on the development process. First, low-quality code is difficult to maintain, meaning small changes or bug fixes can turn into large-scale tasks. This results in developers spending a lot of time understanding existing code, which reduces the time available for actual development work. Also, bad code often causes unexpected bugs, and tracking and fixing these further delays the development process. Consequently, project progress slows down, potentially leading to postponed releases or the need to cut features.

Impact on Team Morale and Productivity

Bad code also negatively impacts the morale and productivity of the development team. When code quality is low, developers feel frustration in their daily work. Continuously working on problematic code lowers team members' motivation and impairs their drive for creativity and innovation. Additionally, the extra work required to improve bad code distracts from original development tasks, causing a decrease in productivity. In an environment where team members cannot work efficiently, it is inevitable that overall team performance will decline.

Impact on Customer Satisfaction and Business

Bad code ultimately affects customer satisfaction and has a negative impact on the business. Bugs and system instability arising from low-quality code damage customer trust and lead to a lower evaluation of the product. Furthermore, project delays and postponed releases impair competitiveness in the market and directly link to the loss of business opportunities. In the long run, continuous quality issues can lead to customer churn and cause a decrease in revenue and market share.

Culture that Breeds Bad Code

Culture Focused on Short-Term Results

In many companies, a culture that emphasizes short-term results is a contributing factor to bad code. In such cultures, quick deadlines and visible results are highly valued, while quality and sustainability often take a back seat. Under the pressure of deadlines, development teams are frequently forced to choose the quick release of features at the expense of code quality. This short-term approach accumulates technical debt for the future, which can lead to project delays and increased costs in the long run.

Management Policies That Disregard Code Quality

When management prioritizes short-term business goals over code quality, the impact ripples across the entire development process. Resources and time required to maintain quality become insufficient, and developers lose the support needed for code refactoring or proper testing. This makes it easier for code that is difficult to maintain, lacks scalability, and is prone to bugs to be produced. A management culture that prioritizes short-term results over quality hinders development processes that maintain a long-term perspective.

Specific Steps for Improvement

To change a culture that breeds bad code, several concrete steps are required. First, management must understand the importance of quality in software development and align it with business objectives. To improve quality, it is essential to secure sufficient time and resources and integrate quality assurance steps into the development process.

Furthermore, development teams require continuous education and training to ensure quality. Adopting best practices such as code reviews, pair programming, and automated testing is an effective way to improve code quality.

It is also important to focus on the management and tracking of technical debt. By regularly evaluating technical debt and making its reduction a part of project planning, long-term quality and project success can be ensured.

Changing a culture that breeds bad code is not easy, but it is indispensable for a company's long-term success. By establishing a culture that values quality, a healthier and more sustainable development process can be built.

Problems of Engineers Writing Low-Quality Code

The existence of engineers who write low-quality code is a significant element of a culture that breeds bad code. This issue is rooted not only in the lack of individual technical skills but also in the absence of education, mentoring, and appropriate coding standards and practices. If engineers fall behind the latest technical trends and best practices, they solve problems using old, inefficient methods, resulting in the production of low-quality code.

To address this, it is first necessary to increase opportunities for education and training. Providing a continuous learning environment for engineers to learn new technologies and programming standards is essential for improving code quality. It is also important to promote knowledge sharing within the team through mentoring and code reviews by experienced engineers. This gives engineers the opportunity to objectively evaluate and improve their own code.

Furthermore, companies need to establish coding standards and guidelines and encourage everyone to comply with them. Standardized coding practices serve as the foundation for producing consistent, high-quality code. Through these efforts, the problem of engineers writing low-quality code can be effectively addressed, improving overall code quality.

Adjusting Coding Styles to Low-Level Engineers

For a company to adapt by lowering its coding styles or standards to match low-level engineers is a harmful strategy in the long run. This approach may seem to solve problems temporarily, but in reality, it further encourages a culture that breeds bad code and can degrade the technical quality of the entire organization. Instead, companies should create an environment where everyone can reach high technical standards.

It is important to provide support and mentoring according to the skill levels of the engineers. For beginners or inexperienced engineers, it is effective to have more experienced team members provide one-on-one guidance on basic programming principles, coding styles, and best practices. Such support helps engineers improve their skills and align with the organization's overall quality standards.

Furthermore, providing opportunities for continuous education and professional growth is crucial. Providing access to workshops, seminars, and online courses so that engineers can learn the latest technical trends and programming techniques is the key to raising the quality of the entire organization.

Finally, to maintain quality standards, it is essential to strengthen processes such as code reviews and automated tests. This ensures that all engineers are expected to write high-quality code and allows for the improvement of technical standards across the entire organization.

Minimum Requirements to Avoid Bad Code

Detailed Code Reviews

To ensure code quality, always conduct code reviews before merging. This is because it is more difficult to fix code when the coding style has taken a turn for the worse than when the result of a process is simply incorrect. It is important to perform detailed code reviews in small units rather than reviewing a large amount of code at once. This keeps the size of Issues and commits small, which is a factor in improving code maintainability. Furthermore, code reviews are important for letting other developers become familiar with your code.

Adherence to Coding Styles

Adherence to coding styles is extremely important. This is because once you allow the coding style to break, other members may learn those same poor coding styles, potentially causing the coding style to become fragmented across the entire project. For example, if the writing style differs between each screen or API, code reading becomes extremely difficult. Therefore, following a coding style is essential for maintaining project quality. If necessary, spend time making corrections to maintain the coding style and contribute to the overall quality improvement of the project.

Breaking Away from Bad Code

Code Refactoring and Reducing Technical Debt

The first step to breaking away from bad code is to improve the quality of the code through refactoring and to reduce technical debt. Refactoring is the process of improving the internal structure of the code without changing its external behavior. This improves code readability and makes it easier to maintain. It is also important to regularly assess technical debt within the codebase and reduce it in a planned manner. Reducing technical debt includes resolving excessive complexity, reducing unnecessary dependencies, and updating or deleting old code. Through these activities, the codebase can be kept in a healthy and manageable state.

Strengthening Code Reviews and Internal Communication

To break away from bad code, it is essential to strengthen the code review process and promote internal team communication. A code review is a process of verifying code written by other developers and suggesting improvements. This improves code quality and promotes knowledge sharing among team members. It is also important to encourage open communication within the team through regular meetings and technical discussions. By creating an environment where team members understand each other's work and cooperate to solve problems, code quality can be continuously improved.

Practices for Continuous Quality Improvement

To break away from bad code, it is necessary to practice continuous quality improvement. This includes introducing automated testing, adopting continuous integration and delivery processes, and establishing coding standards and guidelines. Automated testing allows you to ensure that changes to the code do not adversely affect existing functionality. By adopting continuous integration and delivery, code integration and deployment can be performed more frequently and stably. Furthermore, by establishing and sharing coding standards and guidelines within the team, it becomes possible to maintain consistency and quality of the code. By practicing these, you can improve the environment that breeds bad code and continuously produce high-quality code.

Conclusion

Long-Term Cost of Bad Code

The first step to breaking away from bad code is to improve the quality of the code through refactoring and to reduce technical debt. Refactoring is the process of improving the internal structure of the code without changing its external behavior. This improves code readability and makes it easier to maintain. It is also important to regularly assess technical debt within the codebase and reduce it in a planned manner. Reducing technical debt includes resolving excessive complexity, reducing unnecessary dependencies, and updating or deleting old code. Through these activities, the codebase can be kept in a healthy and manageable state.

Actions for the Company

To break away from bad code, it is essential to strengthen the code review process and promote internal team communication. A code review is a process of verifying code written by other developers and suggesting improvements. This improves code quality and promotes knowledge sharing among team members. It is also important to encourage open communication within the team through regular meetings and technical discussions. Team members can continuously improve code quality by creating an environment where they understand each other's work and collaborate to solve problems.

Lessons Learned as an Organization

To break away from bad code, it is necessary to practice continuous quality improvement. This includes introducing automated testing, adopting continuous integration and delivery processes, and establishing coding standards and guidelines. Automated testing allows you to ensure that changes to the code do not adversely affect existing functionality. By adopting continuous integration and delivery, code integration and deployment can be performed more frequently and stably. Furthermore, by establishing and sharing coding standards and guidelines within the team, it becomes possible to maintain consistency and quality of the code. By practicing these, you can improve the environment that breeds bad code and continuously produce high-quality code.

Discussion