How to evaluate two function in one statement? - windows

How to declare two object in one statement for vb.net?
example
If IsNumeric(TextBox1.Text),(TextBox2.Text) Then
lbl_answer.Text = Val(TextBox1.Text) + Val(TextBox2.Text)
Else
MsgBox("Error only number can be calculate")
End If
I can do
if isnumeric(textbox1.text) then
but I can't say
if isnumeric(textbox1.text), (textbox2.text)
How can I do so?

As nobody did so far let me express your options (straight from the comments - sorry but why those are not answers I don't know):
And
If IsNumeric(TextBox1.Text) And IsNumeric(TextBox2.Text) Then ...
AndAlso (subtle difference: AndAlso don't evaluate the second expression if the first evaluates to false)
If IsNumeric(TextBox1.Text) AndAlso IsNumeric(TextBox2.Text) Then ...
I don't think the LINQ one is really a option.

Related

Refactoring conditional variable assignment

I'm working on a project. Currently I have a fairly large conditional statement, that assigns a value to a variable based on some input parameters. So, I have something like this.
if some condition
x = some value
elsif another condition
x = a different value
...
What's the best way to refactor this? I'm hoping that I might end up with something like
x = some value if some condition || another value if another condition
Is there a pattern for this sort of thing?
Just put the assignment outside the if.
x = if some condition
some value
elsif another condition
a different value
Or you could use a Hash.
x = dict[some condition]
It's not a pattern, but an operator. The one you're referring to is the ternary operator:
If Condition is true ? Then value X : Otherwise value Y
Here is an example:
speed = 90
speed > 55 ? puts("I can't drive 55!") : puts("I'm a careful driver")
Using the ternary statement is short, sweet, and does the job.
x = some condition ? some value :
another condition ? a different value : ...
A conditional statement is also an expression, so one of the first things you can do, if the variable is the same in each condition, is:
x = if cond1
expr1
elsif cond2
expr2
....
end
If the conditions are all states of a single expression, you can make this even neater, using a case statement.
However, the next most obvious re-factoring exercise is to get the big conditional isolated into a method, which should be fed the bare minimum data required to evaluate all the conditions and expressions.
E.g.
# Where conditional is currently, and x assigned, assuming the conditionals
# need a couple of variables . . .
x = foo param1, param2
# Elsewhere
private
def foo p1, p2
if cond1
expr1
elsif cond2
expr2
....
end
end
If you want to refactor for code clarity and flexibility, consider the replacing conditional with polymorphism refactor.
There's not enough detail in your question to go much further with recommendations, but this refactor will make your code base much more resistant to change. If you receive a new requirement, it's bad form to break open the conditional and modify it (more prone to introducing bugs, more difficult to do); it's preferable to create a new object that you can plug into the existing codebase. This flexibility what the Open/Closed Principle (the "O" in the SOLID acronym) describes.

Complex IF THEN statements in VB6 [duplicate]

This question already has answers here:
Closed 10 years ago.
Possible Duplicate:
Does VB6 short-circuit complex conditions?
I am curious about how IF statements are executed in VB6.
For example if I have the statement
If x And y Then
'execute some code
End If
Does the code move on if x is not true? Or does it go ahead and evaluate y even though there is no logical point?
Another example
If x Or y Then
'execute some code
End If
Does the code continue and evaluate y if x is true?
EDIT:
Is there a way to avoid nested IF statements if I want to evaluate very complex conditions and I don't want to waste CPU time?
What you are describing is short circuiting logic, and VB6 doesn't have it...
For example, in VB.Net you might write
If x AndAlso y then...
In this case y is not tested if x turns out to be false.
In your VB6 example, you'll get a Object or With block variable not set error if you try something such as:
Dim x as Object
If Not x Is Nothing And x.y=1 Then
Since object x has not been instantiated.
An unwieldy or-like statement that exhibits short circuiting behaviour:
select case True
case a(), b(), c()
'//if a returns true b & c are not invoked, if b returns true a & b were invoked
case else
...
To answer your edit - avoiding nested IF statements, you can use Select Case, covered in the latter half of this article.
Code snippet from the article:
Select Case strShiftCode
Case "1"
sngShiftRate = sngHourlyRate
Case "2"
sngShiftRate = sngHourlyRate * 1.1
Case "3"
sngShiftRate = sngHourlyRate * 1.5
Case Else
Print "Shift Code Error"
End Select

How to define more one condition in a While

I would like something like that :
While Not RdoRst.EOF And RdoRst(2) = "Foo"
cboComboBox.AddItem RdoRst(1)
cboComboBox.ItemData(cboComboBox.NewIndex) = RdoRst(0)
RdoRst.MoveNext
Wend
I want that the expression 1 (Not RdoRst.EOF) is evaluated first. Then if it returns true, the expression 2 is evaluated too (RdoRst(2) = "Foo"). If expression 1 return false, the expression 2 is not evaluated.
Regards,
Florian
AndAlso is not available in VB6. Try this
Do
If RdoRst.EOF Then Exit Do
If Not RdoRst(2) ="Foo" Then Exit Do
cboComboBox.AddItem RdoRst(1)
cboComboBox.ItemData(cboComboBox.NewIndex) = RdoRst(0)
RdoRst.MoveNext
Loop
The question relates to 'short circuit' evaluation of condition expressions. Well VB6 does not support this feature. I know this is stupid.
While Not RdoRst.EOF
If RdoRst(2) = "Foo" Then
cboComboBox.AddItem RdoRst(1)
cboComboBox.ItemData(cboComboBox.NewIndex) = RdoRst(0)
Else
Exit Wend
End If
RdoRst.MoveNext
Wend

use of goto versus runtime code evaluation

Recently for a programming class, we were given the assignment to write a program in any language that, given n, will produce all the possible derangements for an array p of size n such that p[i] != i for all i: 0 <= i < n. We had to use iterators, e.g. yield.
Example: n=3, [0, 1, 2] is not a derangement, but [2, 0, 1] is as well as [1, 2, 0].
I came up with a pseudocode solution that would work, but the problem was that it required power loops (that is, n nested loops where n is only known at runtime). To do this, I generated n nested loops in Ruby code in a string, then eval-ed the string. My solution worked, however my professor thought that using a few gotos would have been better solution (easier to read, at least) than dynamic code generation.
I was under the impression that goto was always a bad choice. Why might runtime evaluation of dynamically generated code be a worse choice than goto? The generated code is clean and simple, and seems fairly efficient for the given problem. The only user input upon which the code generation depends is n, which is checked to ensure it's an integer value beforehand. It yields only unique derangements, as it should.
I'm not asking for a solution to my programming assignment, I just want to know reasons behind the use of goto over dynamic code evaluation, or vice versa.
Edit: to clarify, the assignment included writing a program using iterators and another using recursion, so the iterative version wasn't necessarily meant to be efficient.
Both GOTO and code generation are inelegant solutions to this problem IMO. There is a recursive algorithm that is probably the right answer here.
That's a really interesting question - I'm not sure that there's a definitive answer.
The problem with goto is its use in an unstructured fashion - a goto is a "massive random leap" so in the general instance, after the jump, you don't know where you came from which causes all kinds of issues both in terms of debugging and maintainability and - in a more formal sense with proving "correctness" of the code. Of course there are languages (I've been around a while) where you don't have an option at which point you impose structure on the code. The bottom line is that its not that GOTO is bad so much as the way that goto is used (and abused) that is bad and that makes its a dangerous construct to have available.
Using code generation and then evaluating the result is clever :) However "clever" is not always a good thing and I suspect that in part the issue with using that as a solution is that its not actually addressing the problem as intended. That may be "cheating" in a sense - at least so far as your professor is concerned - doesn't invalidate your solution but may render it "inelegant". The debugging and maintainance issues also arise in respect of the code.
A recursive solution - especially as I vaguely remember being taught (some 25 years ago) that one can usually unwind recursion into loops - would probably be the most elegant.
Definitely an interesting question!
Without seeing your code, I would tend to side with the prof. If it's a choice between GoTo and dynamic code, I would lean towards the former. GoTo are not always a bad choice.
You can solve almost all problems without the use of GoTos. Specifically with loops you can use the break and continue statements to implitly use gotos while code standard are still maintained.
n nested loops sound like a bad plan, and I suggest that you instead look into a recursive functions. Every single time you need to do a n-loops you should always be thinking recursion.
Dynamic code is not compile time checkable, which means any errors will go undetected until run time. Potentially making them harder to find. For ruby, this would mean that syntax errors would not be found by the IDE or editor, whichever you happen to be using. That is a plus for choosing goto.
I think I would have to see both to make a decision in this case. I haven't seen the code, but I'm willing to bet there is a good solution that doesn't use dynamic code, or goto's. goto is not always bad, but if you are thinking of using it you probably have not made the best design decisions up to this point and probably want to revisit your solution.
In one of my assignement in college, I once had to do something that was relatively similar
My solution was to use a recursive function, passing the array, the size of the array and the nesting level as argument. The function then call itself with nesting level +1, until the nesting level is equal to the size of the array. No Goto, no code evaluation, only clean code!
Example
function computeDerangement(yourArray, loopLevel, arraySize)
{
//We check to see if the loop level is the same as the array size
//if true, then we have executed exactly n loop
if (loopLevel == arraySize) {
display(yourArray); //Display being some kind of function that show the array,
//you get the idea
} else {
while(something) {
//Here you put the logic that you execute at one level of the loop
//Then you call yourself with one more level of nesting
computeDerangement(yourArray, loopLevel + 1, arraySize);
}
}
}
Hope that help!
I have never used goto in my life, so I'm pretty sure there is always a way to avoid them
The main reason people avoid goto statements is that they can make your program more difficult to understand.
Without having seen your code, I'd guess it's more difficult to understand than the equivalent program using goto...
GOTO Solution -- a goto is convenient when simulating a function call. Here's a non-recurisve solution that simply simulates the recursive solution using a stack and a goto label to return to the point where the function call would have occurred.
See the recursive procedure (I have posted this as a separate answer) for comparison.
Option Strict On
Option Explicit On
Module Module1
Dim x As Stack
Private Sub printGeneratedList(ByVal generatedList As List(Of Integer))
For Each el In generatedList
Console.Write(el & " ")
Next
Console.WriteLine()
End Sub
Private Sub generateAux(ByVal i As Integer, ByVal n As Integer, _
ByVal generatedList As List(Of Integer))
Dim stackI As Stack(Of Integer) = New Stack(Of Integer)
Dim stackJ As Stack(Of Integer) = New Stack(Of Integer)
Dim j As Integer
StartLabel:
j = 0
If i >= n Then
printGeneratedList(generatedList)
If stackI.Count = 0 Then
Return
Else
GoTo ReturnLabel
End If
End If
While j < n
If Not j = i Then
If Not generatedList.Contains(j) Then
generatedList.Add(j)
stackI.Push(i)
stackJ.Push(j)
i = i + 1
GoTo StartLabel
ReturnLabel:
i = stackI.Pop()
j = stackJ.Pop()
generatedList.Remove(j)
End If
End If
j = j + 1
End While
If stackI.Count = 0 Then
Return
Else
GoTo ReturnLabel
End If
End Sub
Private Sub generate(ByVal n As Integer)
Console.WriteLine("Generating for n = " & n.ToString())
Dim l As List(Of Integer) = New List(Of Integer)
If n < 0 Then
Throw New Exception("n must be >= 0")
End If
generateAux(0, n, l)
End Sub
Sub Main()
generate(0)
Console.ReadLine()
generate(1)
Console.ReadLine()
generate(2)
Console.ReadLine()
generate(3)
Console.ReadLine()
generate(4)
Console.ReadLine()
End Sub
End Module
goto's are not clean. but if high performance is required, you need to break some of those coding rules sometimes...
if speed is really an important matter, for example if you want to write a library or code you have big exigeance on, you might consider using goto. for sure you have to pay attention that everything goes well.
Comment: At the end, the executing CPU does nothing else than simple jumps. Just only that the programming language / the compiler creates them. use with caution and don't mess with it.
Both the goto solution and dynamic code generation ideas are bad. This is easily solved with a recursive solution as mentioned by others. You simply recursively generate all permutations (standard recursive solution) and when generation is complete (ie at the leaf of the recursion) simply skip returning permutations that are not derangements.
Recursive solution -- here's a solution with early pruning. My only question is regarding enumerations: did he want you to create an enumerator that on each successful call would generate the next item in the list? This would probably be easiest implemented by creating a lambda version of this program - I used to do this in lisp all the time when writing query generators that would generate the next answer to a question when doing prolog-interpreter style queries.
Option Strict On
Option Explicit On
Module Module1
Private Sub printGeneratedList(ByVal generatedList As List(Of Integer))
For Each el In generatedList
Console.Write(el & " ")
Next
Console.WriteLine()
End Sub
Private Sub generateAux(ByVal i As Integer, ByVal n As Integer, _
ByVal generatedList As List(Of Integer))
If i >= n Then
printGeneratedList(generatedList)
Return
End If
For j As Integer = 0 To n - 1
If Not j = i Then
If Not generatedList.Contains(j) Then
generatedList.Add(j)
generateAux(i + 1, n, generatedList)
generatedList.Remove(j)
End If
End If
Next
End Sub
Private Sub generate(ByVal n As Integer)
Console.WriteLine("Generating for n = " & n.ToString())
Dim l As List(Of Integer) = New List(Of Integer)
If n < 0 Then
Throw New Exception("n must be >= 0")
End If
generateAux(0, n, l)
End Sub
Sub Main()
generate(0)
Console.ReadLine()
generate(1)
Console.ReadLine()
generate(2)
Console.ReadLine()
generate(3)
Console.ReadLine()
generate(4)
Console.ReadLine()
End Sub
End Module

