A development environment can often help a programmer to enter field names correctly. In the Julia REPL, when I press the Tab key twice after entering the dot character, it will try to autocomplete and display the available field names:
Now that we have implemented the getproperty and setproperty! functions, the list is no longer accurate. More specifically, the loaded field should not be displayed because it can neither be accessed nor changed. In order to fix this, we can simply extend the propertynames function, as follows:
function Base.propertynames(fc::FileContent)
return (:path, :contents)
end
The propertynames function just needs to return a tuple of valid symbols. After the function is defined, the REPL will only display the valid field names, as follows:
In this section, we have learned how to leverage Julia's property interface to control both read and write access to any field of an object. It is an essential technique to write robust programs.
For example, there is nothing that prevents the program from calling the getfield and setfield! functions directly on any object. It would not be possible to completely hide that from the programmer unless the language is updated to support granular field access controls. Such a feature may be available in the future.
Next, we will look at some patterns related to limiting the scope of variables so that we can minimize the exposure of private variables to the outside world.