Jump to content

Good coding practices in AutoIt


guinness
 Share

Recommended Posts

ClipGet should not be called until absolutely needed to allow the user to change the clipboard contents.


E.G. Don't do

$CheckClipboard = True

While True
    $Clip = Clipget()
    Execute("1+1")
    Select
        Case $CheckClipboard
            If $Clip = "Whatever" Then ClipPut("Whatever")
    EndSelect
WEnd

Do:

$CheckClipboard = True

While True
    Execute("1+1")
    Select
        Case $CheckClipboard
            $Clip = Clipget()
            If $Clip = "Whatever" Then ClipPut("Whatever")
    EndSelect
WEnd

 

Edited by rcmaehl

My UDFs are generally for me. If they aren't updated for a while, it means I'm not using them myself. As soon as I start using them again, they'll get updated.

My Projects

WhyNotWin11
Cisco FinesseGithubIRC UDFWindowEx UDF

 

Link to comment
Share on other sites

  • 5 months later...

My tip is that Global variables is your best friend as long you throw to the garbage the approach of making variables names short as possible and you know what you are doing..

Of course, you do not have to accept it. This is what I got after a long experience(small with C++) and deep thought.

 

My suggested and new coding style is this:

  1. Use globals variables as many as you need. It may be that the more global variables, the more It is better (only if you know what you are doing!! and for you to know what you doing you need to follow the next rules)
  2. Don't use 'g_' . If you do 1), then there is no logic and justification to use this. it will make the code ugly without any benefit.
  3. instead of using 'g_', just don't try to think about short name. Think about long name according to the rules of 4.
  4. (Only about global variables) Instead the prefix 'g_', the prefix need to be about the scope of the variable itself:
    1. If the variable is related to specific function group (so the functions of that group are named this way group_*<FunctionName>) , then the prefix of the variable will be 'group_' and not 'g_'.
    2. (This is true according to my personal experience:) You should accept the fact that the Variables names are going to be long and live with this. If you want to easly improve the script.
    3. You can make the name shorter but only according to these rules
      1. Make the prefix(s) of the Variable shorter BUT only in this way: for example:
        1. If the variable have 2 prefixs: 'SettingsWin' -> 'SubWindow' then the variable name will look like this
          $SettingsWin_SubWindow_SomeVar. This way you should shorten it: $SetWin_SubWin_SomeVar OR
          $SeWi_SuWi_SomeVar. BUT NOT like this: $S_S_SomeVar. You never should shorten the prefix to one character.
          The minimum characters for prefix is 2 (Not including the '_') .
    4. You can use this font mode:It will shorten the names significantly if you use "_" a lot of times.
  5. Use the "_" as a line break. example:
    Instead of writing like this:
    MsgBox(0,'Title','Text',1000)

    You can write like this:
     

    MsgBox  (0, _           ;flag
            'Title', _      ;title
            'Text', _       ;text
            1000)           ;timeout

    This way, when you use long variable name, it will not hurt you. And at the same time, you get better understanding about the parameters of the function.

  6. Divide the code into multiple files

    1. *.Globals files - the files that only the globals variables are written there

    2. Standard files - the files where you write the code

    3. Very important: Tou must to include first the *.Globals files. ONLY then you can include the other files.

    4. Very important: You need to keep as much as possible to write any global variable in the *.Globals file it belong to

  7. AU3Stripper: You have no choice - If you use this coding approach, you need to use AU3Stripper at the compile time.
    If the Variables and the functions names are long, it will hurt the performance.. it is not compile to machine code.

 

 

Edited by Guest
Link to comment
Share on other sites

That is your idea of good coding practice and, although you made some good suggestions. it does not necessarily tally with everyone else's idea. Using global variables has good and bad consequences. I personally avoid using them as much as possible. Avoiding global variables frees up memory and side steps several issues that may sometimes occur.

Edited by czardas
Link to comment
Share on other sites

Of course, everyone will do what is good for him.

Quote

Avoiding global variables frees up memory and side steps several issues that sometimes occur.

This is one the weak reasons why avoid globals.
This is not 1990.. Memory of the PC is not a big problem now.
If you avoid globals, you also avoid their very good benefits.
If the only reson for that is problem mostly belonged to the past,  then it is a bit does not make sense to do it..
But if you have more reasons why to do it and good ones, then it is fine.

If you write it in very  very organized way ( Multiple source code files , good names with prefixes for functions, variables and source code files), you can easaly add functions of this type: "<function>_FreeMem"

Inside each "*.Globals" file ( I mentioned to do it in 6) ), aftere you worte the declaration of the global variables, there in this file just add function with this name <GroupName>_FreeMem()  or  <SomeGroupName>_<SomeVariablesType)>_FreeMem()

In that function, set every variable to it's zero state ( Usually should assign  the value 0 but sometimes you may want to assign  some empty array)

 

 

Link to comment
Share on other sites

  • 8 months later...

hm... as I remember here (in this topic/thread)  was not discused about: "variable meaningful titles/names"

