liveBook · Manning

Accessor method

As explained in Julia as a Second Language

A setter method is a method that assigns or updates a property of an object or structured value.

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

How Julia as a Second Language covers it

How deep it goes
Explains ordinary accessor functions, indexing, higher-order use, validation, assignment, and DomainError handling.
Examples
Uses pizza sales records, map(name, sales), and a propellant setter for a rocket tank.
What it assumes
Assumes familiarity with Julia functions, indexing, tuples, arrays, and composite-object construction.
What you can do after
Apply it via Julia functions to read fields and reject invalid state changes with DomainError.
How it connects
Connects accessor methods with tuples, arrays, map, composite objects, invariants, and exceptions.

Also explained in

Compare how 13 books explain accessor method →

Related concepts

This explainer was generated by Manning's knowledge graph from the text of Julia as a Second Language. The section links point to the parts of the book it draws on.