Comments: Switch(((IIf(([qty_req]-[qty_on_hand])<0,0,([qty_req]-[qty_on_hand])))=0) And ((([qty_on_hand]-[qty_req])/[qty_req])<=0.2),"Please check manually")
I have been struggling with this expression for too long. I keep getting the error "This expression is typed incorrectly, or it is too complex to be evaluated. For example, a numeric expression may contain too many complicated elements. Try simplifying the expression by assigning parts of the expression to variables." I've tried breaking down the expression to see if there was a bracket I the wrong place but I can't figure this out.
Note: The word "Comments" is just the field name (I primarily use the Design View in MS Access).
Update - The goal behind this is to eventually add more conditions to this switch statement, but this first one isn't working so that's why it seems like it doesn't make sense to use a Switch. Also, in pseudo code, this is what the intention of this expression is:
Switch([TransferQTY]=0 And [Req is within 20% of Inventory], "Please check manually")
In regards to the first IIF statement:
IIf([Req-Inventory is negative, that means that we have enough on hand and don't need to send],0, [Req-Inventory])
I think it's simply a check like this:
IIf([qty_req]-[qty_on_hand]<0 And ([qty_on_hand]-[qty_req])/[qty_req]<=0.2,"Please check manually","") AS Comments
The first IIF is just strangely built and has some redundancy to it. The second might give you strange answers because you don't have parans around your numerator. As it's written it could be simplified to:
As for the first IIF, you stated
"IIf([Req-Inventory is negative, that means that we have enough on
hand and don't need to send],0, [Req-Inventory])"
in the context of the switch (psuedo-coded):
Switch([TransferQTY]=0 And [Req is within 20% of Inventory], "Please
check manually")
This is basically saying "If the quantity requested minus thequantity on hand is less than or equal to 0", so instead of an IIF to do the "Less than or equal to" bit, just use <=:
Switch(((qty_req - qty_on_hand) <= 0) AND (((qty_on_hand - qty_req)/qty_req) <= 0.2), "Please Check Manually")
This will work better because Access is balking about the complexity. This dramatically reduces the complexity and accomplishes the same thing.
Also, I've gone a little heavy handed with the parantheses here. You could remove the ones that delineate each of the conditions that the AND function is evaluating and it would be fine.
I've removed the bit here about not using switch that was in a previous version of this answer since OP stated that switch() will be used after this bit starts working.
Related
A vendor I use packages their software with AssemblyScript. They provide some infrastructure and I build on top of it.
Accidentally, I changed my double equal signs ("==") to triple equal signs ("===") in a function that performs equality checks on hexadecimal strings. I spent hours ensuring that the values checked are indeed equal and have the same case sensitivity, but nothing could make the if statement enter the branch I was expecting it to enter, except for going back to "==".
And so I ended up here, asking for help. How is "===" different to "==" in AssemblyScript? Is it some quirk of the language itself or the vendor's parser?
Yes. In AssemblyScript tripple equal ("===") compare raw references and skip overloading operator ("=="). See docs.
There are have proposal avoid this non-standard for TypeScript behaviour. You could check and upvote this issue
The large majority of SonarLint rules that I've come across in Java seemed plausible and justified. However, ever since I've started using SonarLint for VB.NET, I've come across several rules that left me questioning their usefulness or even whether or not they are working correctly.
I'd like to know if this is simply a problem of me using some VB.NET constructs in a suboptimal way or whether the rule really is flawed.
(Apologies if this question is a little longer. I didn't know if I should create a separate question for each individual rule.)
The following rules I found to leave some cases unconsidered that would actually turn up as false-positives:
S1871: Two branches in the same conditional structure should not have exactly the same implementation
I found this one to bring up a lot of false-positives for me, because sometimes the order in which the conditions are checked actually does matter. Take the following pseudo code as example:
If conditionA() Then
doSomething()
ElseIf conditionB() AndAlso conditionC() Then
doSomethingElse()
ElseIf conditionD() OrElse conditionE() Then
doYetAnotherThing()
'... feel free to have even more cases in between here
Else Then
doSomething() 'Non-compliant
End If
If I wanted to follow this Sonar rule and still make the code behave the same way, I'd have to add the negated version of each ElseIf-condition to the first If-condition.
Another example would be the following switch:
Select Case i
Case 0 To 40
value = 0
Case 41 To 60
value = 1
Case 61 To 80
value = 3
Case 81 To 100
value = 5
Case Else
value = 0 'Non-compliant
There shouldn't be anything wrong with having that last case in a switch. True, I could have initialized value beforehand to 0 and ignored that last case, but then I'd have one more assignment operation than necessary. And the Java ruleset has conditioned me to always put a default case in every switch.
S1764: Identical expressions should not be used on both sides of a binary operator
This rule does not seem to take into account that some functions may return different values every time you call them, for instance collections where accessing an element removes it from the collection:
stack.Push(stack.Pop() / stack.Pop()) 'Non-compliant
I understand if this is too much of an edge case to make special exceptions for it, though.
The following rules I am not actually sure about:
S3385: "Exit" statements should not be used
While I agree that Return is more readable than Exit Sub, is it really bad to use a single Exit For to break out of a For or a For Each loop? The SonarLint rule for Java permits the use of a single break; in a loop before flagging it as an issue. Is there a reason why the default in VB.NET is more strict in that regard? Or is the rule built on the assumption that you can solve nearly all your loop problems with LINQ extension methods and lambdas?
S2374: Signed types should be preferred to unsigned ones
This rule basically states that unsigned types should not be used at all because they "have different arithmetic operators than signed ones - operators that few developers understand". In my code I am only using UInteger for ID values (because I don't need negative values and a Long would be a waste of memory in my case). They are stored in List(Of UInteger) and only ever compared to other UIntegers. Is this rule even relevant to my case (are comparisons part of these "arithmetic operators" mentioned by the rule) and what exactly would be the pitfall? And if not, wouldn't it be better to make that rule apply to arithmetic operations involving unsigned types, rather than their declaration?
S2355: Array literals should be used instead of array creation expressions
Maybe I don't know VB.NET well enough, but how exactly would I satisfy this rule in the following case where I want to create a fixed-size array where the initialization length is only known at runtime? Is this a false-positive?
Dim myObjects As Object() = New Object(someOtherList.Count - 3) {} 'Non-compliant
Sure, I could probably just use a List(Of Object). But I am curious anyway.
Thanks for raising these points. Note that not all rules apply every time. There are cases when we need to balance between false positives/false negatives/real cases. For example with identical expressions on both sides of an operator rule. Is it a bug to have the same operands? No it's not. If it was, then the compiler would report it. Is it a bad smell, is it usually a mistake? Yes in many cases. See this for example in Roslyn. Should we tune this rule to exclude some cases? Yes we should, there's nothing wrong with 2 << 2. So there's a lot of balancing that needs to happen, and we try to settle for an implementation that brings the most value for the users.
For the points you raised:
Two branches in the same conditional structure should not have exactly the same implementation
This rule generally states that having two blocks of code match exactly is a bad sign. Copy-pasted code should be avoided for many reasons, for example if you need to fix the code in one place, you'll need to fix it in the other too. You're right that adding negated conditions would be a mess, but if you extract each condition into its own method (and call the negated methods inside them) with proper names, then it would probably improves the readability of your code.
For the Select Case, again, copy pasted code is always a bad sign. In this case you could do this:
Select Case i
...
Case 0 To 40
Case Else
value = 0 ' Compliant
End Select
Or simply remove the 0-40 case.
Identical expressions should not be used on both sides of a binary operator
I think this is a corner case. See the first paragraph of the answer.
"Exit" statements should not be used
It's almost always true that by choosing another type of loop, or changing the stop condition, you can get away without using any "Exit" statements. It's good practice to have a single exit point from loops.
Signed types should be preferred to unsigned ones
This is a legacy rule from SonarQube VB.NET, and I agree with you that it shouldn't be enabled by default in SonarLint. I created the following ticket in our JIRA: https://jira.sonarsource.com/browse/SLVS-1074
Array literals should be used instead of array creation expressions
Yes, it seems to be a false positive, we shouldn't report on array creations when the size is explicitly specified. https://jira.sonarsource.com/browse/SLVS-1075
So I've been trying to do a calculator program in Visual Basic (shouldn't be too bad, I think). So far I got everything down and tested the operators individually. What I'm trying to do is to have the equals sign be able to determine which operator to use and go with it according to the button pressed for operator. I thought maybe if/else or switch/case could work, but I'm either getting addition first (it's the first in the choices) or nothing at all
Maybe I'm validating the wrong variable perhaps. I thought maybe that as an example:
if btnEquals.Text = "(insert operator sign here)" Then
{insert operator statement here}
on an if/else or case would do it, but it's simply not. I have checked in SO for any similar issue in VB, but most are for another language. I know I have to do something to ensure that the buttons coincide with the logical statements
Basically: How do I make the "=" button in the calculator program do the right arithmetic operation when the "+", "-", "/", "*" buttons are pressed? I tried if/else and case/switch and it's not logically giving the right answers.
Edited to clarify for other users.
Thanks in advance!
Already found an easy way to do it and it worked, it was simpler than I thought and was pulling my hair for no reason. Just for future reference. I just added a type char variable and with each arithmetic button (+,-,*,/) assign the arithmetic symbols to the variable and then use if/else or case switch in the "=" button to validate that variable.
Anyone with higher rank, you can go ahead and close this one. Thank you!
Previous research
In several languages (perl, python, php, etc.) there is the <value> += <increment> operator**, which increments a <value> by adding <increment> to it. This can be used in a for loop, which will cumulatively add <increment> to <value> with each iteration. This saves having to type more explicitly (verbosely): <value> = <value> + <increment>.
The trouble with this operator is that one often forgets whether it was += or =+. I often learn I have typed it the wrong way later, the hard way.
I thought I would finally learn the intuition in this PHP tutorial (01:35), but he fumbles it.
Question
Is there an intuitive "in plain english" way of explaining why it is += instead of =+ or was it some convention that was arbitrarily set once upon a time?
If "Yes" to the above, then what is this intuitive way of explaining why it is +=?
** Please let me know in comments what this operator is formally known as.
Putting the non-equals sign before the equals sign reduces perceived ambiguity: a-=b can only mean "Decrement a by b", but a=-b could also mean "Set a to the negated value of b".
This wouldn't technically be ambiguous, since the C parsing rules are clear that token consumption is greedy (that is, if =- were an operator, the parser would always prefer to parse it as =- rather than = -), but clearly it would have been ambiguous from a readability standpoint.
I don't know history behind this one, but I've always just thought of it as
+= "add it first, assign it next". So if you're in a read left to right culture (english) then this makes sense as adding comes first, then assigning comes next.
Please see Sneftel's answer for a very good technical reason.
Today I was working an in-class project with my students when I ran into this bug.
Imgur Link
Pastebin Link
Basically, decTemperature is a String variable that receives an input from the User. In order to teach data validation, short-circuiting, and loops, we were using the following While loop condtionals to force a valid response:
While IsNumeric(decTemperature) = False Or
Convert.ToDecimal(decTemperature) <= 0.0 Or
Convert.ToDecimal(decTemperature) > 135.0
If the user puts in 'abc', in theory the conditional statement should short circuit before reaching the second part of the conditional statement. I attempted the conditional a number of different ways, but ultimately it would crash in every design.
My assumption on the issue probably links closely to an older question I asked about dealing with data types with explicitly setting Option Strict 'on' (although a quick add of Option Strict On in the above code still crashes). That is to say, decTemperature is being processed in each conditional statement before evaluating.
Whatever the case, what is causing the issue and what would be a better approach that still maintains the concepts (that is forcing a valid response from the user)? I have an idea with using a Boolean data type validResponse and setting it, but that seems to be throwing away short-circuiting as a concept.
Or does not short-circuit. Neither does And
OrElse does short-circuit (as well as AndAlso). See OrElse Operator (Visual Basic)
So it should look like this:
While IsNumeric(decTemperature) = False OrElse _
(Convert.ToDecimal(decTemperature) <= 0.0 OrElse _
Convert.ToDecimal(decTemperature) > 135.0)
I would consider using Decimal.TryParse to test the validity of the input.
If you just use Or then every statement is evaluated in every case. That's what the short circuit operators OrElse and AndAlso are for. If you use OrElse the If statement stops the evaluation after the first true statement is detected (or the first false statement in case of an AndAlso).
So in your case the conversion to decimal would be executed in any case. This is avoided with the short circuit operators.