Ternary logic for result (not about ternary operator) [closed] - java

Closed. This question is opinion-based. It is not currently accepting answers.
Want to improve this question? Update the question so it can be answered with facts and citations by editing this post.
Closed 8 years ago.
Improve this question
I have a code (Java for example):
boolean A(...){
if (...) return true;
else return false;
}
void C(...){
if (A) {doSomeThing();}
else {doNothing();}
}
But logic is changed and today i need return 3 cases. It look something like this
int A(...){
if (...){ return int;}
else {
if (...) {return int;}
else {return int;}
}
}
void C(...){
if (A == 1) {doSomeThing1();}
if (A == 2) {doSomeThing2();}
if (A == 3) {doSomeThing3();}
}
Is this a best practices or I should use something other instead of "int"? Or I should change my logic and divide it on two boolean?
P.S. I know that this questions are fully but it disturbs me.

Best practice would be to use enum type instead of boolean.
public enum PossibleValues {
TRUE, FALSE, NEITHER;
}

Actually how many condition you should check is depends on your requirement. For that you can use if-else or swith-cases.

Related

Coding convention for If statement and returning [closed]

Closed. This question is opinion-based. It is not currently accepting answers.
Want to improve this question? Update the question so it can be answered with facts and citations by editing this post.
Closed 1 year ago.
Improve this question
I'm not sure if I'm overthinking this but should I do this
if (!searchList.isEmpty()) {
String search = searchList.get(0).getText();
return List.of(search.split("\n"));
} else {
return null;
}
or should I do this
if (!searchList.isEmpty()) {
String search = searchList.get(0).getText();
return List.of(search.split("\n"));
}
return null;
Some advice :
You should never return a null value. It is a bad practice
You should test for true instead of false. It makes your code more readeable
Your should look like this :
if (searchList.isEmpty()) {
return Collections.emptyList();
}
String search = searchList.get(0).getText();
return List.of(search.split("\n"));
Neither.
if (searchList.isEmpty()) {
return null;
}
String search = searchList.get(0).getText();
return List.of(search.split("\n"));
I didn't like the negative condition ("if not empty") when it wasn't really needed.
The way I think of what I wrote, it's "get rid of the edge case first, then deal with the main logic".
This is of course mere opinion. Eventually you'll develop your own taste for how to lay out code; and good taste is one of the more important attributes of a programmer.

How to check if at least one method return true? [closed]

Closed. This question needs details or clarity. It is not currently accepting answers.
Want to improve this question? Add details and clarify the problem by editing this post.
Closed 1 year ago.
Improve this question
I have an Interface with method:
boolean isForbidden();
and few implementations, which are Spring Components.
In used class, I autowirding all of them and I want to check if at least one of them returning true. How can I do that? Is there a simply way to check it?
Interface:
public interface ForbiddenChecker {
boolean isForbidden();
}
Class:
#Autowired
private List<ForbiddenChecker> validators;
And I want to create a method something like:
public boolean shouldInvokeProcess() {
// at least one component return true
}
What might the body of this method look like?
Feels like I'm missing something here...
public boolean shouldInvokeProcess() {
for (var checker : validators) if (checker.isForbidden()) return false;
return true;
}
If you're one of those 'ooh! shiny new hammer!' folks:
public boolean shouldInvokeProcess() {
return !validators.stream().anyMatch(ForbiddenChecker::isForbidden);
}
Both seem about equally fine, here, and trivial.
If I understand correctly, surely you can just iterate over the list of validators, calling each ones "isForbidden" method. If one returns true then return true from "shouldInvokeProcess"

Alternative to Java IF-ELSE statement for casting object instances [closed]

