“Don’t Marry My Daughter Before You Clean Your Code!”

khalis murfid
Inside PPL B7
Published in
8 min readMar 9, 2020

That’s what that 50 years old programmer said to her daughter boyfriend who is also a programmer. The boyfriend felt a little frustrated and he cursed the old man in his thought. Little that he knows, that old man is the wisest of all programmer and he did it for the greater good.

Photo by Clément H on Unsplash

Our hero today is a man named David who’s also a programmer at some startup in his city. David is so talented at programming. He was the Nation Computer Science Olympic Champion of 3 years in a row. He writes efficient, mind-bending, and unimaginable code that no one could ever think of writing one. He can solve any problem given to him like nobody else.

But our man David has only one weakness. He writes good code, only to himself. David solved any programming problem by himself. He codes by and only for himself. That’s why when other’s programmer take look at his code, they’re as clueless as 5 years old reading a physicist notes. Yeah, David writes a really bad code that only computer and him who can understand it.

So, why the old man really cares about it? up to the point where he forbid David to marry her daughter because of his ‘dirty’ code habit. Let’s see what this clean code about and how to make one.

Introduction

I’ve read somewhere that functions are like simple omelettes. You may think you have mastered it, but you probably never heard that omelettes ( the french one), are one of the hardest recipes to master. How complex could it be? After all, you only need eggs, salt, pepper, and maybe some milk right? And yet, after the very first omelette made by a skilled chef, your thought crumbling before your very eyes. You just tasted a whole different world and you will never think that omelette is simple ever again.

So what’s clean code? What makes a function clean? What code is eligible to be called a ‘dirty’ code?

The Act of Cleaning a Code

Let’s take a look to a code snippet below:

This function is a mess and we all know it. It breaks single principle responsibility and it looks like it needs some time to understand the code. Our login function has at least the following responsibility:

  • Handle nil values and validation
  • Alert presentation
  • Authenticate user and handle the responses
  • Pages Navigation

For you guys who aren’t familiar to Swift, don’t worry because I’m gonna break down and explain the function piece by piece.

First, we got this line:

if let username = username, let password = password { … }

It’s basically telling that the username and password must not be nil. In swift, a variable can be nil values if we add ‘?’ to the end of its type initialization.

Example: var username: String?

Swift is a type-safe language, which means the language helps you to be clear about the types of values your code can work with. If part of your code requires a String, type safety prevents you from passing it nil by mistake because String is different from String? and that’s the way that we can help the function to be cleaner than before.

func login(username: String?, password: String?) { … }

This login function takes 2 parameters and as we can see, both parameters can be nil because of the question mark following the type. Why bother to handle nil values of the parameters, if we can make sure that our parameters will be not nil. After all, our username and password nil values could be handled somewhere else and not in this specific login function.

Let’s clean it up!

func login(username: String, password: String) { … }

See? With this, our login function didn’t have to handle nil values because it has been handled somewhere. Now, let’s move on to the next line.

if password.count < 6 || username.count < 6 { … }

This is a validation check and it should not be implemented in this function. What if sometimes in the future, the requirement change and it needs a different validation? It will add up the condition to refactor our login function which only needs to perform login. This function would suffice:

func areCredentialsValid(username: String, password: String) -> Bool

Why our function name is like asking? Because we want our code to be self-documented. It is much easier if our function name describes exactly what it does, so we don’t have to actually look carefully at the code. Someone who looks at this code would probably guess it right on the first time that this function is to check the validity of our username and password. Now its name is a documentations.

let alertController = UIAlertController(
title: “Invalid credentials”, message:
“Password must contain at least 6 character long”,
preferredStyle: .alert)
present(alertController, animated: true, completion: nil)

I think we all agree that this is a repetitive task and it deserves its own function.

Finally, the piece that this function really needs to implement:

networkManager.authenticate(
username: username,
password: password
) { (_, status) in
if status != 200 || status != 201 {
self?.navigationController?.pushViewController(
DashboardViewController(),
animated: true
)} else {
let alertController = UIAlertController(
title: "Invalid credentials", message:
"Password or Username Wrong",
preferredStyle: .alert)
present(alertController, animated: true, completion: nil)
}
}

