[Backend Tutorial] How to deal with Magic Number in code

I really don't like the term "Magic Number". I see that many people are wrong. I have seen code reviews many times, and someone will comment on any number in the code and say, "This is a magic number. Be sure to put it in front of the file and define a name."

(I also doubt the necessity of putting all variables at the front of the file. I will talk about this topic next time).

I think you can use various numbers in the code, but you need to pay attention to the operation method.

What are magic numbers?

Googling, you can get a bunch of crappy definitions, but the bottom line is that a magic number is a number that is difficult to reason about in your code.

fun generate() {
    for (i in 0 until 52) {
        deck[i] = uniqueCard()
    }
}

Where did 52 come from?

It turns out that this code is to generate a deck of playing cards, because 52 is the number of decks of playing cards, so we can give this number a name.

const val numberOfCardsInADeck = 52

fun generate() {
    for (i in 0 until numberOfCardsInADeck) {
        deck[i] = uniqueCard()
    }
}

This results in more readable and maintainable code. Very good, you have mastered the method of writing clean code.

However, this is just the tip of the iceberg. The problem with this example is that developers can easily find out what 52 is from other parts of the code, which is a fairly simple magic number.

What makes the magic number a real headache for you is that you do n’t understand where it came from. Take the following code to adjust the search algorithm.

fun search(query: String) {
    find(query, 2.4f, 10.234f, 999, Int.MAX_VALUE, false)
}

What do these numbers mean? It is not easy to understand what these figures are for.

What is the problem with magic numbers?

Suppose your application is getting bigger and bigger and you need to search more and more things. Suddenly your search results don't get the results you want.

We have this problem: when I search for cereal, no cereal appears in the results, although I know it is inside.

So after the algorithm has been adjusted for four years, you need to change these values ​​to fix this bug, how do you start?

This is the problem of magic numbers. If these numbers are grouped together with long, descriptive names, together with code documentation, detailing the impact of changing them on search results, it will be easier to maintain.

There are also extra points in explaining the algorithm.

Let us fix this problem.

const val searchWeight = 2.4f // How specific your query must be. Increase this number to get more fuzzy results
const val searchSpread = 10.234f // How spread the result are. Selects more words in a row in the database
const val searchPageSize = 999 // The number of results we want per search page
const val searchMaxResults = Int.MAX_VALUE // We want every possible result from the search
const val shouldSearchIndex = false // We don't want to search indicies

fun search(query: String) {
    find(query, searchWeight, searchSpread, searchPageSize, searchMaxResults, shouldSearchIndex)
}

// Calls our weighted search algorithim. Read the docs about this alogirthim at foo.bar.com
fun find(query: String, weight: Float, spread: Float, pageSize: Int, maxResults: Int, index: Boolean) {}

Do you find it more comfortable to maintain this code? If someone can use this document to solve this bug, it will be more confident.

What is not a magic number?

In reality, numbers that are difficult to reason about do not appear as often as numbers that are easy to reason about. Take these hard-coded numbers as an example

view.height = 42

This is not a magic number. I repeat: this is not a magic number.

I know that this is a nerve for some Java purity and cleansing people.

But this number is not difficult to understand. Its role is completely self-contained: the height of this view is 42, nothing more. If you give it another name, what value will it add?


const val viewHeight = 42

fun buildView() {
    view.height = viewHeight
}

This is just bloated code. This seems to be a small example, but the idea of ​​meaninglessly naming numbers will soon inflate the size of the UI code and only increase the number of lines of meaningless code.

Can I use numbers in my code?

of course can. There are many good codes in the world written with numbers. You only need to keep a few things in mind.

Make sure your number is easy to understand — for example, elementary school students can understand the role of this number.

If you want to change a number, adjust something, or do some calculations on paper to get a hard-coded number, explain clearly. In the code, next to the number. Or at least state in the submission. There must be an explanation for changes to hard-coded numbers.

Bonus: make sure your hard-coded numbers are DRY (non-repeating).

This is not rocket science, but there are many subtleties in using your numbers.

You should be able to do this, thank you for reading!

Thanks to Zack Shapiro.

Original address:

https://medium.com/better-programming/magic-numbers-are-not-that-magic-132297d435f5

Service recommendation

Published 0 original articles · liked 0 · visits 351

Guess you like

Origin blog.csdn.net/weixin_47143210/article/details/105638559