Is not true check, in Java?

And a != true won't work?
That also works, but a != true is much longer than !a and it is also like normal language: Imagine a variable boolean glasIsEmpty. Do you say:
  • If not glas is empty then ....
  • if glas is empty is false then ...

So when we write code, we try to write easily readable code (so you can simply read code out loud and it should make sense) and also avoid complexity that is not required.

So in short: Yes, that works but is is simply uncommon and the shorter expression is prefered.
 
Ty. And why not if (!Boolean.TRUE.equals(isActive))? This will handle null vals correctly as well.

When you have Boolean reference which can be null, then this is of course a valid solution.

But that only makes sense, if you have a value that can be null. And often this is avoided in clean code. Possibilities can be:
  • If you have to handle such values, then you could use Optionals instead of null (or generate it with Optional.ofNullable).
  • if true / false are not enough and you have more states, you could use an enum

As you see: You have a lot of different possibilities. You simply have to choose one (which maybe must be accepted by others, too)
 
I think clean code is important above all else, not so much external acceptance... Would you prefer int instead of the three-valued bool? Do you prefer null or the Optional concept? Lots of questions for possibly the wrong audience.
 
Sollten wir nicht einmal ins Deutsche wechseln? Wir sind hier in einem deutschsprachigen Forum ....



"external acceptance" - that should be defined. Acceptance is a crucial part of professional software development and can be found in multiple areas as design discussions, code reviews, ...

int 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.

When you give values to others (e.g. a result of a method), then Optional is great because you make sure, that the other developer does not create an NPE.
But inside your internal code: When you handle null (and maybe use some tools that check your code), then it is safe and there is no need to create additional instances.

So in short maybe something like
  • Method results / API Design -> Optional
  • Fields, Parameters -> no Optional
 
In professional Java development, writing if (a != true) is considered redundant and "unclean." Here are the reasons why:

Redundancy (Double Logic)
An if statement always expects an expression that evaluates to either true or false.
  • If a is already a boolean variable, it already represents a truth value.
  • By writing (a != true), you are asking the computer to evaluate a, compare it to true, and then generate a new boolean.
It is the linguistic equivalent of saying, "If it is true that it is raining..." instead of simply saying, "If it is raining..."

SyntaxMental TranslationQuality
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

The criticism of Boolean.TRUE.equals(isActive) is that it sometimes silently masks a bug. If isActive is null because a database query failed or a mapper missed a field, treating it as false might lead to hard-to-find logic errors. Sometimes, you want the code to crash (NPE) so you know exactly where the data is missing.

Here is how you would use Optional to handle your Boolean safely:
Instead of checking for null, you wrap the Boolean object. This forces you to think about the "else" case (what happens if the value is missing).
Java:
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
}

If you just want to execute a piece of code only if the value is present and 'true', you can chain methods:
Java:
Optional.ofNullable(isActive)
    .filter(Boolean::booleanValue)
    .ifPresent(this::doSomething);

Why use Optionals over Boolean.TRUE.equals()?
Intent: It tells other developers: "Warning! This value might be missing."

Chaining: You can map the value to something else (e.g., if true, return "Active", if false or null, return "Inactive").

No more null: If your method returns Optional<Boolean>, the caller is forced to handle the empty case, which prevents bugs before they happen.
 
Zuletzt bearbeitet:
Instead of guessing what true, false, or null means, you define exactly what states exist:
Java:
public enum AccountStatus {
    ACTIVE,
    INACTIVE,
    PENDING_VERIFICATION // This is the "third" value that null often tries to hide
}

Why this is better than Boolean or int:
FeatureBoolean (with null)int (0, 1, 2)Enum
Readabilitynull is confusingWhat is 2?PENDING_VERIFICATION
Type SafetyHighLow (any number fits)Highest
ScalabilityStuck at 3 statesHard to manageEasy to add SUSPENDED

Java:
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!
    }
}
 
Zuletzt bearbeitet:
Sollten wir nicht einmal ins Deutsche wechseln? Wir sind hier in einem deutschsprachigen Forum ....
We can. On the other hand, your question in the other thread was also asked in English.

int 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.
In my humble opinion, Optional does not solve any problems when trying to avoid 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.

In practice, Optional does not eliminate null-related issues in Java; it merely shifts them.

First, 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.

Second, 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.

Third, 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.

Fourth, 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.

