object states
simendsjo
simendsjo at gmail.com
Mon Oct 8 01:35:40 PDT 2012
On Sunday, 7 October 2012 at 20:46:09 UTC, Henning Pohl wrote:
> On Sunday, 7 October 2012 at 20:18:15 UTC, Ali Çehreli wrote:
>> Sounds good.
> Thanks.
>
>> You haven't mentioned the invariant keyword, so perhaps you
>> are not aware of that feature?
>>
>> http://dlang.org/class.html#Invariant
>>
>> http://dlang.org/dbc.html
>>
>> Although the docs seem to favor classes, invariant is
>> available for structs as well.
>>
>> Ali
> How would you resolve the issue I wrote in my first post using
> invariants? You cannot add/remove checks from invariants while
> using the object. That's what I made different. But there are
> still some limits given by the language. Look at point 7 for
> instance.
>
> The problem about contract programming in general is you cannot
> use it in public library code. Distinction between logic and
> user input is a very important thing, we really need to improve
> this. You may have noticed that I did not make use of either
> assert or enforce. I didn't want to specify this.
You can create a wrapper struct that includes an invariant:
import std.stdio;
struct Image
{
int width;
void doSomething()
{
}
void modifiesWidth()
{
--width;
}
}
void func(Image img)
{
struct ImgWrapper
{
Image* img;
this(ref Image img)
{
this.img = &img;
}
invariant()
{
assert(img.width == 512);
}
void opDispatch(string s)()
{
mixin("img."~s~"();");
}
}
auto wrapper = ImgWrapper(img);
wrapper.doSomething();
wrapper.modifiesWidth(); // assertion failure
}
void main()
{
Image img = { 512 };
func(img);
}
More information about the Digitalmars-d
mailing list