Are closing brackets counted as statements in Statement Coverage? What about if they come after a return statement? - testing

I'm doing a simple assignment where I have to go over test case coverage(statement coverage, path coverage, etc) of a function.
I've tried endlessly to add code here and StackOverflow won't accept it no matter how I format it, so I'll just explain a very simple example.
Let's say you get to an if statement that has a return statement inside it. In the line below the return line is the if's closing bracket '}'
My professor and our textbook have been pretty vague about what a statement is, but my understanding is that for a line of code to be a statement it has to perform some type of function such as assigning a value to a variable or being a conditional statement like an if or while loop.
So my questions are:
Does the closing bracket count as a statement? Or do they only count as a line?
When the computer is reading the code and hits the return statement, does it jump to the correct number of closing brackets before leaving the function and returning a value?

Closing brackets are not traditionally counted as statements.
Even if they follow a return (or any other kind of unconditional control transfer, e.g. goto to raise exception.).
A more interesting case is:
if (...) {
return;
x=1;
}
The x=1; statement can't get control. Test coverage should tell you it is uncovered because it never gets executed.
This example is exactly the same code, slightly reformatted:
if (...) {
return; x=1; }
Many test coverage tools will show you covered lines rather than covered code, so would mark the return line as covered. That's wrong; x=1; is still uncovered and the coverage display tool should make that clear.
This is especially important if you have a long source line which exits (e.g., by exception) in the middle:
x=foo().bar().baz();
If bar() throws an exception, then foo(). is covered, x=... is not, and baz() is not. This shows why line coverage, while common, can be very misleading.
Now consider this case:
if (a) {
...
if (b)
return;
}
c;
If a and b are true, the return statement executes. Control doesn't flow past the if (b) statement. If a is true and b is false... the return isn't executed and control flows past the if (b) to statement c;. In this case you can argue the } is "covered" even though it isn't a statement. A good coverage tool should show } c; as covered.

Related

Is the `return` statement necessary at the end of an AHK script?

My one-line script:
Shift::Send ^{Space}
Is it necessary to add a return statement like the following?
Shift::Send ^{Space}
return
In the case of a subroutine with a label like you show above, the subroutine will be called and will continue until it gets to either return or exit.
So in this example, return isn't necessary
With functions, return is actually assumed in ahk so you don't necessarily need to include it unless your passing it with an expression.
In either case though, you might want to include it just to make things more readable.
Quote an example from the return documentation to demonstrate what it does:
The first Return separates the hotkey from the subroutine below. If it were not present, pressing the hotkey would cause Sleep 1000 to be executed twice.
#z::
MsgBox The Win-Z hotkey was pressed.
Gosub MySubroutine
return
MySubroutine:
Sleep 1000
return
Also, quote from Hotkeys Introduction and Simple Examples:
If a hotkey needs to execute only a single line, that line can be listed to the right of the double-colon. In other words, the return is implicit:
#n::Run Notepad
As a side note, if binding multiple hotkeys to the same action, we can write:
#a::
#b::MsgBox

Cannot assign an if statement to a variable

The problem here is that I do not understand well the difference between statements and blocks in control flow.
Looking the ternary operator I can use it to assign a variable. But this is an operator, so it is like applying a function--isn't it?
> my $variable = True ?? 34 !! 42;
34
since in the raku documentation says:
if documentation
if
To conditionally run a block of code, use an if followed by a
condition. The condition, an expression, will be evaluated immediately
after the statement before the if finishes. The block attached to the
condition will only be evaluated if the condition means True when
coerced to Bool. Unlike some languages the condition does not have to
be parenthesized, instead the { and } around the block are mandatory:
do documentation
do
The simplest way to run a block where it cannot be a stand-alone statement is by writing do before it:
so this should work in both cases:
> my $variable = do {34};
34
> my $variable = if True {34;} else {43;}
===SORRY!===
Word 'if' interpreted as a listop; please use 'do if' to introduce the statement control word
------> my $variable = if⏏ True {34;} else {43;}
Unexpected block in infix position (two terms in a row)
------> my $variable = if True⏏ {34;} else {43;}
as said in the error I need to add the do:
> my $variable = do if True {34;} else {43;}
34
So the if really does not run the block...or what is the real problem here?
TL;DR: The actual difference is between statement and expression, not statement and block. do is a statement prefix that creates expressions.
if actually creates a statement (anything that is run in Raku is), however, what it's not is an expression. do is a statement prefix, and what it does is turn statements into expressions.
However, if is not really a first-class function that you can assign to a variable or handle around. Whenever you find pieces of syntax such as that one (or for, for instance), you need to prefix them with do to "expressionify" them.
say &say.^name;# OUTPUT: «Sub␤» say &do.^name; # OUTPUT: «===SORRY!=== Error while compiling <tmp>␤Undeclared routine:␤...
say &if.^name; # OUTPUT: «===SORRY!=== Error while compiling <tmp>␤Undeclared routine:␤ if used at line 1␤␤»
So if, by itself, does not create a block, it does not create an expression, it simply creates a statement. You need to precede it with do if you want it to actually turn it into a expression. It does run the block that's behind it, however.
Let's go back to the original question, statements and blocks. Blocks are objects, first-class citizens. You can use them, apply them, pass them around.
my &ifs = { if $_ {34} else {43}};
ifs(True).say; # OUTPUT: «34␤»
Statements are throwaway blocks you simply run. In some cases, they are also expressions: they yield a result which, then, you can assign.
my &ifs = { if $_ {34} else {43}};
my $result = ifs(True).say; # OUTPUT: «34␤»
say $result; # OUTPUT: «True␤»
The ifs(True).say statement prints to output, it also produces a result that can be assigned. All three lines are also statements, and as a matter of fact, expressions too.
Some control structures, however, do not create expressions.
Some others do; for creates a expression; while does not.
if is an example of this. They don't produce a result. You use them for the side effects: running a statement (if true) or another (if not). You might turn them into a block, as above, and pass them around. Or you can just precede them with do and make them produce a throwaway result, which you can then use.
So it will very much depend on your actual use case. You can surround the if statement with curly braces and create a block; or you can simply use the result creating an expression. Or you might want to use it just for the side effects, doing nothing.

