Whats wrong with these beginner style codes? - language-agnostic

I'm a beginner and I was reading https://stackoverflow.com/questions/237241/what-coding-mistakes-are-a-telltale-giveaway-of-an-inexperienced-programmer. I didn't get few things.
1.Why writing something like this is frowned up on?
if (IsAManMan == true) {
Console.WriteLine("It's a MAN, man!");
}
2.what about this?
if (test) {
return true;
}
else {
return false;
}
I don't write code like above. Should it be written this way: return test? or for readability I sometimes write it like return test?true:false or return (test==true)? true:false

In this example:
if (IsAManMan == true) {
Console.WriteLine("It's a MAN, man!");
}
In most languages, if conditions always evaluate a Boolean expression, which means IsAManMan can only either be true or false. Comparing to true or false is thus unnecessary because it's implied. So we just write this instead:
if (IsAManMan) {
Console.WriteLine("It's a MAN, man!");
}
And in this example:
if (test) {
return true;
}
else {
return false;
}
Following the above example, this means test can only either be true or false, which is like saying:
if (true) {
return true;
}
else { // If it's not true, it's false
return false;
}
That's again unnecessarily verbose code, so we just
return test;
instead.
In the end, it's still a matter of preference and readability. For example, if you think if (IsAManMan == true) is easier to interpret than if (IsAManMan), you can still write it that way and the compiler won't mind.

It's just a tautology. If it rains and If it's true that it rains is exactly the same and therefore, you can (or should) leave out superfluous comparisons, checks and returns.

In both cases you're testing the value of a boolean variable. Because your value is already a boolean, there's no need to explicitly test against true because it's implied in the if statement (and similar constructs that contain a boolean test, like loops)
For example
if(isAManMan == true){
//...
}
could evaluate to
if(true == true){ //answer: true
//...
}
or
if(false == true){ //answer: false
//...
}
which is the same as just writing
if(isAManMan){
//...
}
In your 2nd example, you're examining the value of another boolean value before deciding what boolean to return.
Again,
if (test) {
return true;
}else {
return false;
}
could evaluate to
if (true == true) { //returns true
return true;
}else {
return false;
}
or
if (false == true) { //returns false
return true;
}else {
return false;
}
The if statement is redundant, because the variable already holds the value you want to return, hence this is equivalent, and preferred:
return test;
It's important to note though, that your examples are completely valid, however a good compiler will optimise them into the improved versions I gave, so ultimately it comes down to readability and convention. I believe the versions I gave are more readable and closer to the generally accepted conventions.

These codes do same things. In my opinion, its just readability.

Due to this being tagged language-agnostic:
There are languages where keywords can be used for variable names. In FORTRAN, this is a valid statement: IF IF THEN THEN ELSE ELSE.
If true is defined to be a boolean variable with value false, the proposed shorthand solutions are not the same as the more verbose ones. Neither if test, IsAMan, true, and false are not boolean values in the first place.
A real world example in Python 2.0
>>>True = False
>>>True
False
Tongue in cheek.

Say you want to return a boolean, and not the actual value of test for the 2nd case.
You could do
return !!test
in most languages, or something like
return bool(test)
which is more explicit and readable.

Related

What is the use of two not (!!) operator on a variable

I am following a tutorial on browser detection which is using two !! not operator in return. I want to know what is the significance of using 2 !! in a code.
function supports_geolocation() {
return !!navigator.geolocation;
}
I believe !!navigator.geolocation === navigator.geolocation.
Correct me if not and let me know the significance of using two not operator here.
It force returns boolean value.
// navigator.geolocation is GeoLocation object
navigator.geolocation === true // return false
!!navigator.geolocation === true // returns true

AS3: Conditional statement with a non-boolean variable as the condition

