Why Should I Write Clean Code?

Mutual Mobile
Mutual Mobile

--

“Code is the language in which we ultimately express the requirements. We may create languages that are closer to the requirements. We may create tools that help us parse and assemble those requirements into formal structures. But we will never eliminate necessary precision — so there will always be code.”

— Robert C. Martin, Engineer & Author of ‘Clean Code: A Handbook of Agile Software Craftsmanship’

If you’ve been a programmer for any amount of time, there’s no doubt that you once scaled Mt. Bad Code.

And things become even more complicated when it’s you or your team who’s behind it. Bad code slows projects down like nothing else and can make even the nimblest of teams halt dead in the tracks.

Bad code is an insidious issue. It breeds problem after problem, because every fix to it can break two or three other parts of the code. Every modification requires a world of understanding and a zoomed out perspective for it to become parseable.

A common analogy programmers use to describe the pain of bad code says it’s like throwing necklaces into a Zip-Loc bag, shaking them up, and then trying to separate the tangled chain links. Basically — an irretrievable mess.

In a world where time is fast replacing money as the new currency, the irreplaceable importance of clean code is more prominent than ever before.

So What is Clean Code?

The legendary inventor of C++ and the author of the Computer Science classic The C++ Programming Language Bjarne Stroustrup probably said it best when he said,

“I like my code to be elegant and efficient. The logic should be straightforward to make it hard for bugs to hide, the dependencies minimal to ease maintenance, error handling complete according to an articulated strategy, and performance close to optimal so as not to tempt people to make the code messy with unprincipled optimizations.”

And that’s where the value of code hygiene came to the forefront. Practitioners liken the experience to the elegance of orchestral music or to a meanly designed car.

It’s coldly efficient — which in the world of code translates to speedy and productive cycles. It keeps devs from trying to go with quick fixes because the code holds no messy secrets: it’s lean, mean, and absolutely transparent.

But what goes into writing clean code?

Take Steps Toward Clean Code

So how can you transform bad code into clean code? Here are some actions you can take to drive things in the right direction:

1. Define Class Names as Nouns

Classes and objects should be noun or noun phrases like Customer or Account Avoid words like Manager, Processor, Data, Info, or using verbs in the name of a class.

A handy guide would be Naming Conventions from Uncle Bob’s Clean Code Philosophy.

2. Clarify Function Names with Verbs

Methods should be a verb or verb phrase names like postPayment, deletePage, or save. Accessors, mutators, and predicates should be named for their value and prefixed with get, set, and is.

String name = customer.getName();

customer.setName(“john”);

if (customer.isRegistered())…

When constructors are overloaded, use static factory methods with names that describe the arguments. For example,

Complex fulcrumPoint = Complex.FromRealNumber(23.0);

is generally better than

Complex fulcrumPoint = new Complex(23.0);

Consider enforcing this usage by making the corresponding constructors private.

3. Pick One Word per Concept

Every abstract concept merits its own words. Pick it and stick with it all through. For instance, it’s confusing to have fetch, retrieve, and get as equivalent methods of different classes. How do you remember which method name goes with which class?

Sadly, you’d have to know which company, group, or individual wrote the library or class to remember which term was used. Or else you’d risk going down a winding spiral of old headers and forgotten code samples.

4. Encapsulate Conditionals

Boolean logic is hard enough to understand without having to see it in the context of an if or while statement.

Extract functions that explain the intent of the conditional.

For example:

if (shouldBeDeleted(timer))

is preferable to

if (timer.hasExpired() && !timer.isRecurrent())

5. Keep Functions Focused on Doing One Thing–Very Well

Look at this example:

if (includeSuiteSetup) {

WikiPage suiteTeardown = PageCrawlerImpl.getInheritedPage( SuiteResponder.SUITE_TEARDOWN_NAME, wikiPage);

if (suiteTeardown != null) {

WikiPagePath pagePath = suiteTeardown.getPageCrawler().getFullPath(suiteTeardown);

String pagePathName = PathParser.render(pagePath); buffer.append(“!include -teardown .”).append(pagePathName) .append(“\n”);

} } }

