That also works, butAnda != truewon't work?
a != true is much longer than !a and it is also like normal language: Imagine a variable boolean glasIsEmpty. Do you say:Ty. And why notif (!Boolean.TRUE.equals(isActive))? This will handlenullvals correctly as well.
| Syntax | Mental Translation | Quality |
| if (a != true) | "If a is not equal to true..." | Cluttered |
| if (a == false) | "If a is equal to false..." | Clearer, but still wordy |
| if (!a) | "If not a..." | Clean & Standard |
Boolean isActive = fetchStatus(); // Could be true, false, or null
// "If it's null, treat it as false"
boolean status = Optional.ofNullable(isActive).orElse(false);
if (status) {
// Logic for true
}
Optional.ofNullable(isActive)
.filter(Boolean::booleanValue)
.ifPresent(this::doSomething);
public enum AccountStatus {
ACTIVE,
INACTIVE,
PENDING_VERIFICATION // This is the "third" value that null often tries to hide
}
| Feature | Boolean (with null) | int (0, 1, 2) | Enum |
| Readability | null is confusing | What is 2? | PENDING_VERIFICATION |
| Type Safety | High | Low (any number fits) | Highest |
| Scalability | Stuck at 3 states | Hard to manage | Easy to add SUSPENDED |
public void handleStatus(@NonNull AccountStatus status) {
// If status is null, this will throw an NPE immediately,
// which is often better than hiding a bug.
switch (status) {
case ACTIVE -> sendWelcomeEmail();
case INACTIVE -> disableAccess();
case PENDING_VERIFICATION -> notifySupport();
// No 'default' needed if all enum values are covered!
}
}
We can. On the other hand, your question in the other thread was also asked in English.Sollten wir nicht einmal ins Deutsche wechseln? Wir sind hier in einem deutschsprachigen Forum ....
In my humble opinion, Optional does not solve any problems when trying to avoidint for multiple, defined values: When you have a fixed list of defined values: enum should be a good fit.
Regarding null or Optional: Optional is not an replacement for null or so. You just have to evaluate the situation.
null values. You simply cannot completely do without null values. One alternative would be Exceptions, but handling "invalid" return values in valid conditions via Exceptions (program control flow via Exceptions) is not good design.Optional does not eliminate null-related issues in Java; it merely shifts them.null is a fundamental part of Java's type system. An Optional itself is a reference type and can therefore also be null. As a result, Optional cannot fully remove the presence of null from a program.Optional does not reliably prevent runtime errors. Calling Optional.get() on an empty value leads to a NoSuchElementException, which is conceptually no better than a NullPointerException. The error is not avoided; it is simply renamed.null often represents a valid and meaningful state rather than an error. In many APIs, a missing value is a normal outcome (e.g., "entity not found"). Using exceptions to signal such conditions is poor design, as exceptions should represent exceptional situations, not normal control flow.Optional frequently increases code complexity. Simple and explicit null checks are often more readable, easier to debug, and better integrated with existing frameworks than long chains of map, filter, and orElse.Optional mainly as a communication tool for return values, not as a universal replacement for null. It is explicitly discouraged for fields, parameters, or serialization-heavy code.Optional does not solve the null problem; it only wraps it. Since null is unavoidable and often semantically valid, classic Java design with explicit null handling remains one of the most practical and robust approaches.Die Frage ist: Wieso stellst Du in einem deutschsprachigen Forum eine Frage auf Englisch und bleibst so sehr dabei? Und nur weil wir generell versuchen hilfreich zu sein und daher auch auf Englisch antworten wenn die Frage auf Englisch gestellt wurde, ändert nichts daran, dass hier die Hauptsprache Deutsch sein sollte. Ich wundere mich, wieso das überhaupt eine Frage ist, die diskutiert werden sollte...We can. On the other hand, your question in the other thread was also asked in English.
Ein Optional sollte niemals null sein. Selbst einfache statische Codeanalyse-Tools werfen eine mögliche null Zuweisung als Fehler. Daher ist das kein Argument, das zieht.First,nullis a fundamental part of Java's type system. AnOptionalitself is a reference type and can therefore also benull. As a result,Optionalcannot fully remove the presence ofnullfrom a program.
Ja, aber auch hier gilt: Das fangen Tools zur Codeanalyse sauber ab. Und im Gegenzug gibt es sehr schöne fluent Aufbauten, die eben den Check im Code vereinfachen / lesbarer machen.Second,Optionaldoes not reliably prevent runtime errors. CallingOptional.get()on an empty value leads to aNoSuchElementException, which is conceptually no better than aNullPointerException. The error is not avoided; it is simply renamed.
Ja, eine Exception zu werfen ist keine gute Idee. Aber das besagt ja nichts bezüglich Optional.empty aus.Third,nulloften represents a valid and meaningful state rather than an error. In many APIs, a missing value is a normal outcome (e.g., "entity not found"). Using exceptions to signal such conditions is poor design, as exceptions should represent exceptional situations, not normal control flow.
Das sehe ich eben nicht so. Ich sehe den Umgang mit Optional oft als deutlich besser lesbarer an.Fourth,Optionalfrequently increases code complexity. Simple and explicitnullchecks are often more readable, easier to debug, and better integrated with existing frameworks than long chains ofmap,filter, andorElse.
Das ist entspricht doch auch meiner Aussage:Finally, even the Java designers intendedOptionalmainly as a communication tool for return values, not as a universal replacement fornull. It is explicitly discouraged for fields, parameters, or serialization-heavy code.
Optional is not an replacement for null or so.
Den kann ich nicht mehr folgen. Das würde ja besagen, die Entwickler haben da der Java Library etwas gegeben, was schlicht nicht verwendet werden sollte. Und doch wird es innerhalb der Java Library verwendet, z.B. bei Stream (findAny, findFirst, min, max, ....)Zusammenfassend: Vermeiden Sie nach Möglichkeit auch in Ihrem eigenen API-Design die Verwendung von Optional.
Vielleicht erst einmal den ganzen Text lesen, bevor man versuchen will, andere zu belehren. Deine Meinung ist mir ~ schnurz.Ein Optional sollte niemals null sein. Selbst einfache statische Codeanalyse-Tools werfen eine mögliche null Zuweisung als Fehler. Daher ist das kein Argument, das zieht.
True. Optional is not just an arbitrary wrapper for references, but a paradigm. When applied consistently, Optional eleminates the need for null return values. We do the same for multi-valued return values by using collections: instead of returning null, we return an empty collection.Finally, even the Java designers intendedOptionalmainly as a communication tool for return values, not as a universal replacement fornull. It is explicitly discouraged for fields, parameters, or serialization-heavy code.
Ich bin irritiert... entweder hier ist ein Fehler, den alle übersehen haben, oder es wird ein Java-Feature verwendet, das ich noch nicht kenne.boolean isNotTrue = ! var;
Da wurde lediglich eine Bedingung von den Klammern der if Anweisung davor gezogen um das dann sozusagen zu benennen. Das ist ein Weg, um etwas lesbarer zu gestalten. Die Alternative wäre, den Check in eine Methode zu verlagern. Der Name sollte also nicht ausdrücken: "Hier ist immer true drin" (Was man einfach direkt ausdrücken würde) sondern "Irgendwas, was in var drin steckt is not true".Ich bin irritiert... entweder hier ist ein Fehler, den alle übersehen haben, oder es wird ein Java-Feature verwendet, das ich noch nicht kenne.
Da wird doch einfach nur der Wert von var geflippt... das Ergebnis ist doch nicht zwangsweise notTrue, oder?
Genau das hatte mich irritiert. isNotTrue klang für mich nach Konstante. Der Name notVar wäre für mich deutlich verständlicher gewesen. Und idealerweise hätte es im Beitrag oberhalb des ersten Beispiels gestanden, um noch mehr Kontext zu geben.Da wurde lediglich eine Bedingung von den Klammern der if Anweisung davor gezogen um das dann sozusagen zu benennen. Das ist ein Weg, um etwas lesbarer zu gestalten. Die Alternative wäre, den Check in eine Methode zu verlagern. Der Name sollte also nicht ausdrücken: "Hier ist immer true drin" (Was man einfach direkt ausdrücken würde) sondern "Irgendwas, was in var drin steckt is not true".
Then can ou use it: BooleanUtils.isNotTrue(var), this expression is false for var=true only, all other cases (var is null, not a boolean..) are true.<dependency>
<groupId>org.apache.commons</groupId>
<artifactId>commons-lang3</artifactId>
<version>3.12.0</version> <!-- Oder aktuelle Version -->
</dependency>
If the only requirement is this boolean check, then I would not add an additional library for this. You always risk to add vulnerabilities to your application (commons-lang3 is a good example - it had a vulnerability in the past).in my opinion is the best way for this to use libary "Boolutils" from Apache.