The tag has no usage guidance.

learn more… | top users | synonyms

154
votes
19answers
48k views

Should I return from a function early or use an if statement? [closed]

I've often written this sort of function in both formats, and I was wondering if one format is preferred over another, and why. public void SomeFunction(bool someCondition) { if (someCondition) ...
113
votes
23answers
16k views

Elegant ways to handle if(if else) else

This is a minor niggle, but every time I have to code something like this, the repetition bothers me, but I'm not sure that any of the solutions aren't worse. if(FileExists(file)) { contents = ...
67
votes
25answers
22k views

Ternary operator considered harmful? [closed]

For example, would you prefer this one-liner int median(int a, int b, int c) { return (a<b) ? (b<c) ? b : (a<c) ? c : a : (a<c) ? a : (b<c) ? c : b; } or an if/else solution ...
44
votes
11answers
36k views

Why do we have to use break in switch?

Who decided, and basing on what concepts, that switch construction (in many languages) has to be, like it is? Why do we have to use break in each statement? Why do we have to write something like this:...
35
votes
7answers
3k views

How can I reformat my condition to make it better?

I have a condition if(exists && !isDirectory || !exists) {} how can I modify it, so that it may be more understandable.
31
votes
3answers
7k views

if ('constant' == $variable) vs. if ($variable == 'constant')

Lately, I've been working a lot in PHP and specifically within the WordPress framework. I'm noticing a lot of code in the form of: if ( 1 == $options['postlink'] ) Where I would have expected to ...
23
votes
3answers
3k views

Approaches to checking multiple conditions? [duplicate]

What is the best practice for checking multiple conditions, in no particular order? The example in question needs to check four distinct conditions, in any order, and fail showing the correct error ...
18
votes
6answers
4k views

Most readable way to format long if conditions? [closed]

Long winding if conditions should be avoided if at all possible, yet sometimes we all end up writing them. Even if it's a very simple condition, the involved statements are sometimes simply very wordy,...
15
votes
6answers
17k views

Clarification of “avoid if-else” advice [duplicate]

The experts in clean code advise not to use if/else since it's creating an unreadable code. They suggest rather using IF and not to wait till the end of a method without real need. Now, this if/else ...
15
votes
5answers
2k views

If Else - Repeated Code Logic

My boss gave me a project with a particular logic. I have to develop a web page which has to lead the navigator through many cases until he/she arrives at the product. This is the path scheme of the ...
14
votes
3answers
3k views

How to tackle a 'branched' arrow head anti-pattern? [duplicate]

I recently read this question that features, the arrow anti-pattern. I have something similar in code I'm trying to refactor except that it branches. It looks a little something like this: if(...
13
votes
12answers
17k views

How would you refactor nested IF Statements? [duplicate]

I was cruising around the programming blogosphere when I happened upon this post about GOTO's: http://giuliozambon.blogspot.com/2010/12/programmers-tabu.html Here the writer talks about how "one ...
12
votes
3answers
438 views

Is it better to guard the method call or the method itself?

I am writing an application and I got to this point: private void SomeMethod() { if (Settings.GiveApples) { GiveApples(); } if (Settings.GiveBananas) { ...
10
votes
8answers
6k views

How to do a clean refactoring of an If Else Code without leaving any free blocks? [duplicate]

if(condition1) { Statement1A; Statement1B; } else if(condition2) { Statement2; } else if(condition3) { Statement3; } else { Statement1A; Statement1B; } return; I would like to ...
8
votes
3answers
2k views

What is “short-circuiting” in C like languages?

I have heard of the term "short-circuiting" being used in C, C++, C#, Java, and many others. What does this mean and in what scenario would it be used?
8
votes
4answers
2k views

Is the use of explicit ' == true' comparison always bad? [duplicate]

Possible Duplicate: Make a big deal out of == true? I've been looking at a lot of code samples recently, and I keep noticing the use of... if( expression == true ) // do something... ...
8
votes
3answers
3k views

What is the difference (if any) between (null != $object) and ($object != null) when using PHP?

I am used to Java and therefore always think conditions are interpreted from left to right, i.e. there is a vital difference in null != $obj and $obj != null Now this seems not to be the case with ...
7
votes
5answers
581 views

Keep indentation level low [duplicate]

I hear a lot that you should not write functions larger than one screen size, that you should extract things into functions if you call things very often and all these coding guidelines. One of them ...
7
votes
5answers
596 views

Is doing an assignment inside a condition considered a code smell?

Many times I have to write a loop that requires initialization of a loop condition, and an update every time the loop executes. Here's one example: List<String> currentStrings = ...
7
votes
5answers
1k views

What should developers test before submitting their work to testers?

Is there a checklist the developer must go over before passing their work to testers ? Also, what are the conditions/cases the developer must pay attention to ?
6
votes
6answers
1k views

Making Simple IF Statements Shorter

If we assume we have this little snippet of code: string str = "checked"; bool test1; if (str == "checked") { test1 = true; } else { test1 = false; } Is it bad practice to change a simple ...
6
votes
2answers
2k views

Java convention for if/else if order

I have an if/else if structure that on some cases does nothing. From the code I have seen in my career, the "empty" case is normally left out. But when I wrote my code, it just doesn't feel right to ...
5
votes
4answers
1k views

Differences in If… Else… statement

When I first started to learn programming I remember having an argument with my teacher about If Else statements. I was arguing that: if { ... } else if { ... } ... is basically the ...
5
votes
2answers
228 views

Branch twice for unique condition

Consider an application that displays only Foobars belonging to themselves to normal users, and all Foobars to admins: -- Normal users: SELECT * FROM Foobar WHERE user_id=:user_id; -- Admins: SELECT ...
4
votes
4answers
941 views

Using a function's return value as an if condition, good practice?

Do you think it is a good practice to use function return values as if conditions? I'm coding in PHP atm but it holds for many other languages. if(isTheConditionMet($maybeSomeParams)) { } or $res =...
4
votes
3answers
359 views

Ifology - how to write this statement better? [closed]

I'm wondering how to write the if statement in the following block in a better way. It's supposed to operate when $a is 14, 22, 30 and for all following values at intervals of 8, up to some limit. The ...
4
votes
4answers
162 views

Elegant way to handle multiple pathways based on compound condition [closed]

Consider the following: if (x == 5 || x == 10 || x == 12) { if (x == 5) { doSomething() } else if (x == 10) { doSomethingElse() } else { doSomeOtherThing() } ...
4
votes
2answers
142 views

Getting your user agreement right

I'm planning to provide a little service with which you can control your computer from anywere. It exists out of a server (which I will be providing), and two clients (a controlled one and a ...
4
votes
2answers
922 views

Writing a unit test for a platform dependent unit

I have a method to be tested which depends on the OS, what's the best approach for testing the method depending on the OS? Is it to test on every OS that I have I require? Is there a better approach ...
4
votes
2answers
392 views

How to layer if statements when order of logic is irrelevant?

Basically I have a series of logic in my website that can lead to 5 total outcomes. Basically two different if tests and then a catch all else statement. For example: if cond1: if mod1: ...
4
votes
4answers
222 views

Should I repeat condition checking code or put it in a function? [duplicate]

I have a bunch of calls to a method that may or may not need to be made depending on whether certain features are enabled or not. As such, I've wrapped these calls in if blocks checking the enabled ...
3
votes
4answers
257 views

Defining logic without nested if-else statements

I'm working on a somewhat simple game. Currently trying to implement the game logic for moving the pieces around. Logic is something like this: does player have pieces in inventory? if yes: ...
3
votes
1answer
164 views

Is it always possible to separate multiple conditions in an IF statement into individual statements?

I'm trying to find the simplest way to model user-defined conditional statements without resorting to text parsing. This is fairly easy when there is only one condition in the statement because you ...
3
votes
1answer
388 views

Redundant ElseIf-Else Blocks [duplicate]

These types of if-elseif-else blocks appear all over the place, and in no small number (so the less the better). Every time I have to think and decide: Do I want the simpler or the more thorough of ...
3
votes
2answers
148 views

What is a proper way to chain instructions if previous one is ok [duplicate]

I'm currently working on a big file I have to parse and process and each step needs to be done in an order as I do SQL queries and need inserted IDs to make other insertions ... The problem is I often ...
2
votes
8answers
4k views

How does if/else work internally in all programming languages? [closed]

if(true/false){ //if condition is true }else { // if condition is false } Everyone knows about the structure of if-else. But what is if actually? Is it a class method, static method or ...
2
votes
2answers
613 views

What is the difference between if('' == $variable) and if($variable == '') [duplicate]

While using an 'if' statement to check whether a variable is an empty string or not we can write it in two ways i.e. if('' == $variable) and if($variable == ''). I want to know what is the impact of ...
2
votes
3answers
344 views

Should conditional logic be always coded via type system where possible?

I have a choice. Option 1: public class Sample { bool IsRelevant { get; set; } } Option 2: public class Sample { } public class RelevantSample : Sample { } Is there a clear well-known rule ...
2
votes
2answers
201 views

Do nested conditionals have a significant performance impact? [duplicate]

This is a question that lives in my mind from a long time. Does the use of multiple nested conditional statements impact the performance of a taken code? So far I know that programmers have created a ...
2
votes
4answers
291 views

How to properly reverse the if statement when you have two conditions in it?

In PHP I have this if statement ( $first and $second will evaluate to true or false): if ($first && $second) { // evereything is OK } else { throw new Exception()... } My real code ...
2
votes
2answers
178 views

Has any language ever supported a conditional assignment target? [closed]

I've never seen a programming language with conditional assignment targets, eg.: // If (x == y), then var1 will be set to 1, else var2 will be set to 1 ((x == y) ? var1 : var2) = 1 The target of ...
2
votes
2answers
747 views

Why elseif instead of else if?

Few days ago I stopped on some PHP's developers quide (for contributors to particular project) and it stated, that elseif must be strictly used instead of else if -- without giving any reason, why? ...
2
votes
2answers
156 views

Refactoring wordy conditional tests [duplicate]

My first attempt at this question was too theoretical, so I've rewritten it with actual code. See the edit history if you care. Supposing this logic, "suffering" from the arrow anti-pattern: /** *...
2
votes
1answer
115 views

Proper way to refactor multiple if based conditions [duplicate]

I took over a large legacy code base. It has a code like this: if ($route == 'login' || $route == 'logout' || $route == 'forgot-password') { return; } if ($loggedInUser == false && $...
2
votes
0answers
54 views

Dealing with conditional verification logic using guard assertion

I have parametrized test with 2 variants: NULL value and any NOT NULL value From this value is depends one assert: In case NULL it should be checked if object has field1 with value1 In ...
2
votes
0answers
180 views

What's the best pattern to validate a conditional entity? [duplicate]

I'm developing an ASP.NET MVC 5 website and I have a view with a grid. In this grid I have a column which represents an URL property. This url is a link to download some files, but this url should be ...
2
votes
1answer
150 views

Validating data to nest if or not within try and catch

I am validating data, in this case I want one of three ints. I am asking this question, as it is the fundamental principle I'm interested in. This is a basic example, but I am developing best ...
2
votes
3answers
261 views

Conditional construct for a kleenean data type

I was thinking of an hypothetical programming language with a kleenean data type which would implement Kleene's three-valued logic. To sum up, it's an extension of the boolean data type with the three ...
1
vote
3answers
148 views

Enforcing order for two consecutive statements

I have the following code: subroutine foo(int index) { // Check A. // Critical: Check A must precede Check B below. if (index == 1) { return true; } // Check B. ...
1
vote
3answers
223 views

The clock problem - to if or not to if?

Let's say, we have a simple digital clock. To "power" it, we use a routine executed every second. We update seconds part in it. But, what about minutes and hours part? What is better / more ...