Is accessing the fields of a struct a good julia-style?

There have been some discussions about this here on discourse. See, for example, Mutable struct vs closure, especially the part of the discussion starting with the following post:

I’m under the impression that there is a weak consensus that defining accessor functions in the public API of your module is rather better style. But there is also a lot of code (including some parts of the standard library) which exposes internal fields in the user documentation, without it causing much trouble to anybody (and indeed, clever uses of getproperty/setproperty! make this rather future-proof as demonstrated above). So I don’t think there is (yet) a strong and universally shared opinion on this.


If it were me, I think I would go for accessor methods. Or even better, since the type in question is not POD, I would perhaps not worry much about accessing the internal fields of the structure (data and ptrs), and rather try to expose a meaningful API, which allows manipulating this structure in the most relevant way: maybe define getindex/setindex! methods for it to be indexable like an array, maybe in conjunction with eachindex in order to get a list of valid indices. Or an iterate method to iterate over the values in it. In short, with the correct API, maybe the client code does not need to access the data field (or even know it exists!)

6 Likes