In C# I could use Contract.OldValue<T>
in a post-condition to check how a field has changed. How can I do this in D? I've read the relevant page in the documentation, but it doesn't mention this.
Specifically, I'm writing a page renderer and am keeping track of how far down the page it's got in a member variable. I'd like to assert in an out
block that the variable's value is at least as large as it was at the start (i.e. it should have moved down the page, not up).
class Renderer
{
private:
float pos;
public:
void writeText(string text)
in
{
assert(text !is null);
}
out
{
// how to do this?
assert(pos >= oldPos);
}
body
{
...
}
}
Obviously I could add another field just to hold the old value, and manually assign it at the start of the writeText
method, but I'm hoping there's something in the framework that will do this automatically.
There is no language support for it. It's been discussed a few times before (for instance, here's a thread from 2013 discussing it), but I doubt that it'll ever actually be implemented. There are concerns about code breakage if it's implemented (as discussed in that thread), and it's not even possible in the general case (in particular, there is no generic way to do a deep copy of a variable in D, so there really isn't a good way to save the original state of the variable if it isn't a value type). So, while it would be nice to have in principle, it's problematic from a technical standpoint, especially in a systems language that gives you a ton of leeway with how stuff like copying your type works.
So, if you want to save the original state of the variable for comparison in the out contract, you'll need to save it yourself in whatever manner is appropriate for that type of variable.