I am new to Julia and object-oriented programming. I am used to the following practice
function compare_sizes(x,y)
length(x) == length(y) ? "good to go" : error(DimensionMismatch)
end
Now, in object-oriented programming, I want to achieve similar behavior. I naively tried the following
struct Pair
x
y
length(x) == length(y) ? new(x, y) : error(DimensionMismatch)
end
# ERROR: UndefVarError: x not defined
Okay, I think I understand why this happened. After looking up for a couple of hours, I found these threads.
/t/doing-trivial-transformations-and-assertions-inside-a-struct-definition/61054
https://stackoverflow.com/questions/67430487/julia-how-to-use-the-assert-macro-with-a-struct-with-kw-vs-base-kwdef
/t/struct-with-fixed-array-sizes/15396
This led me to read through inner-constructors.
Now I understand that I can achieve what I want by doing the following
struct Pair
x
y
Pair(x, y) = length(x) == length(y) ? new(x, y) : error(DimensionMismatch)
end
A fancier version would be
using StaticArrays
struct SPair{L}
x::SVector{L, Number}
y::SVector{L, Number}
end
SPair(x, y) = length(x) == length(y) ? SPair{length(x)}(x, y) : error(DimensionMismatch)
Also, the documentation says
It is good practice to provide as few inner constructor methods as possible: only those taking all arguments explicitly and enforcing essential error checking and transformation.
However, my question is, how do I make this scale robustly with more properties and checks? Writing inner-constructors with all the arguments multiple times is not a good way; it feels like copy-pasting.
My urge was to go towards metaprogramming, to create error checking inner-constructors. I am aware of this /t/how-to-warn-new-users-away-from-metaprogramming/35022/3
.
Thank you!
P.S. the strings starting with /t/
are links to julialang discourse threads. I didn’t know how to post more than 2 links.