On 03/31/12 10:35, Daniel H wrote:
> if you have a derived type with many private variables, how would you write 'getter and setter methods' for them?
You can write a script that takes your structure definition and generates the Fortran module that defines the structure,
as well as the get/set methods. I've discovered that a lot of that stuff (im my case, at least) is boilerplate and well
suited to a script-code-generation approach.
I am in the midst of doing so using ruby to parse an XML version of my Fortran95/2003 structure definition and spitting
out a module that includes creation/destruction/inspection/get-set-property procedures, as well as I/O procedures so I
can dump objects to file (e.g. if I need to stop a calculation) and then read it in at a later time to continue on from
where I left off.
I had to use a script approach because I can't help tinkering with code... ehem, I mean refactoring... and I'm always
changing the names of existing structure components, or deleting them entirely, or adding new ones, etc. I want to be
able to change just the structure definition, then run my script to get my new/updated module.
The downside is that it's a fair amount of work to make it general purpose. Fun though.
> I am
> thinking in terms of readability, maintainability, efficiency, etc. Here an example, which might be particularly
> inefficient (but I don't know). Thanks in advance.
> module example
> implicit none
> type manyvars
> real :: var1, var2 ! and many more
> integer :: ivar1, ivar2 ! and many more
> procedure :: set => set_real, set_integer
> procedure :: get => get_real, get_integer
> end type manyvars
> pure real function get_real(this, name) result(result)
> type(manyvars), intent(in) :: this
> character(len=*), intent(in) :: name
> select case(name)
> case ('var1')
> case ('var2')
> end select
> end function get_real
> ! ...
> ! analogous for get_integer, etc.
> ! omitted
> end module example