🎓 A1Learner
🔍
0 of 47 lessons completed

Julia Abstract Design

Abstract design is building code around a general type that stands for a whole family of related types. Functions written once against the general type work for every member of the family.

Members of one family get their own area rules

The circle and the square are members of the same family. Each member computes its area in its own way.

abstract type Shape end
struct Circle <: Shape
    r::Float64
end
struct Square <: Shape
    s::Float64
end
area(c::Circle) = 3.141592653589793 * c.r * c.r
area(s::Square) = s.s * s.s
println(round(area(Circle(2.0)), digits=6))
println(area(Square(3.0)))

One shared function serves both members

The shared function takes the general type. Both members get the same answer from it.

abstract type Shape end
struct Circle <: Shape
    r::Float64
end
struct Square <: Shape
    s::Float64
end
describe(sh::Shape) = "a shape"
println(describe(Circle(1.0)))
println(describe(Square(1.0)))

A new member needs no change to the shared function

The triangle joins the family after the shared function exists. The shared function already covers it.

abstract type Shape end
struct Triangle <: Shape
    b::Float64
    h::Float64
end
describe(sh::Shape) = "a shape"
area(t::Triangle) = 0.5 * t.b * t.h
println(describe(Triangle(4.0, 3.0)))
println(area(Triangle(4.0, 3.0)))

Example

abstract type Shape end
struct Circle <: Shape
    r::Float64
end
struct Square <: Shape
    s::Float64
end
area(c::Circle) = 3.141592653589793 * c.r * c.r
area(s::Square) = s.s * s.s
shapes = Shape[Circle(1.0), Square(2.0)]
println(length(shapes))
println(round(sum(area(s) for s in shapes), digits=6))

Key points

  • Abstract type: a type that names a family but never holds a value itself.
  • Concrete member: a struct under the general type that holds real values.
  • Shared function: a function written once against the general type for every member.
  • Use one function against the general type to serve every member type.
  • Extension: adding a new member type needs no change to the shared function.

In this example, the circle and the square are members of one family. The collection holds both members under the general type. The total area adds the circle area and the square area.

Note

only concrete types hold values, so a general type is never built directly.

Try it Yourself

Edit the code, then press Run.

Running is simulated · JuliaHub

Exercise

Which of these can hold a real value?