Jump to content

Is it a Good Idea?: Other Conditions with Case Else


TheDcoder
 Share

Forum's Choice  

14 members have voted

  1. 1. Good or Bad Idea?

    • Good
      3
    • I don't know
      1
    • Bad
      10


Recommended Posts

Hello friends :), I was working on my project today and got a wild idea with Switch..EndSwitch statements, it looks like this:

#include <MsgBoxConstants.au3>

$iWildInteger = 10

Switch $iWildInteger
    Case 1
        MsgBox($MB_OK, "AutoIt Forums", "The value of $iWildInteger is " & 1 & '.')

    Case 2, Else
        MsgBox($MB_OK, "AutoIt Forums", "The value of $iWildInteger is " & 2 & ' or else.')
EndSwitch

A case with Else and another value... I tried it but It didn't work :(, I think its great to have a feature like this so that I don't have to have a separate case for it :D

 

Please note that this is *NOT* a feature request :P, This is a poll for opinion on this feature (before making a feature request in the BT :P), Vote wisely, TD :)

EasyCodeIt - A cross-platform AutoIt implementation - Fund the development! (GitHub will double your donations for a limited time)

DcodingTheWeb Forum - Follow for updates and Join for discussion

Link to comment
Share on other sites

  • Moderators

TheDcoder,

How about posting a real example where having the Else as a separate case causes a problem. The example above can easily be written as:

#include <MsgBoxConstants.au3>

$iWildInteger = 10

Switch $iWildInteger
    Case 1
        MsgBox($MB_OK, "AutoIt Forums", "The value of $iWildInteger is " & 1 & '.')

    Case 2
        ContinueCase

    Case Else
        MsgBox($MB_OK, "AutoIt Forums", "The value of $iWildInteger is " & 2 & ' or else.')
EndSwitch

which is hardly onerous to code.

M23

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

Open spoiler to see 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

 

Link to comment
Share on other sites

I don't see the point of it, at least not from the pseudo example you posted, as it is no different from...

Switch $iWildInteger
    Case 1
        MsgBox($MB_OK, "AutoIt Forums", "The value of $iWildInteger is " & 1 & '.')

    Case Else
        MsgBox($MB_OK, "AutoIt Forums", "The value of $iWildInteger is " & 2 & ' or else.')
EndSwitch

 

AutoIt Absolute Beginners    Require a serial    Pause Script    Video Tutorials by Morthawt   ipify 

Monkey's are, like, natures humans.

Link to comment
Share on other sites

Here is a genuine snippet from my program which clearly demonstrates the problem: 

Global Const $g_esSettingsFile = @ScriptDir & '\settings.ini'

Global Const $CONSOLE_SPEED_INSTANT = 1 ; Not the actual values from my project :P
Global Const $CONSOLE_SPEED_SLOW = 2
Global Const $CONSOLE_SPEED_NORMAL = 3
Global Const $CONSOLE_SPEED_FAST = 4

Switch IniRead($g_esSettingsFile, "console", "speed", "else")
    Case "instant"
        $g_iSettings_TypingSpeed = $CONSOLE_SPEED_INSTANT
        
    Case "slow"
        $g_iSettings_TypingSpeed = $CONSOLE_SPEED_SLOW
        
    Case "normal"
        $g_iSettings_TypingSpeed = $CONSOLE_SPEED_NORMAL
        
    Case "fast"
        $g_iSettings_TypingSpeed = $CONSOLE_SPEED_FAST
        
    Case Else
        $g_iSettings_TypingSpeed = $CONSOLE_SPEED_NORMAL ; Same as normal
EndSwitch

#cs ----------- Contents of settings.ini -----------
[console]
speed=fast
; Fast is my preference ;)
#ce ----------- Contents of settings.ini -----------

; Save the contents as settings.ini at your Script's Directory :)

I am a little confused though, TD :lol:

 

