How should I format this piece of code? - language-agnostic

Here are two ways of calling callscript (in pseudocode):
using duplicate calls
if flag == true
flag = false
callscript
flag = true
else
callscript
endif
using an extra variable
flag2 = flag
flag = false
callscript
flag = flag2
conditions
I have to make sure is that flag is false when the script is called.
Also, the flag value has to be restored to the original value.
Is there a better way to do this than these two? If not, which one of these is a better choice?

The best would be to send the flag along in the call, so that the relation between the flag and the method is clear:
callscript(false)
If that's not an option, and you have to choose between the two, then either one would do. There is no clear winner, readability is about the same for both, so it's just a matter of taste.
The second option would be the better one if the actual call is complicated so that you don't want to repeat it in the code, or if the data type is something more complicated than a boolean.

I would go with variant two with a change to the name of variables to make it a bit more easy to understand.
saved_flag = flag
flag = false
callscript
flag = saved_flag

I like the second one much better, because if you name flag2 in a sensible way (like
backupValueOfFlag = flag
flag = false
callscript
flag = backupValueOfFlag
) it is much clearer what you are doing and why you are doing it.

I think this is why local variables and subroutine parameters have been invented.
Do you really have to work with globals?

I will choose the second one. The first one is too artifical for me - the if there is not for program flow but to preserve the flag value.

As for me, better choice is first one. Because it is more readable and more clear what is going on there.

Related

Assigning Pairs to Already Defined Vars in Kotlin

I'm trying to return a pair from a function and assign it to already defined variables, in Kotlin.
The way I've seen pairs received from a function until now is:
val/var (thing1, thing2) = FunctionReturningPair()
Is it possible to assign already defined variables to the pair? Something like:
var thing1: String
var thing2:int
//do other things here
(thing1, thing2) = FunctionReturningPair()
//note that thing1 and thing2 were ALREADY DEFINED.
Unfortunately that's not allowed as far as I know. The current Kotlin syntax allows for destructuring declarations, but that only works if you declare the variables at that time. In your example you declared the variables above and just want to assign a value.
Looking at the grammar makes it clear that assignment only accepts a directlyAssignableExpression (such as a simpleIdentifier). A declaration instead accepts a multiVariableDeclaration.
I don't see a reason of why that would not work, but apparently it does not. In the docs, I don't see any mention of doing that as well. Usually features are added if there is a consensus that 1. people consider that they are needed. And 2. they are not going to break other things / or be confusing. So I guess that one of those conditions has not been met, or nobody ask for it.
If you really want it, it might be worth checking youtrack to see if somebody else requested it. If they have vote for it, and if not, write a feature request.
Until then, I guess that you are stuck with one of these ways:
val p = functionReturningPair()
thing1 = p.first
thing2 = p.second
OR
functionReturningPair().let { (first, second) -> thing1 = first; thing2 = second }

using the OR function in Excel

I am just trying to use the OR function in Excel for analyzing some string variables. Instead of using a character count to verify whether someone anwered correctly, I would like to use the or function to accept more than one answer as correct.
For instance, return 1 if cell = "she was always there" or "she was there always".
How would I do this?
=IF(OR(A1="this",A1="that"),1,0)
IF takes three values:
The logical test
The value if true
The value if false
Each value can take other functions as it's argument. In this case, we use an OR function as the logical test. The OR can take any number of arguments (I'm sure there is a limit but I've never seen it). Each OR argument takes the form of a logical test and if any of the logical tests are TRUE, then the result of the OR is TRUE.
As a side note, you can nest many functions to create complex tests. But the nesting limit seems to be set at 7. Though there are tricks you can use to get around this, it makes reading the function later very difficult.
If you can live with "TRUE" or "FALSE" returns, then you don't need the IF function. Just:
=OR(A1="she was always there",A1="she was there always")
I found that by Googling "EXCEL OR FUNCTION"
http://office.microsoft.com/en-us/excel-help/or-function-HP010062403.aspx

True until disproven or false until proven?

