Five Ways to Simplify Your Code

shutterstock_252367738 (2)

Most of us aren’t lucky enough to spend our programming lives working on so-called “green-field projects,” i.e., ones that allow you to create the initial code. Since 2000 I’ve probably spent ten years working on existing code and combating (as well as contributing to) technical debt. Finding and fixing bugs is almost a rite of passage for new developers when they on-board with a new company.

Technical debt arises for many reasons—whether moving goal posts, pressure to get code tested and released, high programmer turnover, and lack of documentation. Whatever the reason, it’s likely to bite you if you aren’t careful. So what can you do to ease its burdens? Here are some suggestions.

Refactoring

Understanding someone else’s code can be hard. A useful technique on the way to comprehension is refactoring, or restructuring existing code without changing the code’s outputs; many modern IDEs (Eclipse, IntelliJ, Rad Studio, Visual Studio) have some great tools for refactoring in a way that allows the developer to improve maintainability and internal architecture.

Although I stopped using short variable and function names a long time ago, I recently had to reuse some very old code, experiencing a “Did I really write this?” moment in the process. Refactoring the code made it much easier to read. While giving variables and function meaningful names is simple, that sort of technique is really only relevant to older code; in many cases, it’s more useful to restructure, starting with breaking down huge monolithic functions (typically 300 lines of code or more that can be reduced into a smaller number of functions or even into classes).

One problem with refactoring large functions in languages such as C++ is the local variables. If you have a large quantity of code using local variables, it gets harder to split code out. Remember, the key to refactoring is that it mustn’t introduce new functionality; just simplify the code and don’t introduce new bugs. If you have unit tests, run those tests after each refactoring.

Moving to OOP and/Or Functional Styles

You can write C++ in a purely procedural style, though it can quickly become hard to maintain once your program grows beyond a few hundred lines long. Even small utilities benefit from using classes to hold and process the data—in addition, you’re less likely to forget to free up memory variables if you use the RAII programming idiom.

With Lambda expressions becoming commonplace in several programming languages, there’s much to be gained from using a functional approach; it complements OOP (and procedural code) rather than replacing it. C# has had LINQ for a long time; you can replace for loops and remove the chance of bounds errors using foreach to process lists, etc. Any function that returns a value without causing any side effects could be called functional, but lambda expressions (anonymous functions) are even more so.

Use Compiler Inference

C# has had var for a while, just as C++ 11 introduced auto for declaring variables. Letting the compiler infer the variable type reduces the need for typing (or copy and paste), but it can greatly shorten declarations and increase code readability. The simple example below shows the difference between declaring the type explicitly and then using var.

[csharp]

public static void Main(string[] args) l

{

ZipFileArchiver zf = new ZipFileArchiver();

zf.Execute(args);

}

[/csharp]

Here’s var:

[csharp]

public static void Main(string[] args)

{

var zf = new ZipFileArchiver();

zf.Execute(args);

}

[/csharp]

Unit Testing

Depending on the project, you may not have time to add unit tests; but with testing, it will ultimately take less time to debug. Give them a shot—the boost in confidence you receive when your code passes all tests is amazing.

Is the Code in a Version Control System?

Though they’re more about managing code, the tools provided with Version Control Systems can easily let you see what changes you made in coding, and thus help you undo the changes if your attempt at simplifying merely introduced bugs. (Some can also help you merge changes quickly, as well; a VCS isn’t just for code safety and sharing between teams.)

Conclusion

For developers, fixing others’ code goes with the territory, usually long after that person has moved on to another opportunity. With continual changes and improvements to most popular languages coming along, it pays to stay ahead of the game and use any changes and improvements to simplify existing code.

Image Credit: ronstik/Shutterstock.com

Comments

7 Responses to “Five Ways to Simplify Your Code”

January 14, 2016 at 2:48 pm, VJGoh said:

COMMENTS. Refactoring code is a lot easier if you comment it as you go. (With luck, it already had comments in it.)

Comments are one of the most neglected programming tools. If you comment while you code, revisiting code becomes a lot easier. My Dad once told me that I should write comments for myself, five years in the future. Sure enough, any time I’ve come back to a system five years later, those comments have made the transition a lot easier.

Commenting as you go forces you to put your understanding of the code into words–you don’t even have to keep the comments after you’re done. But if you can’t explain the function of the code in plain speech, you probably don’t understand it well at all.

Reply

January 14, 2016 at 4:04 pm, stewart said:

Comments are definitely under used – but they can only become out of date because developers don’t maintain the comments as the code is changed.

A rule I like to use : comments should not be verbose. Short and Concise to get the message across.

Reply

January 14, 2016 at 6:14 pm, dgrb said:

This will seem like nitpicking, but tekkies already have a bad reputation when it comes to writing…

“Finding and fixing bugs is almost a rite of passage for new developers when they on-board with a new company.”

Since when has “on-board” become a verb? Simpler – and shorter – to have written “when they join a new company”.

Reply

January 15, 2016 at 4:55 am, C. R. said:

1) Buy the book “Clean Code” from Robert C. Martin and use chapter 17 (Smells and heuristics) as an agreed base for code reviews.

2) Move from informal comments to formal ones, if you’ve to explain what your code is doing, it’s that your code is too complicated, uses (clever but hard to understand) tricks and so on:
– Unit tests (the real ones whose are testing the behavior, branching and limits of your methods, not the one to satisfy a code coverage tool by just going over the lines) are documentation on how to use a method and what a method is really doing.
– Never shorten name of the methods, arguments, variables, constants, … readability is at this price.
– put as few informal comments as possible, because they need to be maintained (and it’s costly), they are often redundant and they clutter your source file.

3) Assess your code with automated tools (Findbugs, Sonarqube, Serenity, …)

4) Refactor, refactor and refactor: each commit / push in CVS is a cleaner, more readable and understandable version of the source code.

Reply

January 17, 2016 at 4:49 am, skierpage said:

> it compliments OOP (and procedural code)
“OOP, you look marvellous”?
You mean ” complement”. #typo

Reply

January 21, 2016 at 8:06 am, Geoffrey Atkinson said:

I often decide to re-implement code (oh excuse me… “refactor” code) that has been tested, verified, reviewed, and withstood the test of time… simply because I am incapable of taking the time to understand it.

And who needs a continuous history in version control anyway? Looking a diffs to figure out why things are they way they are is so overrated! Sorry – forgot the sarcasm tag. Why not have VC degenerate into a log of who was working on the code that day?

To suggest refactoring simply because you don’t understand the code is irresponsible. And let’s face it – many developers are incapable of understanding code not written by them.

Refactoring is a powerful technique when used correctly. This suggestion does not qualify as such.

Also – keep in mind… comments often lie. They are often neglected during refactoring sessions.

Reply

January 21, 2016 at 8:42 am, Lawrence Weinzimer said:

Re-factoring and debugging goes with the territory. There’s always room for improvements, collaboration in a task-team easily perfects innovation that you wrought…But get some Copyright protection when and if possible.

Reply

Post a Comment

Your email address will not be published.