I'm writing a short module in Fortran 90/2003 that provides a simple and user friendly interface for counting time between different parts of the execution of a program. Inspired by the tic
, tac
commands in Matlab, the idea is that the user uses the module in a program as follows:
program test use Timer call Tic("timername") ! some heavy stuff call Tac("timername") end program test
Now, I know how I can achieve that result with Fortran intrinsics. My question is how I should do it. I'm doing this to learn good design practices, rather than about Fortran syntax.
I have defined a user defined variable called Timer
, which is the main object that I use to implement the functionality. However there are (at least) two different ways to use this object to let the user using several timers:
a) I can make the user defined variable Timer
public, and then force the user to create timers object by hand. The user has to create as many timers as he needs, and then use methods to handle them.
b) I can hide this type by making it private. Then, to store different timers, I create an array of Timer
objects in the module as a global variable, although private for the module, and every time the user calls the subroutine Tic
, a new timer is defined in this array. In the example above, the user is using a module implemented following the latter approach (note that the program does not use keyword type
at all).
Although the two options work technically (I have already implemented both) each one has advantages and caveats, and the rules I know about software design somehow collide. I wonder which is the best approach from a "orthodox" point of view.
Option a) has the advantage of following better the OOP: the user creates explicitly and object and operates with it. It does not use any global variable.
Option b) has the advantage of being more strongly "encapsulated". By this I mean that the user does not even need to know what a Timer
is, and even about the existence of it. Further, the interface provided to interact with Timer
objects is just a simple string, making the whole module more opaque for the user, which does not need to define Timer
variables on purpose. He/she just uses two subroutines provided by the module that accept a string as input. That's all. The problem is that I have the feeling that this design, based on an array defined for the whole module, goes against the rule of avoiding global variables. It's not a real global variable, since it is private, but still.
So having this two options, which should I go for to produce the most orthodox approach?
PS: maybe there is a third option, which allows the user to create objects indirectly without having access the user defined type (i.e. not just define elements in an existing array, as done in the solution b). I don't know if this is possible at all to create variables at run time. Any idea in this direction is also very welcome.