Sign in to follow this  
Followers 0
czardas

In Defence of Magic Numbers

85 posts in this topic

#1 ·  Posted (edited)

Instead of poluting other people's threads with my opinions I decided to start one of my own.

• Using magic numbers fine tunes your application to squeeze the most out of the system by reducing memory usage and by avoiding the need for extra processing.

• Using magic numbers avoids the problems assiociated with global variable inconsistancies.

• Using magic numbers enables you to easily determine which bits are set and this helps to avoid introducing redundancy into your code.

• Using magic numbers side steps obfuscated and meaningless constant names created by non professionals, and this in turn prevents the associated confusion these names cause.

• Using magic numbers reduces bloat.

• Using magic numbers is fast and convenient.

Edited by czardas
1 person likes this

Share this post


Link to post
Share on other sites



OK, but all of that can be done before compiling, you as the developer shouldn't try and read optimised code as that's not a smart thing to do.


_AdapterConnections()_AlwaysRun()_AppMon()_AppMonEx()_BinaryBin()_CheckMsgBox()_CmdLineRaw()_ContextMenu()_ConvertLHWebColor()/_ConvertSHWebColor()_DesktopDimensions()_DisplayPassword()_DotNet_Load()/_DotNet_Unload()_Fibonacci()_FileCompare()_FileCompareContents()_FileNameByHandle()_FilePrefix/SRE()_FindInFile()_GetBackgroundColor()/_SetBackgroundColor()_GetConrolID()_GetCtrlClass()_GetDirectoryFormat()_GetDriveMediaType()_GetFilename()/_GetFilenameExt()_GetHardwareID()_GetIP()_GetIP_Country()_GetOSLanguage()_GetSavedSource()_GetStringSize()_GetSystemPaths()_GetURLImage()_GIFImage()_GoogleWeather()_GUICtrlCreateGroup()_GUICtrlListBox_CreateArray()_GUICtrlListView_CreateArray()_GUICtrlListView_SaveCSV()_GUICtrlListView_SaveHTML()_GUICtrlListView_SaveTxt()_GUICtrlListView_SaveXML()_GUICtrlMenu_Recent()_GUICtrlMenu_SetItemImage()_GUICtrlTreeView_CreateArray()_GUIDisable()_GUIImageList_SetIconFromHandle()_GUIRegisterMsg()_GUISetIcon()_Icon_Clear()/_Icon_Set()_IdleTime()_InetGet()_InetGetGUI()_InetGetProgress()_IPDetails()_IsFileOlder()_IsGUID()_IsHex()_IsPalindrome()_IsRegKey()_IsStringRegExp()_IsSystemDrive()_IsUPX()_IsValidType()_IsWebColor()_Language()_Log()_MicrosoftInternetConnectivity()_MSDNDataType()_PathFull/GetRelative/Split()_PathSplitEx()_PrintFromArray()_ProgressSetMarquee()_ReDim()_RockPaperScissors()/_RockPaperScissorsLizardSpock()_ScrollingCredits_SelfDelete()_SelfRename()_SelfUpdate()_SendTo()_ShellAll()_ShellFile()_ShellFolder()_SingletonHWID()_SingletonPID()_Startup()_StringCompact()_StringIsValid()_StringRegExpMetaCharacters()_StringReplaceWholeWord()_StringStripChars()_Temperature()_TrialPeriod()_UKToUSDate()/_USToUKDate()_WinAPI_Create_CTL_CODE()_WinAPI_CreateGUID()_WMIDateStringToDate()/_DateToWMIDateString()Au3 script parsingAutoIt SearchAutoIt3 PortableAutoIt3WrapperToPragmaAutoItWinGetTitle()/AutoItWinSetTitle()CodingDirToHTML5FileInstallrFileReadLastChars()GeoIP databaseGUI - Only Close ButtonGUI ExamplesGUICtrlDeleteImage()GUICtrlGetBkColor()GUICtrlGetStyle()GUIEventsGUIGetBkColor()Int_Parse() & Int_TryParse()IsISBN()LockFile()Mapping CtrlIDsOOP in AutoItParseHeadersToSciTE()PasswordValidPasteBinPosts Per DayPreExpandProtect GlobalsQueue()Resource UpdateResourcesExSciTE JumpSettings INISHELLHOOKShunting-YardSignature CreatorStack()Stopwatch()StringAddLF()/StringStripLF()StringEOLToCRLF()VSCROLLWM_COPYDATAMore Examples...

Updated: 04/09/2015

Share this post


Link to post
Share on other sites

#3 ·  Posted (edited)

