Skip to content

Getter and setter procedures for derived types #30

Open
@cmacmackin

Description

@cmacmackin

Some languages such as Python and C# allow the definition of special getter and setter methods. Although these are methods, syntactically they allow the client code to behave as though the represent a public component of the class. This has the following advantages:

  • more compact syntax
  • ability to refactor which type components are public without breaking API

The latter, in particular, is important. It means that a type component can be left public (or protected, if #16 is accepted) without fear of having to break the API when refactoring. This would save the developer from having to manually implement getter and setter routines and reduce the amount of boiler-plate code.

I propose the following syntax:

type example_type
  ! ...
contains
  get :: foo => get_foo
  set :: foo => set_foo
end type

The getters and setters could have permissions just like a type-bound procedure, but given the use-case presumably we'd just want them to always be public. The interface for the getters and setters would be

pure function get_interface(this) result(component)
  class(...), intent(in) :: this
  type(...) [, (pointer | allocatable | dimension | ...)*] :: component
end function

elemental subroutine set_interface(this, value)
  class(...), intent(inout) :: this
  type(...), intent(in) [, (pointer | allocatable | dimension | ...)*] :: value
end subroutine

Client code could then call the getter and setter as follows:

type(example_type) :: bar
integer :: val
val = bar%foo ! invokes getter
bar%foo = val * 2 ! invokes setter

Metadata

Metadata

Assignees

No one assigned

    Labels

    Clause 7Standard Clause 7: Types

    Type

    No type

    Projects

    No projects

    Milestone

    No milestone

    Relationships

    None yet

    Development

    No branches or pull requests

    Issue actions