I've noticed something about my coding that is slightly undefined. Say we have a two dimension array, a matrix or a table and we are looking through it to check if a property is true for every row or nested dimension.
Say I have a boolean flag that is to be used to check if a property is true or false. My options are to:
Initialize it to true and check each cell until proven false. This
gives it a wrong name until the code
is completely executed.
Start on false and check each row until proven true. Only if all rows are true will the data be correct. What is the cleanest way to do this, without a counter?
I've always done 1 without thinking but today it got me wondering. What about 2?
Depends on which one dumps you out of the loop first, IMHO.
For example, with an OR situation, I'd default to false, and as soon as you get a TRUE, return the result, otherwise return the default as the loop falls through.
For an AND situation, I'd do the opposite.
They actually both amount to the same thing and since you say "check if a property is true for every row or nested dimension", I believe the first method is easier to read and perhaps slightly faster.
You shouldn't try to read the value of the flag until the code is completely executed anyway, because the check isn't finished. If you're running asynchronous code, you should guard against accessing the value while it is unstable.
Both methods "give a wrong name" until the code is executed. 1 gives false positives and 2 gives false negatives. I'm not sure what you're trying to avoid by saying this - if you can get the "correct" value before fully running your code, you didn't have run your code in the first place.
How to implement each without a counter (if you don't have a foreach syntax in your language, use the appropriate enumerator->next loop syntax):
1:
bool flag = true;
foreach(item in array)
{
if(!check(item))
{
flag = false;
break;
}
}
2:
bool flag = false;
foreach(item in array)
{
if(!check(item))
{
break;
}
else if(item.IsLast())
{
flag = true;
}
}
Go with the first option. An algorithm always has preconditions, postconditions and invariants. If your invariant is "bool x is true iff all rows from 0-currentN have a positve property", then everything is fine.
Don't make your algorithm more complex just to make the full program-state valid per row-iteration. Refactor the method, extract it, and make it "atomic" with your languages mechanics (Java: synchronized).
Personally I just throw the whole loop into a somewhat reusable method/function called isPropertyAlwaysTrue(property, array[][]) and have it return a false directly if it finds that it finds a case where it's not true.
The inversion of logic, by the way, does not get you out of there any quicker. For instance, if you want the first non-true case, saying areAnyFalse or areAllTrue will have an inverted output, but will have to test the exact same cases.
This is also the case with areAnyTrue and areAllFalse--different words for the exact same algorithm (return as soon as you find a true).
You cannot compare areAnyFalse with areAnyTrue because they are testing for a completely different situation.
Make the property name something like isThisTrue. Then it's answered "yes" or "no" but it's always meaningful.
In Ruby and Scheme you can use a question mark in the name: isThisTrue?. In a lot of other languages, there is a convention of puttng "p" for "predicate" on the name -- null-p for a test returning true or false, in LISP.
I agree with Will Hartung.
If you are worried about (1) then just choose a better name for your boolean. IsNotSomething instead of IsSomething.

How do you write a (simple) variable "toggle"?

Given the following idioms:
1)
variable = value1
if condition
variable = value2
2)
variable = value2
if not condition
variable = value1
3)
if condition
variable = value2
else
variable = value1
4)
if not condition
variable = value1
else
variable = value2
Which do you prefer, and why?
We assume the most common execution path to be that of condition being false.
I tend to learn towards using 1), although I'm not exactly sure why I like it more.
Note: The following examples may be simpler—and thus possibly more readable—but not all languages provide such syntax, and they are not suitable for extending the variable assignment to include more than one statement in the future.
variable = condition ? value2 : value1
...
variable = value2 if condition else value1
In theory, I prefer #3 as it avoids having to assign a value to the variable twice. In the real world though I use any of the four above that would be more readable or would express more clearly my intention.
I prefer method 3 because it is more concise and a logical unit. It sets the value only once, it can be moved around as a block, and it's not that error-prone (which happens, esp. in method 1 if setting-to-value1 and checking-and-optionally-setting-to-value2 are separated by other statements)
3) is the clearest expression of what you want to happen. I think all the others require some extra thinking to determine which value is going to end up in the variable.
In practice, I would use the ternary operator (?:) if I was using a language that supported it. I prefer to write in functional or declarative style over imperative whenever I can.
I tend to use #1 alot myself. if condition reads easier than if !condition, especially if you acidentally miss the '!', atleast to my mind atleast.
Most coding I do is in C#, but I still tend to steer clear of the terniary operator, unless I'm working with (mostly) local variables. Lines tend to get long VERY quickly in a ternary operator if you're calling three layers deep into some structure, which quickly decreases the readability again.
Note: The following examples may be simpler—and thus possibly more readable—but not all languages provide such syntax
This is no argument for not using them in languages that do provide such a syntax. Incidentally, that includes all current mainstream languages after my last count.
and they are not suitable for extending the variable assignment to include more than one statement in the future.
This is true. However, it's often certain that such an extension will absolutely never take place because the condition will always yield one of two possible cases.
In such situations I will always prefer the expression variant over the statement variant because it reduces syntactic clutter and improves expressiveness. In other situations I tend to go with the switch statement mentioned before – if the language allows this usage. If not, fall-back to generic if.
switch statement also works. If it's simple and more than 2 or 3 options, that's what I use.
In a situation where the condition might not happen. I would go with 1 or 2. Otherwise its just based on what i want the code to do. (ie. i agree with cruizer)
I tend to use if not...return.
But that's if you are looking to return a variable. Getting disqualifiers out of the way first tends to make it more readable. It really depends on the context of the statement and also the language. A case statement might work better and be readable most of the time, but performance suffers under VB so a series of if/else statements makes more sense in that specific case.
Method 1 or method 3 for me. Method 1 can avoid an extra scope entrance/exit, but method 3 avoids an extra assignment. I'd tend to avoid Method 2 as I try to keep condition logic as simple as possible (in this case, the ! is extraneous as it could be rewritten as method 1 without it) and the same reason applies for method 4.
It depends on what the condition is I'm testing.
If it's an error flag condition then I'll use 1) setting the Error flag to catch the error and then if the condition is successfull clear the error flag. That way there's no chance of missing an error condition.
For everything else I'd use 3)
The NOT logic just adds to confusion when reading the code - well in my head, can't speak for eveyone else :-)
If the variable has a natural default value I would go with #1. If either value is equally (in)appropriate for a default then I would go with #2.
It depends. I like the ternary operators, but sometimes it's clearer if you use an 'if' statement. Which of the four alternatives you choose depends on the context, but I tend to go for whichever makes the code's function clearer, and that varies from situation to situation.