Also on AutoIt Wiki:
https://www.autoitscript.com/wiki/Best_coding_practices#Names_of_Variables

There is no mention about "variable meaningful titles/names".

For example in this Wiki page there is:
 

For $i = 1 To 10
        $g_vVariableThatIsGlobal &= $i ; This will return 12345678910 totally wiping the previous contents of $g_vVariableThatIsGlobal
    Next

And for this little "for to next" loop I do not see any needs to change it, especially that in this example the loop is inside a small function.

But for some time, I have tried in my UDF's to make the variables "significant titles".

; my old coding habbits
For $i =1 To $aUsers[0][0]
    ......  ...... ......   ......
    ......  ...... ......   ......
    ...... $aUsers[$i][....] ......
    ......  ...... ......   ......
    ......  ...... ......   ......
Next

; my current coding style
For $iUser_idx =1 To $aUsersList[0][0]
    ......  ...... ......   ......
    ......  ...... ......   ......
    ...... $aUsersList[$iUser_idx][...] ......
    ......  ...... ......   ......
    ......  ...... ......   ......
Next

; my old coding habbits
For $oUser In $oUsers.count
    ......  ...... ......   ......
    ......  ...... ......   ......
    ...... $oUser.value ......
    ......  ...... ......   ......
    ......  ...... ......   ......
Next

; my current coding style
For $oUserNode_enum In $oUserNodes_coll.count
    ......  ...... ......   ......
    ......  ...... ......   ......
    ...... $oUserNode_enum.value ......
    ......  ...... ......   ......
    ......  ...... ......   ......
Next

Thanks to them, I avoid many problems with analizing old code.


Even when I try to understand my own old code (older then 3 years), I start with rewriting variable names.
And then I use Au3Check, and finally i start to understand what is going on in this code.

What you think about such convention - I do not mean exactly about the suffix _coll, _enum and _idx but generally about the concept to use "variable meaningful titles/names"  ?

 

Edited by mLipok

Signature beginning:
Please remember: "AutoIt"..... *  Wondering who uses AutoIt and what it can be used for ? * Forum Rules *
ADO.au3 UDF * POP3.au3 UDF * XML.au3 UDF * IE on Windows 11 * How to ask ChatGPT for AutoIt Codefor other useful stuff click the following button:

Spoiler

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

My contribution (my own projects): * Debenu Quick PDF Library - UDF * Debenu PDF Viewer SDK - UDF * Acrobat Reader - ActiveX Viewer * UDF for PDFCreator v1.x.x * XZip - UDF * AppCompatFlags UDF * CrowdinAPI UDF * _WinMergeCompare2Files() * _JavaExceptionAdd() * _IsBeta() * Writing DPI Awareness App - workaround * _AutoIt_RequiredVersion() * Chilkatsoft.au3 UDF * TeamViewer.au3 UDF * JavaManagement UDF * VIES over SOAP * WinSCP UDF * GHAPI UDF - modest begining - comunication with GitHub REST APIErrorLog.au3 UDF - A logging Library * Include Dependency Tree (Tool for analyzing script relations) * Show_Macro_Values.au3 *

 

My contribution to others projects or UDF based on  others projects: * _sql.au3 UDF  * POP3.au3 UDF *  RTF Printer - UDF * XML.au3 UDF * ADO.au3 UDF SMTP Mailer UDF * Dual Monitor resolution detection * * 2GUI on Dual Monitor System * _SciLexer.au3 UDF * SciTE - Lexer for console pane

Useful links: * Forum Rules * Forum etiquette *  Forum Information and FAQs * How to post code on the forum * AutoIt Online Documentation * AutoIt Online Beta Documentation * SciTE4AutoIt3 getting started * Convert text blocks to AutoIt code * Games made in Autoit * Programming related sites * Polish AutoIt Tutorial * DllCall Code Generator * 

Wiki: Expand your knowledge - AutoIt Wiki * Collection of User Defined Functions * How to use HelpFile * Good coding practices in AutoIt * 

OpenOffice/LibreOffice/XLS Related: WriterDemo.au3 * XLS/MDB from scratch with ADOX

IE Related:  * How to use IE.au3  UDF with  AutoIt v3.3.14.x * Why isn't Autoit able to click a Javascript Dialog? * Clicking javascript button with no ID * IE document >> save as MHT file * IETab Switcher (by LarsJ ) * HTML Entities * _IEquerySelectorAll() (by uncommon) * IE in TaskSchedulerIE Embedded Control Versioning (use IE9+ and HTML5 in a GUI) * PDF Related:How to get reference to PDF object embeded in IE * IE on Windows 11

I encourage you to read: * Global Vars * Best Coding Practices * Please explain code used in Help file for several File functions * OOP-like approach in AutoIt * UDF-Spec Questions *  EXAMPLE: How To Catch ConsoleWrite() output to a file or to CMD *

I also encourage you to check awesome @trancexx code:  * Create COM objects from modules without any demand on user to register anything. * Another COM object registering stuffOnHungApp handlerAvoid "AutoIt Error" message box in unknown errors  * HTML editor