Indicator for Changes Made

Is there a way in Stata to execute a piece of code if and only if a previous bit of code actually made changes?
For example, I am concatenating two variables only if one of them meets a regexm() test. I understand that if I run this qualifier as an if command, it only looks at the first observation. Is there a way to run an if command, say
if regexm(var`n', ".*\)$") {
// code
}
and have the if statement return true if the conditional is true for any observation, not just the first one?
For a match in any observation to trigger code, you need to count matches first:
count if regexm(var`n', ".*\)$")
if r(N) > 0 {
// code
}
if r(N) would suffice here, as non-zero arguments are treated as true and r(N) from count can never be negative.

Tool to identify problems in catch blocks

I am looking for a tool (may be build time or eclipse plugin) that can help me to identify if I am not logging the Exception trace/message.
We have a legacy application that has try catch block in which a custom error message is logged. The exception is not logged and is not thrown. So, when a problem occurs, there is no stack trace in the log files that would help to debug the issue. An example of this is:
try {
do something....
} catch (Throwable exception) {
Log.log("<<custom message>>");
}
I need a tool like Coverity or Checkstyle that can help me to identify all such occurrences in my code base.
Thanks and Regards
I'd expect you to be able to do a decent job with any tool that can search text using regular expressions (e.g, grep).
The regex would be something like this:
"catch\W*\(.*\)\W*{\W*Log\.log"
where W stands for some whitespace recognizer that picks up blank and newline.
Your pattern is unique enough I'd expect very few false hits, if the programmers
were consistent with the convention you showed.
[EDIT] OP indicates
I am looking for catch blocks where I am NOT doing the following - '+ exception':
try { do something.... }
catch (Throwable exception)
{ Log.log("<<custom message>>" + exception)
We're back to a regular expression as a pretty decent hack. You need hunt for anyplace that doesn't call Log.log("<<....>", or if it does, doesn't have a following "+exception".
This is awkward to code as a regexp without a "not" operator, but possible. Assuming
the catch clause exists (a different regexp test), and the Log.log call exists, this will probably do it:
"catch\W*\(.*\)\W*{\W*Log\.log\(\".*\+^[\+]"
The last check looks to see if "+" is there. Anything matching this doesn't have the "+".
Our Source Code Search Engine (SCSE) uses the lexemes of the language rather than regexes to enable straightforward searches, so it has a slightly unusual query language written in terms of language lexemes. It also allows "negation" on a larger scale; you can subtract hits in two regions, and that's really useful. This means the following query would do the trick:
'catch' '(' I I ')' '{' I - I=Log '.' I=log '(' S '+' I ')'
This finds hits for all "catch" clauses and the start of the block (assuming it starts with "Log", and subtracts away any matches to the logging idiom. Quoted terms are language atoms. I stands for "I(dentifier)"; it can be any identifier (just I) or constrained to a particular regex for the identifier (of which "Log" is a particularly simple regex). S stands for "S(tring)", also allowing constraints which we don't need for this query. This query has two sub-queries, one part before the minus sign that finds "catch" clauses and a prefix of the catch body, and one part after the minus sign that looks for that idiom OP insists he wants. Any overlaps of results of the second subquery with the first cause the overlapped queries to be "subtracted" (the minus sign) from the result. So the final result are "catch clauses that don't start with a logging step".
A more sophisticated check requires finding the catch clauses, and logging clauses, and verifying that the logging clauses do not occur anywhere in the catch block. The SCSE can't do this by itself. More sophisticated engines that parse and build ASTs can be used to determine this. I know of tools that can do, this too, if OP wants further elaboration.

Multiple returns vs single return

I've used for a long time single-return style (as structural programming style). I've started reading Fowler's "Refactoring" and found "Removing control flag" and "Replace Nested Conditional with Guard Clauses" where he writes, that single return should be avoided.
As for me, there are a lot of benefits using single return, and only some more difficults for reading. So what are the profit using multiple return?
Benefits:
Single return allows easily put breakpoint to return statement
It's easy to add Assert for result value if there are single return
Single return makes code more readable
Even with multiple returns there is one function exit point. It is the closing curly bracket. Just place a breakpoint on it and set a conditional to check rAX (if IA32e).
int f()
{
if (condition)
return 1;
return 0;
} // Place here. Would break at epilog just before return.