Alternative to if-else statements or better approach
Your collection names seems to have a pattern based on the filter fields, if that's the case this approach may work.
Object marketFilter = filter.getAllMarket();
Object cmtsFilter = filter.getAllCmts();
Object packageFilter = filter.getAllPackage();
Object nodeFilter = filter.getAllNodes();
if(marketFilter != null){
query.addFilterField("_id.market", MongoQuEry.OP_IN, filter.getMarket());
}
.
.
. upto filter N
String collectionName = getCollectionName(marketFilter, ... filter N)
/*
create a function getCollectionName(filter1, ... filterN)
in this function you can generate collection name by checking which
filters are not null.
*/
NOTE :- This approach will work only if your collection names are based on the filters.
Alternative to if else statements or suggest best approach
It looks like you're implementing a search method for each possible combination of your search criteria. You shouldn't do it like that. Instead, the method filtering the elements should test each criterion:
public List<Element> search(List<Element> allElements, UserInputs criteria) {
List<Element> acceptedElements = new ArrayList<>();
for (Element e : allElements) {
if (isAccepted(e, criteria)) {
acceptedElements.add(e);
}
}
return acceptedElements;
}
private boolean isAccepted(Element e, UserInputs criteria) {
String firstName = criteria.getFirstName();
if (isCriterionFilled(firstName) && !hasFirstName(e, firstName)) {
return false;
}
String lastName = criteria.getLastName();
if (isCriterionFilled(lastName) && !hasLastName(e, lastName)) {
return false;
}
String phone = criteria.getPhone();
if (isCriterionFilled(phone) && !hasPhone(e, phone)) {
return false;
}
return true;
}
What is the better alternative for If else in implementing the logic in a program? | C#
Sum up and centralize the totaling operation in a separate method and check the state each of the Checkboxes while doing the sum:
public decimal TotalCosts()
{
decimal total = 0.0m;
if ({Oil Changed Checked})
total += {Oil Cost};
if ({Transmission checked})
total += {Transmission total};
if ({Repair Clutch})
total += {Clutch Cost}; // Maybe call a separate method ClutchTotal()?
... { Do this for all check boxes }
return total;
}
Don't attempt to individually add things together for disparate operations (as you did with the both_var = radiatorRush_var + transmissionFlush_var;
, that is your confusion.
Finite State Machine
I mentioned a finite state machine logic which is useful in organizing any code.
Think of a vending machine, it has to take all different types of coins as well as dollar bills and it has certain states before it can provide product. By mapping out all states and then centralizing the code to handle each state, that will go far in make the code bug free and maintainable.
If one adds a dime into the machine, the state goes from Welcome
into summing up the current coins and dollars but not providing the product. That state is true until total > cost, then the Vend
state is hit which distributes the product. It doesn't go back to the Welcome
state until it finishes a final step of provide any monies if overpayment
.
By setting up states one can organize one's code to handle all situations as you are seeing in your app.
A better alternative to using a long series of if/else if statements in C?
Use a loop. You'll also need an array of the minimum data value for each grade. Here's some untested code as an example:
for (int i = 9; i >= 0; i--)
{
if (data[y] >= minDataValueForGrade[i])
{
grades[i]++;
break;
}
}
It's short, easy to read, and makes it really easy to change the values that correspond to each grade.
Is there an alternative to using IF / ELSE statements
? : operator is exactly that, a "cleaner" if-else
http://msdn.microsoft.com/en-us/library/ty67wk28.aspx
classify = (input < 0) ? "negative" : "positive";
There are also switch statements for larger combinations:
http://www.w3schools.com/js/js_switch.asp
switch(n)
{
case 1:
execute code block 1
break;
case 2:
execute code block 2
break;
default:
code to be executed if n is different from case 1 and 2
}
Polymorphism is an abstract concept, not a way to write a statement. It's the practice of creating a method/function/class/etc where type is at least SOMEWHAT ambiguous. So the same method could return a result if fed, say, an integer for parameter 1, the same as if you were to feed an array into the same parameter.
Alternative to multiple if else statements in JavaScript?
You can use an object as a map:
function getCode(input) { var inputMap = { "Corporation": "534", "LLC": "535", "LLP": "536", "Partnership": "537", "Sole Proprietorship": "538", "Limited Partnership": "539" };
var defaultCode = "540"; return inputMap[input] || defaultCode;}
console.log(getCode("LLP"));console.log(getCode("Lorem Ipsum"));
Alternate for if-else
That is probably the best solution. It is very easy to read and see exactly what you're doing.
Using the ternary operator even for one statement can sometimes be a bit much to read depending on your code.
There are a huge number of alternatives here. You could say that many OOP design patterns are themselves just alternatives to if statements, but for a simple case like this it is unnecessary to go that far.
What is the best way to replace or substitute if..else if..else trees in programs?
These constructs can often be replaced by polymorphism. This will give you shorter and less brittle code.
what is the better alternative to following if-else ladder in java?
Use a LinkedHashMap<String, String>
:
LinkedHashMap<String, String> mapping = new LinkedHashMap<>();
mapping.put("unsupported", "unsupported");
mapping.put("final_result", "final_result");
// ... etc
Then iterate the map until you find a matching key:
for (Map.Entry<String, String> entry : mapping.entrySet()) {
if (str.contains(entry.getKey()) {
mailType = entry.getValue();
break;
}
}
The key point here is that LinkedHashMap
preserves insertion order (unlike HashMap
) so you can actually specify the order in which you want to test for matches (other map implementations do this too, e.g. Guava's ImmutableMap
; LinkedHashMap
is simply one that you have out of the box).
If you need to nest this for the outer cases, you can simply apply the same pattern:
LinkedHashMap<String, LinkedHashMap<String, String>> outerMapping =
new LinkedHashMap<>();
outerMapping.put("template", mapping);
outerMapping.put("properties", someOtherMapping);
And then just iterate through the keys in the same way:
for (Map.Entry<String, LinkedHashMap<String, String>> outerEntry : outerMapping.entrySet()) {
if (str.contains(outerEntry.getKey()) {
// Apply the iteration above, using outerEntry.getValue().
}
}
Related Topics
I Get a Status 200 When Connecting to the Websocket, But It Is an Error
How to Pass Variables Between Cucumber-Jvm Steps
How to Sort Arraylist of Objects by Timestamp and Get Last Five Elements
@Notnull:Validation Custom Message Not Displaying
How to Solve Gradle Error Cannot Find Symbol
Spring Kafka - How to Reset Offset to Latest With a Group Id
Gradle Java9 Could Not Target Platform: 'Java Se 9' Using Tool Chain: 'Jdk 8 (1.8)'
Calling Mutiple Webservice At Same Time in Spring Java
Reading a Text File Character by Character into a 2D Array in Java
How to Change the Background Color of a Textfield Without Changing the Border in Javafx
Custom Pagination by Array List
Alternative to If-Else Statements or Better Approach
Getting Java.Lang.Classnotfoundexception: Javax.Servlet.Servletcontext in Junit
Spring Jpa/Hibernate Transaction Force Insert Instead of Update
How to Find Out If String Has Already Been Url Encoded
Disable Spring Security Config Class for @Webmvctest in Spring Boot