On Modifying Program Code

June 11, 2022

What Is a Code Change

Every software project has a lifecycle, and however long or short it is, it involves code changes. Whether you are fixing earlier defects or iterating on each story in agile development, code modifications happen to some degree.

Why Code Changes Happen

Code changes are very common, yet they are something we should try to avoid. Think in extremes. At one end is code so universally compatible that it meets business needs without any modification. Such code does exist in practice: if you treat business code not as real code but as business logic flow, then in a script-driven service framework the foundation is written in an efficient native language (for example C++) using general design models and abstractions. That foundation rarely changes, and the business scripts on top are driven by it, so this code almost never needs modification—only the business scripts do (no-code solutions are another form of this extreme thinking). At the other end is the opposite: business logic is scattered into every corner of the code with hardly any abstraction layer. If you are not familiar with the business, such code is hard to read; every business change directly triggers a code change, and both maintainability and reusability are low.

None of us want to modify code, because changes cost money, time, and effort—and we do it merely to make up for earlier shortcomings? So why not think ahead for the later stages from the start and do preventive work? It is better for the project's health and lowers maintenance costs down the line.

How to Make Code Changes

We can try to avoid changing code, but sometimes we have to. So making changes well and reducing their shortcomings also improves the quality of the project's code.

How to write elegant code has always been well documented; the computing industry has a wealth of material on it.

Common-Sense Rules for Code

Most people know the common-sense rules. They don't matter to the code's logic, since they have nothing to do with the code itself, but following them reduces mistakes.

Code Alignment

Generally, using spaces instead of tabs noticeably improves this, especially in team development (with advanced editors that format code automatically, alignment is hardly something you need to worry about).

Code Comments

Comments are also part of code formatting. Sensible comments help developers understand the code and work more efficiently. Today there are all kinds of comment formats, some of which generate rich API documentation, and so on—all to make the code easier to read and understand later.

What to Watch for in Code Logic

When it comes to logic flow, code written by different people with different habits can differ enormously, but plenty of good logic patterns are worth learning from. Unlike the formatting rules above, logic flow directly affects how well the compiled code runs.

Conditional Statements

Often the conditions checked in code are simple, and the program may only care about one case, so the ELSE case gets ignored. This is a bad habit, and the resulting code quality is not high.

Consider this code:

cpp
void make_node(const std::unordered_map<std::string>& poll, std::unordered_map<std::string>& result)
{
  if (is_wanted(poll, 0)) {
    store_result(result, load_item(poll, 0));
  }

  if (is_wanted(poll, 1)) {
    store_result(result, load_item(poll, 1));
  }

  if (is_wanted(poll, 2)) {
    store_result(result, load_item(poll, 2));
  }
}

This is a typical case of a missing ELSE. It leads to redundant execution and lowers runtime quality.

We can modify it appropriately:

cpp
void make_node(const std::unordered_map<std::string>& poll, std::unordered_map<std::string>& result)
{
  if (is_wanted(poll, 0)) {
    store_result(result, load_item(poll, 0));
    return;
  }

  if (is_wanted(poll, 1)) {
    store_result(result, load_item(poll, 1));
    return;
  }

  if (is_wanted(poll, 2)) {
    store_result(result, load_item(poll, 2));
    return;
  }
}

The redundant execution is gone. The idea is to let every ELSE fall through by default. This style is very common when checking whether a function's conditions are met before executing:

cpp
bool check_condition(int flags, std::vector<int>& result)
{
  if (flags == 0) return false;

  if (flags & 0xa0 && flags & 0x0c) return false;

  if (flags & 0x80) return update_result_v1(result);

  if (flags & 0x02) return update_result_v2(result);

  return update_result(result);
}

Loop Statements

Loops are for iterative execution, but a program needs a deterministic result in finite time, so misusing loops also produces low-quality code, as below:

cpp
void maybe_infinite_loop(int flags, std::vector<int>& result)
{
  for (;;) {
    if (check_flags(&flags)) break;
    if (check_flags_v1(&flags)) continue;
    store_result(flags, result);
  }
}

These few lines may well be defective. Assuming check_flags and check_flags_v1 are not based on the State pattern, the code can loop forever.

Finite Loops

For the code above, you can design a simple state transition table so that every transition path goes from a start state to a terminal state. Introducing the State pattern gives:

cpp
void finite_loop(int flags, std::vector<int>& result)
{
  for (auto it = state_start(&flags); it != state_end(&flags); it++) {
    if (check_flags(&flags)) break;
    if (check_flags_v1(&flags)) continue;
    store_result(flags, result);
  }
}

This logic has a deterministic end point.

Try Not to Break Loop Levels

First, look at a headache-inducing snippet:

cpp
void bad_loop(int flags)
{
  for (;;) {
    if (check_flags_v1(&flags)) break;
___end1:
    func_v1();
    for (;;) {
      if (check_flags_v2(&flags)) goto ___end1;
___end2:
      func_v2();
      for (;;) {
        if (check_flags_v3(&flags)) break;
        if (check_flags_v4(&flags)) goto ___end1;
        if (check_flags_v5(&flags)) goto ___end2;
      }
    }
  }
}

Code like this is extremely hard to maintain; untangling its logic takes a lot of time and effort. So, the same rule applies: avoid goto statements wherever possible, and avoid complex, chaotic control flow.

The improved code:

cpp
void bad_loop(int flags)
{
  int state = 0; // initial state
  for (auto it = state_start(&state); it != state_end(&state); it++) {
    if (check_flags(&state)) break;

    if (check_flags_v1(&flags)) break;

    func_v1();

    if (check_flags_v2(&flags)) state_move(&flags, 5); // 5 - __end1

    if (check_flags_v2(&flags)) state_move(&flags, 6); // 6 - __end2

    if (check_flags_v3(&flags)) state_move(&flags, 4);

    if (check_flags_v4(&flags)) state_move(&flags, 3);

    if (check_flags_v5(&flags)) state_move(&flags, 2);
  }
}

The improved code is not only easier to understand, but its complexity is clearly reduced and it runs more efficiently.

In deeply nested loops, don't jump across levels. Again, avoid goto; otherwise it is easy to break the logical structure and make the code a mess.

Duplicate Code Blocks

Sometimes code contains several small snippets that do nearly the same thing (quite possibly left behind by someone's Ctrl+C / Ctrl+V and tweaks) and are used frequently. Such code can be further refactored into a single reusable function.

Tracking Execution with State Flags

State flags are really the State pattern design described above (used for deterministic for loops). In fact, the State pattern is not just for loops—it can be used anywhere. For complex execution flows, though, the State pattern makes the flow easier to abstract and easier to debug and troubleshoot. Its benefits are obvious, which is why many well-designed architectures choose it for handling complex flows.

Code Philosophy

As far as code goes, if it satisfies the following, it can be called excellent code:

  • Passes all tests
  • Contains no duplicate code
  • Expresses all of the system's design ideas
  • Contains as few entities as possible (for example, types and functions)

Naming Conventions

  • snake_case
  • UpperCamelCase (PascalCase)
  • lowerCamelCase

A consistent variable naming convention makes code easier to discuss and understand, which improves team productivity.

Code Formatting

Code formatting is mainly about the conventions or defaults for whitespace, line breaks, and the like. Editors can usually be customized for these, and the team can share one coding standard so that the same project does not end up with different display styles due to inconsistent formatting.

Code Abstraction

Code abstraction deserves some discussion. In software engineering you must understand design patterns—not by memorizing every pattern, but by understanding the common ones and knowing when to use them and what problems they solve.

Why Use Design Patterns?

When solving the same problem, different people may express it in different ways, and the differences become even more visible at the code level. In a team project, such code may be maintained by dozens of people at once, and having each of them untangle its specific logic costs a lot of time and effort. So why not let the team communicate in a common language? That is why design patterns exist at the logical level. If Zhang San writes logic that expresses the Facade pattern, Li Si only needs to know the Facade pattern to understand the logic at a glance after reading the code. The team saves a great deal of time and effort and can put that energy into more meaningful work.

Design patterns are the common underlying logic of application software development, so the first thing a developer needs to do is abstract functional logic into design patterns (if you can't, it generally means you haven't mastered design patterns).

The Law of Demeter: A module's users should not know the internal details of the objects it uses.

Unit Testing

Unit testing is a tool for verifying the correctness of functional modules in code. If all of the software's modules are correct, the integrated code is easy to debug and very likely correct too. Functional modules are a local problem, while integrated software is a global one. If the global behavior is wrong, it means there are errors in the order or interdependencies of the parts, so we don't need to look inside the modules again—we only need to adjust the order or dependencies between modules to fix the problem.

Rules of Emergent Design

  • Pass all tests
  • Refactor the code
  • No duplicate code
  • Express the programmer's intent
  • Minimize the number of classes and methods

Concurrency

In multithreaded systems, concurrency problems arise. Concurrency means that the timing of multiple execution nodes' use of a resource is nondeterministic.

Concurrency vs. parallelism: Concurrency means the timing of multiple execution nodes' use of a single resource is nondeterministic—you cannot tell who goes first. Parallelism means multiple execution nodes may use a single resource at the same time. In practice, solving concurrency problems well also solves parallelism problems.

Mutual Exclusion and Synchronization

Precisely because the timing of multiple execution nodes' use of a single resource is nondeterministic, we need a mechanism for mutually exclusive, synchronized use.

First, there is mutual exclusion. It is an exclusive operation: while a resource is in use, it is locked, and other users cannot acquire it.

Operating systems express this with P and V operations:

scss
  P()
  do_resource()
  V()

P and V are both atomic. After P is executed, if the resource is already in use, P blocks until the resource is free. Once V executes, the resource is released, and one user blocked on P immediately gains access and continues the acquire/use/release cycle.

C++ uses the same mechanism:

cpp
static std::unordered_map<std::string> resource;
static std::mutex mut;

void cosume_resource() // called by multiple threads
{
  mut.lock();
  consume(&resource);
  mut.unlock();  
}

C++ also allows a kind of atomic lock (spin lock), suitable when the resource is held for a bounded time. It works by making threads wait so that only one thread consumes the resource at a time. It fits logic where resource consumption is brief, and because of its simple structure it is often more efficient than a mutex.

cpp
static int lck = 0;

void atomic_lock()
{
  while (lck < 0) {}
  lck--;
}

void consume_resource() // called by multiple threads
{
  atomic_lock();
  consume_resource(&resource);
}

Synchronization is derived from mutual exclusion: it is the problem of synchronizing two mutually exclusive operations. Again, it is expressed with P and V.

For the producer:

scss
P(S1)
P(N1)
do_produce()
V(N1)
V(S2)

Here the mutex M is used to lock the container pool (the pool must be locked whenever it changes). Each time one item is produced, the counting lock corresponding to N is incremented.

The corresponding consumer is:

scss
P(S2)
P(N2)
resource = get()
V(N2)
V(S1)
do_consume(resource)

The Producer–Consumer Concept

Producer and consumer are an abstraction of the mutual exclusion and synchronization problem, with a more general way of taking and using resources—usually a resource container pool. As long as producers have not filled the pool, they can keep storing resources; consumers can keep consuming until the pool is empty. This makes mutual exclusion and synchronization more efficient.

In C++, the producer and consumer can be expressed like this:

cpp
static std::mutex producer_lock;
static std::mutex consumer_lock;
static std::mutex poll_lock;

static std::unordered_map<std::string> poll;

void produce() // multi-threaded producer
{
  producer_lock.lock();
  poll_lock.lock();
  do_produce(&poll);
  poll_lock.unlock();
  consumer_lock.unlock();
}

void consume() // multi-threaded consumer
{
  consumer_lock.lock();
  poll_lock.lock();
  auto resource = get(&poll);
  poll_lock.unlock();
  producer_lock.unlock();
  do_consume(resource);
}

Links

Improving Computer Program Readability to Aid Modification

Clean Code