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

**URL:** https://discourse.julialang.org/t/is-accessing-the-fields-of-a-struct-a-good-julia-style/23623
**Category:** General Usage
**Created:** [April 28, 2019, 5:34pm UTC](https://discourse.julialang.org/t/is-accessing-the-fields-of-a-struct-a-good-julia-style/23623 "2019-04-28T17:34:26Z")
**Posts on this page:** 1
**Showing post:** 5

<div class="post-metadata">

### Author: ![ffevotte](https://sea2.discourse-cdn.com/julialang/user_avatar/discourse.julialang.org/ffevotte/32/6587_2.png) [@ffevotte](https://discourse.julialang.org/u/ffevotte)
#### Post date: [April 28, 2019, 7:35pm UTC](https://discourse.julialang.org/t/is-accessing-the-fields-of-a-struct-a-good-julia-style/23623/5 "2019-04-28T19:35:32Z")

</div>

There have been some discussions about this here on discourse. See, for example, [Mutable struct vs closure](https://discourse.julialang.org/t/mutable-struct-vs-closure/20233), especially the part of the discussion starting with the following post:

> [@Mutable struct vs closure](https://discourse.julialang.org/t/mutable-struct-vs-closure/20233/21):
>
> Possibly, but Julia does not offer what you call traditional encapsulation, a mechanism designed to explicitly hide state (or make it difficult to access). Instead, I try to stick to the following implicit rules: only methods of the same module should modify fields of a structure, reading fields is kind of borderline, if it is needed to done frequently, it should be done with an accessor, or documented as the recommended API. If you are really paranoid, you could redefine Base.getprop…

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!)

---

_[View the full topic](https://discourse.julialang.org/t/is-accessing-the-fields-of-a-struct-a-good-julia-style/23623)._
