views:

87

answers:

4

I found the following code in my team's project:

Public Shared Function isRemoteDisconnectMessage(ByRef m As Message)
    isRemoteDisconnectMessage = False
    Select Case (m.Msg)
        Case WM_WTSSESSION_CHANGE
            Select Case (m.WParam.ToInt32)
                Case WTS_REMOTE_DISCONNECT
                    isRemoteDisconnectMessage = True
            End Select
    End Select
End Function

Never mind that the function doesn't have a return type (I can easily add 'As Boolean'); what I'm wondering is, could there be any reason to prefer the above over the following (to me, much more readable) code?

Public Shared Function isRemoteDisconnectMessage(ByRef m As Message) As Boolean
    Return m.Msg = WM_WTSSESSION_CHANGE AndAlso _
           m.WParam.ToInt32() = WTS_REMOTE_DISCONNECT
End Function

To put the question in general terms: Does it make sense to use a switch (or, in this case, Select Case) block--and/or nested blocks--to test a single condition? Is this possibly faster than a straightforward if?

+2  A: 

I don't believe it actually matters in terms of speed, the compiler should be able to optimize it.

I think it would just be a matter of preference.

Brandon
+4  A: 

If you're worried about performance...profile. Otherwise you can't go wrong erring on the side of readability...

Jason Punyon
Wow, I asked this question like a year ago. Looks like a pretty silly question now. Well, just doing the rounds of some ultra-late answer accepting...
Dan Tao
+1  A: 

My rule of thumb is to use a switch statement when the number of if/else conditions is greater than three. I don't have any data behind why this makes sense other than readability/maintainability seems to decrease as the number of if/else conditions increases.

Stephen Doyle
+1  A: 

I think the answer in the specific case you've given is no - it doesn't make sense, as suggested in other answers one would hope that the compilers would optimise away any practical differences.

I'd put money on this being a bit of cut, paste and delete coding - taking a generalised set of nested case statements and extracting that one bit that gives you the yes/no result you need.

If this were something similar in-line and/or there was a function call where the return flag is set then one might, possibly, be at a point where one could start to justify it but not as it is.

Murph