Meh, for styles and things like that there is pretty much no chance of them ever changing, so go for it and it's not too bad.

Magic numbers should be avoided like the plague as soon as it gets into things that could possibly change in the future. So things like using hard coded constants for the size of data types for example. If it's a number of your own devising then also avoid magic numbers, so if your program accepts a password that should be a minimum of 6 characters it's very important you don't just use the number 6. As the code grows you'll be using the same value in lots of places, and you get a mess.

Guinness and myself have said many times that in your personal code you do what you want and we won't judge you. For code that has to be maintained by others, or code that will be used by less experienced programmers for learning from, use the constants.

And finally, all of your arguments are very good reasons for using a lower level compiled language. So the question remains, why use AutoIt?

Edited by Mat
1 person likes this

Share this post


Link to post
Share on other sites

#4 ·  Posted (edited)

Point 4 is really my biggest qualm - not understanding the constant names because they are sometimes more obfuscated than the binary. Words have meaning and if this meaning is corrupted by a programmer, it just adds confusion. I discovered this with midi messages, where some developer thought it was clever to use the term 'Velocity' in place of the standard term 'Attack'. This confused me for several years.

Edited by czardas

Share this post


Link to post
Share on other sites

Point 4 is really my biggest qualm - not understanding the constant names because they are sometimes more obfuscated than the binary. Words have meaning and if this meaning is corrupted by a programmer, it just adds confusion. I discovered this with midi messages, where some developer thought it was clever to use the term 'Velocity' in place of the standard word 'Attack'. This confused me for several years.

 

Lol at non-professionals as well, in many cases it's the professionals we need to worry about: MB_ICONASTERISK always makes me chuckle.

In 99% of cases I'm sure the constant is well named though. 

Share this post


Link to post
Share on other sites

#6 ·  Posted (edited)

Yeah most of the names are okay but stupid things do happen. ^_^ I'm also in favour of using global constants for a lot of stuff, but I think there is too much bad said about magic numbers. They are not evil at all. Using them also has a down side.

MB_ICONASTERISK >_<

Edited by czardas

Share this post


Link to post
Share on other sites

I am always thinking from the perspective of others mainting my code. I guess it comes from working on the help file and UDFs that I am stuck in my ways (which are far from perfect.)


_AdapterConnections()_AlwaysRun()_AppMon()_AppMonEx()_BinaryBin()_CheckMsgBox()_CmdLineRaw()_ContextMenu()_ConvertLHWebColor()/_ConvertSHWebColor()_DesktopDimensions()_DisplayPassword()_DotNet_Load()/_DotNet_Unload()_Fibonacci()_FileCompare()_FileCompareContents()_FileNameByHandle()_FilePrefix/SRE()_FindInFile()_GetBackgroundColor()/_SetBackgroundColor()_GetConrolID()_GetCtrlClass()_GetDirectoryFormat()_GetDriveMediaType()_GetFilename()/_GetFilenameExt()_GetHardwareID()_GetIP()_GetIP_Country()_GetOSLanguage()_GetSavedSource()_GetStringSize()_GetSystemPaths()_GetURLImage()_GIFImage()_GoogleWeather()_GUICtrlCreateGroup()_GUICtrlListBox_CreateArray()_GUICtrlListView_CreateArray()_GUICtrlListView_SaveCSV()_GUICtrlListView_SaveHTML()_GUICtrlListView_SaveTxt()_GUICtrlListView_SaveXML()_GUICtrlMenu_Recent()_GUICtrlMenu_SetItemImage()_GUICtrlTreeView_CreateArray()_GUIDisable()_GUIImageList_SetIconFromHandle()_GUIRegisterMsg()_GUISetIcon()_Icon_Clear()/_Icon_Set()_IdleTime()_InetGet()_InetGetGUI()_InetGetProgress()_IPDetails()_IsFileOlder()_IsGUID()_IsHex()_IsPalindrome()_IsRegKey()_IsStringRegExp()_IsSystemDrive()_IsUPX()_IsValidType()_IsWebColor()_Language()_Log()_MicrosoftInternetConnectivity()_MSDNDataType()_PathFull/GetRelative/Split()_PathSplitEx()_PrintFromArray()_ProgressSetMarquee()_ReDim()_RockPaperScissors()/_RockPaperScissorsLizardSpock()_ScrollingCredits_SelfDelete()_SelfRename()_SelfUpdate()_SendTo()_ShellAll()_ShellFile()_ShellFolder()_SingletonHWID()_SingletonPID()_Startup()_StringCompact()_StringIsValid()_StringRegExpMetaCharacters()_StringReplaceWholeWord()_StringStripChars()_Temperature()_TrialPeriod()_UKToUSDate()/_USToUKDate()_WinAPI_Create_CTL_CODE()_WinAPI_CreateGUID()_WMIDateStringToDate()/_DateToWMIDateString()Au3 script parsingAutoIt SearchAutoIt3 PortableAutoIt3WrapperToPragmaAutoItWinGetTitle()/AutoItWinSetTitle()CodingDirToHTML5FileInstallrFileReadLastChars()GeoIP databaseGUI - Only Close ButtonGUI ExamplesGUICtrlDeleteImage()GUICtrlGetBkColor()GUICtrlGetStyle()GUIEventsGUIGetBkColor()Int_Parse() & Int_TryParse()IsISBN()LockFile()Mapping CtrlIDsOOP in AutoItParseHeadersToSciTE()PasswordValidPasteBinPosts Per DayPreExpandProtect GlobalsQueue()Resource UpdateResourcesExSciTE JumpSettings INISHELLHOOKShunting-YardSignature CreatorStack()Stopwatch()StringAddLF()/StringStripLF()StringEOLToCRLF()VSCROLLWM_COPYDATAMore Examples...

