<p>What is a magic number?</p>

<p>Why should it be avoided?</p>

<p>Are there cases where it's appropriate?</p>

[{'answer_id': 47885, 'author': 'Brian R. Bondy', 'author_id': 3153, 'author_profile': 'https://Stackoverflow.com/users/3153', 'pm_score': 4, 'selected': False, 'text': '<p>A magic number is a sequence of characters at the start of a file format, or protocol exchange.  This number serves as a sanity check.</p>\n\n<p>Example:\nOpen up any GIF file, you will see at the very start: GIF89.  "GIF89" being the magic number.</p>\n\n<p>Other programs can read the first few characters of a file and properly identify GIFs. </p>\n\n<p>The danger is that random binary data can contain these same characters.  But it is very unlikely. </p>\n\n<p>As for protocol exchange, you can use it to quickly identify that the current \'message\' that is being passed to you is corrupted or not valid.   </p>\n\n<p>Magic numbers are still useful.</p>\n'}, {'answer_id': 47888, 'author': 'somas1', 'author_id': 412, 'author_profile': 'https://Stackoverflow.com/users/412', 'pm_score': 5, 'selected': False, 'text': '<p>Have you taken a look at the Wikipedia entry for <a href="http://en.wikipedia.org/wiki/Magic_number_(programming)" rel="noreferrer">magic number?</a></p>\n\n<p>It goes into a bit of detail about all of the ways the magic number reference is made.  Here\'s a quote about magic number as a bad programming practice </p>\n\n<blockquote>\n  <p>The term magic number also refers to the bad programming practice of using numbers directly in source code without explanation. In most cases this makes programs harder to read, understand, and maintain. Although most guides make an exception for the numbers zero and one, it is a good idea to define all other numbers in code as named constants.</p>\n</blockquote>\n'}, {'answer_id': 47889, 'author': 'Kyle Cronin', 'author_id': 658, 'author_profile': 'https://Stackoverflow.com/users/658', 'pm_score': 3, 'selected': False, 'text': '<p>I assume this is a response to my <a href="https://stackoverflow.com/questions/47878/codereview-tiny-encryption-algorithm-for-arbitrary-sized-data#47880">answer</a> to your earlier question. In programming, a magic number is an embedded numerical constant that appears without explanation. If it appears in two distinct locations, it can lead to circumstances where one instance is changed and not another. For both these reasons, it\'s important to isolate and define the numerical constants outside the places where they\'re used.</p>\n'}, {'answer_id': 47890, 'author': 'Michael Stum', 'author_id': 91, 'author_profile': 'https://Stackoverflow.com/users/91', 'pm_score': 7, 'selected': False, 'text': '<p>A Magic Number is a hard-coded value that may change at a later stage, but that can be therefore hard to update.</p>\n\n<p>For example, let\'s say you have a Page that displays the last 50 Orders in a "Your Orders" Overview Page. 50 is the Magic Number here, because it\'s not set through standard or convention, it\'s a number that you made up for reasons outlined in the spec.</p>\n\n<p>Now, what you do is you have the 50 in different places - your SQL script (<code>SELECT TOP 50 * FROM orders</code>), your Website (Your Last 50 Orders), your order login (<code>for (i = 0; i &lt; 50; i++)</code>) and possibly many other places.</p>\n\n<p>Now, what happens when someone decides to change 50 to 25? or 75? or 153? You now have to replace the 50 in all the places, and you are very likely to miss it. Find/Replace may not work, because 50 may be used for other things, and blindly replacing 50 with 25 can have some other bad side effects (i.e. your <code>Session.Timeout = 50</code> call, which is also set to 25 and users start reporting too frequent timeouts).</p>\n\n<p>Also, the code can be hard to understand, i.e. "<code>if a &lt; 50 then bla</code>" - if you encounter that in the middle of a complicated function, other developers who are not familiar with the code may ask themselves "WTF is 50???"</p>\n\n<p>That\'s why it\'s best to have such ambiguous and arbitrary numbers in exactly 1 place - "<code>const int NumOrdersToDisplay = 50</code>", because that makes the code more readable ("<code>if a &lt; NumOrdersToDisplay</code>", it also means you only need to change it in 1 well defined place.</p>\n\n<p>Places where Magic Numbers are appropriate is everything that is defined through a standard, i.e. <code>SmtpClient.DefaultPort = 25</code> or <code>TCPPacketSize = whatever</code> (not sure if that is standardized). Also, everything only defined within 1 function might be acceptable, but that depends on Context.</p>\n'}, {'answer_id': 47895, 'author': 'Nick Retallack', 'author_id': 2653, 'author_profile': 'https://Stackoverflow.com/users/2653', 'pm_score': 4, 'selected': False, 'text': '<p>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.</p>\n\n<p>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".</p>\n\n<p>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.</p>\n'}, {'answer_id': 47902, 'author': 'Marcio Aguiar', 'author_id': 4213, 'author_profile': 'https://Stackoverflow.com/users/4213', 'pm_score': 10, 'selected': True, 'text': '\n\n<p>A magic number is a direct usage of a number in the code.</p>\n\n<p>For example, if you have (in Java):</p>\n\n<pre class="lang-java prettyprint-override"><code>public class Foo {\n    public void setPassword(String password) {\n         // don\'t do this\n         if (password.length() &gt; 7) {\n              throw new InvalidArgumentException("password");\n         }\n    }\n}\n</code></pre>\n\n<p>This should be refactored to:</p>\n\n<pre class="lang-java prettyprint-override"><code>public class Foo {\n    public static final int MAX_PASSWORD_SIZE = 7;\n\n    public void setPassword(String password) {\n         if (password.length() &gt; MAX_PASSWORD_SIZE) {\n              throw new InvalidArgumentException("password");\n         }\n    }\n}\n</code></pre>\n\n<p>It improves readability of the code and it\'s easier to maintain. Imagine the case where I set the size of the password field in the GUI. If I use a magic number, whenever the max size changes, I have to change in two code locations. If I forget one, this will lead to inconsistencies.</p>\n\n<p>The JDK is full of examples like in <code>Integer</code>, <code>Character</code> and <code>Math</code> classes.</p>\n\n<p>PS: Static analysis tools like FindBugs and PMD detects the use of magic numbers in your code and suggests the refactoring.</p>\n'}, {'answer_id': 47923, 'author': 'Rob Rolnick', 'author_id': 4798, 'author_profile': 'https://Stackoverflow.com/users/4798', 'pm_score': 2, 'selected': False, 'text': '<p>It is worth noting that sometimes you do want non-configurable "hard-coded" numbers in your code. There are a number of <a href="http://en.wikipedia.org/wiki/Magic_number_(programming)" rel="nofollow noreferrer">famous ones</a> including 0x5F3759DF which is used in the optimized inverse square root algorithm. </p>\n\n<p>In the rare cases where I find the need to use such Magic Numbers, I set them as a const in my code, and document why they are used, how they work, and where they came from.</p>\n'}, {'answer_id': 47936, 'author': 'Andrew', 'author_id': 826, 'author_profile': 'https://Stackoverflow.com/users/826', 'pm_score': 0, 'selected': False, 'text': "<p>@eed3si9n: I'd even suggest that '1' is a magic number. :-)</p>\n\n<p>A principle that's related to magic numbers is that every fact your code deals with should be declared exactly once. If you use magic numbers in your code (such as the password length example that @marcio gave, you can easily end up duplicating that fact, and when your understand of that fact changes you've got a maintenance problem.</p>\n"}, {'answer_id': 48068, 'author': 'DGentry', 'author_id': 4761, 'author_profile': 'https://Stackoverflow.com/users/4761', 'pm_score': 3, 'selected': False, 'text': '<p>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.</p>\n\n<p>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.</p>\n\n<p>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.</p>\n'}, {'answer_id': 48220, 'author': 'Sören Kuklau', 'author_id': 1600, 'author_profile': 'https://Stackoverflow.com/users/1600', 'pm_score': 4, 'selected': False, 'text': '<p>A magic number can also be a number with special, hardcoded semantics. For example, I once saw a system where record IDs > 0 were treated normally, 0 itself was "new record", -1 was "this is the root" and -99 was "this was created in the root". 0 and -99 would cause the WebService to supply a new ID.</p>\n\n<p>What\'s bad about this is that you\'re reusing a space (that of signed integers for record IDs) for special abilities. Maybe you\'ll never want to create a record with ID 0, or with a negative ID, but even if not, every person who looks either at the code or at the database might stumble on this and be confused at first. It goes without saying those special values weren\'t well-documented.</p>\n\n<p>Arguably, <a href="http://thedailywtf.com/Articles/Classic-WTF-The-Phantom-of-The-System.aspx" rel="noreferrer">22, 7, -12 and 620</a> count as magic numbers, too. ;-)</p>\n'}, {'answer_id': 364532, 'author': 'Community', 'author_id': -1, 'author_profile': 'https://Stackoverflow.com/users/-1', 'pm_score': 4, 'selected': False, 'text': "<p>A problem that has not been mentioned with using magic numbers...</p>\n\n<p>If you have very many of them, the odds are reasonably good that you have two different <em>purposes</em> that you're using magic numbers for, where the <em>values</em> happen to be the same.</p>\n\n<p>And then, sure enough, you need to change the value... for only one purpose.</p>\n"}, {'answer_id': 1554616, 'author': 'Ascalonian', 'author_id': 65230, 'author_profile': 'https://Stackoverflow.com/users/65230', 'pm_score': 1, 'selected': False, 'text': "<p>What about initializing a variable at the top of the class with a default value? For example:</p>\n\n<pre><code>public class SomeClass {\n    private int maxRows = 15000;\n    ...\n    // Inside another method\n    for (int i = 0; i &lt; maxRows; i++) {\n        // Do something\n    }\n\n    public void setMaxRows(int maxRows) {\n        this.maxRows = maxRows;\n    }\n\n    public int getMaxRows() {\n        return this.maxRows;\n    }\n</code></pre>\n\n<p>In this case, 15000 is a magic number (according to CheckStyles). To me, setting a default value is okay. I don't want to have to do:</p>\n\n<pre><code>private static final int DEFAULT_MAX_ROWS = 15000;\nprivate int maxRows = DEFAULT_MAX_ROWS;\n</code></pre>\n\n<p>Does that make it more difficult to read? I never considered this until I installed CheckStyles.</p>\n"}, {'answer_id': 18184180, 'author': 'Oskytar', 'author_id': 400120, 'author_profile': 'https://Stackoverflow.com/users/400120', 'pm_score': -1, 'selected': False, 'text': '<p>What about return variables?</p>\n\n<p>I specially find it challenging when implementing <strong>stored procedures</strong>.</p>\n\n<p>Imagine the next stored procedure (wrong syntax, I know, just to show an example):</p>\n\n<pre><code>int procGetIdCompanyByName(string companyName);\n</code></pre>\n\n<p>It return the Id of the company if it exists in a particular table. Otherwise, it returns -1.\nSomehow 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:</p>\n\n<pre><code>int procGetIdCompanyByName(string companyName, bool existsCompany);\n</code></pre>\n\n<p>By the way, what should it return if the company does not exists? Ok: it will set <em>existesCompany</em> as <strong>false</strong>, but also will return -1.</p>\n\n<p>Antoher option is to make two separate functions:</p>\n\n<pre><code>bool procCompanyExists(string companyName);\nint procGetIdCompanyByName(string companyName);\n</code></pre>\n\n<p>So a pre-condition for the second stored procedure is that company exists.</p>\n\n<p>But i\'m afraid of concurrency, because in this system, a company can be created by another user.</p>\n\n<p>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?</p>\n'}, {'answer_id': 30743302, 'author': 'jguiraud', 'author_id': 3570922, 'author_profile': 'https://Stackoverflow.com/users/3570922', 'pm_score': 0, 'selected': False, 'text': '<p>Another advantage of extracting a magic number as a constant gives the possibility to clearly document the business information.</p>\n\n<pre><code>public class Foo {\n    /** \n     * Max age in year to get child rate for airline tickets\n     * \n     * The value of the constant is {@value}\n     */\n    public static final int MAX_AGE_FOR_CHILD_RATE = 2;\n\n    public void computeRate() {\n         if (person.getAge() &lt; MAX_AGE_FOR_CHILD_RATE) {\n               applyChildRate();\n         }\n    }\n}\n</code></pre>\n'}, {'answer_id': 33325478, 'author': 'Liberty Lover', 'author_id': 1096587, 'author_profile': 'https://Stackoverflow.com/users/1096587', 'pm_score': 5, 'selected': False, 'text': "<h1>Magic Number Vs. Symbolic Constant: When to replace?</h1>\n<p>Magic: Unknown semantic</p>\n<p>Symbolic Constant -&gt; Provides both correct semantic and correct context for use</p>\n<p>Semantic: The meaning or purpose of a thing.</p>\n<p>&quot;Create a constant, name it after the meaning, and replace the number with it.&quot; -- Martin Fowler</p>\n<p>First, magic numbers are not just numbers. Any basic value can be &quot;magic&quot;. Basic values are manifest entities such as integers, reals, doubles, floats, dates, strings, booleans, characters, and so on. The issue is not the data type, but the &quot;magic&quot; aspect of the value as it appears in our code text.</p>\n<p>What do we mean by &quot;magic&quot;? To be precise: By &quot;magic&quot;, we intend to point to the semantics (meaning or purpose) of the value in the context of our code; that it is unknown, unknowable, unclear, or confusing. This is the notion of &quot;magic&quot;. A basic value is not magic when its semantic meaning or purpose-of-being-there is quickly and easily known, clear, and understood (not confusing) from the surround context without special helper words (e.g. symbolic constant).</p>\n<p>Therefore, we identify magic numbers by measuring the ability of a code reader to know, be clear, and understand the meaning and purpose of a basic value from its surrounding context. The less known, less clear, and more confused the reader is, the more &quot;magic&quot; the basic value is.</p>\n<h1>Basics</h1>\n<p>We have two scenarios for our magic basic values. Only the second is of primary importance for programmers and code:</p>\n<ol>\n<li>A lone basic value (e.g. number) from which its meaning is unknown, unknowable, unclear or confusing.</li>\n<li>A basic value (e.g. number) in context, but its meaning remains unknown, unknowable, unclear or confusing.</li>\n</ol>\n<p>An overarching dependency of &quot;magic&quot; is how the lone basic value (e.g. number) has no commonly known semantic (like Pi), but has a locally known semantic (e.g. your program), which is not entirely clear from context or could be abused in good or bad context(s).</p>\n<p>The semantics of most programming languages will not allow us to use lone basic values, except (perhaps) as data (i.e. tables of data). When we encounter &quot;magic numbers&quot;, we generally do so in a context. Therefore, the answer to</p>\n<blockquote>\n<p>&quot;Do I replace this magic number with a symbolic constant?&quot;</p>\n</blockquote>\n<p>is:</p>\n<blockquote>\n<p>&quot;How quickly can you assess and understand the semantic meaning of the\nnumber (its purpose for being there) in its context?&quot;</p>\n</blockquote>\n<h1>Kind of Magic, but not quite</h1>\n<p>With this thought in mind, we can quickly see how a number like Pi (3.14159) is not a &quot;magic number&quot; when placed in proper context (e.g. 2 x 3.14159 x radius or 2<em>Pi</em>r). Here, the number 3.14159 is mentally recognized Pi without the symbolic constant identifier.</p>\n<p>Still, we generally replace 3.14159 with a symbolic constant identifier like Pi because of the length and complexity of the number. The aspects of length and complexity of Pi (coupled with a need for accuracy) usually means the symbolic identifier or constant is less prone to error. Recognition of &quot;Pi&quot; as a name is a simply a convenient bonus, but is not the primary reason for having the constant.</p>\n<h1>Meanwhile: Back at the Ranch</h1>\n<p>Laying aside common constants like Pi, let's focus primarily on numbers with special meanings, but which those meanings are constrained to the universe of our software system. Such a number might be &quot;2&quot; (as a basic integer value).</p>\n<p>If I use the number 2 by itself, my first question might be: What does &quot;2&quot; mean? The meaning of &quot;2&quot; by itself is unknown and unknowable without context, leaving its use unclear and confusing. Even though having just &quot;2&quot; in our software will not happen because of language semantics, we do want to see that &quot;2&quot; by itself carries no special semantics or obvious purpose being alone.</p>\n<p>Let's put our lone &quot;2&quot; in a context of: <code>padding := 2</code>, where the context is a &quot;GUI Container&quot;. In this context the meaning of 2 (as pixels or other graphical unit) offers us a quick guess of its semantics (meaning and purpose). We might stop here and say that 2 is okay in this context and there is nothing else we need to know. However, perhaps in our software universe this is not the whole story. There is more to it, but &quot;padding = 2&quot; as a context cannot reveal it.</p>\n<p>Let's further pretend that 2 as pixel padding in our program is of the &quot;default_padding&quot; variety throughout our system. Therefore, writing the instruction <code>padding = 2</code> is not good enough. The notion of &quot;default&quot; is not revealed. Only when I write: <code>padding = default_padding</code> as a context and then elsewhere: <code>default_padding = 2</code> do I fully realize a better and fuller meaning (semantic and purpose) of 2 in our system.</p>\n<p>The example above is pretty good because &quot;2&quot; by itself could be anything. Only when we limit the range and domain of understanding to &quot;my program&quot; where 2 is the <code>default_padding</code> in the GUI UX parts of &quot;my program&quot;, do we finally make sense of &quot;2&quot; in its proper context. Here &quot;2&quot; is a &quot;magic&quot; number, which is factored out to a symbolic constant <code>default_padding</code> within the context of the GUI UX of &quot;my program&quot; in order to make it use as <code>default_padding</code> quickly understood in the greater context of the enclosing code.</p>\n<p>Thus, any basic value, whose meaning (semantic and purpose) cannot be sufficiently and quickly understood is a good candidate for a symbolic constant in the place of the basic value (e.g. magic number).</p>\n<h1>Going Further</h1>\n<p>Numbers on a scale might have semantics as well. For example, pretend we are making a D&amp;D game, where we have the notion of a monster. Our monster object has a feature called <code>life_force</code>, which is an integer. The numbers have meanings that are not knowable or clear without words to supply meaning. Thus, we begin by arbitrarily saying:</p>\n<ul>\n<li>full_life_force: INTEGER = 10 -- Very alive (and unhurt)</li>\n<li>minimum_life_force: INTEGER = 1 -- Barely alive (very hurt)</li>\n<li>dead: INTEGER = 0 -- Dead</li>\n<li>undead: INTEGER = -1 -- Min undead (almost dead)</li>\n<li>zombie: INTEGER = -10 -- Max undead (very undead)</li>\n</ul>\n<p>From the symbolic constants above, we start to get a mental picture of the aliveness, deadness, and &quot;undeadness&quot; (and possible ramifications or consequences) for our monsters in our D&amp;D game. Without these words (symbolic constants), we are left with just the numbers ranging from <code>-10 .. 10</code>. Just the range without the words leaves us in a place of possibly great confusion and potentially with errors in our game if different parts of the game have dependencies on what that range of numbers means to various operations like <code>attack_elves</code> or <code>seek_magic_healing_potion</code>.</p>\n<p>Therefore, when searching for and considering replacement of &quot;magic numbers&quot; we want to ask very purpose-filled questions about the numbers within the context of our software and even how the numbers interact semantically with each other.</p>\n<h1>Conclusion</h1>\n<p>Let's review what questions we ought to ask:</p>\n<p>You might have a magic number if ...</p>\n<ol>\n<li>Can the basic value have a special meaning or purpose in your softwares universe?</li>\n<li>Can the special meaning or purpose likely be unknown, unknowable, unclear, or confusing, even in its proper context?</li>\n<li>Can a proper basic value be improperly used with bad consequences in the wrong context?</li>\n<li>Can an improper basic value be properly used with bad consequences in the right context?</li>\n<li>Does the basic value have a semantic or purpose relationships with other basic values in specific contexts?</li>\n<li>Can a basic value exist in more than one place in our code with different semantics in each, thereby causing our reader a confusion?</li>\n</ol>\n<p>Examine stand-alone manifest constant basic values in your code text. Ask each question slowly and thoughtfully about each instance of such a value. Consider the strength of your answer. Many times, the answer is not black and white, but has shades of misunderstood meaning and purpose, speed of learning, and speed of comprehension. There is also a need to see how it connects to the software machine around it.</p>\n<p>In the end, the answer to replacement is answer the measure (in your mind) of the strength or weakness of the reader to make the connection (e.g. &quot;get it&quot;). The more quickly they understand meaning and purpose, the less &quot;magic&quot; you have.</p>\n<p>CONCLUSION: Replace basic values with symbolic constants only when the magic is large enough to cause difficult to detect bugs arising from confusions.</p>\n"}]
['https://Stackoverflow.com/questions/47882', 'https://Stackoverflow.com', 'https://Stackoverflow.com/users/2915/']