The tag has no usage guidance.

learn more… | top users | synonyms

151
votes
19answers
46k 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) ...
1
vote
1answer
107 views

The Same Behavior for Boolean and Exception

The following code uses a boolean preference active: In the active state, it does an operation which could throw an exception. On this exception, it does fall back to the non-active state. let active ...
112
votes
23answers
15k 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 = ...
0
votes
1answer
39 views

jQuery, deferrers and “if” conditionals

How could I simplify the following code? I suspect that it can be simplified by using the $.Deferred class, but I don't know how. if (condition) { $.get('url').done(function () { done(); ...
14
votes
3answers
2k 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: ...
3
votes
4answers
245 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: ...
2
votes
0answers
51 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 ...
0
votes
1answer
114 views

How to structure huge conditional statement?

I'm creating some kind of a "personal assistant" application which is basically a web service that receives a message and then does something according to it. For example I send "what time is it?" ...
1
vote
2answers
103 views

Why are the Coffman conditions necessary for a deadlock to occur?

Quoting https://en.wikipedia.org/wiki/Deadlock#Necessary_conditions : A deadlock situation can arise if all of the following conditions hold simultaneously in a system: Mutual exclusion: ...
12
votes
3answers
435 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) { ...
1
vote
1answer
81 views

Rewriting conditionals in OOP without generics

Let's say I have a set of objects, foo f; bar br; baz bz; I also have a string of JSON data, string JSONstring; Depending on the object type of the JSON string, I need to transform it into ...
1
vote
3answers
147 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
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
4answers
278 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
3answers
340 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
175 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 ...
1
vote
1answer
201 views

How harmful is using switch(true) as a way to handle multiple conditional statements? [duplicate]

I recently saw something like the following: switch(true) { case iAmAmazing(): { return 'some html'; } case isVariable: { return 'some other html'; } case ...
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?
0
votes
0answers
68 views

Is there a school of thought where while(1) or while (true) is a code smell? [duplicate]

My employer requires code reviews for all devs, and new employees are required to to have their code reviewed by a senior dev. Initially, trainees get to pick a small project they are working on and ...
0
votes
3answers
148 views

Eliminating the bad cases in if to get a nicer code

I have read this link Should I return from a function early or use an if statement? and it triggered a conflict in my head. I agree that it looks nicer and cleaner and I guess that would be the way I ...
3
votes
1answer
156 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 ...
2
votes
2answers
191 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 ...
66
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 ...
4
votes
4answers
161 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() } ...
0
votes
2answers
133 views

Why does presence of value evaluate as “Truthy” in Python? [e.i. Types evaluate True in conditionals]

Example: if float: print('float is true?') returns: Why do all objects other than ones explicitly defined as False or "False" evaluate truthfully?
2
votes
2answers
155 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: /** ...
13
votes
12answers
16k 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 ...
1
vote
4answers
149 views

Better way of handling pre conditions and logging

1. Imagine you have the following: void Foo::doFoo() { if (!isConditionValid()) { log("doFoo not possible because condition is not valid"); return; } if ...
2
votes
0answers
176 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 ...
-1
votes
3answers
90 views

When not to use early return? [duplicate]

Nesting is unavoidable, however in most cases returning early is a more viable option. Consider the following snippet: MyRoutine(argument) { if (0 == argument) { SubRoutine(argument); ...
3
votes
2answers
143 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 ...
0
votes
1answer
127 views

Code Inside Catch Block

This question is related to both of these questions - Efficient try / catch block usage? and Dealing with error in data - Idempotent approach. When I encounter a void while reading a GIS data file I ...
0
votes
2answers
344 views

What algorithm should I use for a lot of if else(s)?

I have to implement a lot of if else statements and I'm thinking of using Decision Tree but I'm not sure if it's going to be the right algorithm. I don't want to insert a piece of html code based on ...
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 ...
2
votes
1answer
113 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 && ...
0
votes
3answers
163 views

Using conditions again and again or just create different methods [duplicate]

I have a method, function DoThis(bool isHuman) { // Do something if(isHuman) { //call his dad } else { //its a animal - let animal resuce know } // add some blah blah code ...
3
votes
1answer
386 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 ...
44
votes
11answers
35k 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 ...
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 ...
0
votes
2answers
323 views

How to avoid spaghetti code when I have a lot of conditions? [duplicate]

I have the following problem: An user can withdraw money from 2 payment systems (but the number of payment systems can change anytime in the future). If user has a trusted account on either of ...
4
votes
3answers
357 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 ...
2
votes
2answers
609 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 ...
0
votes
1answer
233 views

Avoid Code Repetition in Condition Statements [duplicate]

I have been programming for over 15 years now. I consider myself a very good programmer, but I understand (like all of us) there are things that I need to work on. One of these things is code ...
4
votes
2answers
390 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: ...
-1
votes
2answers
744 views

Confusion in my If Else ,Else If Condition. in C# [closed]

I have three column as follows: Month Tech Circle According to this column I need to fetch the data. In Month Column, Data is : Jan,feb, March... and so on. In Tech Column, Data is : Gsmnqi, ...
1
vote
2answers
131 views

Apply filter only if not null

My function takes an optional parameter, type, which is used to filter through a collection. However, the filter should only apply if the parameter is passed in (in other words, non-null). If the ...
1
vote
2answers
699 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? ...
1
vote
2answers
3k views

What is “condition testing” (as defined by the ISTQB Syllabus) actually good for? [duplicate]

I am currently checking through the syllabus for the ISTQB "Technical Test Analyst" certification. This syllabus (henceforth called "TTA syllabus") contains a chapter dedicated to "condition testing" ...
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 ...
7
votes
5answers
581 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 = ...