tupleof seems to break encapsulation

Jacob Carlborg doob at me.com
Sun Sep 6 13:02:45 UTC 2020


On 2020-09-05 07:14, 60rntogo wrote:

> I wouldn't dispute that it is useful, but that's besides the point. If I 
> declare something private, it's usually because I want to preserve 
> certain invariants and I want the compiler to provide a guarantee that I 
> don't accidentally violate them. As it stands, the compiler cannot 
> guarantee that if I use tupleof.
> 
> I don't really have an issue with read-only access to private fields 
> (but arguments could be made against it) and then serialization would 
> still be possible. However, if my struct is supposed to maintain 
> invariants, then any attempt at deserialization that naively reads from 
> a tuple without establishing these invariants should fail to compile.

I wouldn't mind if `tupleof` was not allowed in @safe code, which Walter 
mentions in one of the linked issues. Although it would be a breaking 
change.

Secondly, my serialization library, Orange [1], uses `tupleof` to read 
and write fields. It also supports before and after hooks for both 
serialization and deserialization. This allows to implement any 
invariants that are not covered by just restoring the fields. It also 
supports implementing a method that allows to take full control of the 
(de)serialization of a specific type.

Thirdly, you can do the same thing with pointer arithmetic. Although 
this is not allowed if @safe code.

[1] https://github.com/jacob-carlborg/orange

-- 
/Jacob Carlborg


More information about the Digitalmars-d-learn mailing list