Below you will find pages that utilize the taxonomy term “Enumeration”
Fortran: Enumeration, part 3
In the previous post we properly encapsulated the integer
level with a log_level_t
derived type, achieving type safety.
Now, let’s consider the following feature request: we want to show the log level in front of the message. We could do it with decoration of course, but in the scope of this article, let’s do it in the log()
subroutine directly. In this case we’re “lucky” that we can access the module-private data component level
, so we can do a select case
on it to determine what string should be printed:
Fortran: Enumeration, part 2
In the previous post we introduced a derived type log_level_t
. The type of data passed to the log()
procedure is still an integer
though:
subroutine log(message, level)
character(len=*), intent(in) :: message
integer, intent(in) :: level
! ...
end subroutine log
This doesn’t stop anyone from passing a completely meaningless integer
value as the level
argument to log()
.
Increasing type-safety
We’d like to increase type-safety and the way to do it is by using a more specific type. In our case, it would be great if we could use log_level_t
as the argument type for level
:
Fortran: Enumeration, part 1
In the post about decoration we declared log levels as follows:
module logging_base
! ...
integer, parameter, public :: LOG_DEBUG = 0
integer, parameter, public :: LOG_INFO = 1
integer, parameter, public :: LOG_WARN = 2
integer, parameter, public :: LOG_ERROR = 3
integer, parameter, public :: LOG_FATAL = 4
! ...
end module logging_base
This is somewhat useful, but requires a dedicated only
mention when importing each of these constants, which isn’t very nice:
program main
use logging_base, only: log, LOG_DEBUG, LOG_WARN
! ...
call log('A debug message', LOG_DEBUG)
! ...
call log('A warning', LOG_WARN)
end program main
Although we could live with that, the bigger issue remains: this is not a type-safe solution. Any integer
may be passed as an argument for level
, and the compiler wouldn’t warn us. For example: