Write Less Code

I have recently come across multiple sources that recommended writing less code or just enough code to get the job done. Fewer lines of source code mean fewer lines of code that needs to be documented, tested, and maintained.

In a situation where lines of code is not being used as a performance metric, lines of code should be minimized while adhering to a project’s constraints. A project’s constraints may require that the source code is readable. In the interest of security, it may require checks to be redundant. The project may also require the software to be compartmentalized with well defined interfaces. The need to add whitespace for enhancing readability, conditional statements to address security, and interface declarations to increase modularity will undoubtedly increase source code length. Writing less code should be done by writing only code that addresses the project’s objectives, and eliminating unnecessary or nonoperational code.

I have seen code implemented as follows:


int f( int x )
{
  int y = 0;
  if( x > 0 )
  {
    // some processing...
    y = 1;
    goto DONE; 
  }

  if( x == 0 )  
  {
    // some processing....
    y = 0;
    goto DONE;
  }

  if( x < 0 )
  {
    // some processing...
    y = -1;
    goto DONE;
  }
DONE:
  return y;
}

Using goto to handle cases in C or C++ where Java’s labeled breaks would be useful is arguable. The same arguments for the use of goto do not apply to the code that resembles the sample that is presented above.

Some may say that the use of an explicit goto, increases security by creating a redundant jump statement, one that is explicitly added to the other that is implicitly inserted into machine code by the compiler. After viewing the assembler code that is optionally generated by the compiler, it is proven for the situation that I experienced that the goto is ignored.

Though the goto statements are ignored by the compiler, they are distractions to people who read the source code. Rather than simply reading code that is well structured, a reader will need to search for the code label that is the target of the goto. The insertion of redundant jump statements is best implemented by the compiler. This reduces the noise that is introduced into the application source code.

In my most recent experience, minimizing lines of source code was accomplished by eliminating superfluous gotos. The updated source code is similar to the following:


int f( int x )
{
  int y = 0;
  if( x > 0 )
  {
    // some processing...
    y = 1;
  }
  else if( x == 0 )  
  {
    // some processing....
    y = 0;
  }
  else if( x < 0 )
  {
    // some processing...
    y = -1;
  }
  return y;
}

As a result, source code length is reduced, readability is increased, and testing coverage is simplified.

Questions, comments, and responses are welcomed and appreciated.

Leave a Reply