by haberman · 3y ago · 0 comments
This feels like a mistake to me. I own and maintain a C library, and lack of private struct members is one of the things that causes the most problems. My users frequently reach into struct members even though I really do not want them to. This causes problems when those members have subtly different semantics than what they expect. It's even worse when I want to change the internal representation, and I have to track down all my users' code and change it accordingly.
In C, my only options are:
(1) Define the structure in a .c file instead of .h. This works great in cases where I can take the performance hit of not being able to inline accesses of those struct members. But for performance-critical structures where I need to be able to inline, this is not an option.
(2) Make the member names something like private_foo, internal_foo, etc. and hope my users take the hint. But this also makes my own code more ugly and creates longer lines that are more likely to wrap.
Unfortunately Zig is even less capable than C in this regard, because Zig takes away option (1). Since there is no header/source split in Zig, I cannot make a struct opaque by defining it in a source file only. Though I do see that there is "opaque {}", perhaps that plus some casting could accomplish a similar thing?
I see that rationale for not having private struct members was given here: https://github.com/ziglang/zig/issues/9909#issuecomment-9426...
> The idea of private fields and getter/setter methods was popularized by Java, but it is an anti-pattern. Fields are there; they exist. They are the data that underpins any abstraction. My recommendation is to name fields carefully and leave them as part of the public API, carefully documenting what they do. [...] In my subjective experience, public fields generally lead to better abstractions by eliminating the temptation to attempt full encapsulation, when the more effective strategy is to provide composable abstraction layers.
Java does indeed represent an anti-pattern of verbose and frequently trivial getters and setters. But newer languages like C#, Swift, and Dart have more elegant and low-overhead syntax for properties, even allowing a property to move between being an actual field member and being derived, without breaking users.
As a library maintainer, full encapsulation is very important for evolution of a system over time. The only way for layers to truly be layers is if the contract at each layer boundary is clear. Otherwise the layers gel together and you cannot safely change any one layer independently.
Something like so:
/// The internal implementation of this type.
const PrivateType = struct {
// Private fields.
field_a: u32,
field_b: bool,
// Public object exposed
public: PublicType,
// private functions here.
}
/// This gets exposed to the public API
pub const PublicType = struct {
// Public fields.
field_a: u32,
// Public functions here.
pub fn create(alloc: Allocator) !*PublicType {
var priv = try alloc.create(PrivateType);
return &priv.public;
}
/// Flips internal field b.
pub fn flip(p: *PublicType) void {
// Grabs the PrivateType that contains this PublicType as a field.
const self = @fieldParentPtr(PrivateType, "public", p);
self.*.field_b = !self.*.field_b;
}
}The purpose of this was to eliminate the need for "friend" classes.
This sometimes conflicts with what people coming from C and C++ are used to with everything being in one file (after headers are added by the preprocessor). But having modules gives opportunities for better ways to organize the code.
As for trivial property accessors and setters, those get inlined, so are not overhead.
Other languages would call these "internal", not "private".
It's not an anti-pattern.
This is how Java provides the exact functionality that you describe as very important (field encapsulation). Because Java doesn't support properties, it needs to go through getters and setters.
As you point out, more modern languages support this functionality directly in the language with properties.
Properties help avoid this anti-pattern by making it possible to transparently swap in a computed property for what used to be a plain field. This removes the incentive to proactively create trivial getters and setters "just in case."
Something has indeed gone wrong. The struct has succumbed to being a "kitchen sink".
Although there's some serious meat in a few places (e.g the growth amortization and associated mechanisms) many of the methods defined for these types are trivial.
In C++ they don't look trivial because of layers of pre-processor cruft, terrible lack of language hygiene, and the perverse insistence that today's code should compile correctly with a compiler that's as old as Shrek (the movie that is).
But they are, ultimately, still trivial, even if writing a *= 2; takes sixteen lines of macros and a dozen structure tricks to ensure that compiler doesn't think we meant the global variable a, or the structural type a, or the function named a, or a dozen other things we couldn't possibly know about because this language is very, very stupid.
Here's Vec's implementation of a commonly used method:
pub fn is_empty(&self) -> bool {
self.len() == 0
}
Here's Zig's implementation of another commonly used method: pub fn pop(self: *Self) T {
const val = self.items[self.items.len - 1];
self.items.len -= 1;
return val;
}
I expect if I poke around in D I'll find similar, although the last time I did that I found a bug, and the experience wasn't fun so I think I'll pass.Java's getters and setters *are* properties. Just with more syntactic sugar than languages that natively support properties, but the semantic is exactly the same.
if as a library writer you don't want me to access your private struct layout and as a user I want to, I promise there is absolutely nothing that I won't try, from casting to bytes and working there, passing things from / to DLL writtens in C, to running your program in a VM, etc. So why try to fight this fight? Just tell your users that go outside of the sanctioned route that you won't help them just like a car manufacturer won't help you hack into their engine but you still can and should be able to if you want to
Like the default is the compiler will throw a warning if you access a private field with a default reference.
So things like this works but the compiler bitches.
printf("what hell is bar doing %i", foo.bar); // throws a warning 'bar is private'
But you can have a reference that's all in for api functions.And also a reference that will throw a warning for any attempt access fields. The idea being it's a pure handle.
And, there are valid reasons for a library writer to want to warn people off using certain fields, but still have them in-structure. Work-in-progress, internal machinery that the writer may wish to refactor at their leisure, whatever.
You could write that warning up in the documentation, but it's probably better as a structural affordance in the code, because then it's not just enforceable, but also lends itself to automation.
Readers should have realistic expectations. It's not substantially downhill to write C like code. I ran into this bug right off the bat. TL/DL: Zig's linker does not pull in dynamic libs. It finds static libs but alas the .tsk doesn't give expected behavior anyway:
https://github.com/ziglang/zig/issues/14939
A. Kelly (head Zig dev), to his credit, seems to already be on top of in this through a related bug:
https://github.com/ziglang/zig/issues/14963
I didn't expect to run into link problems on day 1.
That seems similar to using "opaque {}", if I am understanding you correctly?
I think either of those solutions could potentially work, at the cost of one explicit cast in each function that actually needs to access the data. I would love to know if this works well enough in practice.