winhttp.au3 related : * https://www.autoitscript.com/forum/topic/206771-winhttpau3-download-problem-youre-speaking-plain-http-to-an-ssl-enabled-server-port/

"Homo sum; humani nil a me alienum puto" - Publius Terentius Afer
"Program are meant to be read by humans and only incidentally for computers and execute" - Donald Knuth, "The Art of Computer Programming"
:naughty:  :ranting:, be  :) and       \\//_.

Anticipating Errors :  "Any program that accepts data from a user must include code to validate that data before sending it to the data store. You cannot rely on the data store, ...., or even your programming language to notify you of problems. You must check every byte entered by your users, making sure that data is the correct type for its field and that required fields are not empty."

Signature last update: 2023-04-24

Link to comment
Share on other sites

hello I'm not a too good in coding practices. But I try to use variable meaningful titles/names when I think Its required.

 

;~ If Its for some Internal array manipulation I use something like this
;Also When things are too obviously
For $i = 1 To $aArray[0][0]
    ...... ...... ...... ......
    ...... ...... ...... ......
    ...... $aArray[$i][....]......
    ...... ...... ...... ......
    ...... ...... ...... ......
Next



;~ If Is something of the main script where I know I  use many For statements in a function
;if Is a 2D Array I use some meaningful const Index
Local Const Enum $eNAME, $eEMAIL, $eADDRESS
For $iIndex = 1 To $aUserInfo[0][0]
    ...... ...... ...... ......
    ...... ...... ...... ......
    ...... $aUserInfo[$iIndex][$eNAME]......
    ...... ...... ...... ......
    ...... ...... ...... ......
Next

;when I work with many GUIs I use something like this for may globals

#Region GUI Main
;here some relevant information
Global $g_MIdListViewUsers, $g_MhListViewUsers, $g_MIdtxtClientName, $g_MIdbtnAccept
#EndRegion GUI Main

#Region GUI Report
;here some relevant information
Global $g_RIdListViewUsers, $g_RhListViewUsers, $g_RIdtxtClientName, $g_RIdbtnAccept
#EndRegion GUI Report


;I think when I use object is enough somethig like this
For $oUser In $oUsers.count
    ...... ...... ...... ......
    ...... ...... ...... ......
    $oUserCredentials = $oUser.GetCredentials
    ...... ...... ...... ......
    ...... ...... ...... ......
    For $oUserCredential In $oUserCredentials
        ...... ...... ...... ......
        ...... ...... ...... ......
    Next
    ...... ...... ...... ......
    ...... ...... ...... ......
Next

;basically I denote is a list just pluralizing my variable's name

Of course everyone gets used to their own style. I try to get a better coding practices each day reading around the web.

 

Saludos

 

 

Link to comment
Share on other sites

6 hours ago, Danyfirex said:

I try to get a better coding practices each day reading around the web.

Just like me :)

 

Signature beginning:
Please remember: "AutoIt"..... *  Wondering who uses AutoIt and what it can be used for ? * Forum Rules *
ADO.au3 UDF * POP3.au3 UDF * XML.au3 UDF * IE on Windows 11 * How to ask ChatGPT for AutoIt Codefor other useful stuff click the following button:

Spoiler

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

My contribution (my own projects): * Debenu Quick PDF Library - UDF * Debenu PDF Viewer SDK - UDF * Acrobat Reader - ActiveX Viewer * UDF for PDFCreator v1.x.x * XZip - UDF * AppCompatFlags UDF * CrowdinAPI UDF * _WinMergeCompare2Files() * _JavaExceptionAdd() * _IsBeta() * Writing DPI Awareness App - workaround * _AutoIt_RequiredVersion() * Chilkatsoft.au3 UDF * TeamViewer.au3 UDF * JavaManagement UDF * VIES over SOAP * WinSCP UDF * GHAPI UDF - modest begining - comunication with GitHub REST APIErrorLog.au3 UDF - A logging Library * Include Dependency Tree (Tool for analyzing script relations) * Show_Macro_Values.au3 *

 

My contribution to others projects or UDF based on  others projects: * _sql.au3 UDF  * POP3.au3 UDF *  RTF Printer - UDF * XML.au3 UDF * ADO.au3 UDF SMTP Mailer UDF * Dual Monitor resolution detection * * 2GUI on Dual Monitor System * _SciLexer.au3 UDF * SciTE - Lexer for console pane

Useful links: * Forum Rules * Forum etiquette *  Forum Information and FAQs * How to post code on the forum * AutoIt Online Documentation * AutoIt Online Beta Documentation * SciTE4AutoIt3 getting started * Convert text blocks to AutoIt code * Games made in Autoit * Programming related sites * Polish AutoIt Tutorial * DllCall Code Generator * 

Wiki: Expand your knowledge - AutoIt Wiki * Collection of User Defined Functions * How to use HelpFile * Good coding practices in AutoIt * 

OpenOffice/LibreOffice/XLS Related: WriterDemo.au3 * XLS/MDB from scratch with ADOX

