Description
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