Is it better to use NOT or <> when comparing values?

Is it better to use NOT or to use <> when comparing values in VBScript?
is this:
If NOT value1 = value2 Then
or this:
If value1 <> value2 Then
better?
EDIT:
Here is my counterargument.
When looking to logically negate a Boolean value you would use the NOT operator, so this is correct:
If NOT boolValue1 Then
and when a comparison is made in the case of the first example a Boolean value is returned. either the values are equal True, or they are not False. So using the NOT operator would be appropriate, because you are logically negating a Boolean value.
For readability placing the comparison in parenthesis would probably help.
The latter (<>), because the meaning of the former isn't clear unless you have a perfect understanding of the order of operations as it applies to the Not and = operators: a subtlety which is easy to miss.
Because "not ... =" is two operations and "<>" is only one, it is faster to use "<>".Here is a quick experiment to prove it:
StartTime = Timer
For x = 1 to 100000000
If 4 <> 3 Then
End if
Next
WScript.echo Timer-StartTime
StartTime = Timer
For x = 1 to 100000000
If Not (4 = 3) Then
End if
Next
WScript.echo Timer-StartTime
The results I get on my machine:
4.783203
5.552734
Agreed, code readability is very important for others, but more importantly yourself. Imagine how difficult it would be to understand the first example in comparison to the second.
If code takes more than a few seconds to read (understand), perhaps there is a better way to write it. In this case, the second way.
The second example would be the one to go with, not just for readability, but because of the fact that in the first example, If NOT value1 would return a boolean value to be compared against value2. IOW, you need to rewrite that example as
If NOT (value1 = value2)
which just makes the use of the NOT keyword pointless.

Resources