Proper way to evaluate booleans in if else statements - objective-c

Sorry in advance if this has been answered somewhere, but I did look around for a while and didn't find anything.
I'm coding in Objective-C, but this is mostly a general coding question. I'm essentially wondering if there is a proper, professional way to write if else statements involving booleans. Specifically, I would like to know if
There is a "fastest" "best" coding practice for the ordering of if else statments involving booleans
Is there a more aesthetically popular way of writing them?
So, for example, here are three different ways I'm wondering about
Method 1
if (myBool)
{
//Do something
}
else
{
//Do something else
}
Method 2
if (myBool)
{
//Do something
}
else if (!myBool)
{
//Do something else
}
Method 3
if (myBool)
{
//Do something
}
if (!myBool)
{
//Do something else
}
I know this sounds kinda dumb and is really harping on subtle details. I'm mostly wondering about these different methods in terms of code readability. It almost seems like method 2/3 is best to me in terms of readability. This allows you to search for specific cases of that variable, which might be easier in large files. Maybe this is a minute point, and really doesn't matter though.
Method 1 seems like the most common to me, and is what I would pick by default. But for more experienced coders out there, is there a specific way to do this, or just preference?

1. There is a "fastest" "best" coding practice for the ordering of if else statments involving booleans
"Put the case you normally expect to process first. This is in line with the general principle of putting code that results from a decision as close as possible to the decision...[putting the normal case after the if] puts the focus on reading the main flow rather than on wading through the exceptional cases, so the code is easier to read overall."
Code Complete, 2nd Edition, pages 356-357.
2. Is there a more aesthetically popular way of writing them?
In normal logic flow it is better to use Method 1

One thing to take into consideration is the values you are expecting.
In this case, boolean only has two possible values, and therefore makes sense if we use Method 1 as the most "convenient" way.
Method 2 works effectively when you have more than 2 possible values to be checked.
Method 3 on the other hand is convenient when value of myBool may change after the first [if] condition.

I think Method1 is common and efficient also.
1. In method3 if myBool is true then there is no need of checking 2nd if condition.
2. In method2 there is no need of 2nd if because bool have only 2 values either it is yes/true or no/false. Use else if only there are more than 2 cases.
3. When you are using if else or if else if you should provide condition according to probability. Means condition which satisfied most must be placed first.

A neat way of doing if/else for very simple assignments
int num;
if (isNegative) {
num = -1;
} else {
num = 1;
}
Short hand would be:
int num = isNegative ? -1 : 1; // --> condition ? true : false
I wouldn't suggest this for complex conditions/assignments as can get messy. But I've found it useful for compacting very simple if/else assignments.

Related

Is it acceptable to use `to` to create a `Pair`?

