O.O.P in Julia

No need to make it work with object.value syntax. It’s not very Julian anyway. Personally, I hide almost all object.value calls behind a getter as it makes refactors easier later. Use a global and have a accessor function that gets/sets it. Here’s an example:

const Type1_goodness = Ref(3.0) # use Ref to make it mutable

struct Type1
    bigness::Float64
end

struct Type2
    bigness::Float64
    coolness::Float64
    goodness::Float64
end

bigness(x::Type1) = x.bigness
coolness(x::Type1) = 2.0 # hard-coded, but could also reference a global const if it makes sense
goodness(x::Type1) = Type1_goodness[] # access the global const Ref
setgoodness!(x::Type1, val) = Type1_goodness[] = val # set the global

bigness(x::Type2) = x.bigness
coolness(x::Type2) = x.coolness
goodness(x::Type2) = x.goodness
# cannot setgoodness!(::Type2, val) because it is not mutable
#  but you could make it construct a new Type2 with the new goodness and *not* mutate the original, depending on your needs

coolness(Type1(4.0)) # 2.0 - not a field but we can still get the value
coolness(Type2(5.0, 6.0, 7.0)) # 6.0 - read the field

goodness(Type1(4.0)) # 3.0 - the original default value
setgoodness!(Type1(4.0), 9.0) # 9.0 - we've set the value for all Type1 now
goodness(Type1(8.0)) # 9.0 - read the shared value
1 Like

Yep…

Question is: why not do what granddaddy (the guy with parentheses) does (right)?

That is, creating the “getter” automatically? :slight_smile:

1 Like

Consider getproperty the automatic getter. But it’s limited (yes, you can redefine getproperty but that isn’t very ergonomic). You also can’t (with .property syntax) provide additional arguments to getproperty, which you might later decide you want for certain properties.

Suppose I removed the goodness field from Type2 because I decided I wanted it to be defined by goodness(x::Type2) = bigness(x) + coolness(x). Multiple dispatch and extensibility are easy for getters but a total pain for getproperty. That’s where this pattern starts to be more useful. The larger the number of “inter-compatible” types you start to get, the more useful it is to be able to easily and orthogonally define behavior with methods rather than amending an increasingly complicated getproperty.

Obviously both approaches can work, but in my travels I’ve sometimes regretted relying on getproperty but never getters.

3 Likes

Weeeellll

(defstruct type-1 bigness)
(defstruct (type-2 (:include type-2)) coolness goodness)

Do TRT (granddaddy knows a few things). I really, really wish Julia did TRT as well. :slight_smile:

MA

1 Like