Quiz 1.10: Inheritance and composition


Q1: Inheritance and call dispatch

Given the following code snippet:

abstract type Foo end
struct Aaa <: Foo end
struct Bbb <: Foo end
struct Ccc end
foo(x::Foo) = println("Hello")
foo(x::Aaa) = println("Good day!")
foo(x)      = print("Welcome!")

Match the following commands with their corresponding outputs.

foo(Foo())

foo(Aaa())

foo(Bbb())

foo(Ccc())

RESOLUTION

We can't initialise an object from an abstract type, so foo(Foo()) raises an error. The other calls follow the rule that the method dispatched is the one stricted (more restrictive, in terms of parameters types) for which there is a match.

The correct matches are:

  • foo(Foo()) -> Error
  • foo(Aaa()) -> "Good Day"
  • foo(Bbb()) -> "Hello"
  • foo(Ccc()) -> "Welcome!"

Q2: Composition

Given the following code snippet:

struct Address
  road
  city
  country
end
struct CompanyData
  name
  address::Address
  revenues
end
struct Farm
  cData::CompanyData
  agrArea
  livUnits
end

Which of the following sentences are correct ?

RESOLUTION

The design principle used in the code is composition and it has several advantages over inheritance. The default constructor leads to very verbose syntax, but this could be largely simplified by writing a custom constructor. To access the fields of our object we can use the dot notation (eventually chained) or explicitly call getField(obj,:fieldName). The answer uses a useful package that extends the default pipe operator of Julia.

The correct answers are:

  • The snippet emploies a composition design principle
  • To build a Farm object I can use the constructor call Farm(CompanyData("Future Farm",Address("Road of farms","Smalltown","Joyland"),10000),100,0)
  • I can simplify the creation of objects by implementing a custom constructor
  • To access the country of farm farmABC we can use the syntax farmABC.cData.address.country
  • To access the country of farm farmABC we can use @pipe getfield(aFarm,:cData) |> getfield(_,:address) |> getfield(_,:country) provided the package Pipe is installed and loaded