P.S My RSS Reader broke :(

Edited by TheDcoder

EasyCodeIt - A cross-platform AutoIt implementation - Fund the development! (GitHub will double your donations for a limited time)

DcodingTheWeb Forum - Follow for updates and Join for discussion

Link to comment
Share on other sites

i have sometimes used the Else case for handling the default value (where there must be one), leaving the rest of the cases for non-default values. this approach seems to match the scenario of your example.

and in general, if you find yourself needing to use such redundant syntax (as JohnOne pointed out), then you should inspect your script logic. there is probably something not quite right with it.

P.S. and (yet again) thanks to Melba23 for expanding my English vocabulary, this time with "onerous".

 

Signature - my forum contributions:

Spoiler

UDF:

LFN - support for long file names (over 260 characters)

InputImpose - impose valid characters in an input control

TimeConvert - convert UTC to/from local time and/or reformat the string representation

AMF - accept multiple files from Windows Explorer context menu

DateDuration -  literal description of the difference between given dates

Apps:

Touch - set the "modified" timestamp of a file to current time

Show For Files - tray menu to show/hide files extensions, hidden & system files, and selection checkboxes

SPDiff - Single-Pane Text Diff

 

Link to comment
Share on other sites

  • Moderators

TheDcoder:

I see 2 solutions:

- Use ContinueCase as I suggested above:

Switch IniRead($g_esSettingsFile, "console", "speed", "else")
    Case "instant"
        $g_iSettings_TypingSpeed = $CONSOLE_SPEED_INSTANT
        
    Case "slow"
        $g_iSettings_TypingSpeed = $CONSOLE_SPEED_SLOW
        
    Case "fast"
        $g_iSettings_TypingSpeed = $CONSOLE_SPEED_FAST
        
    Case "normal"
        ContinueCase ; Run next case code

        

    Case Else
        $g_iSettings_TypingSpeed = $CONSOLE_SPEED_NORMAL ; Same as normal
EndSwitch

- Set the IniRead default return to the "normal" setting:

Switch IniRead($g_esSettingsFile, "console", "speed", "normal") ; normal as default
    Case "instant"
        $g_iSettings_TypingSpeed = $CONSOLE_SPEED_INSTANT
        
    Case "slow"
        $g_iSettings_TypingSpeed = $CONSOLE_SPEED_SLOW
        
    Case "fast"
        $g_iSettings_TypingSpeed = $CONSOLE_SPEED_FAST
        
    Case "normal"
        $g_iSettings_TypingSpeed = $CONSOLE_SPEED_NORMAL
EndSwitch

The second option seems the more elegant to me.

M23

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

Open spoiler to see 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

 

Link to comment
Share on other sites

@JohnOne I would love to :yes:, OK, Lets consider some things before we start:

We are reading a key from a settings.ini file, In other (normal) terms, we are reading the user's preference on the mentioned option (speed of console actually, I can't explain it :P). We need to set the appropriate value to the appropriate variable in order to make our program work :), We use Switch...EndSwitch for this purpose, this is where we waste a line by setting the default setting, the default setting is the same as the 'normal speed' setting :), So if you use something like:

Case "normal", Else
    $g_iSettings_TypingSpeed = $CONSOLE_SPEED_NORMAL

Then we can save the line and looks neat too :)! Hope you may understand :yes:.

 

@orbs Do you mean something like this?:

Case Else ; Else replaces 'normal'
    $g_iSettings_TypingSpeed = $CONSOLE_SPEED_NORMAL

Yeah it works but it does pose some difficulty to the reader of the code to understand it :)

 

@Melba23 Nice little sneaky idea :P, Yeah it solves my problem :D

It would not work (referring to the second solution), What if the value of 'speed' is 'bugfinder'? $g_iSettings_TypingSpeed would be empty and my program would crash :wacko:

But Still! I am not leaving my suggestion behind :P, I want to see if others find it useful (if my proposal *is* implemented)

 

P.S Reply storm :P

Edited by TheDcoder

EasyCodeIt - A cross-platform AutoIt implementation - Fund the development! (GitHub will double your donations for a limited time)

DcodingTheWeb Forum - Follow for updates and Join for discussion

Link to comment
Share on other sites

  • Moderators

TheDcoder,

What if the value of 'speed' is 'bugfinder'?

Easy. Everything other than "instant/slow/fast" falls under the Else case:

Switch IniRead($g_esSettingsFile, "console", "speed", "Nothing set at the moment!")
    Case "instant"
        $g_iSettings_TypingSpeed = $CONSOLE_SPEED_INSTANT
        
    Case "slow"
        $g_iSettings_TypingSpeed = $CONSOLE_SPEED_SLOW
        
    Case "fast"
        $g_iSettings_TypingSpeed = $CONSOLE_SPEED_FAST
        
    Case Else ; normal/bugfinder/anything other then the 3 words above
        $g_iSettings_TypingSpeed = $CONSOLE_SPEED_NORMAL
EndSwitch

M23

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

Open spoiler to see 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

 

Link to comment
Share on other sites

  • Moderators

ThDcoder,

I am not "jumping on" you - and I have yet to see the "flaw" that you claim to have found as I have managed to deal with every case (pun intended) you have so far put forward.

M23

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

Open spoiler to see 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

 

Link to comment
Share on other sites

So all this is to spare a line of code? It's just not practical, TheDcoder.

Also, don't take this wrong I know you're young, but all those faces you put in posts, make the post look stupid, like a 6 year old's colouring book.

AutoIt Absolute Beginners    Require a serial    Pause Script    Video Tutorials by Morthawt   ipify 

Monkey's are, like, natures humans.

Link to comment
Share on other sites

I disagree with JohnOne about the smileys, My brain simply skims past the smileys.  I don't think the smileys make you look stupid either, it actually helps the reader understand your emotions better.  It wouldn't take any additional time for me to read the smileys.  I agree with Melba, I don't see a problem to begin with.  While I do agree that yes, It would be nice if you could do case 2, Else, I don't think it solves any problems by doing so.