Finally, even the Java designers intended 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.

Conclusion: 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.

Zusammenfassend: Vermeiden Sie nach Möglichkeit auch in Ihrem eigenen API-Design die Verwendung von Optional.
 
Der Trend geht eindeutig zur Vermeidung von null, @see JSpecify oder auch JSR-305. Optional ist nur ein erster Schritt in Richtung Null-Sicherheit und kann viele Probleme vermeiden. Lesbarkeit und Komplexität sind auch subjektive Wahrnehmungen. Ein Einsteiger sieht die Verwendung von null vermutlich ganz anders, als lesbar und verständlich. Fehler im Zusammenhang mit Nullreferenzen dürften zu den häufigsten Programmierfehlern zur Laufzeit gehören. Tony Hoare, der Erfinder der Nullreferenz, entschuldigte sich 2009 öffentlich für seinen "Billion-Dollar Mistake", die Einführung der Null-Referenz in ALGOL W. In modernen Sprachen wie Swift, Kotlin oder Rust ist die Zuweisung von "nil" bzw. "null" standardmäßig nicht erlaubt.
 
We can. On the other hand, your question in the other thread was also asked in English.
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...

Und es ist doch ok, wenn Du eine Meinung hast. Nur wenn Du eine Meinung hast: Wieso fragst Du dann erst nach? Daher stellt sich mit gerade die Frage, was hier Deine Absicht ist Tobias (Davon gehe ich zumindest gerade aus).

Aber spielen wir das Spiel einmal mit:

First, 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.
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.

Second, 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.
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.

Third, 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.
Ja, eine Exception zu werfen ist keine gute Idee. Aber das besagt ja nichts bezüglich Optional.empty aus.

Fourth, 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.
Das sehe ich eben nicht so. Ich sehe den Umgang mit Optional oft als deutlich besser lesbarer an.

Finally, even the Java designers intended 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.
Das ist entspricht doch auch meiner Aussage:
Optional is not an replacement for null or so.

Zusammenfassend: Vermeiden Sie nach Möglichkeit auch in Ihrem eigenen API-Design die Verwendung von Optional.
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, ....)

Noch einmal ganz deutlich: Du darfst Deine Meinung haben und ich habe keine Intention, diese ändern zu wollen.

Wenn man das Thema etwas vertiefen will: Joshua Bloch hat in Effective Java, 3rd Edition in Item 55 auch relativ ausführlich etwas zu Optionals geschrieben.
 
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.
Vielleicht erst einmal den ganzen Text lesen, bevor man versuchen will, andere zu belehren. Deine Meinung ist mir ~ schnurz. 😉

Und Vielleicht sollte sich @Oneixee5 mal auf Java beziehen, in der sie ja selbsternannte Expertin ist.

Du siehst, eine solche Diskussion macht an dieser Stelle eigentlich keinen Sinn mehr.

Alles Gute
 
Finally, even the Java designers intended 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.
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.
 
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?
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".

Also das Beispiel ist aus meiner Sicht in so fern schlecht, als das
a) keine sinnvollen Namen Verwendung gefunden haben (Das ist aber ohne Kontext einfach nicht sinnvoll machbar.
b) das Beispiel ist für dieses Refactoring einfach schlecht. Von !var zu notVar liefert nicht wirklich eine höhere Lesbarkeit, den beides wird gleich gelesen. Was anderes ist, wenn man komplexe Überprüfungen hat, dann kann sowas sinn machen weil da halt nicht nur irgendwas steht von wegen a && b && !c sondern du hast da eine Dokumentation .... wenn das also abprüft, ob ein gegebener Code die CleanCode Anforderungen erfüllt, dann hast Du nur ein var isCleanCode = a && b && !c und schon muss man nicht mehr prüfen: Was war das noch einmal?

ABER: Darum ging es hier weniger. (Unter dem Strich ging es auch nur darum, dass unserem Tobias langweilig war und er Bespassung gesucht hat)
 
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".
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.
 
Hello Anon0,
in my opinion is the best way for this to use libary "Boolutils" from Apache.
With Maven you can bind it inside the pom like:
<dependency>
<groupId>org.apache.commons</groupId>
<artifactId>commons-lang3</artifactId>
<version>3.12.0</version> <!-- Oder aktuelle Version -->
</dependency>
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.
 

Neue Themen


Zurück
Oben