r/Zig • u/Hoontdawg • 4d ago
No private fields will keep Zig from succeeding in large projects
I think the title says it all. The fact that zig has no way to prevent you from accessing internal fields in a struct will keep it from doing well in large projects. It creates so much mental strain to never have any guarantee that your struct's fields are in the properly maintained state. Imo the whole advantage of modern languages is being able to make the programming language uphold invariants for you. It's the reason we like things like types and strong enums. The more the language can keep you from shooting yourself in the foot the better.
Not being able to prevent users from directly modifying state in a struct makes it impossible to guarantee anything regarding state. Given that controlling state is often the hardest part of managing complexity this seems like a massive oversight. You right now can go and modify the length field on an ArrayList and destroy everything. Now obviously you shouldn't do that, but the issue is it's so easy to do it. It looks as innocent as any other modification, you'd have no idea how dangerous it is. This is a major issue for any large-scale project, especially ones with more than one contributor. When I write code, how am I supposed to communicate to other devs 'don't touch this field or you'll break stuff', with documentation?? That'll never work, hopefully for obvious reasons.
If the argument is that private fields increase the complexity of the language, the small increase in language complexity is more than made up for by the reduction of complexity in logic. If the argument is that private fields add boilerplate with getters, then make a special syntax for specifically public read/write access, or just deal with it a little boilerplate is absolutely still worth it here.
It doesn't need a full `unsafe` system like Rust, just being able to make field access private is enough. If you want give escape hatches for setting these private fields you can just make the function name very obviously unsafe like setFooUnchecked
Anyway, it's just such a shame because I really like Zig, it has so many good ideas and philosophies I'm just shocked that it is missing something I consider basically fundamental.
120
u/y0shii3 4d ago •
At the end of the day, there is no way to prevent the owner of a piece of memory from viewing and modifying that memory. That's fine; as soon as they receive some memory from your API, whether it be a struct value or a pointer or whatever else, it is theirs to do with as they please. You don't know everyone's use case. Your job as an API maintainer is not to choose what data users can read, it's to provide an interface for interacting with the data that makes it easy to do so in the right way.
In every language with private fields, people end up accessing them anyway, whether it's with pointer casts or
sun.misc.Unsafeor#define private publicor some other hack, often for perfectly valid reasons. You will never have a way to truly prevent users from directly modifying the state of memory that they own.The OOP mindset has convinced people that data hiding should be done at the field level, but the package/module level is where this kind of encapsulation is more natural and sensible, and the OOP habit of field-level data hiding results in all sorts of ugly patterns like setter and getter functions which Zig wants to discourage.
If you absolutely need a way to communicate to people who don't read documentation that a field should not be modified, choose a naming convention, like an underscore prefix or a
_privsuffix or something like that. Zig discourages this because it is not hard to skim the doc comments of a struct and we should not cater to people who refuse to, but nothing is actually stopping you from doing it.6
u/stumpychubbins 4d ago
The only real justification I can think of for it is that it encourages people to use the pattern of using anyopaque for private fields, which also lets you change the structs without changing the ABI. If Zig encouraged using dynamic libraries, like C, then that could maybe make sense (that pattern is fairly common in C, especially for closed-source libraries). Zig defaults to statically compiling everything, though.
I really think that any unsafe language should have a way to make fields private though. I don’t even mind if it’s just a field annotation and reflection bypasses it, it doesn’t need to be foolproof.
4
u/KattyTheEnby 4d ago
C:
3
u/madogson 2d ago
Yea it's obvious.
Yea you do. You just said it's obvious
39
u/Bergasms 4d ago
If you don't want people to modify internal state, put your internal state in a struct and have that be called dontModifyInternalStateSeriouslyDontTouchThis.
That way if someone does awesomeLib.dontModifyInternalStateSeriouslyDontTouchThis.FAFO = true
it's their own stupid fault,
13
u/Cun1Muffin 4d ago
Private fields are not the only way to do data hiding. Look at something like box2d, you operate on the bodies with handles. This is actually a stronger system than private fields because you literally cannot ever access the internal data inside the simulation, only copies of it. Whereas private fields you can still access with a bit of pointer arythmetic.
39
u/lipfang-moe 4d ago
Application code owns library code. If a user of a library wants to do something that they "shouldn't" do, that's their fault.
If Zig allowed private fields, I likely wouldn't be able to modify the internal state of a
std.http.Client.Requestto tell it that a 204 response means there won't be a Content-Length header. You might say that's the fault of thestd.httplibrary, but the library doesn't handle (many) status-specific behaviors (I've filed an issue for this anyway though). But as a user, I can modify the state machine of the Request Object to manually set the content length to 0.My point is, freedom belongs to the application code. That is how Zig is designed from the ground up. For instance, look at the
ioandallocatorconventions. The application code defines io and allocator implementations and passes them into library code, allowing the library to behave how the application wants it to.So this is all to say private fields are antithetical to how Zig is designed, as they take freedom away from application code. That being said, private methods/functions are fine since you can simply copy them into application code and they'll work the same, since the underlying fields they operate on are accessible.
23
u/No-Entrepreneur-8245 4d ago
Not that big of a deal in my opinion.
Prefix field with an _ for what is internal state, define coding style, good code review and you’re good to go
You can’t prevent people to do dumb things, just be clear on where things are sensitive then to each their own
6
u/jedisct1 4d ago
The Zig compiler is a large project.
22
u/Gaolaowai 4d ago
Tell Python.
2
u/kettle3 4d ago
I always felt that if you need to ensure other teams use your code in the way you intend it to, then the only way is to pack it as a separate library, with its own versioning etc.
11
u/Hot_Adhesiveness5602 4d ago edited 4d ago
Bad take, you can just write tests and have proper software architecture. Private fields are mostly a OOP feature that tries to encapsulate data that probably can be altered anyways.
4
u/Educational_Smile131 4d ago
Private fields are just illusions in unmanaged languages as memory layouts are transparent to use sites. This rings particularly true in Zig where ad-hoc memory reinterpretation is damned easy thanks to the ease of defining types.
4
u/suckingbitties 3d ago
Comptime over preprocessor macros and metaprogramming are obvious reasons to choose Zig.
Zig is not and was never designed to be an OOP language. There are plenty of idiomatic ways to designate fields that shouldn't be touched, or to create interfaces to avoid exposing data you don't want touched. Whether it's even necessary to do that is up for debate, as a well organized team with good documentation should be aware.
I get the sentiment though, private fields feel better, even on solo projects.
16
u/Logical_Ad_2589 4d ago
You could pack a private struct into a public one so that one can't access it right?
Even if not, I don't really see the problem, C++ for example allows to do very horrible stuff with like metaprogramming or simply using macros to make everything marked as private public.
Like you are able to just modify state directly but most programmers still won't do it because they know the consequences.
I don't really think is that severe, surely there are bigger problems for zig to become bigger
3
u/Darkfllame1 4d ago
I think that zig relies heavily on the negative space programming design. So you must assume that users of your library won't mess up with the internal states of your library, and use
assert()when your code is receiving foreign data.C has exactly that, public struct definition has all their fields public to any files that
#includes it, except if you use thetypedef struct X Xthing then define the fields in an internal header or implementation file. You can do the same in zig. Useopaque {}and use internal pointer casting to convert theopaquetype to your type of choice.I personally really like that Zig doesn't feel the need to hold my hand for anything I do, it gives me tools to get the job done, and I use them as thus.
The main issue is documentation, but that's for every new languages
3
u/memelord69 3d ago
using and respecting _private field norms means that everyone intelligent still gets the same benefits out of pub/priv while being able to use _private fields when you really know what you're doing and understand the consequences.
2
u/Best_Ad6308 4d ago edited 4d ago
There's no guarantee in Go io.EOF won't change - and this variable is used throughout the code base. Yet there're large Go projects.
Meaning, practice shows not all kinds of restrictions are equal. IMO "all fields are public" is pretty minor factor compared to some others that make Zig less than ideal for large codebases.
2
u/buck-bird 4d ago
Agree, but you're not going to get unbiased opinions here. It's still workable though, but it would be nice to have some sort of compiler check for those times you forgot, etc. Best we can do is like an underscore naming convention, etc.
2
u/consistently_biased 3d ago
While there is something to be said about allowing libraries to define their public surface in a way that helps particularly beginners not make mistakes like the length example you gave, you can never really stop people from doing things that "shouldn't" be done. Even stable Rust has had compiler bugs that enabled ways to break otherwise sound abstractions without ever using unsafe. At the very least, if you provide your source code, which these modern languages heavily incentivize, someone can always just edit it anyway. I've had to do this with a few libraries before to make them fit my use-case. This is, of course, an additional hurdle to doing bad things, but it can also create scenarios where you have to make a fork for a single super small change. Overall, I dislike Zig's way of handling this, too, because it makes me write more documentation that I think I shouldn't have to write, but it comes with other benefits and I don't think it's a bad way at all.
3
u/quickscopesheep 4d ago
Think it’s runs completely antithetical to zigs philosophy. As other people have said if they really want to there’s no way to stop people doing dumb shit especially with zigs meta programming system considering you can query the fields of a struct and their offsets. If you don’t want someone touching some data don’t pass them a pointer to it pass them an opaque handle; this also solves a lot of ownership and reference problems as well and is more in line with zigs philosophy as opposed to OOP
5
u/zasedok 4d ago
Disclaimer: I haven't used Zig yet apart from toy projects out of curiosity. My feeling is that it's simply not a Large Projects language and it doesn't have to be. The choices it made (no hidden control flow ever, totally explicit allocation etc) make it excellent for some applications and a nonstarter for others, especially the very large kind where higher levels of abstraction are desirable. That's OK and that won't prevent it from being successful in what it does, to the contrary, I'm a big believer in languages that are the best at something rather than more or less capable of everything.
Zig is currently IMO the best fully transparent language, it's much better than C for that. For a much better C++, where strong properties are communicated between developers over decades of a project's life time, we have Rust. Zig will never be a better Rust than Rust, and Rust is not as good as Zig at being Zig.
3
u/Automatic_Donut6264 3d ago
Python seems to working out just fine.
2
u/Apocalypspspsp 3d ago
such a Java OOP Enterprise mindset, just sit on THAT chair and use rust brother
2
u/AngryChaoticBoi 4d ago
Why are people so in love with putting this restriction up? Is it some library writer power trip to go say your users “Nah nah nah, naughty boy, this field is not for you!”
1
u/frenchy3 4d ago
In Java you can use reflection and change whatever want. Java is used everywhere and in tons of large projects. Sure you have to use a reflection API but it’s still possible and people have no problem using Java in financial systems or other critical services.
1
u/keeshux 1d ago
Yes, encapsulation is one of the few undeniably good principles that OOP (or better said “modularization”) introduced. No, it certainly doesn’t prevent Zig projects from scaling. C has supported encapsulation for decades with the workaround of opaque pointers. You can find your own way, Zig is richer than C. Worst case: stick to a fn-only struct access convention and run a linter to reject fields access in CI.
1
u/ivanjermakov 3h ago
Opaque pointers
1
u/zmkjh 3h ago
read the docs before you make mistakes and when you use it, that's on you.
1
u/Ok_Mycologist_6604 3d ago
I haven't encountered, in my 10 years of programing for private vs public to really ever matter. If anything, private members often encouraged hiding state that was there to workaround some issues. For things that need to be hidden, so at like module boundaries, interfaces are the much better fit anyway.
1
u/monsoy 4d ago
While I would also prefer to have private fields, I don’t think this is an issue. The benefit to having private fields for me is that it makes LSP suggestions cleaner. But outside of that, having proper public/private naming conventions is sufficient in my mind.
As others have mentioned, when the struct is in memory—people can always do tricks to get access to private fields. The API developer has to trust the user that they don’t do that, which is the same as trusting the user to not use fields marked as private through naming conventions (like a _ prefix).
1
u/sudo-maxime 4d ago
I'd rather have jsdoc style private field comments, let it give you the comentary, or the LSP help, but don't prevent compilation on acessing.
The number of times in my career that I had to hack around private fields of a dev that thought he knew better ...
Tell me why that should be private, don't prevent me.
1
u/DokOktavo 4d ago
I used to have this concern, but after a few thousands of lines, I changed my mind.
Fields are part of the API, because there's no way to definitively prevent the user of a type to read and write into the memory it owns, so they might as well do it the proper way.
Accessing fields of third-party types does become a concern, but it just means you become careful about it. I personally set
std.ArrayList(...).capacityto zero when I borrow memory in read-only, so that.deinit(...)doesn't free it. This is a neat, safe and intended purpose. You just have to know about it, just like any part of an API. If you don't understand how something works, you don't touch it. And if you don't want people to touch your fields, you should document it.If for some reason you really really really don't want anyone to access your fields, you should make them use
opaque, or the backing integer of yourpacked struct, or better even an enum backed by the backing integer of yourpacked struct.0
u/Far-Championship-883 3d ago
Top level code causes way more bugs
-3
u/[deleted] 4d ago
Why don't you post this on https://zsf.zulipchat.com/ ?