removing default case requirement?

ryuukk_ ryuukk.dev at gmail.com
Fri Mar 31 15:48:17 UTC 2023


On Friday, 31 March 2023 at 15:20:41 UTC, Steven Schveighoffer 
wrote:
> Imagine if every `if` statement required you to write an `else` 
> clause, even if it was empty. The idea would be, that you have 
> to affirmatively attest that you didn't want to have a special 
> case for when it didn't match the condition.
>
> How fast do you think that everyone would run screaming for the 
> exits?
>
> But we have such a thing, in the `default:` case requirement.
>
> In my code, it happens quite a bit that I throw an exception in 
> the default case, or return something, but there's still a lot 
> of `default: break;` code in there.
>
> But consider a few things here:
>
> 1. I have `final switch` at my disposal whenever I need it, 
> which allows me to avoid `default:` and is really meant for "I 
> want to make sure I handle everything"
> 2. If you forget to return something, or throw an exception, 
> the compiler will still let you know (i.e. some code paths 
> don't return a value). This counts for the majority of places 
> where I have a `default` case that's not just `break;`.
> 3. I know in my experience (yours may vary) that when I forget 
> to include a default, it's usually because I forgot to include 
> `default: break;`. So the rule hasn't really helped me avoid 
> bad code.
> 4. `switch` is already bloated enough with the requirement for 
> `break` or `goto` between cases.
>
> If we wanted to relax this requirement it's actually an easy 
> change -- no currently-compiling code will break.
>
> Why not? How much does this rule help you, vs. annoy you?
>
> -Steve

Indeed, there are many rules like this one that just doesn't make 
sense, and just makes you type more, removing clarity from your 
own code

Also requiring "break" is annoying, all modern languages moved 
away from this noisy syntax and went the pattern matching and 
enum as expression route, and it feels much better to use

D stuck with C's enums and C's switch model



More information about the Digitalmars-d mailing list