DEV Community

loading...
Cover image for Beautiful Code

Beautiful Code

hesamzakerirad profile image Hesam Rad ・4 min read

What is art?

If I were to answer this question, I'd say that ANYTHING in its finest state is art.

Code is no different.

To me, a programmer, high quality code is the absolute form of art. Recognizing beautiful code is not a hard thing to do. Do you find it hard to appreciate Mona Lisa? NO! You just have to see it and that's it.

Again, code is no different.

So why do many of us write something just to get it to run?

These are the reasons:

  • The deadline is close.
  • The boss needs it right away.
  • The codebase is trash.
  • I'm frustrated, I just want it to be over.
  • I need more money so the more projects I can get, the more money.
  • Oh yeah! This should work. [Copying code from Stackoverflow.]

I can go on but I you get the point.

These are the scenarios which lead to low quality code.

High quality code VS low quality code

  • High quality code:

    1. is cleaner.
    2. is more readable.
    3. is maintainable.
    4. is faster.
    5. is reusable.
    6. is better!
  • Low quality code:

    1. is NOT clean.
    2. is NOT readable.
    3. is NOT maintainable; and if you doubt me, ask me in 2 years!
    4. is NOT fast.
    5. is NOT reusable.
    6. is horrible!

I know you love code, and to demonstrate my point, I brought a little piece of code that I wrote over a year ago.

It's a simple function that receives a coupon from database and marks it as used.

public function revokeCoupon(Request $request) {
    $request->validate([
        'code' => 'required | integer'
    ]);
    $code = $this->checkIfCodeIsValid($request);
    if($code) {
        $flag = $this->checkIfCodeIsNotRevoked($code);
        if($flag) {
            $order = $this->getOrderAssociatedWithCode($code);
            if($order) {
                DB::connection('my_online_shop')
                    ->table('revoke_list')
                    ->where('code' , $code->code)
                    ->update(['revoked' => 1 ]);
                return redirect()->back()->with('message' , self::SUCCESSFUL_UPDATE_MESSAGE);
            }
        } else {
            return redirect()->back()->with('warning' , self::CODE_ALREADY_REVOKED);
        }
    } else {
        return redirect()->back()->with('error' , self::NO_SUCH_CODE);
    }
    return redirect()->back()->with('error' , self::UNSUCCESSFUL_UPDATE_MESSAGE);
}
Enter fullscreen mode Exit fullscreen mode

Oh humanity! How could I have written this? This is exactly what I was referring to as low quality code.

So I decided to make it better.

public function revokeCoupon(Request $request) {
    $request->validate([
        'code' => 'required | integer'
    ]);

    $code = $this->checkIfCodeIsValid($request);
    if(!$code) {
        return redirect()->back()->with('error' , self::NO_SUCH_CODE);
    }

    $flag = $this->checkIfCodeIsNotRevoked($code);
    if(!$flag) {
        return redirect()->back()->with('warning' , self::CODE_ALREADY_REVOKED);
    }

    $order = $this->getOrderAssociatedWithCode($code);
    if(!$order) {
        return redirect()->back()->with('error' , self::UNSUCCESSFUL_UPDATE_MESSAGE);
    }

    DB::connection('my_online_shop')
        ->table('revoke_list')
        ->where('code' , $code->code)
        ->update([
            'revoked' => 1 
        ]);
    return redirect()->back()->with('message' , self::SUCCESSFUL_UPDATE_MESSAGE);
}
Enter fullscreen mode Exit fullscreen mode

I KNOW! I KNOW! It's still too long and it breaks the SOLID. I just wanted to get rid of all the nested if statements to make it a little cleaner.

Next step was to get rid of the validation. I'm not going to go over the details of the process because that is topic for another post. (Click for more details.)

public function revokeCoupon(RevokeCouponRequest $request) {

    $code = $this->checkIfCodeIsValid($request);
    if(!$code) {
        return redirect()->back()->with('error' , self::NO_SUCH_CODE);
    }

    $flag = $this->checkIfCodeIsNotRevoked($code);
    if(!$flag) {
        return redirect()->back()->with('warning' , self::CODE_ALREADY_REVOKED);
    }

    $order = $this->getOrderAssociatedWithCode($code);
    if(!$order) {
        return redirect()->back()->with('error' , self::UNSUCCESSFUL_UPDATE_MESSAGE);
    }

    DB::connection('my_online_shop')
        ->table('revoke_list')
        ->where('code' , $code->code)
        ->update([
            'revoked' => 1 
        ]);
    return redirect()->back()->with('message' , self::SUCCESSFUL_UPDATE_MESSAGE);
}
Enter fullscreen mode Exit fullscreen mode

Much cleaner!

I could have done more and cleaned those functions a bit more but I was satisfied with the results; So I saved the code and pushed it to my gitlab.

As you can see this last version of the code is certainly better than the first version, more readable and maintainable.

Now that you know the benefits of high quality code, you might be asking how to write such code? Am I right? If so, let's get to it.

How to write high quality code?

There are actually to sides to this:

  1. The non-technical side
  2. The technical side
The non-technical side

In order to write good code you need to develop a few characteristic traits.

  • Patience. Let's face it; we are going to fail. If you wanna give up after a few times, you better change you career! I'm just being honest. Software engineering is a field in which you have to solve a problem you have never solved before.

  • Passion. I found that being passionate about something can make you tireless and undefeated and this can get you anywhere you want in this world.

  • Persistence. Remember, it doesn't matter that you have failed
    1000 times, I only has to work once! So code again.

The technical side

Ok here's the part you've been waiting for. To write high quality code you need to follow these simple rules.

  • Pay attention to your variable/method names. revokeCoupon is way better that my_cool_function.

  • Sometimes it's better to consider the false side of your if condition because that might make you code easier to understand; for example:

//textbook
if($condition) {
    return $jobNumberOne
} else {
    return $jobNumberTwo
}

//using this tip
if(!$condition) {
    return $jobNumberTwo
}
return $jobNumberOne
Enter fullscreen mode Exit fullscreen mode
  • Don't repeat yourself when coding. This is actually a famous principle also known as DRY!

  • Split up long functions into shorter functions. I'm happy that I knew this tip back when I was writing that nightmare in the beginning of the post. Imagine if it was just one long function! Gosh!

These were a few simple rules to get you started. I'll try think of more ways to share with you.

If you have your own ways of clean coding, I'd be more than happy to know about them.

Until the next post, take care 🖤

Link to cover image

Discussion (0)

pic
Editor guide