Reputation: 427
Some of my fortran subroutines have a gigantic amount of inputs passed to them, sometimes even 30 or 40. The reason for this is twofold, first, those subroutines have many clearly directly related subroutines which need some of those variables as input, and second, to avoid defining global variables, and the solution for this seems to be to pass every variable to a subroutine explicitly every time.
This seems unacceptable to me, but I don't really have a solution for it, and I am not 100% sure that it is a problem in the first place, perhaps this is the right way to do things in this language.
My question is then: is this a problem? If it is, is there a better way to manage scope in this language, without necessarily introducing objects?
Upvotes: 2
Views: 499
Reputation: 60008
I can see why the designers want to avoid global variables. I have to work with a code that took the opposite approach, almost no arguments and everything is in the global state in various modules and it is terrible, no matter how much they use the only
clause in the use
statements.
We can safely say that this amount of arguments (say 30) is way too large. All code style guidelines will probably agree with that. It is often a bit unpleasant to work with the many arguments libraries like LAPACK require, and that is nowhere close to 30.
There are several ways Fortran 90 and more recent can reduce the number of arguments.
Firstly, you can couple logically related variables into a derived type
type particle
integer :: species
real :: mass
real :: x, y, z
real :: vx, vy, vz
...
end type
Secondly, by using assumed shape arrays you can avoid passing the array dimensions. This allows modern LAPACK interfaces to have significantly smaller number of arguments, for example (both the Netlib and the MKL interfaces).
subroutine sub(A, NX, NY, NZ)
integer :: NZ, NY, NZ
real :: A(NX, NY, NZ)
vs.
subroutine sub(A)
real :: A(:,:,:)
This change requires explicit interface for the procedure so in practise the procedures have to be moved into modules.
Both these changes are rather significant changes and require significant refactoring efforts for large legacy codes.
Upvotes: 4