static if enhancement

Timon Gehr via Digitalmars-d digitalmars-d at puremagic.com
Mon Jun 27 11:14:26 PDT 2016


On 27.06.2016 13:05, cym13 wrote:
> On Monday, 27 June 2016 at 08:16:18 UTC, Claude wrote:
>> On Saturday, 25 June 2016 at 11:27:01 UTC, cym13 wrote:
>>> We are talking about early returns (checking for something and
>>> returning as soon as possible) which are a well-known and efficient
>>> way to reduce indentation levels and increase modularity. You can't
>>> come and say "What? You want it to work? Man, you should have thought
>>> your code better!": the very reason this subject is discussed is to
>>> allow people to deal with indentation levels!
>>
>> I didn't want to sound like that. But my post was unclear. Though, in
>> the example, it looks nice, and I understand one would want such a
>> feature. I think it could be abused in some other cases and make the
>> code less readable.
>>
>> I had in mind some cross-platform libraries written in C with #if
>> #elif and #endif all other the place (used with compiler switches).
>> And I reckon the current "static if" is a good tool that fits well
>> with the rest of the language to properly mark different sections of
>> code, and have different implementations. The fact it gives another
>> indentation level could be seen as an opportunity to better modularize
>> code (it's what I meant).
>>
>> So I find that special case (having code after a "static if()
>> {return;}" treated like in the "else" block) a bit unintuitive, and
>> could be prone to bad practice and confusion.
>
> What's unintuitive about it (real question)? It would make it behave
> more like a standard if and early returns are very common, well
> understood and good practice:
>
> void func(int* somepointer) {
>      if (somepointer == null)
>          return;
>      [rest of the code]
> }
>
> When seeing such code (which generally leads to cleaner functions) the
> meaning is quite obvious, I fail to see who would expect static if to
> behave otherwise.

Me, because that's what it means to evaluate the condition at compile 
time and only compiling in the appropriate branch. This is additional 
and special behaviour and it destroys the orthogonality of 'static if' 
and 'return'. (I don't feel strongly about the change, but the idea that 
the new behavior should be expected anyway is flawed.)

> Of course knowing how it works it makes sense that
> making it work that way isn't easy

It's rather easy.

> but it sounds more like a leaky
> abstraction than something more intuitive to me.

My preferred option is to simply add 'static return' to avoid the 
context-dependence.


More information about the Digitalmars-d mailing list