An accessor method is a focused function for reading or updating one property of a structured value. Accessor functions can retrieve tuple or array fields, while setter methods update state and can enforce rules before assignment. section 4.9 section 8.2
Good accessors make structured data easier to process and safer to modify:
- Define small, ordinary functions such as name, portion, and price instead of repeating positional indexing throughout the program. section 4.9
- Use getter accessors with higher-order operations such as map to extract a property from every record. section 4.9
- Make setters validate proposed changes and throw DomainError when an update would violate an invariant. section 8.2
Pizza records and a tank setter
For pizza records, name(pizza) = pizza[1] and price(pizza) = pizza[3] hide positional details behind meaningful functions. For a tank, propellant!(tank, amount) assigns the new amount only when 0 <= amount + drymass(tank) <= totalmass(tank); otherwise it throws DomainError. section 4.9 section 8.2
Listing 8.7 Propellant setter maintaining the tank invariant
function propellant!(tank::Tank, amount::Real)
if 0 <= amount + drymass(tank) <= totalmass(tank) #1
tank.propellant = amount
else
msg = "Propellant mass plus dry mass must be less than total mass"
throw(DomainError(amount, msg)) #2
end
end
Inspect the setter implementation to see validation, assignment, and exception handling in one compact Julia example. section 8.2