to is an infix function within the standard library. It can be used to create Pairs concisely:
0 to "hero"
in comparison with:
Pair(0, "hero")
Typically, it is used to initialize Maps concisely:
mapOf(0 to "hero", 1 to "one", 2 to "two")
However, there are other situations in which one needs to create a Pair. For instance:
"to be or not" to "be"
(0..10).map { it to it * it }
Is it acceptable, stylistically, to (ab)use to in this manner?
Just because some language features are provided does not mean they are better over certain things. A Pair can be used instead of to and vice versa. What becomes a real issue is that, does your code still remain simple, would it require some reader to read the previous story to understand the current one? In your last map example, it does not give a hint of what it's doing. Imagine someone reading { it to it * it}, they would be most likely confused. I would say this is an abuse.
to infix offer a nice syntactical sugar, IMHO it should be used in conjunction with a nicely named variable that tells the reader what this something to something is. For example:
val heroPair = Ironman to Spiderman //including a 'pair' in the variable name tells the story what 'to' is doing.
Or you could use scoping functions
(Ironman to Spiderman).let { heroPair -> }
I don't think there's an authoritative answer to this.  The only examples in the Kotlin docs are for creating simple constant maps with mapOf(), but there's no hint that to shouldn't be used elsewhere.
So it'll come down to a matter of personal taste…
For me, I'd be happy to use it anywhere it represents a mapping of some kind, so in a map{…} expression would seem clear to me, just as much as in a mapOf(…) list.  Though (as mentioned elsewhere) it's not often used in complex expressions, so I might use parentheses to keep the precedence clear, and/or simplify the expression so they're not needed.
Where it doesn't indicate a mapping, I'd be much more hesitant to use it.  For example, if you have a method that returns two values, it'd probably be clearer to use an explicit Pair.  (Though in that case, it'd be clearer still to define a simple data class for the return value.)
You asked for personal perspective so here is mine.
I found this syntax is a huge win for simple code, especial in reading code. Reading code with parenthesis, a lot of them, caused mental stress, imagine you have to review/read thousand lines of code a day ;(

Objective C : Ternary operator with multiple statements

As the title says i was wondering if there is a way to use ternary operators with multiple statements in Objective C.
I know it can be easily done in some other languages like javascript, php, C etc but i couldn't find a solution for Objective C.
I want to implement something like this:
a > b ? ( statement1, statement2, statement3 ) : ( statement1, statement2 );
Basically i just want to avoid a lot of if-else blocks to maintain better code readability.
Please also suggest if using ternary operators instead of if-else blocks can harm app performance to a noticeable extent.
The Conditional operator ?: is not a replacement for an if/else block. I'm sure you could tweak the logic to make it work, but that would only obscure the meaning more.
My question is, "what are you saving?"
a > b ? ( statement1, statement2, statement3 ) : ( statement1, statement2 );
if (a > b) { statement1; statement2; statement3; } else { statement1; statement2; }
The if/else block is a grand total of 7 characters longer.
An even bigger question is, "Can the logic be composed in a better way?"
Look to see if the flow can be done differently with fewer ifs.
Look for places to create sub-routines.
You can easily do this; just be aware that the ternary operator can only include expressions, including comma expressions. So your statements can only be expressions, assignments, method calls etc. but no if / return / while and so on. And the ternary operator wants a result, so the last expressions in each group must have the same type; you can just add (void) 0 at the end of each list.
That said, you are most definitely not making your code more readable. Everyone reading it will start swearing at you and doubt your mental sanity. So don't do it.
The solution for your question (#user3752049) is:
a > b ? ^{ statement1; statement2; statement3;}() : ^{statement1; statement2;}();
Thanks

Multiple equations in one boolean statement

I think this is a really general programming question, since boolean syntax is more or less the same in a lot of common languages.
But still my question is for php and javascript mainly.
Suppose I want to write an if statement which returns true if a variable is equal to 2,3, or 5.
And this variable has a very long name, so like this:
if((An_Object_With_A_Long_Name.Has_Also_An_Array[With_An_Index_Too]==2)
|| (An_Object_With_A_Long_Name.Has_Also_An_Array[With_An_Index_Too]==3)
||(An_Object_With_A_Long_Name.Has_Also_An_Array[With_An_Index_Too]==5))
{
return true;
}
and I really want my code look shorter, it is less depressing to read it months after :)
so can I simplify this into something like
if(An_Object_With_A_Long_Name.Has_Also_An_Array[With_An_Index_Too]==2||3||5)
Thanks for help !
Cheater way out: For that if statement, assign An_Object_With_A_Long_Name to Object i. (If you plan to have to compare this variable several times, assign Object i the pointer of An_Object_With_A_Long_Name.

If Statement Optimization - comparing character strings vs constant boolean flags

Consider the following Java code:
public void DoStuff(String[] strings, boolean preEval)
{
final String compareTo = "A Somewhat Long String of Characters";
for ( int i = 0; i < strings.length; ++i )
{
if ( preEval )
{
if( strings[i].equals(compareTo) )
{
//do something process intensive
}
}
//do something process intensive
}
}
Now pay attention to if (preEval) and the inner statement within that. If the algorithm in use requires a condition such as preEval, does it make sense to include the preEval condition for the purposes of code optimization?
From my understanding, evaluating to see if a conditional flag resolves to true or false is much faster than iterating through a collection of characters and comparing each character within that collection with another corresponding character from a different collection.
My knowledge of assembly is about 30% I'd say in terms of the internals and opcodes/mnemonics involved, hence why I'm asking this question.
Update
Note: the code posted here is meant to be language independent; I simply chose Java just for the sake of something tangible and easy to read, as well as something which is widely known among the programmer community.
I would say that this would probably be an optimization in most cases.
That said, you should not spend time on optimizing code that has not been measured.
This might for example not be a worthwhile optimization if:
most of your cases involves few strings or very short strings.
it takes a long time to calculate the preEval parameter before calling the function.
Measure your code under realistic circumstances, identify your bottle necks, then you optimize.
A less costly approach might be to use a HashSet::contains(string) method to check for existence of a string in a collection. You can probably design away the need for string compares while iterating using a HashSet of strings or a HashMap keyed by String.
I always try to use a HashMap where i can to avoid conditional logic entirely.
_ryan

What is your preferred boolean pair: 1/0 Yes/No True/False?

When dealing with MySQL, I typically use the BOOLEAN type, which is equivalent to TINYINT(1), or 1/0
In most languages I work with, true/false is preferred
When displaying forms, sometimes "Yes / No" makes more sense
enum Bool
{
True,
False,
FileNotFound
};
http://thedailywtf.com/Articles/What_Is_Truth_0x3f_.aspx
In code: true/false.
In the UI: Yes/No or OK/Cancel
true and false makes a lot more sense to me, in code - partly through familiarity, I'm sure. I suspect I'd get used to yes and no pretty quickly. 1 and 0 really doesn't work for me though.
Consider the expression
age == 5
It's a test for truth-hood. Is the value of age 5? Yes, it's true. Both "yes" and "no" would be fine for me, but the idea that the answer to the question "Is the value of age 5?" is "1" seems pretty counter-intuitive to me. Just because that's the typical binary representation of truth-hood doesn't mean it's a useful one at a higher abstraction.
Which is easier to read?
while(true) {}
while(yes) {}
while(1) {}
I'll stick with true for most cases.
Here are rules I live by...
Rule #1
Use well defined constants in the programming languages that you use to communicate with the CPU, i.e., true/false in most modern cases for boolean values. If a database offers a boolean type or some such equivalent, of course it should be used.
Rule #2
Interact with users of your software by using their preferred language and idiom, i.e., Yes/No questions should offer Yes/No (or perhaps an alternative to No, such as Cancel).
Rule #3
Uncertainty should be expressed in terms of scope, i.e., "that depends", which will be followed up by the question "on what?". I know developers who answer the question by copying and pasting just about every dependency they may need into every code file of a project as a 'using' statement. That's just sloppy, and please bother to alphabetize or at least group namespaces together.
When a bool Just Isn't Enough
Incidentally, an interesting twist to this, available in C#, is Nullable;
The you can write
Nullable<bool> RespondToIritatingQuestion()
{
return new Nullable<bool>();
}
OR
bool? RespondToIritatingQuestionWithSytle()
{
return new bool?();
}
and the questioner would need to evaluate your response before even knowing what the answer, if there is one, might be...
bool? answer = RespondToIritatingQuestionWithStyle();
if (answer.HasValue)
Trace.WriteLine("The bloke responded with " + answer.Value.ToString());
else
Trace.WriteLine("The bloke responded with 'depends'.");
1 or 0 for SQL. SQL has a boolean type for a reason. Also, in very large databases, it can effect performance.
I use booleans for true/false fields in databases. Some people use ENUM('true', 'false'), but thats not my preference. For programming languages, I always use true/false, even if setting it to 0 or 1 will work. And if the form requires 'yes'/'no', I still use booleans to represent the values, but display them as strings that are more logical.