Updated: 04/09/2015

Share this post


Link to post
Share on other sites

I am always thinking from the perspective of others mainting my code. I guess it comes from working on the help file and UDFs that I am stuck in my ways (which are far from perfect.)

 

It's good to have the constant names availabe for sure. The global constant system has many advantages. I just don't see everything being as simple as black and white, that's all.

Share this post


Link to post
Share on other sites

People like 1 general rule.

If we said "always use numbers" there'd be broken code everywhere.

If we say "always use names" the code should always work (albeit sub-optimally).

So the general rule is to go with the latter unless you can find a good reason not to.

Share this post


Link to post
Share on other sites

#10 ·  Posted (edited)

Well in debugging I often find it easier to fix an erroneous number. Variables I create are normally local in scope and I try to avoid writing any unclear code and introduce comments where I feel it is appropriate. Admittedly I'm not always successful in this. Generally I use binary as the mainstay of most of my apps. I need to see the numbers to be able to work with it. The numbers don't have to be hard coded and can be replaced by local variables if used more than once.

Edited by czardas

Share this post


Link to post
Share on other sites

I use magic numbers when I need a quick and dirty solution. When i start to get serious I use constants.

My 0.02 cents.


My UDFs and Tutorials:

Spoiler

UDFs:
Active Directory (NEW 2017-04-18 - Version 1.4.8.0) - Download - General Help & Support - Example Scripts - Wiki
OutlookEX (NEW 2017-02-27 - Version 1.3.1.0) - Download - General Help & Support - Example Scripts - Wiki
ExcelChart (2015-04-01 - Version 0.4.0.0) - Download - General Help & Support - Example Scripts
Excel - Example Scripts - Wiki
Word - Wiki
PowerPoint (2015-06-06 - Version 0.0.5.0) - Download - General Help & Support

Tutorials:
ADO - Wiki

 

Share this post


Link to post
Share on other sites

I do behind closed doors.


