6

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

 3 years ago
source link: https://dev.to/marwangalal746/how-to-overcome-the-problem-of-long-if-statements-by-look-up-tables-3b31
Go to the source link to view the article. You can view the picture content, updated content and better typesetting reading experience. If the link is broken, please click the button below to view the snapshot at that time.
neoserver,ios ssh client
Cover image for How to overcome the problem of many if statements by Look up tables.

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

Aug 14

・1 min read

Introduction

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

Problem

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.

Solution

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.

Example

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 {
        fmt.Println("January")
} 
else if numOfMnths == 2 {
        fmt.Println("February")
}
.
.
.
Enter fullscreen modeExit fullscreen mode

We can solve it by Look up table like that:

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

Enter fullscreen modeExit fullscreen mode

Conclusion

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.


About Joyk


Aggregate valuable and interesting links.
Joyk means Joy of geeK