Standard way to supply hints to branches
H. S. Teoh
hsteoh at qfbox.info
Fri Aug 23 18:34:58 UTC 2024
On Sat, Aug 24, 2024 at 05:43:33AM +1200, Richard (Rikki) Andrew Cattermole via Digitalmars-d wrote:
>
> On 24/08/2024 5:39 AM, Manu wrote:
[...]
> > For instance, an extraordinarily common function pattern is to
> > receive some inputs, validate a few things, and then do the thing at
> > the end with valid inputs.
> > Validations are usually a series of exclusionary checks framed as
> > `if(fails_validity_check) return;`
> > That flow keeps code in a nice linear flow, it doesn't introduce any
> > scopes at all... but it's the opposite of what the assume(true)
> > prediction rule wants.
[...]
> If you want to propose something like an attribute on if statement, I'd be
> keen to see it (in ideas forum).
>
> ```d
> void func() {
> @unlikely
> if (random() > 0.5)
> return;
> @likely
> else {
>
> }
> }
> ```
This would be very nice to have. I have quite a lot of code with early
return, because it keeps nesting down to a sane level. But there are two
opposing cases: the first is Manu's case, you want to validate
parameters and abort early if you find something amiss.
But the second case is, you exit early to avoid an expensive computation
if an initial stab got the right answer / is good enough / or the answer
is cached and you just return it instead of recomputing it.
The second case works well with the assume(true) prediction rule. But
the first case works poorly. I'd say a standardized attribute would be
very nice to have.
T
--
Doubt is a self-fulfilling prophecy.
More information about the Digitalmars-d
mailing list