DEV Community

Cover image for How to overcome the problem of many if statements by Look up tables.
Marwan Galal
Marwan Galal

Posted on

How to overcome the problem of many if statements by Look up tables.


In this guide I will show you a way to overcome the many if statements which faces most of beginner programmers.


Assume that you have a task and after you finished and tested it, you found a case which not covered, so you add an else if statement to convert it, but time after time, your code became full of if and else if statements and the makes your code not readable for others.


One of the ways to solve this problem is Look up table, it's just a data structure that we store the cases of the problem with it.
Look up table makes our code readable because we can access the cases by direct access if we use an array.


If you want to write a program which take a number of the month and output the name of the month, for example, If you input 1, It will output January.
You can solve this problem with long If statements, But your code will not be readable like that:

if numOfMnths == 1 {
else if numOfMnths == 2 {
Enter fullscreen mode Exit fullscreen mode

We can solve it by Look up table like that:

months :=[12] string{"January", "February", ...}
//if numOfMnths is equal 1 it will print January

Enter fullscreen mode Exit fullscreen mode


Look up table helps you to make your code more readable for you and others using the suitable data structure for your problem and it's very useful with simple problems.

Top comments (0)