r/FlutterDev • u/mkhytar_mkhoian • 21d ago
Discussion Dart’s if-case pattern is nice, but I replaced it with plain code. Where do you think it’s worth it?
Dart 3 gave us a lot of nice language features. One of them is the “if-case” pattern.
While working on my library, I had this code:
AdjustEvent toAdjustEvent(String eventToken) {
final adjustEvent = parameters.toAdjustEvent(eventToken)..setRevenue(revenue, currency);
if (deduplicationId case final id?) adjustEvent.deduplicationId = id;
return adjustEvent;
}It’s short. But to read it, you need to know Dart’s pattern rules. if (x case final id?) means “if x isn’t null, call it id and run this”.
I rewrote it in plain style:
AdjustEvent toAdjustEvent(String eventToken) => parameters.toAdjustEvent(eventToken)
..setRevenue(revenue, currency)
..deduplicationId = deduplicationId;And here is the interesting part. When I looked closely, the null check wasn’t needed at all. The SDK field already accepts null and skips it when sending. So the plain version is not only easier to read, it’s also simpler.
The fancy line was protecting from something that couldn’t go wrong.
And this is really important when you write a library or design a public API. Your code will be read by many people with different Dart experience: users who open your source to understand what happens, and contributors who want to fix something. In app code only your team reads it, but in a library every clever line becomes a small barrier for someone else. Plain code makes your library easier to trust and easier to contribute to.
I still think patterns are great in some places, like checking JSON shape:
if (json case {'name': String name, 'age': int age}) {
return User(name, age);
}There it replaces several lines of checks and casts. But in my case it was just extra complexity.
Curious how you use them. Where do patterns really pay off for you, and do you write differently when the code is a library?
8
u/raman4183 21d ago edited 21d ago
> if (x case final id?) means “if x isn’t null, call it id and run this”
Your interpretation is slightly off, “id?” represents the case when deduplicationId is nullable, bind it to a non-nullable variable called id and continue otherwise skip this if block.
> When I looked closely, the null check wasn’t needed at all. The SDK field already accepts null and skips it when sending. So the plain version is not only easier to read, it’s also simpler.
Naturally, your rewrite is simpler because
1 - your rewrite doesn’t have any conditional check.
2 - you were forcefully and unnecessarily checking a scenario which is possibly already handled by “AdjustEvent” setter internally.