Functional behavior

The reason to have a hierarchy is to create an abstraction about common behaviors for types. For example, the Apartment and House types have the same supertype, Property. This is intentional because they both represent some kind of physical dwelling at a certain location. So, we can define a function for any Property as follows:

"""
location(p::Property)

Returns the location of the property as a tuple of (latitude, longitude).
"""
location(p::Property) = error("Location is not defined in the concrete type")

You may ask, What have we done? We have just implemented a function that does nothing but return an error! Well, believe it or not, defining this function actually serves several purposes:

  • It makes it clear that any concrete subtype of Property must implement the location function.
  • At runtime, if the location function is not defined for the respective concrete type, then this particular function will be called and a reasonable error will be thrown so that the programmer can correct the bug.
  • The document string right above the function definition contains a useful description that concrete subtypes of Property should implement.

Alternatively, we can define an empty function instead:

"""
location(p::Property)

Returns the location of the property as a tuple of (latitude, longitude).
"""
function location(p::Property) end

What is the difference between an empty function and one that throws an error? For this empty function, there will be no runtime error if the concrete type does not implement this function.

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

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