I've seen conditional statements where the condition is just a variable, which is not a boolean variable. The variable is for an object.
if (myVariable) {
doThis();
}
It seems to be checking if myVariable is null or not. Is that all it is doing? Is this good programming practice? Wouldn't it be better to do this?
if (myVariable != null) {
doThis();
}
It seems much clearer that way.
To properly answer your question:
Using an if statement with an object like that, will check if the object exists.
So if object is null or undefined it will evaluate to the equivalent of false otherwise it will be the equivalent of true.
As far as "good programming practice" goes, that is very opinion based and best left out of StackOverflow.
There is no performance hit and you will find it very common in ECMAScript based languages (like AS3 and JS) - However, many stricter languages (like C# for instance) require an explicit Boolean check so if you program in multiple languages you may find it easier to be consistent.
It's entirely up to you!
Here are some additional examples you may want to consider:
var str:String;
if(str) //will evaluate as false as str is null/undefined
if(str = "myValue") //will evaluate true, as it will use the new assigned value of the var and you're allowed to assign values inside an if condition (though it's ugly and typically uneccessary)
var num:Number;
if(num) //will evaluate as false
num = 1;
if(num) //will evaluate as true
num = 0;
if(num) //will evaluate as false since num is 0
num = -1;
if(num) //will evaluate as true
var obj:Object
if(obj) //will evaluate false
obj = {};
if(obj) //will evaluate true (even though the object is empty, it exists)
var func:Function;
if(func) //false
func = function(){};
if(func) //true - the function exists
function foo():Boolean { return false; }
if(foo) //true - the function exists
if(foo()) //false, the return of the function is false
function foo1():void { return; };
if(foo1()) //false as there is no return type
if (myVariable) // fine but not really explicit.
I usually use:
if (myVariable !== null) // more readable to me

How can I create a default boolean value for a configuration using BND

I am using BND annotations to assist with creating a configuration managed by OSGI cm.
Here is my simple config
#Meta.AD(required = false, type = Type.Boolean, deflt = "false")
boolean enabled();
I have used the BND configuration annotation library quite a few times, but this is the first time that I would like to use a boolean type.
I have read through this
And it talks about an integer or other alternative number based handling of booleans for convenience. The thing is the deflt method always returns a string value, if my type was an integer I would do "2" (these are parsed). But booleans don't seem to be parsed in the configurable BND code up to this assignment point.
if (resultType == boolean.class || resultType == Boolean.class) {
if ( actualType == boolean.class || actualType == Boolean.class)
return o;
if (Number.class.isAssignableFrom(actualType)) {
double b = ((Number) o).doubleValue();
if (b == 0)
return false;
else
return true;
}
return true;
I would like to further know why this returns true when the deflt value is never even parsed. I expected this to more closely follow the spec and return false, since cm would try to do Boolean.parseFrom, so anything not "true" equal ignore case is false.
All of this isn't a complete failure because if I change the value through cm it works correctly after setting to true, and then false again, but obviously that was just an effort at wondering if it would ever work.
Simply I would like to know if anyone knows how to set a BOOLEAN default value using BND's configuration annotations.
Thanks

if ( object != null ) instead of if ( object ) in AS3

Is there any reason to use if ( object != null ) in a conditional instead of the more concise if ( object ). I see the former more often, but it seems like the two are equivalent and the latter shorter.
different objects are treated differently. there are some values that can never be null and might erroneously trigger false when you don't want it to.
Booleans can never be null.
if a Boolean is defined but not given a value it is treated as false;
var bool:Boolean;
trace(bool); // false
bool = true;
trace(bool); // true
int can never be null as well.
if an int is defined but not given a value, it is treated as 0;
var i:int;
trace(i); // 0
trace(Boolean(i)); // false
i = -1;
trace(Boolean(i)); // true
i = 0;
trace(Boolean(i)); // false
i = 1;
trace(Boolean(i)); // true
Number act similar to int.
if a Number is defined but not given a value, it is treated as NaN
var num:Number;
trace(num); // NaN
trace(Boolean(num)); // false
num = -1.1;
trace(Boolean(num)); // true
num = 0;
trace(Boolean(num)); // false
num = 1.1;
trace(Boolean(num)); // true
Strings are the worst.
if a String is defined but not given a value, it is treated as null!
var str:String;
trace(str); // null
trace(Boolean(str)); // false
str = ""
trace(Boolean(str)); // false
str = "hello";
trace(Boolean(str)); // true
it is very rare in my code that i only do 'if (obj)' since most of the time there is something more specific that i truly care about.
The following code will have an object evaluate to false, even though the object is not null:
class SomeWrapper
{
var value: Object;
SomeWrapper(Object value)
{
this.value = value;
}
/// Overriden method from Object, see ActionScript 3 reference
function valueOf()
{
return value;
}
}
var myWrapper = new SomeWrapper(false);
if(myWrapper)
{
trace("myWrapper evaluates to true.");
}
else
{
trace("myWrapper evaluates to false.");
}
The else block will execute in the example above, because myWrapper evaluates to false (its valueOf method returns whatever value the wrapper contained, in this case false) even though myWrapper is not a null reference. The problem is that the above does not only test nullability of reference, it implicitly invokes valueOf method, courtesy of Flash Player virtual machine. This behavior of course may or may not be what you wanted - do you want to test whether myWrapper is a null value or whether it carries a null value? (or both perhaps).
Verbosity in this case is your friend, otherwise you gain code readability in return for potential runtime errors.
if (expression) tests the truthiness of expression by getting its boolean value. Since null and undefined are both falsy, if (object) "works" for making sure object isn't null.
Problem is, though, 0, false, and '' are also falsy. When you use if (object), the code you're trying to keep from running when it's null would also be ignored when object is zero, an empty string, or the actual boolean false. Often, that's not what you want.
If you can't guarantee that object is either null or a type other than string, number, or boolean (or their respective object types), then if (object != null) is less likely to mean something unintended.

Should I use `!IsGood` or `IsGood == false`?

I keep seeing code that does checks like this
if (IsGood == false)
{
DoSomething();
}
or this
if (IsGood == true)
{
DoSomething();
}
I hate this syntax, and always use the following syntax.
if (IsGood)
{
DoSomething();
}
or
if (!IsGood)
{
DoSomething();
}
Is there any reason to use '== true' or '== false'?
Is it a readability thing? Do people just not understand Boolean variables?
Also, is there any performance difference between the two?
I follow the same syntax as you, it's less verbose.
People (more beginner) prefer to use == true just to be sure that it's what they want. They are used to use operator in their conditional... they found it more readable. But once you got more advanced, you found it irritating because it's too verbose.
I always chuckle (or throw something at someone, depending on my mood) when I come across
if (someBoolean == true) { /* ... */ }
because surely if you can't rely on the fact that your comparison returns a boolean, then you can't rely on comparing the result to true either, so the code should become
if ((someBoolean == true) == true) { /* ... */ }
but, of course, this should really be
if (((someBoolean == true) == true) == true) { /* ... */ }
but, of course ...
(ah, compilation failed. Back to work.)
I would prefer shorter variant. But sometimes == false helps to make your code even shorter:
For real-life scenario in projects using C# 2.0 I see only one good reason to do this: bool? type. Three-state bool? is useful and it is easy to check one of its possible values this way.
Actually you can't use (!IsGood) if IsGood is bool?. But writing (IsGood.HasValue && IsGood.Value) is worse than (IsGood == true).
Play with this sample to get idea:
bool? value = true; // try false and null too
if (value == true)
{
Console.WriteLine("value is true");
}
else if (value == false)
{
Console.WriteLine("value is false");
}
else
{
Console.WriteLine("value is null");
}
There is one more case I've just discovered where if (!IsGood) { ... } is not the same as if (IsGood == false) { ... }. But this one is not realistic ;) Operator overloading may kind of help here :) (and operator true/false that AFAIK is discouraged in C# 2.0 because it is intended purpose is to provide bool?-like behavior for user-defined type and now you can get it with standard type!)
using System;
namespace BoolHack
{
class Program
{
public struct CrazyBool
{
private readonly bool value;
public CrazyBool(bool value)
{
this.value = value;
}
// Just to make nice init possible ;)
public static implicit operator CrazyBool(bool value)
{
return new CrazyBool(value);
}
public static bool operator==(CrazyBool crazyBool, bool value)
{
return crazyBool.value == value;
}
public static bool operator!=(CrazyBool crazyBool, bool value)
{
return crazyBool.value != value;
}
#region Twisted logic!
public static bool operator true(CrazyBool crazyBool)
{
return !crazyBool.value;
}
public static bool operator false(CrazyBool crazyBool)
{
return crazyBool.value;
}
#endregion Twisted logic!
}
static void Main()
{
CrazyBool IsGood = false;
if (IsGood)
{
if (IsGood == false)
{
Console.WriteLine("Now you should understand why those type is called CrazyBool!");
}
}
}
}
}
So... please, use operator overloading with caution :(
According to Code Complete a book Jeff got his name from and holds in high regards the following is the way you should treat booleans.
if (IsGood)
if (!IsGood)
I use to go with actually comparing the booleans, but I figured why add an extra step to the process and treat booleans as second rate types. In my view a comparison returns a boolean and a boolean type is already a boolean so why no just use the boolean.
Really what the debate comes down to is using good names for your booleans. Like you did above I always phrase my boolean objects in the for of a question. Such as
IsGood
HasValue
etc.
The technique of testing specifically against true or false is definitely bad practice if the variable in question is really supposed to be used as a boolean value (even if its type is not boolean) - especially in C/C++. Testing against true can (and probably will) lead to subtle bugs:
These apparently similar tests give opposite results:
// needs C++ to get true/false keywords
// or needs macros (or something) defining true/false appropriately
int main( int argc, char* argv[])
{
int isGood = -1;
if (isGood == true) {
printf( "isGood == true\n");
}
else {
printf( "isGood != true\n");
}
if (isGood) {
printf( "isGood is true\n");
}
else {
printf( "isGood is not true\n");
}
return 0;
}
This displays the following result:
isGood != true
isGood is true
If you feel the need to test variable that is used as a boolean flag against true/false (which shouldn't be done in my opinion), you should use the idiom of always testing against false because false can have only one value (0) while a true can have multiple possible values (anything other than 0):
if (isGood != false) ... // instead of using if (isGood == true)
Some people will have the opinion that this is a flaw in C/C++, and that may be true. But it's a fact of life in those languages (and probably many others) so I would stick to the short idiom, even in languages like C# that do not allow you to use an integral value as a boolean.
See this SO question for an example of where this problem actually bit someone...
isalpha() == true evaluates to false??
I agree with you (and am also annoyed by it). I think it's just a slight misunderstanding that IsGood == true evaluates to bool, which is what IsGood was to begin with.
I often see these near instances of SomeStringObject.ToString().
That said, in languages that play looser with types, this might be justified. But not in C#.
Some people find the explicit check against a known value to be more readable, as you can infer the variable type by reading. I'm agnostic as to whether one is better that the other. They both work. I find that if the variable inherently holds an "inverse" then I seem to gravitate toward checking against a value:
if(IsGood) DoSomething();
or
if(IsBad == false) DoSomething();
instead of
if(!IsBad) DoSomething();
But again, It doen't matter much to me, and I'm sure it ends up as the same IL.
Readability only..
If anything the way you prefer is more efficient when compiled into machine code. However I expect they produce exactly the same machine code.
From the answers so far, this seems to be the consensus:
The short form is best in most cases. (IsGood and !IsGood)
Boolean variables should be written as a positive. (IsGood instead of IsBad)
Since most compilers will output the same code either way, there is no performance difference, except in the case of interpreted languages.
This issue has no clear winner could probably be seen as a battle in the religious war of coding style.
I prefer to use:
if (IsGood)
{
DoSomething();
}
and
if (IsGood == false)
{
DoSomething();
}
as I find this more readable - the ! is just too easy to miss (in both reading and typing); also "if not IsGood then..." just doesn't sound right when I hear it, as opposed to "if IsGood is false then...", which sounds better.
It's possible (although unlikely, at least I hope) that in C code TRUE and FALSE are #defined to things other than 1 and 0. For example, a programmer might have decided to use 0 as "true" and -1 as "false" in a particular API. The same is true of legacy C++ code, since "true" and "false" were not always C++ keywords, particularly back in the day before there was an ANSI standard.
It's also worth pointing out that some languages--particularly script-y ones like Perl, JavaScript, and PHP--can have funny interpretations of what values count as true and what values count as false. It's possible (although, again, unlikely on hopes) that "foo == false" means something subtly different from "!foo". This question is tagged "language agnostic", and a language can define the == operator to not work in ways compatible with the ! operator.
I've seen the following as a C/C++ style requirement.
if ( true == FunctionCall()) {
// stuff
}
The reasoning was if you accidentally put "=" instead of "==", the compiler will bail on assigning a value to a constant. In the meantime it hurts the readability of every single if statement.
Occasionally it has uses in terms of readability. Sometimes a named variable or function call can end up being a double-negative which can be confusing, and making the expected test explicit like this can aid readability.
A good example of this might be strcmp() C/C++ which returns 0 if strings are equal, otherwise < or > 0, depending on where the difference is. So you will often see:
if(strcmp(string1, string2)==0) { /*do something*/ }
Generally however I'd agree with you that
if(!isCached)
{
Cache(thing);
}
is clearer to read.
I prefer the !IsGood approach, and I think most people coming from a c-style language background will prefer it as well. I'm only guessing here, but I think that most people that write IsGood == False come from a more verbose language background like Visual Basic.
Only thing worse is
if (true == IsGood) {....
Never understood the thought behind that method.
The !IsGood pattern is eaiser to find than IsGood == false when reduced to a regular expression.
/\b!IsGood\b/
vs
/\bIsGood\s*==\s*false\b/
/\bIsGood\s*!=\s*true\b/
/\bIsGood\s*(?:==\s*false|!=\s*true)\b/
For readability, you might consider a property that relies on the other property:
public bool IsBad => !IsGood;
Then, you can really get across the meaning:
if (IsBad)
{
...
}
I prefer !IsGood because to me, it is more clear and consise. Checking if a boolean == true is redundant though, so I would avoid that. Syntactically though, I don't think there is a difference checking if IsGood == false.
In many languages, the difference is that in one case, you are having the compiler/interpreter dictate the meaning of true or false, while in the other case, it is being defined by the code. C is a good example of this.
if (something) ...
In the above example, "something" is compared to the compiler's definition of "true." Usually this means "not zero."
if (something == true) ...
In the above example, "something" is compared to "true." Both the type of "true" (and therefor the comparability) and the value of "true" may or may not be defined by the language and/or the compiler/interpreter.
Often the two are not the same.
You forgot:
if(IsGood == FileNotFound)
It seems to me (though I have no proof to back this up) that people who start out in C#/java type languages prefer the "if (CheckSomething())" method, while people who start in other languages (C++: specifically Win32 C++) tend to use the other method out of habit: in Win32 "if (CheckSomething())" won't work if CheckSomething returns a BOOL (instead of a bool); and in many cases, API functions explicitly return a 0/1 int/INT rather than a true/false value (which is what a BOOL is).
I've always used the more verbose method, again, out of habit. They're syntactically the same; I don't buy the "verbosity irritates me" nonsense, because the programmer is not the one that needs to be impressed by the code (the computer does). And, in the real world, the skill level of any given person looking at the code I've written will vary, and I don't have the time or inclination to explain the peculiarities of statement evaluation to someone who may not understand little unimportant bits like that.
Ah, I have some co-worked favoring the longer form, arguing it is more readable than the tiny !
I started to "fix" that, since booleans are self sufficient, then I dropped the crusade... ^_^ They don't like clean up of code here, anyway, arguing it makes integration between branches difficult (that's true, but then you live forever with bad looking code...).
If you write correctly your boolean variable name, it should read naturally:
if (isSuccessful) vs. if (returnCode)
I might indulge in boolean comparison in some cases, like:
if (PropertyProvider.getBooleanProperty(SOME_SETTING, true) == true) because it reads less "naturally".
For some reason I've always liked
if (IsGood)
more than
if (!IsBad)
and that's why I kind of like Ruby's unless (but it's a little too easy to abuse):
unless (IsBad)
and even more if used like this:
raise InvalidColor unless AllowedColors.include?(color)
Cybis, when coding in C++ you can also use the not keyword. It's part of the standard since long time ago, so this code is perfectly valid:
if (not foo ())
bar ();
Edit: BTW, I forgot to mention that the standard also defines other boolean keywords such as and (&&), bitand (&), or (||), bitor (|), xor (^)... They are called operator synonyms.
If you really think you need:
if (Flag == true)
then since the conditional expression is itself boolean you probably want to expand it to:
if ((Flag == true) == true)
and so on. How many more nails does this coffin need?
If you happen to be working in perl you have the option of
unless($isGood)
I do not use == but sometime I use != because it's more clear in my mind. BUT at my job we do not use != or ==. We try to get a name that is significat if with hasXYZ() or isABC().
Personally, I prefer the form that Uncle Bob talks about in Clean Code:
(...)
if (ShouldDoSomething())
{
DoSomething();
}
(...)
bool ShouldDoSomething()
{
return IsGood;
}
where conditionals, except the most trivial ones, are put in predicate functions. Then it matters less how readable the implementation of the boolean expression is.
We tend to do the following here:
if(IsGood)
or
if(IsGood == false)
The reason for this is because we've got some legacy code written by a guy that is no longer here (in Delphi) that looks like:
if not IsNotGuam then
This has caused us much pain in the past, so it was decided that we would always try to check for the positive; if that wasn't possible, then compare the negative to false.
The only time I can think where the more vebose code made sense was in pre-.NET Visual Basic where true and false were actually integers (true=-1, false=0) and boolean expressions were considered false if they evaluated to zero and true for any other nonzero values. So, in the case of old VB, the two methods listed were not actually equivalent and if you only wanted something to be true if it evaluated to -1, you had to explicitly compare to 'true'. So, an expression that evaluates to "+1" would be true if evaluated as integer (because it is not zero) but it would not be equivalent to 'true'. I don't know why VB was designed that way, but I see a lot of boolean expressions comparing variables to true and false in old VB code.