Hacker News new | comments | show | ask | jobs | submit login
Preconditions Should be Checked Explicitly (twistedoakstudios.com)
5 points by Strilanc on Apr 2, 2013 | hide | past | web | favorite | 4 comments



I've been thinking about this recently too, and I think this is an area which is ripe for a language feature.

Currently we have 3 (ugly) options:

1: Validate before method call (bad for obvious reasons)

2: Validate immediately within method (does the job, but looks ugly).

3: Add some kind of pre-processing via method annotations which will do the validation for you.

Wouldn't it be better if we could assert the validation requirements directly within the method definition?

For example:

    public boolean doSomethingFor(10 > int iterations > 0)...
Obviously this isn't the most concise example, but I think it demonstrates the point. I guess the problem with this is it makes future changes to the preconditions confusing / difficult - depending upon how exactly this feature would end up being implemented. I'm imagining that this wouldn't interfere directly with the method signature, and would instead be turned into code much like the one in the example during compilation.


I think it's a better idea, in some languages at least, to extend the signature to contain general preconditions and postconditions.

    public boolean doSomethingFor(int iterations) {
        // this is considered part of the semantic signature
        requires iterations > 0 && iterations < 10;
        
        // implementation
        ...
    }
Putting it in the types is a good idea, but extremely complicated. You need full dependent types to make it work.


Good article as usual, I'd argue that in TDD preconditions are absolutely critical because otherwise your tests cannot possibly be considered complete. At the end of the day preconditions usually amount to if (valid) continue else throw

If they did turn out to be a bottleneck in the future then modifying or even removing them shouldn't affect visible behavior.


Yes, tests are a good way to ensure the behavior of invalid cases stays consistent.




Guidelines | FAQ | Support | API | Security | Lists | Bookmarklet | Legal | Apply to YC | Contact

Search: