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")
许可以下: CC-BY-SA归因
不隶属于 StackOverflow
scroll top