Authentication call is what this function should solely do. But first, let’s take look at the status checking first:

if status != 200 || status != 201 { ... }

It’s a real bad because it’s hardcoded and nobody knows those status number will always be 200 and 201. It will be better if we use something else to help validate those. This is where this enum comes in rescue:

enum HttpResponseStatus: Int {
case success
case failed
init(_ statusCode: Int) {
switch statusCode {
case 200..<300:
self = .success
default:
self = .failed
}
}
}

What’s enum? Apple doc says:

An enumeration defines a common type for a group of related values and enables you to work with those values in a type-safe way within your code.

Let’s cut to the chase and not deeply talking about enum because it’s a whole another topic, but you may read it on here for more information.

If we call HttpResponseStatus(200), it will return HttpResponseStatus.success. If we call HttpResponseStatus(400), it will return HttpResponseStatus.failed.

Long story short, if we call the HttpResponseStatus with any number between 200 and 300, it will always return .success and it will return .failed for anything other than those values.

Now we can check the status with just this one line:

if HttpResponseStatus(status) == .success { ... }

Now all that’s is left is just extract the following lines:

if HttpResponseStatus(status) == .success { 
self?.navigationController?.pushViewController(
DashboardViewController(),
animated: true
)} else {
let alertController = UIAlertController(
title: "Invalid credentials", message:
"Password or Username Wrong",
preferredStyle: .alert)
present(alertController, animated: true, completion: nil)}

Those lines tell us that if the status is .success, it will go to the Dashboard page. Otherwise, it will send an alert saying that the credential is wrong.

An improved version might look like this:

Notice how the above code reads from top to bottom, easily readable which makes our function(s) closer to Single Responsibility Principle. However, validateCredentials function seems problematic because it also handles alert presentation. It will be another topic because it talks about design patterns and view controller should only handle UI.

And that’s it, guys! That’s how we clean a code. I just wanted you guys to know that this act of cleaning code maybe cannot be applied to other programming language or frameworks because as we know, different region have their own omelette and that’s why you should do your own research for clean code in your preferences programming language or frameworks.

Recap

My definitions of clean code, despite the differences in its implementation between different language, are as follows:

  1. Clean code is simple. It’s fun to writes overly clever codes like David. But you need to remember that your code is not your own. Be mindful about your code implementation. Sometimes, a simple code is more beneficial than efficient code.
  2. Clean code is readable. A good code is a code that explains itself. Yep, if someone wants to modify or to use your code, they need good readability because the reader will almost certainly fail to understand the original author’s intent if a code naming convention is bad. You need meaningful names for every code you write
  3. Clean code is elegant. Reading a clean code should make you happy and excited because it’s like reading a well-made novel. Clean code must contain no duplication because who want to wasted time reading a repetitive story on a book.
  4. Clean code is focused. Every function, class, or module must only have one intention. Their responsibility must remain solid even when their surroundings change.
  5. Clean code doesn't rely on short lines number. Yes just like our example, we just expand our code from 28 lines to 62 lines. But it’s so much easier to understand the latter than the former. More lines don't always mean its worse.
  6. Clean code is handling error with grace. As developers, we are expected to make sure that the code does what it is expected to do. However, the issue is not handling the error; the issue is handling the error in a clean readable way. Error handling will be different in different language and frameworks, so my suggestion is, start your function with error handling first.
  7. Clean code is your pride. Two words: Craftsmanship Matters.

Your code is not your own code. It will be read, used, and modified by other people so you better make the best of it.

Let’s get back to our story:

“Don’t Marry My Daughter Before You Clean Your Code!”

The very next day David come again to talk to the old programmer. He has read this article and learn to write clean code from different sources. He is a genius so one night is all it takes to master clean code. He comes with confidence and shows the old man his new knowledge.

The old man sits down on his chair and calmly said:

“If you care enough about other people to actually writes a clean code, then it means you will be care enough about my daughter. David, you may marry my daughter.”

And that’s the story of a man who just knows that clean code is what makes a good person.

--

--