_AdapterConnections()_AlwaysRun()_AppMon()_AppMonEx()_BinaryBin()_CheckMsgBox()_CmdLineRaw()_ContextMenu()_ConvertLHWebColor()/_ConvertSHWebColor()_DesktopDimensions()_DisplayPassword()_DotNet_Load()/_DotNet_Unload()_Fibonacci()_FileCompare()_FileCompareContents()_FileNameByHandle()_FilePrefix/SRE()_FindInFile()_GetBackgroundColor()/_SetBackgroundColor()_GetConrolID()_GetCtrlClass()_GetDirectoryFormat()_GetDriveMediaType()_GetFilename()/_GetFilenameExt()_GetHardwareID()_GetIP()_GetIP_Country()_GetOSLanguage()_GetSavedSource()_GetStringSize()_GetSystemPaths()_GetURLImage()_GIFImage()_GoogleWeather()_GUICtrlCreateGroup()_GUICtrlListBox_CreateArray()_GUICtrlListView_CreateArray()_GUICtrlListView_SaveCSV()_GUICtrlListView_SaveHTML()_GUICtrlListView_SaveTxt()_GUICtrlListView_SaveXML()_GUICtrlMenu_Recent()_GUICtrlMenu_SetItemImage()_GUICtrlTreeView_CreateArray()_GUIDisable()_GUIImageList_SetIconFromHandle()_GUIRegisterMsg()_GUISetIcon()_Icon_Clear()/_Icon_Set()_IdleTime()_InetGet()_InetGetGUI()_InetGetProgress()_IPDetails()_IsFileOlder()_IsGUID()_IsHex()_IsPalindrome()_IsRegKey()_IsStringRegExp()_IsSystemDrive()_IsUPX()_IsValidType()_IsWebColor()_Language()_Log()_MicrosoftInternetConnectivity()_MSDNDataType()_PathFull/GetRelative/Split()_PathSplitEx()_PrintFromArray()_ProgressSetMarquee()_ReDim()_RockPaperScissors()/_RockPaperScissorsLizardSpock()_ScrollingCredits_SelfDelete()_SelfRename()_SelfUpdate()_SendTo()_ShellAll()_ShellFile()_ShellFolder()_SingletonHWID()_SingletonPID()_Startup()_StringCompact()_StringIsValid()_StringRegExpMetaCharacters()_StringReplaceWholeWord()_StringStripChars()_Temperature()_TrialPeriod()_UKToUSDate()/_USToUKDate()_WinAPI_Create_CTL_CODE()_WinAPI_CreateGUID()_WMIDateStringToDate()/_DateToWMIDateString()Au3 script parsingAutoIt SearchAutoIt3 PortableAutoIt3WrapperToPragmaAutoItWinGetTitle()/AutoItWinSetTitle()CodingDirToHTML5FileInstallrFileReadLastChars()GeoIP databaseGUI - Only Close ButtonGUI ExamplesGUICtrlDeleteImage()GUICtrlGetBkColor()GUICtrlGetStyle()GUIEventsGUIGetBkColor()Int_Parse() & Int_TryParse()IsISBN()LockFile()Mapping CtrlIDsOOP in AutoItParseHeadersToSciTE()PasswordValidPasteBinPosts Per DayPreExpandProtect GlobalsQueue()Resource UpdateResourcesExSciTE JumpSettings INISHELLHOOKShunting-YardSignature CreatorStack()Stopwatch()StringAddLF()/StringStripLF()StringEOLToCRLF()VSCROLLWM_COPYDATAMore Examples...

Updated: 04/09/2015

Share this post


Link to post
Share on other sites

#14 ·  Posted (edited)

I'm grateful for your responces. Now the other side of my gemini self wants to promote the use of global constants. :argue:  It's an internal tug of war. I know I shouldn't take stuff like this too seriously. :)

Edited by czardas

Share this post


Link to post
Share on other sites

Not as an addition to this discussion but more of a question

We can still use both atm as far as i understand

But for names it must be Beta?

And will this change one day so it has to be names?

Share this post


Link to post
Share on other sites

Not as an addition to this discussion but more of a question

We can still use both atm as far as i understand

But for names it must be Beta?

And will this change one day so it has to be names?

 

In the betas you'll find a lot more of the names documented, and used in examples. Most of them were already in Constants.au3 so are already in the stable (just not documented)

It can't be changed to just names. 

Share this post


Link to post
Share on other sites

Yes use the constant names; unless, like Mat said earlier, you have a good reason not to use them. Also explore Bitwise functions to broaden your understanding of how the system actually works.

Share this post


Link to post
Share on other sites

#19 ·  Posted (edited)

so 0 is technically the absence of a magic number, and therefore ok?  I find it more default than magic in most cases.

msgbox(0, "", $DebugString)  <-- will be the last number i stop using, its too easy to both author and understand.

Edited by boththose
1 person likes this

,-. .--. ________ .-. .-. ,---. ,-. .-. .-. .-.
|(| / /\ \ |\ /| |__ __||| | | || .-' | |/ / \ \_/ )/
(_) / /__\ \ |(\ / | )| | | `-' | | `-. | | / __ \ (_)
| | | __ | (_)\/ | (_) | | .-. | | .-' | | \ |__| ) (
| | | | |)| | \ / | | | | | |)| | `--. | |) \ | |
`-' |_| (_) | |\/| | `-' /( (_)/( __.' |((_)-' /(_|
'-' '-' (__) (__) (_) (__)

Share this post


Link to post
Share on other sites

#20 ·  Posted (edited)

so 0 is technically the absence of a magic number, and therefore ok?

:laser:

The day I have to type MB_DUNNOWHAT while debugging, instead using a quick zero, is the day I stop coding. Publishing code is a different matter. I think I have slight dislexia - you will notice I do a lot of edits to my posts.

Edit

I meant dyslexia

Edited by czardas

Share this post


Link to post
Share on other sites

Create an account or sign in to comment

You need to be a member in order to leave a comment

Create an account

Sign up for a new account in our community. It's easy!


Register a new account

Sign in

Already have an account? Sign in here.


Sign In Now
Sign in to follow this  
Followers 0