Implementing getter functions

In mainstream object-oriented languages, we often implement getters for accessing the fields of an object. In Julia, we can also create getter functions. When implementing getter functions, we can choose which fields to expose as part of the application programming interface (API). For our example, we will implement getter functions for both fields, as follows:

get_heatmap(s::Simulation) = s.heatmap
get_stats(s::Simulation) = s.stats

Our choice of function names here is somewhat non-idiomatic for the Julia language. A better convention is to use the nouns directly:

heatmap(s::Simulation) = s.heatmap
stats(s::Simulation) = s.stats

So, when we read the code that uses the heatmap function, we can read it as the heatmap of the simulation. Likewise, we can read it as the statistics of the simulation when the stats function is used.

These getter functions serve the purpose of defining a formal data retrieval interface for the object. If we ever need to change the names (or even the types) of the underlying fields, it would be fine as long as the public interface does not change. Furthermore, we could even remove the stats field and implement the statistical calculation directly in the stats function. Backward compatibility can now be easily maintained for any program that uses this object.

Next, we will look at write access for objects.

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

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