IE Related:  * How to use IE.au3  UDF with  AutoIt v3.3.14.x * Why isn't Autoit able to click a Javascript Dialog? * Clicking javascript button with no ID * IE document >> save as MHT file * IETab Switcher (by LarsJ ) * HTML Entities * _IEquerySelectorAll() (by uncommon) * IE in TaskSchedulerIE Embedded Control Versioning (use IE9+ and HTML5 in a GUI) * PDF Related:How to get reference to PDF object embeded in IE * IE on Windows 11

I encourage you to read: * Global Vars * Best Coding Practices * Please explain code used in Help file for several File functions * OOP-like approach in AutoIt * UDF-Spec Questions *  EXAMPLE: How To Catch ConsoleWrite() output to a file or to CMD *

I also encourage you to check awesome @trancexx code:  * Create COM objects from modules without any demand on user to register anything. * Another COM object registering stuffOnHungApp handlerAvoid "AutoIt Error" message box in unknown errors  * HTML editor

winhttp.au3 related : * https://www.autoitscript.com/forum/topic/206771-winhttpau3-download-problem-youre-speaking-plain-http-to-an-ssl-enabled-server-port/

"Homo sum; humani nil a me alienum puto" - Publius Terentius Afer
"Program are meant to be read by humans and only incidentally for computers and execute" - Donald Knuth, "The Art of Computer Programming"
:naughty:  :ranting:, be  :) and       \\//_.

Anticipating Errors :  "Any program that accepts data from a user must include code to validate that data before sending it to the data store. You cannot rely on the data store, ...., or even your programming language to notify you of problems. You must check every byte entered by your users, making sure that data is the correct type for its field and that required fields are not empty."

Signature last update: 2023-04-24

Link to comment
Share on other sites

pro tip. don't ever use DIM

also, lots of global variables can get you into trouble in my experience. I prefer to pass parameters and set properties

meaningful variable names are good too

if others can read your code and understand it without lots of comments, you are doing it right.

Edited by Earthshine

My resources are limited. You must ask the right questions

 

Link to comment
Share on other sites

  • 1 month later...

I use Global sparingly, in all languages. don't be a pig and eat up all the resources, plus, it's EASY to hose yourself. Using tons of globals is and ALWAYS WAS stupid. it is the LAZIEST thing you can do. DON'T DO IT! as few globals as necessary and that's it. Use constants for things that don't change globally as well.

 

Autonomous functions contain their own variables, LOCAL vars, the way it should be. If your code is modifying vars in many source files, you can hose yourself without realizing it

Edited by Earthshine

My resources are limited. You must ask the right questions

 

Link to comment
Share on other sites

From here https://www.autoitscript.com/forum/topic/191475-good-coding-rules-was-case-statement-structure/

By @LarsJ

The rule is that Case statements with most events should be in top of the list.

Explained by @jchd

It isn't a rule, but something you can consider in any on-the-fly interpreted language. Consider this simple sequence:

If <Condition> Then
    [13,000 lines of code]
Else
    [Action]
End

It's obvious that, unless a form of compilation has taken place which can jump direct to [Action] when <Condition> isn't met, the interpreter will have to read and ignore 13,000 lines, something which wastes time. Hence if you expect the false branch to be significantly more frequent than the true branch, you should swap them and negate Condition.

 

Contributed by @Earthshine

 

  1. Follow Modular design patterns in general. Split things into small autonomous units. Never  glom everything into a monolithic structure. (this one is important. Having one place to edit in case of changes instead of many files to edit. maintainability)
  2. Use good meaningful variable names
  3. Don't get carried away with macros, not to say don't use them
  4. Keep functions small, over 50 lines and you need new supporting functions (this works well with C/C++/C# but not sure if applicable to AutoIT and otehr scripting languages, but I try to do this with AutoIT. Most of what makes my functions longer are just logging if they get long in AutoIT cause I am a logging fool
  5. Don't follow the Single Entry Single Exit nonsense bullcrap either. If you run into a condition you need to break from the function, then do it
  6. Don't use GoTo statements (obviously they lead to spaghetti logic that can't be maintained)
  7. Use Constants for strings and stuff that does not change. that way, when something needs to change, it changes in one spot, not many

 never send an IF to do a SWITCH's (case) job

 

Edited by Skysnake

Skysnake

Why is the snake in the sky?

Link to comment
Share on other sites

  • 2 months later...

I just started to wonder if "Good coding practices in AutoIt" should also contain hints as to create a code to be "compatible" with such tools as
Au3Check
and
Au3Stripper

 

Signature beginning:
Please remember: "AutoIt"..... *  Wondering who uses AutoIt and what it can be used for ? * Forum Rules *
ADO.au3 UDF * POP3.au3 UDF * XML.au3 UDF * IE on Windows 11 * How to ask ChatGPT for AutoIt Codefor other useful stuff click the following button:

Spoiler

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