Link to comment
Share on other sites

$age = 14;
switch ($age) {
  case 14:
    var_dump('So much to learn');
    break;
  case 15: default:
 // So horrible to read
    var_dump('So much to learn but getting older');
}

If you want to add "hacks" to AutoIt, then just migrate to PHP (a language you know)

UDF List:

 
_AdapterConnections()_AlwaysRun()_AppMon()_AppMonEx()_ArrayFilter/_ArrayReduce_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: 22/04/2018

Link to comment
Share on other sites

I don't think the smileys make you look stupid either

I agree with JohnOne that they make the POST look stupid.  objective data in, objective data out.  start inserting other things like feelings and nonchalance and that is what you can expect in return from your audience.

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

Link to comment
Share on other sites

@Melba23 I think I pointed it out in post #8 and you corrected your "flaw" in post #9

@JohnOne Ok, I will try to reduce the amount of smileys in my posts and start inserting something other than them as @boththose suggested...

@guinness I might just stick to AutoIt, PHP is not my thing really (The main thing which I am concerned in PHP is performance because the script runs on a single server and a single script can be executed a thousand times, so god knows how the server feels, poor server :P). Nice representation of (my) life through that PHP snippet, I have to agree that PHP isn't an eye-candy language...

 

TD :)

EasyCodeIt - A cross-platform AutoIt implementation - Fund the development! (GitHub will double your donations for a limited time)

DcodingTheWeb Forum - Follow for updates and Join for discussion

Link to comment
Share on other sites

Also, don't take this wrong I know you're young, but all those faces you put in posts, make the post look stupid, like a 6 year old's colouring book.

Don't agree, they indicate tone and humor, and I find TheDcoder to be quite mature for his age.

Make sure brain is in gear before opening mouth!
Remember, what is not said, can be just as important as what is said.

Spoiler

What is the Secret Key? Life is like a Donut

If I put effort into communication, I expect you to read properly & fully, or just not comment.
Ignoring those who try to divert conversation with irrelevancies.
If I'm intent on insulting you or being rude, I will be obvious, not ambiguous about it.
I'm only big and bad, to those who have an over-active imagination.

I may have the Artistic Liesense ;) to disagree with you. TheSaint's Toolbox (be advised many downloads are not working due to ISP screwup with my storage)

userbar.png

Link to comment
Share on other sites

I agree with JohnOne that they make the POST look stupid.  objective data in, objective data out.  start inserting other things like feelings and nonchalance and that is what you can expect in return from your audience.

You guys really ought to get a life, way too serious ... and in my view, one of the biggest problems with the world. :frantics:

Stay in touch with your inner child. :P

There are no rewards for being so super mature you are a boring old fart. o:)

P.S. Don't bother to start an argument with me, for I shall not reply. There will be those who agree with me, and those like yourselves, who do not, and will not change anyway. I made my replies, purely in support of TheDcoder and those who wish to be all encompassing as a human being.

Edited by TheSaint

Make sure brain is in gear before opening mouth!
Remember, what is not said, can be just as important as what is said.

Spoiler

What is the Secret Key? Life is like a Donut

If I put effort into communication, I expect you to read properly & fully, or just not comment.
Ignoring those who try to divert conversation with irrelevancies.
If I'm intent on insulting you or being rude, I will be obvious, not ambiguous about it.
I'm only big and bad, to those who have an over-active imagination.

I may have the Artistic Liesense ;) to disagree with you. TheSaint's Toolbox (be advised many downloads are not working due to ISP screwup with my storage)

userbar.png

Link to comment
Share on other sites

  • Moderators

TheDcoder,

I think I pointed it out in post #8 and you corrected your "flaw" in post #9

I would argue that the "flaw" is in your code which would apparently allow the user to enter garbage values into the ini file. I would expect that any incorrect values would be weeded as the ini was being modified and the user invited to enter a correct value - or more elegantly, particularly as the value choice is so limited, have the user select from a read-only combo or radio group so that only valid values can be added to the ini.

But either way, I still do not see a "flaw" in the Switch structure which requires Else to be an added parameter rather than a separate case.

M23

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

Open spoiler to see 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

 

Link to comment
Share on other sites

...is in your code which would apparently allow the user to enter garbage values into the ini file. I would expect that any incorrect values would be weeded as the ini was being modified and the user invited to enter a correct value...

Do you think that I use a input box to let the user input anything? :P. I was taking precautions when the user *manually* edits the .ini file (preventing the program from suffering an ugly crash :P)

EasyCodeIt - A cross-platform AutoIt implementation - Fund the development! (GitHub will double your donations for a limited time)

DcodingTheWeb Forum - Follow for updates and Join for discussion

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

×
×
  • Create New...