Using colons to put two statements on the same lin

2019-01-07 22:08发布

问题:

Is it considered bad practice to use colons to put two statements on the same line in Visual Basic?

回答1:

There is nothing inherently wrong with using the colon to combine statements. It really depends on the context but as long as it doesn't reduce readability, there is nothing wrong with it.

As a general rule I avoid using the colon for this purpose. I find it's more readable to have one statement per line. However this is not a colon specific issue. I avoid doing the same with a semi-colon in C# or C++. It's just a personal preference.



回答2:

It's a good practice in moderation, because sometimes readability is enhanced by concatenating two lines:

  • when the lines are short and intimately related
  • when the lines are short and trivial

    Option Compare Database:  Option Explicit   ''My favorite!
    rsDataSet.Close:          Set rsDataSet= Nothing
    

Don't do it if:

  • it hurts readability.
  • it complicates debugging. Control structures such as If...Then need to stay clean. You'll be glad you kept it simple when it's time to set a break point.
  • it compromises future editing. Often you want to keep sections portable. Moving or re-structuring a block of code is easily hindered by attempts to minimize your code.


回答3:

In general, I'd advise against it, as it makes for busier code.

However, for simple tasks, there is nothing wrong with it. For instance:

for i = 1 to 10: ProcessFoo(i): next

I think a line like this is short enough not to cause confusion.



回答4:

I'll take the other side. I don't like dense lines of code. It is easier to skim code when lines are not combined.

Combining statements also makes it easier to create long functions that still fit on a single screen.

It isn't a major sin, I just don't like it.

I also don't like one line If statements.



回答5:

To me you shouldn't say "never do thus", you should just say "If you do this, a possible problem is such and such." Then just weigh the pros and cons for yourself. The pro is brevity/few lines of code. Sometimes this can aid readability. For instance some people use it to do vb.Net declarations:

Dim x As Long: x = 1

Or wait loops:

Do Until IE.ReadyState = READYSTATE_COMPLETE: DoEvents: Loop

But obviously you can really make it rough on someone too:

Public Sub DoYouKnowWhatThisDoes()
    MsgBox Example
End Sub

Private Function Example()
    Const s$ = "078243185105164060193114247147243200250160004134202029132090174000215255134164128142"
    Const w% = 3: Const l% = 42: Dim i%, r$: For i = 1 To l Step w: r = r & ChrW$(Mid$(s, i, w) Xor Mid$(s, i + l, w)): Next: Example = r
End Function

Another practical reason that you might not want to use this approach is breakpoints. Breakpoints can only be set by the line. So if you have several things executing on the same line you can't isolate the second thing. It will stop on the first statement. (This is also one of the reasons some people don't like single line ifs.) It just complicates debugging a little.

I usually don't use colons in production code for this reason. However I do use them to improve the brevity of "copy/paste" code that I post in forums and elsewhere. YMMV:)



回答6:

I've only ever used it when I'm clsoing a recordset and setting the variable to nothing. I figure one line instead of two gives me more lines of code on the screen and doesn't detract from readability.

I've seen it used in simple select cases such as the following but that would be as far as I would go.

 Select Case success
      Case ERROR_FILE_NO_ASSOCIATION: msg = "no association"
      Case ERROR_FILE_NOT_FOUND: msg = "file not found"
      Case ERROR_PATH_NOT_FOUND: msg = "path not found"
      Case ERROR_BAD_FORMAT:     msg = "bad format"

from http://vbnet.mvps.org/index.html?code/system/findexecutable.htm

And even then I would've lined up the "msg =" portion.



回答7:

I realize this is a very old question, but it was the first result on my Google search, so I hope I can be forgiven for chiming in here.

There is one situation (exactly what led me here in fact) in which this approach is not only useful, it's the only way to accomplish the desired result: the Immediate window. Any code you want to execute in the Immediate window must all be on one line. So in order to use any form of Do, Case, For, While, or With in the Immediate window, you will need to use colons.



回答8:

It is considered bad practice in most of the sites at which I have worked. And by most of the VB developers with whom I have worked. And in my head. If I see it, I will admit that I would almost certainly change it. I say "almost" because I admit there's a possibility that I could find a piece of code that looked better that way. I don't expect to see it in my lifetime, though.

I also really don't like one-line **If**s either.

Both are most likely hangovers from the days of VGA (640x480) monitors; that's no excuse these days.



回答9:

I've never seen this mentioned in an official capacity at any of the companies which I've worked. But I do think that using colons excessively can start to make your code less readable and more of a pain to maintain.

I do tend to use these myself at times, for example when checking for cancel in one of my recent projects:

If _bCancel Then Status = CancelProcess() : Return Status

Putting this in kept my code readable than the alternative IF block.

But it can be taken too far, I've recently inherited a project which is replete with examples of taking colon usage too far :

    Select Case GetStringValue(Index).Trim.ToLower
        Case "yes", "y" : GetBooleanValue = True
        Case "no", "n" : GetBooleanValue = False
        Case Else : GetBooleanValue = Nothing
    End Select

Personally I find the above to be a bit much.



回答10:

I've seen it used in class declarations when using inheritance or implementing an interface:

Public Class DerivedClass : Inherits BaseClass
   ...
End Class

But like the others, I also discourage its use.

Chris



回答11:

I like this one

Using pro As New Process() : With pro

        ...

    End With
End Using


回答12:

The answer to the question is No. Anything beyond No is purely subjective and wasteful irrespective of the answer outside of a simple No. Below is my waste of typing.

Are you some sort of slave? Do as you wish. You are the center of your universe not some stranger from StackOverflow. If you work for a company the question is mute because coding style would already be defined and completely out of your control. As for one's self, who in this universe is going to ever in all eternity look at let along care about your code.

I would choose A over B. As evident this shows the purpose of a colon without the use of a colon. It's to save space. Below saves space and makes code far more readable. Keeps It Simple Stupid. Same for ternary ? : usage. When the code is inherently complex then a colon, single line if then else, or ternary no longer should be considered.

'================================================================
'A
If somevalue1 = 0 Then AddLogTry("True") Else AddLogFalse("False")
If somevalue2 = 0 Then AddLogTry("True") Else AddLogFalse("False")
If somevalue3 = 0 Then AddLogTry("True") Else AddLogFalse("False")
'================================================================

'================================================================
'B
If somevlaue1 = 0 Then
  AddLogTrue("True")
Else
  AddLogFalse("False")
EndIf

If somevlaue2 = 0 Then
  AddLogTrue("True")
Else
  AddLogFalse("False")
EndIf

If somevlaue3 = 0 Then
  AddLogTrue("True")
Else
  AddLogFalse("False")
EndIf
'================================================================


标签: vb.net vba vb6