Linked lists, pointer tricks and good taste

Here is a good example of clean coding and refactoring. Even for such a small piece of code, refactoring is always good (if done properly of course).

Refactoring and clean coding are not separate tasks that you should do when you have extra time or when your boss gives you permission to do it. They are a part of the software development (or coding) process. When you write code, you should always pay attention to clean coding and as you write the code, if something doesn’t feel OK, you should immediately refactor and get rid of the problem.

I’ve worked on methods with 400+ lines of code, crazy if statements that no one understands, code with indentation so deep that it doesn’t make sense anymore and many unsolved mystery bugs. I witnessed some cases where the code does not do what it was supposed to do with extras like no logging, no errors on sentry, no nothing. This one time the team lead called me to fix the situation. The code was the one I just described and what was expected of me? Solve the problem just by looking at 400 lines of code. We didn’t even have the slightest clue of what was happening. Of course I knew that was not possible at that very moment, I told him we needed logging to figure it out but the response was something like: “You are a senior developer, you should be able to solve it.”.

I have no idea why the culture around coding is so limited and narrow for most of the coders. I think it is probably about the quality of software being so abstract and hard to measure. Anyone can code something that works but most of the coders, educated or not, cannot code high quality code. It is something like learning to read and write your mother language. We all learn to read and write in elementary school but most people, even in adulthood, have a hard time to write a good sentence. For example, let’s assume that I want to express to you that tonight I want to eat a hamburger. I can do this in many many ways but the most straightforward way is like this:

“Tonight I want to eat a hamburger.”

This is really easy to understand, very simple. Now imagine I am really really bad at expressing myself, like a really bad programmer. I will say something like this:

“After sun goes away today I want put in my stomach meat between bread.”

Here I am trying to express the same thing but it’s longer and takes more time to understand. I can go on like this as much as I want to. Here’s one more example:

“After 6 hours after hour 16:00 minus 1 hour I want to make my stomach full with cooked meat between two pieces of bread.”

So now imagine a program with 50000 lines of these. That’s what bad code looks like and that code needs refactoring.

Anti-pattern: Pyramid of Doom

Here is a good 7 minute read about one of the most common anti-patterns I encounter: the pyramid of doom. This is one of the first things I write about when creating a coding guideline in a company.

It increases the complexity of the code and thus it decreases maintainability and testability. All the details about why most projects have at least one pyramid of doom are in the article. Here is the link again: https://itnext.io/pyramid-of-doom-the-signs-and-symptoms-of-a-common-anti-pattern-c716838e1819

Below, you can find the example pyramid of doom written in the article and how I would fix it. I added some numbers to “//some code here” lines so that we can understand what moves where.

function login(){ 
    if(user == null){ 
        //some code here 1 
        if(userName != null){ 
            //some code here 2
            if(passwordMatch == true){ 
                //some code here 3
                if(returnedval != 'no_match'){    
                    //some code here 4
                    if(returnedval != 'incorrect_password'){ 
                        //some code here 5
                    } else{ 
                        //some code here 6
                    }         
                } else { 
                    //some code here 7
                }
            } else { 
                //some code here 8
            }
        } else { 
            //some code here 9
        }
    }
}

// How to write it better:
function login(){
    if(user != null)
        return
    //some code here 1
    if(userName == null){
        //some code here 9
        return
    }
    //some code here 2
    if(!passwordMatch){
        //some code here 8
        return
    }
    //some code here 3
    if(returnedVal == 'no_match'){
        //some code here 7
        return
    }
    //some code here 4
    if(returnedval == 'incorrect_password'){
        //some code here 6
        return
    }

    //some code here 5
}

As you can see, there is no more pyramid and there are no else clauses anymore. You just read the code in a straight line and you’re done! Happy refactoring the pyramids of doom everyone.

Complexity-Free Factory Pattern

Factory pattern is one of the most used patterns in software architectural design. But once used, it usually comes with unwanted complexity. The reason for this, is the use of many conditional statements like if or switch.

In our everyday use of factories, when a parameter is passed to the factory’s creator method, implementation goes through n numbers of conditional blocks to figure out what to return. This approach not just increases the complexity but also causes a lack of readability. To prevent this situation, registering a reference type variable that holds the reference to the class into a map will save the code from any type of complexity such as cognitive or cyclomatic…

Here there are two examples written in java and python. In these examples we have a payment system. You can pay by credit card or debit card. In both cases the payment methods are registered into a map and resolved when needed – lazy initialization – without conditional statements.