pageData.setContent(buffer.toString()); return pageData.getHtml();

}

Well, there’s a lot going on here with too many levels of abstraction. There’s too much going on at too many different levels of abstraction. There are strange strings and odd function calls mixed in with doubly nested if statements controlled by flags.

However, with the help of simple method extractions, minor renaming, and gentle restructuring, you can transform bad code into good code.

With just a few simple method extractions, some renaming, a little restructuring, we were able to capture the intent of the function in the few lines of listing

public static String renderPageWithSetupsAndTeardowns( PageData pageData, boolean isSuite) throws Exception {

if (isTestPage(pageData))

includeSetupAndTeardownPages(pageData, isSuite);

return pageData.getHtml();

}

6. Avoid Passing Flags to Functions

Let’s face it: Flag arguments are ugly. Passing a boolean into a function is a terrible practice. It immediately complicates the signature of the method, loudly proclaiming that this function does more than one thing. It does one thing if the flag is true, and another if the flag is false!

Ugly:

showProgressBar(true)

showProgressBar(false)

Pretty:

showProgressBar()

hideProgressBar()

7. Use Fewer Arguments

Passing a few arguments makes a function simpler to understand and easy to write test cases.

For example:

myFunction(float x, float y)

Can be simplified to:

myFunction(Points coordinates)

8. Use Exceptions Instead of Error Codes

The problem with these approaches is that they clutter the caller. The caller must check for errors immediately after the call and, unfortunately, it’s easy to forget.

To negate this, it’s better to throw an exception when you encounter an error. The calling code is cleaner and its logic isn’t obscured by error handling.

Bad practice:

public class DeviceController { …

public void sendShutDown() { DeviceHandle handle = getHandle(DEV1); // Check the state of the device

if (handle != DeviceHandle.INVALID) {

// Save the device status to the record field retrieveDeviceRecord(handle);

// If not suspended, shut down

if (record.getStatus() != DEVICE_SUSPENDED) {

pauseDevice(handle); clearDeviceWorkQueue(handle); closeDevice(handle);

} else {

logger.log(“Device suspended. Unable to shut down”);

}

} else {

logger.log(“Invalid handle for: “ + DEV1.toString()); }

}

… }

Using Exceptions:

public class DeviceController { …

public void sendShutDown() {

try {

tryToShutDown();

} catch (DeviceShutDownError e) {

logger.log(e);

}

}

9. Delete Commented Code

Comments maketh not bad code. And informative comments are always preferred. But commenting out your code? Well, it’s best if you avoid it.

InputStreamResponse response = new InputStreamResponse();

response.setBody(formatter.getResultStream(), formatter.getByteCount());

// InputStream resultsStream = formatter.getResultStream();

// StreamReader reader = new StreamReader(resultsStream);

// response.setContent(reader.read(formatter.getByteCount()));

Because anyone else who encounters your commented out code would hesitate to delete it. They would reason that it’s there for a reason and might just let it sit until it gathers like the dregs at the bottom of a cheap bottle of wine.

10. Make the Commitment

It’s not enough to write the code well. It needs to be maintained over time because code degradation is one of the most preventable problems out there.

So if you’re ever in doubt, think back to the Boy Scouts of America and the simple rule they stick to: Leave the campground cleaner than you found it.

That’s why experience matters when it comes to coding. Best practices have a way of ingraining themselves into developers that pay attention.

Perhaps that’s why Fortune 500s like Walmart, Nike and global pioneers like The Economist and AccuWeather trust our team of award-winning developers to deliver quality each time. Clean and custom code has a way of expressing its idea to the fullest, ensuring business owners and creators never compromise on their vision.

So if you’re ever looking to understand why clean and custom code can be your business’s biggest differentiator, reach out to us over here.

Maybe one conversation is all it takes to spark the change you’re looking for.

--

--

Mutual Mobile
Mutual Mobile

We’re an innovation consultancy that brings digital experiences to life through an integrated approach to design and technology.