Skip to content

Replace "PREFER using ?? to convert null to a boolean value." with more precise guideline #4388

@munificent

Description

@munificent

Page URL

https://dart.dev/guides/language/effective-dart/usage#prefer-using--to-convert-null-to-a-boolean-value

Page source

No response

Describe the problem

The guideline currently suggests using ?? <bool> instead of == <bool> or != <bool> when dealing with a nullable Boolean. But the ?? operator often doesn't type promote in ways that you want, which is why the guideline also has a large exception that mostly cancels out the guidance.

Also, the examples all use ?., which makes it seem like the rule is advocating or at least has something to do with null-aware operators.

Really, the key point of the guideline is that equality operators are all very confusing when you have a Boolean literal on one side and a nullable Boolean expression on the other. If you see:

if (foo == true) { ... }

It appears to have nothing to do with null and that the == true is pointless and the code should instead be:

if (foo) { ... }

But that chances the behavior if foo happens to be nullable. You could improve this code with:

if (foo ?? false) { ... }

Now the ?? operator makes it clear that something to do with null is happening. But it's equally valid (and often better because of type promotion) to do:

if (foo != null && foo) { ... }

This guideline shouldn't be that ?? is good, it's more that == true etc. are bad.

Expected fix

We should clearly target the guideline to the behavior we want to avoid. Something like: "DON'T use true or false in equality operators."

If the other operand isn't nullable, then it's always simpler to eliminate the equality operator and add ! if needed. If the other operand is nullable, you should use ?? or an explicit null check to make that clear.

Additional context

No response

Metadata

Metadata

Assignees

Labels

a.effective-dartRelates to the best practices explained in Effective Dartd.enhancementImproves docs with specific aske0-minutesCan complete in < 60 minutes of normal, not dedicated, worke1-hoursCan complete in < 8 hours of normal, not dedicated, workp3-lowValid but not urgent concern. Resolve when possible. Encourage upvote to surface.

Type

No type

Projects

No projects

Milestone

No milestone

Relationships

None yet

Development

No branches or pull requests

Issue actions