How to deal with inconsistent objects due to mutation

pablosanjose
Wed, 16 Mar 2022 11:45:46 +0000
General Usage

This is a bit of a basic philosophical question about type and API design. I would love the input of more experienced coders, since I suspect I might be approaching my problem wrong.

I have a type in essence similar to:

struct Wrapper
    v::Vector{Int}
    length::Int
end

The field length should equal length(v) for consistency. This is a toy example, but in the real world length is a bunch of extra fields that should be consistent with field v. Moreover, the API requires that the user can access field v, so I have an exported vector(p::Wrapper) = p.v

The problem is that I have no way to forbid that the user does push!(vector(p), 1), which breaks the internal consistency of p. I see a number of options, all of which are very bad for performance. Is there a standard approach to deal with this problem in Julia?

20 posts - 10 participants