Has TRUE always had a non-zero value?

I have a co-worker that maintains that TRUE used to be defined as 0 and all other values were FALSE. I could swear that every language I've worked with, if you could even get a value for a boolean, that the value for FALSE is 0. Did TRUE used to be 0? If so, when did we switch?
The 0 / non-0 thing your coworker is confused about is probably referring to when people use numeric values as return value indicating success, not truth (i.e. in bash scripts and some styles of C/C++).
Using 0 = success allows for a much greater precision in specifying causes of failure (e.g. 1 = missing file, 2 = missing limb, and so on).
As a side note: in Ruby, the only false values are nil and false. 0 is true, but not as opposed to other numbers. 0 is true because it's an instance of the object 0.
It might be in reference to a result code of 0 which in most cases after a process has run, a result code of 0 meant, "Hey, everything worked fine, no problems here."
I worked at a company with a large amount of old C code. Some of the shared headers defined their own values for TRUE and FALSE, and some did indeed have TRUE as 0 and FALSE as 1. This led to "truth wars":
/* like my constants better */
#undef TRUE
#define TRUE 1
#undef FALSE
#define FALSE 0
If nothing else, bash shells still use 0 for true, and 1 for false.
Several functions in the C standard library return an 'error code' integer as result. Since noErr is defined as 0, a quick check can be 'if it's 0, it's Ok'. The same convention carried to a Unix process' 'result code'; that is, an integer that gave some inidication about how a given process finished.
In Unix shell scripting, the result code of a command just executed is available, and tipically used to signify if the command 'succeeded' or not, with 0 meaning success, and anything else a specific non-success condition.
From that, all test-like constructs in shell scripts use 'success' (that is, a result code of 0) to mean TRUE, and anything else to mean FALSE.
On a totally different plane, digital circuits frecuently use 'negative logic'. that is, even if 0 volts is called 'binary 0' and some positive value (commonly +5v or +3.3v, but nowadays it's not rare to use +1.8v) is called 'binary 1', some events are 'asserted' by a given pin going to 0. I think there's some noise-resistant advantages, but i'm not sure about the reasons.
Note, however that there's nothing 'ancient' or some 'switching time' about this. Everything I know about this is based on old conventions, but are totally current and relevant today.
I'm not certain, but I can tell you this: tricks relying on the underlying nature of TRUE and FALSE are prone to error because the definition of these values is left up to the implementer of the language (or, at the very least, the specifier).
System calls in the C standard library typically return -1 on error and 0 on success. Also the Fotran computed if statement would (and probably still does) jump to one of three line numbers depending on the condition evaluating to less than, equal to or greater than zero.
eg: IF (I-15) 10,20,10
would test for the condition of I == 15 jumping to line 20 if true (evaluates to zero) and line 10 otherwise.
Sam is right about the problems of relying on specific knowledge of implementation details.
General rule:
Shells (DOS included) use "0" as "No
Error"... not necessarily true.
Programming languages use non-zero
to denote true.
That said, if you're in a language which lets your define TRUE of FALSE, define it and always use the constants.
Even today, in some languages (Ruby, lisp, ...) 0 is true because everything except nil is true. More often 1 is true. That's a common gotcha and so it's sometimes considered a good practice to not rely on 0 being false, but to do an explicit test. Java requires you do this.
Instead of this
int x;
....
x = 0;
if (x) // might be ambiguous
{
}
Make is explicit
if (0 != x)
{
}
I recall doing some VB programming in an access form where True was -1.
I remember PL/1 had no boolean class. You could create a bit and assign it the result of a boolean expression. Then, to use it, you had to remember that 1 was false and 0 was true.
For the most part, false is defined as 0, and true is non-zero. Some programming languages use 1, some use -1, and some use any non-zero value.
For Unix shells though, they use the opposite convention.
Most commands that run in a Unix shell are actually small programs. They pass back an exit code so that you can determine whether the command was successful (a value of 0), or whether it failed for some reason (1 or more, depending on the type of failure).
This is used in the sh/ksh/bash shell interpreters within the if/while/until commands to check conditions:
if command
then
# successful
fi
If the command is successful (ie, returns a zero exit code), the code within the statement is executed. Usually, the command that is used is the [ command, which is an alias for the test command.
The funny thing is that it depends on the language your are working with. In Lua is true == zero internal for performance.. Same for many syscalls in C.
It's easy to get confused when bash's true/false return statements are the other way around:
$ false; echo $?
1
$ true; echo $?
0
I have heard of and used older compilers where true > 0, and false <= 0.
That's one reason you don't want to use if(pointer) or if(number) to check for zero, they might evaluate to false unexpectedly.
Similarly, I've worked on systems where NULL wasn't zero.
In the C language, before C++, there was no such thing as a boolean. Conditionals were done by testing ints. Zero meant false and any non-zero meant true. So you could write
if (2) {
alwaysDoThis();
} else {
neverDothis();
}
Fortunately C++ allowed a dedicated boolean type.
In any language I've ever worked in (going back to BASIC in the late 70s), false has been considered 0 and true has been non-zero.
I can't recall TRUE being 0.
0 is something a C programmer would return to indicate success, though. This can be confused with TRUE.
It's not always 1 either. It can be -1 or just non-zero.
For languages without a built in boolean type, the only convention that I have seen is to define TRUE as 1 and FALSE as 0. For example, in C, the if statement will execute the if clause if the conditional expression evaluates to anything other than 0.
I even once saw a coding guidelines document which specifically said not to redefine TRUE and FALSE. :)
If you are using a language that has a built in boolean, like C++, then keywords true and false are part of the language, and you should not rely on how they are actually implemented.
In languages like C there was no boolean value so you had to define your own. Could they have worked on a non-standard BOOL overrides?
DOS and exit codes from applications generally use 0 to mean success and non-zero to mean failure of some type!
DOS error codes are 0-255 and when tested using the 'errorlevel' syntax mean anything above or including the specified value, so the following matches 2 and above to the first goto, 1 to the second and 0 (success) to the final one!
IF errorlevel 2 goto CRS
IF errorlevel 1 goto DLR
IF errorlevel 0 goto STR
The SQL Server Database Engine optimizes storage of bit columns. If there are 8 or less bit columns in a table, the columns are stored as 1 byte. If there are from 9 up to 16 bit columns, the columns are stored as 2 bytes, and so on.
The string values TRUE and FALSE can be converted to bit values: TRUE is converted to 1 and FALSE is converted to 0.
Converting to bit promotes any nonzero value to 1.
Every language can have 0 as true or false
So stop using number use words true
Lol
Or t and f 1 byte storage