My contribution (my own projects): * Debenu Quick PDF Library - UDF * Debenu PDF Viewer SDK - UDF * Acrobat Reader - ActiveX Viewer * UDF for PDFCreator v1.x.x * XZip - UDF * AppCompatFlags UDF * CrowdinAPI UDF * _WinMergeCompare2Files() * _JavaExceptionAdd() * _IsBeta() * Writing DPI Awareness App - workaround * _AutoIt_RequiredVersion() * Chilkatsoft.au3 UDF * TeamViewer.au3 UDF * JavaManagement UDF * VIES over SOAP * WinSCP UDF * GHAPI UDF - modest begining - comunication with GitHub REST APIErrorLog.au3 UDF - A logging Library * Include Dependency Tree (Tool for analyzing script relations) * Show_Macro_Values.au3 *

 

My contribution to others projects or UDF based on  others projects: * _sql.au3 UDF  * POP3.au3 UDF *  RTF Printer - UDF * XML.au3 UDF * ADO.au3 UDF SMTP Mailer UDF * Dual Monitor resolution detection * * 2GUI on Dual Monitor System * _SciLexer.au3 UDF * SciTE - Lexer for console pane

Useful links: * Forum Rules * Forum etiquette *  Forum Information and FAQs * How to post code on the forum * AutoIt Online Documentation * AutoIt Online Beta Documentation * SciTE4AutoIt3 getting started * Convert text blocks to AutoIt code * Games made in Autoit * Programming related sites * Polish AutoIt Tutorial * DllCall Code Generator * 

Wiki: Expand your knowledge - AutoIt Wiki * Collection of User Defined Functions * How to use HelpFile * Good coding practices in AutoIt * 

OpenOffice/LibreOffice/XLS Related: WriterDemo.au3 * XLS/MDB from scratch with ADOX

IE Related:  * How to use IE.au3  UDF with  AutoIt v3.3.14.x * Why isn't Autoit able to click a Javascript Dialog? * Clicking javascript button with no ID * IE document >> save as MHT file * IETab Switcher (by LarsJ ) * HTML Entities * _IEquerySelectorAll() (by uncommon) * IE in TaskSchedulerIE Embedded Control Versioning (use IE9+ and HTML5 in a GUI) * PDF Related:How to get reference to PDF object embeded in IE * IE on Windows 11

I encourage you to read: * Global Vars * Best Coding Practices * Please explain code used in Help file for several File functions * OOP-like approach in AutoIt * UDF-Spec Questions *  EXAMPLE: How To Catch ConsoleWrite() output to a file or to CMD *

I also encourage you to check awesome @trancexx code:  * Create COM objects from modules without any demand on user to register anything. * Another COM object registering stuffOnHungApp handlerAvoid "AutoIt Error" message box in unknown errors  * HTML editor

winhttp.au3 related : * https://www.autoitscript.com/forum/topic/206771-winhttpau3-download-problem-youre-speaking-plain-http-to-an-ssl-enabled-server-port/

"Homo sum; humani nil a me alienum puto" - Publius Terentius Afer
"Program are meant to be read by humans and only incidentally for computers and execute" - Donald Knuth, "The Art of Computer Programming"
:naughty:  :ranting:, be  :) and       \\//_.

Anticipating Errors :  "Any program that accepts data from a user must include code to validate that data before sending it to the data store. You cannot rely on the data store, ...., or even your programming language to notify you of problems. You must check every byte entered by your users, making sure that data is the correct type for its field and that required fields are not empty."

Signature last update: 2023-04-24

Link to comment
Share on other sites

  • Moderators

Personally I would say no. This thread started with the aim to teach good practices: structure and syntax and readability. Interaction with external tools would, in my mind, be a separate thread so as not to muddy the waters. Just my 2¢

"Profanity is the last vestige of the feeble mind. For the man who cannot express himself forcibly through intellect must do so through shock and awe" - Spencer W. Kimball

How to get your question answered on this forum!

Link to comment
Share on other sites

Thank you for yours opinion.

For such comments I ask before I take actions.

I waiting in hope for few more comments.

 

Edited by mLipok

Signature beginning:
Please remember: "AutoIt"..... *  Wondering who uses AutoIt and what it can be used for ? * Forum Rules *
ADO.au3 UDF * POP3.au3 UDF * XML.au3 UDF * IE on Windows 11 * How to ask ChatGPT for AutoIt Codefor other useful stuff click the following button:

Spoiler

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

My contribution (my own projects): * Debenu Quick PDF Library - UDF * Debenu PDF Viewer SDK - UDF * Acrobat Reader - ActiveX Viewer * UDF for PDFCreator v1.x.x * XZip - UDF * AppCompatFlags UDF * CrowdinAPI UDF * _WinMergeCompare2Files() * _JavaExceptionAdd() * _IsBeta() * Writing DPI Awareness App - workaround * _AutoIt_RequiredVersion() * Chilkatsoft.au3 UDF * TeamViewer.au3 UDF * JavaManagement UDF * VIES over SOAP * WinSCP UDF * GHAPI UDF - modest begining - comunication with GitHub REST APIErrorLog.au3 UDF - A logging Library * Include Dependency Tree (Tool for analyzing script relations) * Show_Macro_Values.au3 *

 

