Questions tagged [conditions]

The tag has no usage guidance.

Filter by
Sorted by
Tagged with
3
votes
2answers
251 views

Conditional vs Logical Testing

I would like to get your code thought and views on using conditional vs logical testing. For example: To test the conditions of truthness of all of the following variables, their currect status is ...
0
votes
0answers
70 views

Should I repeat unnecessary else condition? [duplicate]

I would like to know what the best way is for dealing with a situation where I repeatedly check a condition within a function using an if-elif-else chain, and if the condition is else, I raise an ...
2
votes
2answers
82 views

API Race conditions

I have an API in which we expect a emailID and a certain deal data. The case is we want to keep the dealId and contactId(email) to be unique. Creating a deal requires data insertion in multiple ...
1
vote
2answers
310 views

Avoid if-else block in favor of default assignment followed by if

A colleague, and frankly better software engineer that me, is telling me that this pattern let variable = someDefaultVariable(); if (some_boolean) { variable = someOtherValue(); } is better than ...
2
votes
3answers
190 views

Reconciling MVC with a strategy pattern

I am working on a Rails application which employs a classic MVC as its fundamental structure. In that structure the controller is supposed to be responsible for "which view to render when". Now after ...
2
votes
1answer
96 views

Should special case be inside or outside the for loop here?

For example, suppose I have 2 arrays: let arr1=[5,2,1]; let arr2=["abcde","ab","a"]; my work is simple : to check if length of strings in arr2 are larger than corresponding element with same index ...
3
votes
4answers
1k views

What is the most concise way to test a boolean condition with many AND clauses?

I have a function which returns the availability of a module, where the module is only available if multiple conditions are all met. The code looks like this: bool isShipAvailable() { bool ...
0
votes
3answers
109 views

Approaches for not complex conditions

I encountered code like this below. I was told its fine, and boilerplate is not always better. I agree boilerplate might be bad, but I am not sure about something like this: if (entity....
-1
votes
1answer
160 views

Enforcing IF, ELSEIF and ELSE on collection of ojects

I am designing a project where I have to enforce IF, ELSEIF and ELSE conditions on collection of objects. For example: public class Box { private List<Item> items; } I want to define IF ...
1
vote
1answer
311 views

How to compute cyclomatic complexity for empty whiles and if + breaks?

This is closely related to this question which asks about the complexity of the following: while (x > level) x = x – 1; x = 0 Using the graph method it has a Complexity = 2. Fred Swartz ...
3
votes
6answers
2k views

Best approach - convert multiple conditional if -else in a more handy design

I have a class that handles the state of a response, called StockResponse. The code has multiple ifs to handle each state of the stock. Most of the cases has a default behaviour, but some conditions ...
3
votes
3answers
188 views

Best practice to avoid partial branches

I do a lot of coding in python and got a lot of if conditions without an else statement so to say partial branches. E.g.: # if a certain kwarg was passed to a function call if kwargs.get('a_option'):...
0
votes
3answers
305 views

Which is more readable: early returns, or conditionals? [duplicate]

I’m writing an asynchronous, Promise-returning function. In the processing I test some conditions, and if the conditions pass, the promise should be fulfilled (resolved), but if one fails, then the ...
0
votes
1answer
91 views

Multi-dimensional if-elseif-else block to call different functions

I have a function a plugin that is called whenever the WebAPI's "Plugin" endpoint is called in the main project, and that has to process the HTTP request. The request holds more information about what ...
45
votes
13answers
14k views

How do I edit a chain of if-else if statements to adhere to Uncle Bob's Clean Code principles?

I'm trying to follow Uncle Bob's clean code suggestions and specifically to keep methods short. I find myself unable to shorten this logic though: if (checkCondition()) {addAlert(1);} else if (...
3
votes
2answers
6k views

PHP : Better way to print html in if-else conditions

Please refer the following two forms of the same code First: <?php if(some_condition){ ?> <li><a target="_blank" href="example.com/channel1/" class="xyz">If content</a>&...
167
votes
15answers
44k views

Developer insists if statements shouldn't have negated conditions, and should always have an else block

I have an acquaintance, a more seasoned developer than me. We were talking about programming practices and I was taken aback by his approach on 'if' statements. He insists on some practices regarding ...
2
votes
2answers
1k views

Long chained method calls contained within an if statement shown on a sequence diagram

Just wondering if there is a good way to do this? Currently i'm performing the method calls as if they were happening prior to the conditional block, then comparing what would be the result in "[...
2
votes
1answer
87 views

How do I implement a run-only-once method when all criteria are met for the first time run it?

I need a run-only-once method that when all the criteria are met, say A&B&C are true, run the codes once, but only once. So if later on all the criteria are met again (A&B&C are true ...
2
votes
2answers
1k views

Store conditional expression in database

We have an application that allows users to enter conditionals in the form bound op x op bound2, we store this as a string, and then parse it at runtime to evaluate it. It is a decent amount of work, ...
18
votes
7answers
1k views

Should “else” be used in situations where control flow renders it redundant?

I sometimes stumble upon code similar to the following example (what this function does exactly is out of the scope of this question): function doSomething(value) { if (check1(value)) { return -...
3
votes
3answers
377 views

Does if-else optimization in PHP have any effect?

Consider a scenario, where A occurs frequently like 4 out 5 times, and B only in rare cases, we can write our conditional statement in two ways: if(A) //do something else // do something if B, only ...
6
votes
2answers
2k views

Is it good practice to use array.pop() assignment in a while loop condition?

Just saw a code snippet that used an array pop assignment in the while condition; was wondering if this is acceptable/good practice? var arr = [0,1,2,3,4,5]; var current; while (current = arr.pop()) {...
-2
votes
3answers
593 views

Nested if statements or multiple if statements [duplicate]

Which way is better? -- Option 1------------- if ( condition1 ) { statement1 } else { exit program } if ( condition2 ) { statement2 } else { exit program } ----...
1
vote
5answers
294 views

How to optimize performance of sequential condition checks in Java?

I am writing a program that looks for a solution of a diophantine equation. The program is cycling for (int d = 0; d <= max; d++) { for (int c = 0; c < d; c++) { boolean ...
0
votes
1answer
161 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 ...
1
vote
1answer
90 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(); ...
4
votes
4answers
1k 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
162 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 case ...
0
votes
1answer
708 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
1k 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: at ...
1
vote
1answer
94 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 ...
12
votes
3answers
490 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
3answers
169 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. ...
3
votes
4answers
4k 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
246 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 the ...
5
votes
3answers
783 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 ...
0
votes
3answers
165 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
510 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
2answers
3k 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 ...
4
votes
4answers
204 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
554 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?
3
votes
2answers
198 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: /** * ...
1
vote
4answers
220 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
376 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
267 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
173 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 ...
1
vote
1answer
465 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
364 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
4k 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 ...