I'm trying to develop some good programming practices and today I am working on a program that will take info from textboxes, radiobuttons and checkboxes. I know I could do it like this, for example:
TextBoxResult.Text = Val(TextBoxNumbA.Text) + Val(TextBoxNumbB.Text)
and it will work. Or I could also do it like this and it will work as well:
Dim result, numberA, numberB as Integer
numberA = Val(TextBoxNumbA.Text)
numberB = Val(TextBoxNumbB.Text)
result = numberA + numberB
TextBoxResult.Text = result
My question is: which is the proper way to do it? The short way without declaring variables or the long way declaring variables? How do software companies handle this?
Ignoring the horrible val part. Should you use intermediate variables?
Yes if it makes the code more comprehensible. In the case you posted I don't believe it does, but that's only my opinion.
Seeing as you are using VB.net, don't worry about the extra memory required, the compiler will deal with that. In an interpreted language it could be an issue, but code is not written for computers to "understand", it's written for programmers to. Always go for comprehensible first. You can make it incomprehensible once you are sure it's correct...
Val is a left over Legacy function. I would recommend switching to type specific converters. This also provides protection for values that are not convertible like letters. Remember to convert types. Turn Option Strict On and you will see.
Integer.TryParse
Dim result As integer = 0
Dim numberA, numberB as Integer
If Integer.TryParse(TextBoxNumbA.Text, numberA) Then
If Integer.TryParse(TextBoxNumbB.Text, numberB) Then
result = numberA + numberB
End If
End If
TextBoxResult.Text = result.ToString("n2")
Related
Trying to develop an VS extension to help with migration from vb6 to Vb.net using Roslyn.
Unfortunately I am not having much luck with detecting the "DoEvents" expression in my source as I get NULL from my GetDeclaredSymbol during the detection.
My bad coding is......
Register the action:
context.RegisterSyntaxNodeAction(AddressOf ExpressionStatementDec, SyntaxKind.InvocationExpression)
Try and detect the "DoEvents" expression:
Private Sub ExpressionStatementDec(context As SyntaxNodeAnalysisContext)
Dim GotYou = context.SemanticModel.GetDeclaredSymbol(context.Node)
Dim WhatExpression = context.Node.ToFullString.ToString
' Find DoEvents.
If RemoveWhitespace(WhatExpression) = "DoEvents" Then
Dim diag = Diagnostic.Create(Rule, GotYou.Locations(0), GotYou.Name)
context.ReportDiagnostic(diag)
End If
End Sub
I have tried loads of options for trying to get the right type of object for "GotYou" but no luck so far.
Any pointers appreciated :)
Edit Additional info:
I have tried GetSymbolInfo but when I am detecting "DoEvents" in the context.Node.ToFullString.ToString I am still not getting anything in the context.SemanticModel.GetSymbolInfo(context.Node) as below.
Thanks,
Richard
If you want to look at what a invocation is referencing, call GetSymbolInfo not GetDeclaredSymbol.
Don’t have Visual Studio handy in order to get the code, but...
I believe what you want is something like:
Dim WhatExpression = TryCast(CType(context.Node, InvocationExpressionSyntax).Expression, IdentifierNameSyntax)?.Identifier.Text
This isn’t all of it, you could be dealing with a memberaccessexpression, in which case it’s probably not what you are looking for. The options would be a bit easier to handle with pattern matching in C#, but that’s the general idea. You don’t need the semantic tree at this point, because you first want to verify that you are dealing with the right text. Once you’ve got that, you can see where it comes from and whether it is something you need to deal with. Getting the semantic model is expensive, no reason to do so when (outside of your unit test) it is rarely going to be needed.
In VB.NET, there's no == operator for comparison, so the = operator serves that purpose as well as assignment. I have a function, and I want it to return the boolean result of a comparison, without storing that result in a variable:
Private Function foo() As Boolean
Dim bar As Integer = 1
Return bar = 2
End Function
Returns: False
OK, but what's the value of bar?
Private Function foo() As KeyValuePair(Of Boolean, Integer)
Dim bar As Integer = 1
Return New KeyValuePair(Of Boolean, Integer)(bar = 2, bar)
End Function
Returns: False, 1
It looks like = will perform a comparison when the statement context demands it, but is this guaranteed? That is, can I be sure that bar will never be set to 2 in this situation?
Also, I know that VB.NET doesn't allow chained inline assignments, which may be for the best. Does this odd = behavior cause any other quirks I should be aware of?
You cannot do in-line assignments in VB, Assignment is an explicit statement:
[Let] <<target-reference>> = <<value-expression>>
The Let is optional and implicit, and hardly ever used anymore. The general rule that you can use to distinguish the [Let] command from equality testing is that for Let, no other keyword may come before the target-reference in the statement. AFAIK, in all cases of = as equality testing, there is one or more other keywords that precede it in the statement.
In your first example, the keyword Return precedes your =, so it's an equality test, and not an assignment.
In your first example you can do either:
Return 2
or
bar = 2
Return bar
As for your question "OK, but what's the value of bar?", bar still equals one.
= in VB cause no quirks. It works exactly as documented, and it always has (including its predecessor, BASIC back to 1968).
If you are starting to code in VB (coming from a language like C#), you should start getting used to the peculiar VB way of doing things; which is based on the idea: as simple and intuitive for the programmer as possible. "If assignation and comparison happen always in different contexts, why not using the same operator and let the context define its exact meaning?" -> VB-way of seeing things. "No, different realities have to be accounted for by different operators. End of the discussion" -> C#-way. :)
Is this reliable? Can you blindly trust on these not-always-clear-for-a-programmer bits? Sure, VB.NET peculiarities are highly-reliable and trustworthy. You can always use = (or Is on some contexts, but VS would tell you) and be completely sure that the code will do what is expected. But the question is: are you sure that you write exactly what you want?
This last question is what, perhaps, is more criticable of VB and what might give some problems to programmers from other languages: the higher the flexibility, the more likely is that you make an error; mainly if you are used to a different format.
Regarding the chained inline assignments, I honestly don't see its true utility (and never use them in C#). Regarding other differences with respect to C#, there are plenty of them; in some cases, I think that the C# approach is better; other times, the VB.NET one. On readability/length of code, I can refer to the With Statement I have always found somehow useful which is not present in C#.
One way to have 100% sure that the expression will be evaluated as an boolean expression is to use ()
e.g
Dim a = 2
Return (a = 1)
Since you cannot set a value to a variable wihtin the parenthesis.
What i want to say is: on an return statament for example you cant assing a value to a variable so, even if you use
a = 1
The compilator knows that this expression only can be an boolean expression.
The same to the if statament and so on..
Heh back in QB45 days we used to exploit the fact that "True" was the numeric value -1. So you would see code like x = 1 - x * (x < 6) (translation: increment x, but reset to 1 when it gets to 6)
I've been using LINQ so much in the last couple of weeks that when I had to write a one line function to remove < and > from a string, I found that I had written it as a LINQ query:
Public Function StripLTGT(text As String) As String
Return String.Join("", (From i As Char In text.ToCharArray Where i <> "<"c Where i <> ">"c).ToArray)
End Function
My question is, is it better to do it with LINQ as above or with StringBuilder as I've always done, as below:
Public Function StripLTGT(text As String) As String
Dim a As New StringBuilder(text)
a = a.Replace("<", "")
a = a.Replace(">", "")
Return a.ToString
End Function
Both work, the second one is easier to read, but the first one is designed for executing queries against arrays and other enumerables.
Regex.Replace("[<>]", "")
Is much more straightforward.
Or:
myString = myString.Replace("<", "").Replace(">", "")
Whether or not option A, B or C is faster than the others is hard to say because option A may be better on small strings while option B may be better on long strings, etc.
Either one should really be fine in terms of functionality. The first one is not efficient as is. The ToArray call is doing far more work than necessary (if you're on .NET 4.0, it is not needed anyway), and the ToCharArray call is not needed. Basically the characters in the input string are being iterated a lot more than they need to be, and extra arrays are allocated superfluously.
I wouldn't say this particularly matters; but you asked about efficiency, so that's why I mention it.
The second one seems fine to me. Note that if you wanted to go the one-line route, you could still do so with a StringBuilder and I think still have something more concise than the LINQ version (though I haven't counted characters). Whether or not this even outperforms the more direct String.Replace option is kind of unclear to me, though:
' StringBuilder.Replace version:
Return New StringBuilder(text).Replace("<", "").Replace(">", "").ToString()
' String.Replace version:
Return text.Replace("<", "").Replace(">", "")
Given a datatable containing two columns like this:
Private Function CreateDataTable() As DataTable
Dim customerTable As New DataTable("Customers")
customerTable.Columns.Add(New DataColumn("Id", GetType(System.Int32)))
customerTable.Columns.Add(New DataColumn("Name", GetType(System.String)))
Dim row1 = customerTable.NewRow()
row1.Item("Id") = 1
row1.Item("Name") = "Customer 1"
customerTable.Rows.Add(row1)
Dim row2 = customerTable.NewRow()
row2.Item("Id") = 2
row2.Item("Name") = "Customer 2"
customerTable.Rows.Add(row2)
Dim row3 = customerTable.NewRow()
row3.Item("Id") = 3
row3.Item("Name") = "Customer 3"
customerTable.Rows.Add(row3)
Return customerTable
End Function
Would you use this snippet to retrieve a List(Of Integer) containing all Id's:
Dim table = CreateDataTable()
Dim list1 As New List(Of Integer)
For i As Integer = 0 To table.Rows.Count - 1
list1.Add(CType(table.Rows(i)("Id"), Integer))
Next
Or rather this one:
Dim list2 = (From r In table.AsEnumerable _
Select r.Field(Of Integer)("Id")).ToList()
This is not a question about whether to type cast the Id column to Integer by using .Field(Of Integer), CType, CInt, DirectCast or whatever but generally about whether or not you choose Linq over forloops as the subject implies.
For those who are interested: I ran some iterations with both versions which resulted in the following performance graph:
graph http://dnlmpq.blu.livefilestore.com/y1pOeqhqQ5neNRMs8YpLRlb_l8IS_sQYswJkg17q8i1K3SjTjgsE4O97Re_idshf2BxhpGdgHTD2aWNKjyVKWrQmB0J1FffQoWh/analysis.png?psid=1
The vertical axis shows the milliseconds it took the code to convert the rows' ids into a generic list with the number of rows shown on the horizontal axis. The blue line resulted from the imperative approach (forloop), the red line from the declarative code (linq).
Whatever way you generally choose: Why do you go that way and not the other?
Whenever possible I favor the declarative way of programming instead of imperative. When you use a declarative approach the CLR can optimize the code based on the characteristics of the machine. For example if it has multiple cores it could parallelize the execution while if you use an imperative for loop you are basically locking this possibility. Today maybe there's no big difference but I think that in the future more and more extensions like PLINQ will appear allowing better optimization.
I avoid linq unless it helps readability a lot, because it completely destroys edit-and-continue.
When they fix that, I will probably start using it more, because I do like the syntax a lot for some things.
For almost everything I've done I've come to the conclusion that LINQ is optimized enough. If I handcrafted a for loop it would have better performance, but in the grand scheme of things we are usually talking milliseconds. Since I rarely have a situation where those milliseconds will make any kind of impact, I find it's much more important to have readable code with clear intentions. I would much rather have a call that is 50ms slower than have someone come along and break it altogether!
Resharper has a cool feature that will flag and convert loops into Linq expressions. I will flip it to the Linq version and see if that hurts or helps readability. If the Linq expression more clearly communicates the intent of the code, I will go with that. If the Linq expression is unreadable, I will flip back to the foreach version.
Most of the performance issues don't really compare with readability for me.
Clarity trumps cleverness.
In the above example, I would go with the the Linq version since it clearly explains the intent and also locks out people accidently adding side effects in the loop.
I recently found myself wondering whether I've been totally spoiled by LINQ. Yes, I now use it all the time to pick all sort of things out from all sort of collections.
I started to, but found out in some cases, I saved time by using this approach:
for (var i = 0, len = list.Count; i < len; i++) { .. }
Not necessarily in all cases, but some. Most extension methods use the foreach approach of querying.
I try to follow these rules:
Whenever I'm just querying (filtering, projecting, ...) collections, use LINQ.
As soon as I'm actually 'doing' something with the result (i.e, introduce side effects), I'll use a for loop.
So in this example, I'll use LINQ.
Also, I always try to split up the 'query definition' from the 'query evaluation':
Dim query = From r In table.AsEnumerable()
Select r.Field(Of Integer)("Id")
Dim result = query.ToList()
This makes it clear when that (in this case in-memory) query will be evaluated.
Closed. This question is opinion-based. It is not currently accepting answers.
Want to improve this question? Update the question so it can be answered with facts and citations by editing this post.
Closed 5 years ago.
Improve this question
Is it considered bad practice to use colons to put two statements on the same line in Visual Basic?
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.
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.
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.
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.
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:)
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.
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.
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.
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.
I like this one
Using pro As New Process() : With pro
...
End With
End Using
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
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
'================================================================