My contribution to others projects or UDF based on  others projects: * _sql.au3 UDF  * POP3.au3 UDF *  RTF Printer - UDF * XML.au3 UDF * ADO.au3 UDF SMTP Mailer UDF * Dual Monitor resolution detection * * 2GUI on Dual Monitor System * _SciLexer.au3 UDF * SciTE - Lexer for console pane

Useful links: * Forum Rules * Forum etiquette *  Forum Information and FAQs * How to post code on the forum * AutoIt Online Documentation * AutoIt Online Beta Documentation * SciTE4AutoIt3 getting started * Convert text blocks to AutoIt code * Games made in Autoit * Programming related sites * Polish AutoIt Tutorial * DllCall Code Generator * 

Wiki: Expand your knowledge - AutoIt Wiki * Collection of User Defined Functions * How to use HelpFile * Good coding practices in AutoIt * 

OpenOffice/LibreOffice/XLS Related: WriterDemo.au3 * XLS/MDB from scratch with ADOX

IE Related:  * How to use IE.au3  UDF with  AutoIt v3.3.14.x * Why isn't Autoit able to click a Javascript Dialog? * Clicking javascript button with no ID * IE document >> save as MHT file * IETab Switcher (by LarsJ ) * HTML Entities * _IEquerySelectorAll() (by uncommon) * IE in TaskSchedulerIE Embedded Control Versioning (use IE9+ and HTML5 in a GUI) * PDF Related:How to get reference to PDF object embeded in IE * IE on Windows 11

I encourage you to read: * Global Vars * Best Coding Practices * Please explain code used in Help file for several File functions * OOP-like approach in AutoIt * UDF-Spec Questions *  EXAMPLE: How To Catch ConsoleWrite() output to a file or to CMD *

I also encourage you to check awesome @trancexx code:  * Create COM objects from modules without any demand on user to register anything. * Another COM object registering stuffOnHungApp handlerAvoid "AutoIt Error" message box in unknown errors  * HTML editor

winhttp.au3 related : * https://www.autoitscript.com/forum/topic/206771-winhttpau3-download-problem-youre-speaking-plain-http-to-an-ssl-enabled-server-port/

"Homo sum; humani nil a me alienum puto" - Publius Terentius Afer
"Program are meant to be read by humans and only incidentally for computers and execute" - Donald Knuth, "The Art of Computer Programming"
:naughty:  :ranting:, be  :) and       \\//_.

Anticipating Errors :  "Any program that accepts data from a user must include code to validate that data before sending it to the data store. You cannot rely on the data store, ...., or even your programming language to notify you of problems. You must check every byte entered by your users, making sure that data is the correct type for its field and that required fields are not empty."

Signature last update: 2023-04-24

Link to comment
Share on other sites

  • 8 months later...
On 7.01.2013 at 2:24 AM, Mat said:

DRY and KISS, fail fast, SoC and single responsibility... Most of those are common sense and apply not just to programming. This on the other hand is a bit like the bible. You aren't expected to always follow it literally, stoning is generally frowned upon by modern society.

Single entry and exit (SESE). Usually overlooked with good reason but can be important, a GUI loop that looks like this is not good:

While 1
    Switch GUIGetMsg()
        Case $GUI_EVENT_CLOSE
            Exit
    EndSwitch
WEnd

This would be better:

While 1
    Switch GUIGetMsg()
        Case $GUI_EVENT_CLOSE
            ExitLoop
    EndSwitch
WEnd

Usually there are multiple places in the loop that should end the GUI (a cancel button, an action completing etc). If you were to add resources that need freeing, the second design means that code can go after the loop and be guaranteed to execute.

Same applies for functions.

Bad:

Func Foo($i)
    If $i < 12 Then Return "Foo"
    Return "Bar"
EndFunc

Better:

Func Foo($i)
    Local $ret = "Bar"
    If $i < 12 Then $ret = "Foo"

    Return $ret
EndFunc

You can now add code that will always be executed immediately before returning from the function (like freeing resources).

I'm not saying go for it and rewrite all your scripts like this. Trying to can result in larger and more unreadable code. But bear it in mind when you write your code.

Do you still follow this "rule" after these five years or have you changed your approach to this matter ?

As to mentioned by You GUI concept I fully agree even more.  My experience has brought me to the point where most of my programs have already been moved to such a structure as below:

#cs
    some header: includes, script settings, glablas, enums etc....
#ce

#Region - INIT / MAIN / EXIT
_Init()
_Main()
_Exit()
Exit ; one exit point

Func _Main()
    #cs
        some code ....
    #ce
    While 1
        Switch GUIGetMsg()
            Case $GUI_EVENT_CLOSE
                ExitLoop ; exit MAIN LOOP
            Case $1
                ; any other code or function call
            Case $2
                ; any other code or function call
            ........
            Case $xyz
                ; any other code or function call
        EndSwitch
    WEnd

    ; some GUI CleanUp

    Return ; from _Main() to "GLobal Scope"
EndFunc   ;==>_Main

Func _Init()
    ; some function sets to init program
EndFunc   ;==>_Init