Here is the java version. You can check out PaymentFactory.java line 12, 13 and 14 to see this kind of usage. 

import java.util.function.Supplier;

public class PaymentProcessor {

    public static void main(String[] args){
        Supplier<Card> creditCard = PaymentFactory.getInstance().get(PaymentFactory.PaymentType.CREDIT_CARD);
        Supplier<Card> debitCard = PaymentFactory.getInstance().get(PaymentFactory.PaymentType.DEBIT_CARD);

        creditCard.get().charge(10.0);
        debitCard.get().charge(10.0);
        creditCard.get().charge(14.0);
        debitCard.get().charge(12.0);
        creditCard.get().charge(11.0);
        debitCard.get().charge(9.0);
    }
}
import java.util.EnumMap;
import java.util.Map;
import java.util.function.Supplier;

class PaymentFactory {

    private Map<PaymentType, Supplier<Card>> paymentList;
    private static PaymentFactory instance;

    private PaymentFactory()
    {
        paymentList = new EnumMap<>(PaymentType.class);
        paymentList.put(PaymentType.CREDIT_CARD, CreditCard::new);
        paymentList.put(PaymentType.DEBIT_CARD, DebitCard::new);
    }

    static PaymentFactory getInstance()
    {
        if (instance == null) {
            instance = new PaymentFactory();
        }

        return instance;
    }

    Supplier<Card> get(PaymentType type)
    {
        return paymentList.get(type);
    }

    enum PaymentType {
        CREDIT_CARD,
        DEBIT_CARD
    }
}
public class DebitCard implements Card {
    @Override
    public void charge(double amount) {
        System.out.println("Debit card charged " + amount + "$");
    }
}
public class CreditCard implements Card {
    @Override
    public void charge(double amount) {
        System.out.println("Credit card charged " + amount + "$");
    }
}
public interface Card {
    void charge(double amount);
}


from enum import Enum


class PaymentType(Enum):
    credit_card = 1
    debit_card = 2


class Card:
    def charge(self, amount):
        raise NotImplementedError


class CreditCard(Card):
    def charge(self, amount):
        print("Credit card charged {}$".format(amount))


class DebitCard(Card):
    def charge(self, amount):
        print("Debit card charged {}$".format(amount))


class PaymentFactory(object):
    payment_list = {
        PaymentType.credit_card: CreditCard,
        PaymentType.debit_card: DebitCard
    }

    @staticmethod
    def get(payment_type):
        assert payment_type in PaymentFactory.payment_list, "Payment type not found in factory."
        return PaymentFactory.payment_list[payment_type]


def main():
    credit_card = PaymentFactory.get(PaymentType.credit_card)()
    debit_card = PaymentFactory.get(PaymentType.debit_card)()

    credit_card.charge(10.0)
    debit_card.charge(10.0)
    credit_card.charge(14.0)
    debit_card.charge(12.0)
    credit_card.charge(11.0)
    debit_card.charge(9.0)


if __name__ == '__main__':
    main()

 

In addition to everything I described above; the main reason I wanted to write about this subject is that when you are new to design patterns and in this specific case, factory pattern, you will probably google it and see tons of examples. In most examples, the factory will use conditionals as I described at the beginning. Then one day, when you are brave enough, you will run a code quality analyzer on your code and it will raise alarms telling you to remove those conditionals. Then maybe(!) you will come to the same conclusion by yourself but you will lose time because you didn’t do it this way in the first place. So I hope someone someday reads this and saves a little bit of time. 

Technology Stack

  • OpenJDK Runtime Environment (build 10.0.2+13-Ubuntu-1ubuntu0.18.04.4)
  • Python 3.6.7

Acknowledgements

Berk Kibarer for writing the java version of the code and for helping to write the article.

Best Paper Awards in Computer Science (since 1996)

I came across this post on hackernews. Just like the title says, it lists many interesting papers from 1996 to 2018. I said in my first ever post that I am very into refactoring and clean coding these days so from this list one particular paper caught my eye: Understanding Misunderstandings in Source Code written by Dan Gopstein, Jake Iannacone, Yu Yan, Lois DeLong, Yanyan Zhuang, Martin K.-C. Yeh, Justin Cappos.

They talk about something they call “atoms of confusion” that are the smallest sections in source code that have the potential to confuse developers. They have a scientific way of finding these and so help developers and/or companies improve source code and cut development costs coming from these confusions. Here is the paper: https://atomsofconfusion.com/papers/understanding-misunderstandings-fse-2017.pdf