Say I have 2 related types (previously seen in a 2016 thread with a similar topic):
struct Student
age::Int
name::AbstractString
grade::Real
function Student(a, n, g)
0 < a < 120 || error("age must be in the range 0-120")
0 < g < 5 || error("grade must be in the range 0-5")
new(a, n, g)
end
end
struct Employee
age::Int
name::AbstractString
salary::Int
function Employee(a, n, s)
0 < a < 120 || error("age must be in the range 0-120")
s > 20000 || error("salary is below minimum")
new(a, n, s)
end
end
(yes, this example is contrived)
These types share members and some functionality. Obviously, I would want to reuse both.
Is this the best way to re-write this code?
struct PersonData
age::Int
name::AbstractString
function PersonData(a, n)
0 < a < 120 || error("age must be in the range 0-120")
new(a,n)
end
end
age(pd::PersonData) = pd.age
#...
struct Student
pd::PersonData
grade::Real
function Student(a, n, g)
0 < g < 5 || error("grade must be in the range 0-5")
new(PersonData(a,n),g)
end
end
age(s::Student) = age(s.pd)
#...
struct Employee
pd::PersonData
salary::Int
function Employee(a, n, s)
s > 20000 || error("salary is below minimum")
new(PersonData(a, n), s)
end
end
age(e::Employee) = age(e.pd)
#...