Func _Exit()
    ; some function sets to CleanUp - before Exit
EndFunc   ;==>_Exit
#EndRegion - INIT / MAIN / EXIT

#Region - FUNCTIONS
; any other functions
#EndRegion - FUNCTIONS

 

But with regard to the method of leaving the function, my experience from the last few years, directed me in a different direction - I will try to describe it in the next few days.
If I went the wrong path, you will be able to correct me.

Edited by mLipok

Signature beginning:
Please remember: "AutoIt"..... *  Wondering who uses AutoIt and what it can be used for ? * Forum Rules *
ADO.au3 UDF * POP3.au3 UDF * XML.au3 UDF * IE on Windows 11 * How to ask ChatGPT for AutoIt Codefor other useful stuff click the following button:

Spoiler

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

My contribution (my own projects): * Debenu Quick PDF Library - UDF * Debenu PDF Viewer SDK - UDF * Acrobat Reader - ActiveX Viewer * UDF for PDFCreator v1.x.x * XZip - UDF * AppCompatFlags UDF * CrowdinAPI UDF * _WinMergeCompare2Files() * _JavaExceptionAdd() * _IsBeta() * Writing DPI Awareness App - workaround * _AutoIt_RequiredVersion() * Chilkatsoft.au3 UDF * TeamViewer.au3 UDF * JavaManagement UDF * VIES over SOAP * WinSCP UDF * GHAPI UDF - modest begining - comunication with GitHub REST APIErrorLog.au3 UDF - A logging Library * Include Dependency Tree (Tool for analyzing script relations) * Show_Macro_Values.au3 *

 

My contribution to others projects or UDF based on  others projects: * _sql.au3 UDF  * POP3.au3 UDF *  RTF Printer - UDF * XML.au3 UDF * ADO.au3 UDF SMTP Mailer UDF * Dual Monitor resolution detection * * 2GUI on Dual Monitor System * _SciLexer.au3 UDF * SciTE - Lexer for console pane

Useful links: * Forum Rules * Forum etiquette *  Forum Information and FAQs * How to post code on the forum * AutoIt Online Documentation * AutoIt Online Beta Documentation * SciTE4AutoIt3 getting started * Convert text blocks to AutoIt code * Games made in Autoit * Programming related sites * Polish AutoIt Tutorial * DllCall Code Generator * 

Wiki: Expand your knowledge - AutoIt Wiki * Collection of User Defined Functions * How to use HelpFile * Good coding practices in AutoIt * 

OpenOffice/LibreOffice/XLS Related: WriterDemo.au3 * XLS/MDB from scratch with ADOX

IE Related:  * How to use IE.au3  UDF with  AutoIt v3.3.14.x * Why isn't Autoit able to click a Javascript Dialog? * Clicking javascript button with no ID * IE document >> save as MHT file * IETab Switcher (by LarsJ ) * HTML Entities * _IEquerySelectorAll() (by uncommon) * IE in TaskSchedulerIE Embedded Control Versioning (use IE9+ and HTML5 in a GUI) * PDF Related:How to get reference to PDF object embeded in IE * IE on Windows 11

I encourage you to read: * Global Vars * Best Coding Practices * Please explain code used in Help file for several File functions * OOP-like approach in AutoIt * UDF-Spec Questions *  EXAMPLE: How To Catch ConsoleWrite() output to a file or to CMD *

I also encourage you to check awesome @trancexx code:  * Create COM objects from modules without any demand on user to register anything. * Another COM object registering stuffOnHungApp handlerAvoid "AutoIt Error" message box in unknown errors  * HTML editor

winhttp.au3 related : * https://www.autoitscript.com/forum/topic/206771-winhttpau3-download-problem-youre-speaking-plain-http-to-an-ssl-enabled-server-port/

"Homo sum; humani nil a me alienum puto" - Publius Terentius Afer
"Program are meant to be read by humans and only incidentally for computers and execute" - Donald Knuth, "The Art of Computer Programming"
:naughty:  :ranting:, be  :) and       \\//_.

Anticipating Errors :  "Any program that accepts data from a user must include code to validate that data before sending it to the data store. You cannot rely on the data store, ...., or even your programming language to notify you of problems. You must check every byte entered by your users, making sure that data is the correct type for its field and that required fields are not empty."

Signature last update: 2023-04-24

Link to comment
Share on other sites

  • 1 year later...
On 12/21/2012 at 9:48 PM, czardas said:

The ini file was just an example of reading a value instead of having it declared globally. I generally do something like this:

Instead of this:

Global $gArg1 = True, $gArg2 = False

Func _main()
    _1of2($gArg1)
    _2of2($gArg2)
EndFunc

Func _1of2($vParam)
    ; some algorithm
EndFunc

Func _2of2($vParam)
    ; some algorithm
EndFunc

Try to do something like this:

Func _main()
    Local $aArgs[2] = [True, False]
    _1of2($aArgs[0])
    _2of2($aArgs[1])
EndFunc

Func _1of2($vParam)
    ; some algorithm
EndFunc