Closed. This question needs details or clarity. It is not currently accepting answers.
Want to improve this question? Add details and clarify the problem by editing this post.
Closed 2 years ago.
Improve this question
I have this code:
entity.conditions().forEach(entityCondition - > {
if (entityCondition instanceof LinkCondition) {
LinkCondition condition = (LinkCondition) entityCondition;
} else if (entityCondition instanceof OppositeLinkCondition) {
//...
} else if (entityCondition instanceof PropertyEqualCondition) {
//...
} else if (entityCondition instanceof PropertyLocalTimeRangeCondition) {
//...
}
// and 20 or so, more conditions...
});
In which I am looking for an alternative than IF-ELSE statement, a more elegant approach in dealing with dozens of instanceof conditions.
Unfortunately, there is no such syntax in Java yet. You can try Kotlin which already supports this:
val b = when (a) {
is String -> a.length
is Int -> a
is Long -> (a and 0xFFFFFFFF).toInt()
else -> a.hashCode()
}
As #Progman pointed out, this question is similar to other questions, you should check them out too.

Java: Sum of digits from String with Streams [closed]

Closed. This question is opinion-based. It is not currently accepting answers.
Want to improve this question? Update the question so it can be answered with facts and citations by editing this post.
Closed 2 years ago.
Improve this question
Example:
Input: abc565xyz
Output: 16
Which variant would be better? Thanks.
public static int sumOfDigits(String s) {
return s.chars().filter(Character::isDigit).reduce(0, (i0, i1) -> i0 + Character.digit(i1, 10));
}
public static int sumOfDigits(String s) {
return s.chars().filter(Character::isDigit).mapToObj(a -> a - '0').reduce(0, (a, b) -> a + b);
}
public static int sumOfDigits(String s) {
return s.chars().filter(Character::isDigit).mapToObj(a -> Character.digit(a, 10)).reduce(0, Integer::sum);
}
Define better. What version of Java? Which release? Which platform are you planning on running it? In short, without testing it on the target platform it's very hard to say.
BTW, instead of mapToObj and an explicit reduce, it would be better to do
return s.chars().filter(Character::isDigit).map(a -> Character.digit(a, 10)).sum();
Mapping an int to an Object is probably the most expensive part and you did that in two of your versions. So, as posted, the first one is probably "best".

What should I return instead of null? [closed]

Closed. This question is opinion-based. It is not currently accepting answers.
Want to improve this question? Update the question so it can be answered with facts and citations by editing this post.
Closed 3 years ago.
Improve this question
I've heard that it is bad practice to return null.
What are the alternatives to returning null in this case?
public RollingStock getHeadPoint() {
if (!train.isEmpty()) {
return train.get(0);
} else {
return null;
}
}
IMHO, the best option is to return an Optional<RollingStock>, like the foillowing:
public Optional<RollingStock> getHeadPoint() {
if (!train.isEmpty()) {
// or even Optional.ofNullable, if you are not sure
// whether train.get(0) is null or not
return Optional.of(train.get(0));
} else {
return Optional.empty();
}
}
Assuming train is a collection, as an alternative to manual wrapping the value into an Optional you could use Stream API:
public Optional<RollingStock> getHeadPoint() {
return train.stream()
.findFirst();
}
In some cases using inline train.stream().findFirst() may be more preferable than wrapping it into a separate method.
Once you already modified your method getHeadPoint to return Optional<RollingStock> you can use it as follows:
// ...
RollingStock headPoint = getHeadPoint().orElse(yourDefaultRollingStock);
// or
RollingStock headPoint = getHeadPoint().orElseGet(aMethodGettingYourDefaultRollingStock());
// or
RollingStock headPoint = getHeadPoint().orElseThrow(() -> new Exception("The train is empty!"));
// or
getHeadPoint().ifPresent(headPoint -> doSomethingWithHeadPoint(headPoint));
You could define a TrainIsEmptyException and throw that when the train is empty. Make it a checked Exception. Or you can just return null.
You should differentiate "get" and "search/find" methods :
getHeadPoint : some train should exist. If not, it's against your business, throw an exception
findHeadPoint : non-existence of the train is coherent to your business, return null

Categories