Consider the following contrived example:
Suppose I wanted to implement my own custom Weight
types and let’s say that some of them can be converted to standard units (pounds, kilograms, etc.) while others (for some strange reason) are not convertible to other units at all. What’s the recommended way to define the types in this scenario? I could define a Weight
type that has an isconvertible
field and then in my convert_to(w::Weight, units)
function just check to see if it’s convertible, throwing an Error if not.
struct Weight
value::Real
isconvertible::Bool
end
function convert_to(w::Weight, units)
w.isconvertible == false && throw(ArgumentError("Sorry, this weight is not convertible to other units"))
end
Or, I could just define Weight
as an abstract type and then have ConvertibleWeight
and NonConvertibleWeight
as subtypes. Is there a preferred/recommended way to deal with this kind of situation?