Discouraging direct field access

While getter and setter functions are convenient, it is easy to forget about these functions and so the program ends up accessing the fields directly. That would be too bad, as we have just spent all that effort creating getter and setter functions and they end up getting bypassed.

A possible solution is to discourage direct field access by renaming the fields to something that looks obviously private. A common convention is to prepend the field names with underscores.

For our example, we can redefine the struct as follows:

mutable struct Simulation{N}
_heatmap::Array{Float64, N}
_stats::NamedTuple{(:mean, :std)}
end

These oddly named fields will then only be used within the implementation of the Simulation type, and all external usages will avoid them. Such a convention discourages the programmer from making the mistake of accessing the fields directly.

However, some of us may not be very satisfied with this solution because the use of a coding convention is a very weak method for enforcing the proper use of the programming interface. Such concern is very valid especially when we hold ourselves to a higher standard of software robustness. So, in the next section, we will explore a stronger technique that will allow us to control access programmatically.

..................Content has been hidden....................

You can't read the all page of ebook, please click here login for view all page.
Reset
13.58.39.23