Func _2of2($vParam)
    ; some algorithm
EndFunc

This is the simplest example I can think of. Instead of using global, try to use local variables.

I just started messing around with the AutoIt3Wrapper Directives last night and enabled one from, I believe, Au3Check that showed me a warning I had not seen before.

I usually place a few Global variables at the top of my script like $Title which is what I use for MsgBox() or anything else where one of the parameters is a window title (it makes little sense to pass that as a function parameter).

Otherwise, my philosophy is to be conservative when it comes to creating Global variables, and instead try to use Local variables and pass them to functions as arguments.  That is what I have been doing in AutoIt forever.  My code would look like this (borrowing your example and modifying it to my structure):

Local $gArg1 = True, $gArg2 = False

_1of2($gArg1)
_2of2($gArg2)

Exit

Func _1of2($vParam)
    ; some algorithm
EndFunc

Func _2of2($vParam)
    ; some algorithm
EndFunc

I have a bachelor of science and a masters in Computer Science, and one of the concepts drilled into my brain from years of object oriented programming is to keep member variables private so that they cannot be manipulated in any way other than through the object’s built-in setter methods.  This way you enforce the integrity of the member variables’ contents.  So, that probably explains why I avoid global variables - I prefer that functions “properly” manipulate Global variables, and making a variable local helps enforce that.

So, imagine my surprise when yesterday I ran sample code like the one I posted above and it warned me that I was declaring the two variables as Local but they were technically in a Global scope.  I understand now why that is; all of this time I have been treating AutoIt’s global space (for lack of a better term) as the equivalent of main() in other languages, but that’s incorrect.

So, if I want to stick to my philosophy of minimizing the use of Global variables for the reasons I stated, I need to adapt my program template to look like your second example, where you explicitly recreate the concept of main().

Of all the years of AutoIt code examples I have seen, I can probably count on one hand the number of times I have seen anyone explicitly recreating main() to enforce this.  I think this should be emphasized in discussions concerning usage of Global variables in AutoIt.

Func _main()
    Local $aArgs[2] = [True, False]
    _1of2($aArgs[0])
    _2of2($aArgs[1])
EndFunc

Func _1of2($vParam)
    ; some algorithm
EndFunc

Func _2of2($vParam)
    ; some algorithm
EndFunc
Link to comment
Share on other sites

3 hours ago, mlazovjp said:

So, imagine my surprise when yesterday I ran sample code like the one I posted above and it warned me that I was declaring the two variables as Local but they were technically in a Global scope.

That's well documented in the help file under the Local/Global keyword explanations. Anything declared in the Global scope regardless of the keyword used (local/global/static) will be a global variable.

AutoIt has 2 types of variable scopes, Global and Local, there's no file scope, there's no loop scopes, etc. Just the 2.

If I posted any code, assume that code was written using the latest release version unless stated otherwise. Also, if it doesn't work on XP I can't help with that because I don't have access to XP, and I'm not going to.
Give a programmer the correct code and he can do his work for a day. Teach a programmer to debug and he can do his work for a lifetime - by Chirag Gude
How to ask questions the smart way!

I hereby grant any person the right to use any code I post, that I am the original author of, on the autoitscript.com forums, unless I've specifically stated otherwise in the code or the thread post. If you do use my code all I ask, as a courtesy, is to make note of where you got it from.

Back up and restore Windows user files _Array.au3 - Modified array functions that include support for 2D arrays.  -  ColorChooser - An add-on for SciTE that pops up a color dialog so you can select and paste a color code into a script.  -  Customizable Splashscreen GUI w/Progress Bar - Create a custom "splash screen" GUI with a progress bar and custom label.  -  _FileGetProperty - Retrieve the properties of a file  -  SciTE Toolbar - A toolbar demo for use with the SciTE editor  -  GUIRegisterMsg demo - Demo script to show how to use the Windows messages to interact with controls and your GUI.  -   Latin Square password generator

Link to comment
Share on other sites

9 hours ago, BrewManNH said:

That's well documented in the help file under the Local/Global keyword explanations. Anything declared in the Global scope regardless of the keyword used (local/global/static) will be a global variable.

AutoIt has 2 types of variable scopes, Global and Local, there's no file scope, there's no loop scopes, etc. Just the 2.

@BrewManNH You are absolutely correct.  I read that numerous times throughout the AutoIt documentation, but for some reason it didn’t register in my brain properly until I enabled more verbose logging.

I was just suggesting that another way to drive that point home would be to include @czardas example code that shows how you can mimic the behavior of other languages and how they treat variable scopes by calling a main() function.    Obviously, you don’t HAVE to do it that way, but in this thread people made some valid points regarding best practices for global and local variables; I was just agreeing with czardas that using main() like that was a subtle, but effective, way to allow one to use global variables in the global scope and create local variables outside of the global scope but could still be used through the script.

Basically, trying to compare and contrast the AutoIt approach with other languages as another way to reinforce what you had quoted from the documentation.

Link to comment
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
 Share

  • Recently Browsing   0 members

    • No registered users viewing this page.
×
×
  • Create New...