2 ms·
I think the rule they present might be mostly related to the fact that they're using Rust. The combination of using structs that can be constructed from literal
by saghm 4y ago
I think the rule they present might be mostly related to the fact that they're using Rust. The combination of using structs that can be constructed from literals rather than objects (compared to Java with objects being created by constructors), having field-specific visibility on struct fields (compared to C with visibility being determined by the header file), and requiring all fields to have values specialized when constructed (compared to Go, which will implicitly initialize missing fields to the zero-value for the type) means that having mixed visibility for struct fields in Rust leaves you with the sometimes surprising behavior where you can access fields directly but run into errors when you try to create a struct by specifying all those fields. I think this rule of thumb is basically a modified version of the "use getters/setters instead of public fields" rule of thumb in Java but with an exception for fully transparent structs. It might be a bit too dogmatic to require all the time, but I think it has some merit in terms of API hygiene. If I don't want users to be able to manually construct instances of my struct, then allowing them to manually set some of the fields often might be an anti-pattern, since I presumably prevent manual construction to ensure some invariant over the fields of the struct. Enforcing this rule makes sure that you think twice about allowing arbitrary mutation over only a subset of a struct (which could lead to false assumptions about the internal state of a struct) while still giving you a fairly easy workaround if you do in fact need this (by just implementing getter/setter methods).