Mutable struct vs closure

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:

  1. only methods of the same module should modify fields of a structure,

  2. 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.getproperty(::MyObject, _) = error("no access to fields")

or similar. But you always have Base.getfield to circumvent this. There is really no way to protect people if they want to do something stupid.

2 Likes