USE with ONLY
| Import only names | |
| Rename on import | |
| Avoid clashes | |
| One use per need |
Import only names
Plain use imports everything, which clutters the namespace: the only clause lists exactly the names this program needs.
With use stats, only double_it the program sees one procedure and nothing else, so stray names cannot collide.
program onlydemo
implicit none
use stats, only: double_it
print *, double_it(21)
end program onlydemo
./onlydemo
42
Rename on import
Rename imports to fit local style or dodge a clash: twice becomes a local alias for double_it with no copy and no wrapper.
The new name points at the same procedure, so every fix in the module reaches the alias at once.
program renamedemo
implicit none
use stats, only: twice => double_it
print *, twice(21)
end program renamedemo
./renamedemo
42
Avoid clashes
Two modules may export the same name: importing both plainly is ambiguous, but two narrow only lists keep them apart.
Pick step from physics and draw from graphics, and each call resolves to exactly one procedure.
program clash
implicit none
use physics, only: step
use graphics, only: draw
call step()
call draw()
end program clash
One use per need
Keep each use line small and local: import at the top of the unit that needs it and list only the names that unit calls.
Small import lists document dependencies at a glance and make future renames painless.
program styled
implicit none
use stats, only: double_it
use mtools, only: triple
print *, double_it(3) + triple(3)
end program styled
./styled
15
Next: INTENT
Article author: Arthur Isaev