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 6 years ago.
Improve this question
I know this is a dumb question probably already answered, but I can't find an easy to search for it. My question is should I be using "else" when I don't need to? Using VB.NET...
Function IsHappy(hasBeer As Boolean)
If hasBeer = True Then Return "Happy"
msgbox("I'm sad")
Return "Sad"
End Function
Or...
Function IsHappy(hasBeer As Boolean)
If hasBeer = True Then
Return "Happy"
Else
msgbox("I'm sad")
Return "Sad"
End If
End Function
These look the same to me, except that the first one is just a bit less code to look, but the second one is a bit clearer though more verbose. Is there a reason to pick one of these over the other?
Edit: Removed the obvious short cut of just returning hasBeer and made it slightly more complex
To clarify, I'm just trying to figure out if there is a good reason to use an else statement when the IF is going to exit your early if you don't. Is it just a style choice with no clear preference?
It depends.
Here, I'd use an early exit:
Function IsHappy(hasBeer As Boolean) as Boolean
If hasBeer Then
Return True
End If
' Complicated logic to determine whether another reason
' for being happy can be determined
...
Return False ' No reason found
End Function
Here, I'd use If and Else:
Function IsHappy(hasBeer As Boolean) As Boolean
If hasBeer Then
' Do some side effects
...
Return True
Else
' Do other side effects
...
Return False
End If
End Function
In your example, I'd simply use
Function IsHappy(hasBeer As Boolean) As Boolean
Return hasBeer
End Function
I know your hasBeer flag is just an example - the logic is likely to be much more complex.
I prefer the first option because there is less visual clutter. I might add whitespace before the last line - it makes it very clear that any path that gets this far returns false.
Verbosity is not, in and of itself, a problem. Performance being equal, clarity almost always trumps clever code in real world applications.
Related
Closed. This question needs debugging details. It is not currently accepting answers.
Edit the question to include desired behavior, a specific problem or error, and the shortest code necessary to reproduce the problem. This will help others answer the question.
Closed 5 years ago.
Improve this question
I am trying to convert an old Fortran program with a lot of nested goto statements to VBA but I am getting error mentioned in the title. The way I am converting is each statement, I made it a function and instead of goto then i call the function or statement, but apparently that's not a proper way of doing it. What else can I do? Thanks in advance.
If you cannot see where the endless loop is, try adding a public counter to all of the functions. If it exceeds a given value, stop the program. Then try to debug with F8 to see the endless loop. I mean something like this:
Option Explicit
Public counter As Long
Public Sub TestMe()
While True
FunctionSomething
Wend
End Sub
Public Function FunctionSomething()
counter = counter + 1
If counter > 100 Then Stop
End Function
Now if you run TestMe it would stop on the 100th iteration.
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 7 years ago.
Improve this question
For the functions I have, I have many scenarios where, based on IF checks, I have
MyFunction = False
Exit Function
When it reaches the end of the function, then and only then does the MyFunction = True occur. Because of the repetition of the False assignment, I was wondering if it is good practice to instead initially set MyFunction = False for example after the Dim of variables, and then only have it become true when everything goes through properly. Is there any reason this would either increase robustness or decrease it?
Every type of variable has an 'empty' value (after Dim without setting it to something). Boolean values are always false... numerical values are 0, strings are "" and variant / objects are empty... setting it to something it already is, only can slow down.
Knowing that its not neccessary to set a bool to false after dim... (or a numerical value to 0)
EDIT:
This also counts for functions even if there is something like Function MyFunction(Optional a as Boolean = True) as Boolean a will be False at the start then it checks if there is something to set to and if not it will be set to true.... also the function itself will be false at the start. It is differnt when doing something in C or other scripting languages, but VBA is set to change all bits inside a reserved range for a value to 0.
Closed. This question needs debugging details. It is not currently accepting answers.
Edit the question to include desired behavior, a specific problem or error, and the shortest code necessary to reproduce the problem. This will help others answer the question.
Closed 7 years ago.
Improve this question
I have a textbox of maxLength 8. the 1st two characters must be "PM" or "00". I tried split(), but didnt work.
Use substring() method
Dim s As String = TextBox1.Text.Substring(0, 2)
If s = "PM" Or s = "00" Then
MessageBox.Show("good!")
Else
MessageBox.Show("bad!")
End If
Or you can use StartsWith()
If TextBox1.Text.StartsWith("PM") OR TextBox1.Text.StartsWith("00") Then
'Do something
End If
Another option is to use regular expressions:
Dim re As New Regex("PM|00")
If re.IsMatch(TextBox1.Text) Then
'do something
End If
The benefit is that when you decide what to do with the other 6 characters, you can modify the above to capture and return those (in full or part), without having to rewrite your code. You can even process multiple occurrences of PM|00 in one string and capture them all.
Useful resource, a Regex sandbox:
https://www.regex101.com/
Maybe you can try this:
if textbox1.text like "PM*" or textbox1.text like "00*" then
Do something
else msgbox("You don't have pm or 00 to start with!")
end if
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 8 years ago.
Improve this question
Many of the applications I develop tap into the databases of pre-existing applications (I develop largely for small businesses that are trying to expand cheaply); A lot of this kind of work involves grabbing information out of other applications' databases (for example "site name", etc).
I normally have class libraries to do this kind of work, saving on database calls where possible. For example I might have a function like the below:
Private Function GetSiteName(ByVal dbPath As String) As String
Dim returned As String
Dim conn As New AdsConnection("data source = " & Path & "; ServerType=remote|local; TableType=CDX")
Dim cmd As AdsCommand
Try
conn.Open()
cmd = conn.CreateCommand()
cmd.CommandText = "select stSiteName from Sites;"
returned = cmd.ExecuteScalar
conn.Close()
Return returned
Catch e As AdsException
' write to log here
End Try
End Function
(For those not familiar, in the particular example above I'm accessing a database from Advantage Database Server).
In the above example, I would get a warning saying not all code paths return a value. If I move the Return statement to just before the End Function (outside the Try...Catch block, I would get a warning saying the variable may not be initialised.
Is there a standard/preferred way of handling this? At the moment I generally handle by putting the error message into the returned value, then testing for it from the calling code but it feels clunky to me.
The problem is that you handled the exception in your function. A handled exception is transparent to the caller, i.e. code outside this function will have no way of determining whether the exception was raised. This design is only correct when your function behaves correctly even when a exception is raised (hence can be handled).
When the catch statement is executed, the function does not know what value to return. That is the problem. You should not catch the exception at this level. You should let the exception raise, then past it to the upper level, where you can show appropriate error messages to the user.
The problem you are facing has nothing to do with Error Handling in particular. The compiler issues a warning if a function doesn't return something on all code paths, and you can choose it ignore it, since it is not categorized as an Error.
e.g. You will get the same warnings with If...Else if the code inside either If or Else doesn't return a value. Similarly you will get the warning in a Select..Case block if at least one of the Case blocks don't return a value.
It is however good to pay attention to what warnings the compiler issues and minimize the number of such warnings.
There are two approaches around this problem.
Keep multiple exit points in your function and ensure that all the exit points return some value.
Initialize your variable with some default value, and keep only one exit point for the function.
While it is debatable which one of the above is better, I personally like the second approach. It is better from code maintenance perspective too (when the function is too large).
For Example, you can initialize the variable with empty value or nothing to get rid of that warning.
Dim returned As String = String.Empty
...
Try
...
Catch e As AdsException
...
End Try
...
Return returned
In this example, you have 4 code paths from where the function can exit out (shown by ... in the example above). Assume that you had 10 or 15. You get a warning if you do not set the return value on any of the code paths. The above solution solves the problem by initializing the variable at the beginning, and return it at the end. Then you need not worry which code path sets the variable and which doesn't.
Closed. This question needs to be more focused. It is not currently accepting answers.
Want to improve this question? Update the question so it focuses on one problem only by editing this post.
Closed 8 years ago.
Improve this question
code1
while
dim number as integer = 0
'some code here
end while
code2
dim number as integer
while
number = 0
'some code here
end while
What is the difference in code 1 and code 2 in terms of speed?
What else is their difference?
What is the best practice to use? thank you
In code 1, your variable's scope is constrained to the while-block.
In code 2, your variable's scope goes beyond the while-block. For example if you define your while block within a function, the scope of the variable is the whole function.
You can note the difference if you have the same variable within multiple blocks:
while
dim number as integer = 0
x = number // x is 0
number = 1
end while
while
dim number as integer = 0
x = number // x is 0
end while
This code is fine, where as the following
dim number as integer = 0
while
x = number // x is 0
number = 1
end while
while
x = number // x is 1
end while
Both ways are fine. Speaking of performance - do not care, if you need to improve the performance of your code you will most likely need to touch a different place. Things like this are therefore often called "micro-optimizations".
Speaking of practice, it is usually best to define the variable as close to its use as possible. So if you only need the variable (and its state) within your while-loop, define it there. If you need to read the value after the while-loop, define it outside. If you use a tool like ReSharper it will even suggest to move your definition to the inner scope (here the while loop) if you place it outside and do not use it afterwards.
There should be no difference in speed of the 2 approaches. the compiler will optimize this for you. You can check the resultant IL code using Ildasm.exe.
The "best practice" is to use the smallest possible scope, i.e. code 2.
You shouldn't care about speed difference between these two. It will be extremely small (if any!).
Other differences? Second code makes number accessible after while loop, which may or may not what you want.
General rule: keep variables at the smallest possible scope, which means if you only need the variable within loop, declare it within loop. If you need it's value to be accessible when loop ends, declare it before loop.