Sign in to follow this  
Followers 0
Auto42

Questions regarding AutoIt coding practice

4 posts in this topic

Hi

I read the topic to the "Best coding practice" in the AutoIt wiki and tried to adapt my code to those recommendations. I used the #AutoIt3Wrapper_Au3Check_Parameters=-q -d -w 1 -w 2 -w 3 -w- 4 -w 5 -w 6 -w- 7 statement too to check my code. Some questions to the coding practice remain:

 

1 )

Does it make sense to declare and initialize variables as shown in the AutoIt-Wiki:

;Bad
Local $iSomeVar1, $aiArray = 0
Local $iSomeVar2 = 5

;Good
Local $iSomeVar1 = 0, $iSomeVar2 = 5
Local $aiArray = 0

 Source: AutoIt Wiki

Elsewhere in this forum (experienced coders) wrote it would make no functionally difference to declare variables in that way and that variables should only initialized when necessary:

;Declared string-var
Local $sSomeString

;Declared and initialized string-var ("Bad" practice?)
Local §sSomeString = ''

Does this apply to integers and arrays as well? In the case citeded above the $aiArray is initialized as integer. Where is the difference in this example (is there really a difference?):

; Array var is initialized as int and casted to array
Local $aiArray = 0
; Redeclare and assign values later on
$ai Array[3] = [1, 2, 3]

; Array var is initialized as string and casted to array
Local $aiArray
; Redeclare and assign values later on
$ai Array[3] = [1, 2, 3]

I am not sure how to declare and intialize empty arrays.

 

2)

Is it good coding practice to declare and assign variables where needed, especially when used as return value of build-in functions? Example:

Func example()
    Local $sTestString
    Local $asStringArray
    Local $bSomeBool
    Local $iNum = 42
    #cs------------------
    Many other lines of necessary code of this function here
    ...
    ...
    ...
    #ce------------------
    $sTestString = StringFormat("%04i/%02i/%02i", '14', '12', '9')
    ;....
    $asStringArray = StringRegExp("Jan01 Feb02 Mar03 ", "(?i)\w[A-Z]{2,2}", 3)
    ;....
    $bSomeBool = IsNumber($iNum)
EndFunc



Func example2()
    Local $iNum = 42
    #cs------------------
    Many other lines of necessary code of this function here
    ...
    ...
    ...
    #ce------------------
    Local $sTestString = StringFormat("%04i/%02i/%02i", '14', '12', '9')
    ;....
    Local $asStringArray = StringRegExp("Jan01 Feb02 Mar03 ", "(?i)\w[A-Z]{2,2}", 3)
    ;....
    Local $bSomeBool = IsNumber($iNum)
EndFunc

Which example function is coded more clear / better?

 

3)

My last question does not really refer to AutoIt. It sometimes happens that a (main)function calls an other (sub)function that modifies or returns a value to the (main)function. If the (main)function does not commit the variable that will be modified, I have to declare (and maybe initialize) the variable twice: In the (main)function itselfs and in the (sub)function. I asked myself if would be a better idea to declare all those variable just once (in the mainfunction) and commit the value to the subfunction? Example:

; Example 1 (declare and initialize twice)
Func Main($aiArray $bIndicate)
    Local $iModifiedInt = 0
    If $bIndicate Then
        $iModifiedInt = Subfunc($aiArray)
    EndIf
EndFunc

Func Subfunc($aiArray)
    Local $iModifiedInt = 0
    ; other code / build-in functions....
    If @error Then
        Seterror(1)
        Return
    If (Ubound($aiArray) <> 1) Then $iModifiedInt = 34
    Return $iModifiedInt
EndFunc


; Example 2 (declare and initialize once)
Func Main($aiArray $bIndicate)
    Local $iModifiedInt = 0
    If $bIndicate Then
        $iModifiedInt = Subfunc($aiArray, $iModifiedInt)
    EndIf
EndFunc

Func Subfunc($aiArray, $iModifiedInt)
    ; other code / build-in functions....
    If @error Then
        Seterror(1)
        Return
    If (Ubound($aiArray) <> 1) Then $iModifiedInt = 34
    Return $iModifiedInt
EndFunc


; Example 3 (declare and initialize once and assign ByRef)
Func Main($aiArray $bIndicate)
    Local $iModifiedInt = 0
    If $bIndicate Then
        Subfunc($iModifiedInt, $aiArray)
    EndIf
EndFunc

Func Subfunc(ByRef $iModifiedInt, $aiArray,)
    ; other code / build-in functions....
    If @error Then
        Seterror(1)
        Return
    If (Ubound($aiArray) <> 1) Then $iModifiedInt = 34
EndFunc

Please enlighten me :idea: .

Auto42

Share this post


Link to post
Share on other sites



Auto42,

Let me try to answer - but I would point out that this is purely my opinion and not everyone will necessarily agree! ;)

- 1a. Declaring variables. I tend only to declare variables that are used in loops or reassigned in conditional structures at the top of the script/function - other variables are declared when needed in the script. An example of this is >here - why declare the variables only needed for the "Convert mp3 to hybrid wav" case if they are not going to be used?

- 1b: Declaring arrays. Neither of the 2 cases you posit will work - if you declare/redeclare an array you need to define the scope at that point, so I see little to be gained by pre-declaring arrays that will be subsequently defined.

- 1c. Empty arrays. When you say "empty array" do you mean an array with no elements or an array with empty elements? If the former then you merely need declare it as Local $aiArray[0] - that way it is defined as an array datatype and the _Array* functions will work on it. If you want an array of empty elements, then just declare the array but do not define the elements: Local $aiArray[10] gives you an array with 10 empty elements.

- 2. See 1a above.

- 3. Example 3 is the one to use - ByRef is a very useful way to modify variables.

I hope that helps - please ask again if yo have any queries about what I have said. :)

M23


Any of my own code posted anywhere on the forum is available for use by others without any restriction of any kind._______My UDFs:

Spoiler

ArrayMultiColSort ---- Sort arrays on multiple columns
ChooseFileFolder ---- Single and multiple selections from specified path treeview listing
Date_Time_Convert -- Easily convert date/time formats, including the language used
ExtMsgBox --------- A highly customisable replacement for MsgBox
GUIExtender -------- Extend and retract multiple sections within a GUI
GUIFrame ---------- Subdivide GUIs into many adjustable frames
GUIListViewEx ------- Insert, delete, move, drag, sort, edit and colour ListView items
GUITreeViewEx ------ Check/clear parent and child checkboxes in a TreeView
Marquee ----------- Scrolling tickertape GUIs
NoFocusLines ------- Remove the dotted focus lines from buttons, sliders, radios and checkboxes
Notify ------------- Small notifications on the edge of the display
Scrollbars ----------Automatically sized scrollbars with a single command
StringSize ---------- Automatically size controls to fit text
Toast -------------- Small GUIs which pop out of the notification area

 

Share this post


Link to post
Share on other sites

Thanks for your advice M23. I looked some of your code pieces (signature) to get a feeling how you code.

In my opinion ByRef is nice and maybe good regarding the performance but the readability of the code gets worse :ermm: . Especially for an external third person its more difficult to see immediately which parameter / variable of the function is modified if more than one value is commited to the function.

Auto42

Share this post


Link to post
Share on other sites

The wiki entry about best practices is also good.


_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

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