Opened 3 years ago
Last modified 3 years ago
#55662 new enhancement
Eliminating magic numbers
Reported by: |
|
Owned by: | |
---|---|---|---|
Milestone: | Awaiting Review | Priority: | normal |
Severity: | normal | Version: | |
Component: | General | Keywords: | |
Focuses: | coding-standards | Cc: |
Description
Magic numbers in code are unique values with unexplainable meaning. These numbers can be confusing to the reader. To learn more, see: https://en.wikipedia.org/wiki/Magic_number_(programming)
Using this example:
$max_filesize = 5 * 1024 * 1024
;
A common way to eliminate those numbers is by using either comments or constants. Example:
$max_filesize = 5 * 1024 * 1024; // 5 MB
$max_filesize = 5 * MB_IN_BYTES;
WordPress counts at least 20 instances of using 1024
in PHP, either meaning filesize, screen, or image dimensions. Using constant definitions would instantly differentiate their meaning when browsing the code.
Another example is fileupload_maxk
, which defaults to 1500
. If we define that size using a constant, we could easily update all related instances without having to inspect those manually: simply by updating the constant value. This cohesiveness aids in reducing regressions.
All of the occurrences of
1024
are within external libraries, or simply don't refer to Kilobytes.Using the
KB_IN_BYTES
constant for those would be incorrect. The majority of the non-KB numbers happen to be the image constants, which while duplicative, centralising it within a constant wouldn't necessarily be beneficial or provide cleaner code, as the sizes should never be used for anything other than a function default (Generally, WordPress refers to things by the human-readable slug, such as 'large').Here's a list of the not-in-external-code uses I quickly pulled:
Regarding
fileupload_maxk
& 1500 it might make sense to swap that to a constant, it would be helpful to define a default for network-wide via code, however, there's not exactly many cases of it:I'm more concerned about the one lonely default of 300 :)