What is a magic number, and why is it bad?

2018-12-31 00:29发布

What is a magic number?

Why should it be avoided?

Are there cases where it's appropriate?

15条回答
琉璃瓶的回忆
2楼-- · 2018-12-31 01:26

In programming, a "magic number" is a value that should be given a symbolic name, but was instead slipped into the code as a literal, usually in more than one place.

It's bad for the same reason SPOT (Single Point of Truth) is good: If you wanted to change this constant later, you would have to hunt through your code to find every instance. It is also bad because it might not be clear to other programmers what this number represents, hence the "magic".

People sometimes take magic number elimination further, by moving these constants into separate files to act as configuration. This is sometimes helpful, but can also create more complexity than it's worth.

查看更多
美炸的是我
3楼-- · 2018-12-31 01:26

I've always used the term "magic number" differently, as an obscure value stored within a data structure which can be verified as a quick validity check. For example gzip files contain 0x1f8b08 as their first three bytes, Java class files start with 0xcafebabe, etc.

You often see magic numbers embedded in file formats, because files can be sent around rather promiscuously and lose any metadata about how they were created. However magic numbers are also sometimes used for in-memory data structures, like ioctl() calls.

A quick check of the magic number before processing the file or data structure allows one to signal errors early, rather than schlep all the way through potentially lengthy processing in order to announce that the input was complete balderdash.

查看更多
姐姐魅力值爆表
4楼-- · 2018-12-31 01:29

What about return variables?

I specially find it challenging when implementing stored procedures.

Imagine the next stored procedure (wrong syntax, I know, just to show an example):

int procGetIdCompanyByName(string companyName);

It return the Id of the company if it exists in a particular table. Otherwise, it returns -1. Somehow it's a magic number. Some of the recommendations I've read so far says that I'll really have to do design somthing like that:

int procGetIdCompanyByName(string companyName, bool existsCompany);

By the way, what should it return if the company does not exists? Ok: it will set existesCompany as false, but also will return -1.

Antoher option is to make two separate functions:

bool procCompanyExists(string companyName);
int procGetIdCompanyByName(string companyName);

So a pre-condition for the second stored procedure is that company exists.

But i'm afraid of concurrency, because in this system, a company can be created by another user.

The bottom line by the way is: what do you think about using that kind of "magic numbers" that are relatively known and safe to tell that something is unsuccessful or that something does not exists?

查看更多
登录 后发表回答