ESCOMP / ESCOMP/CTSM

Refactor a complex if statement into a logical function

Open
#3,644 0 comments 0 reactions 0 assignees View on GitHub
b4b code health enhancement modernization size: small
Dominant language
Fortran
Stars
352
Forks
361
Avg merge
2d 21h
Merged PRs (30d)
7

Description

This is often something that's helpful to make code readable and complex if statements to be unit-testable. The logic for a complex if statement can be hard to understand. That also means that it's good to have a logical function to replace it so that the code where it's used is more clear, and the function can be unit-tested for correctness elsewhere.

There's a specific instance of this I saw in CanopyFluxes, and suggest doing the following.

Here's the original message:
And actually maybe what would be better would be to make the original if even more complex so that if it's triggered it does the same thing. If you do that I'd suggest you make a little logical function to put it in though.

So something like:

``` fortran
if ( combine_leaf_and_stem(p) )then
frac_rad_abs_by_stem(p) = 0.0_r8
sa_stem(p) = 0.0_r8
end if
.
.
.
logical function combine_leaf_and_stem( p )
if ( is_tree(patch%itype(p)) .or. is_shrub(patch%itype(p) )then
! combine leaf and stem if dbh is less than a minimum diameter
if ( dbh(p) < min_stem_diameter )then
combine_leaf_and_stem = .true.
! Also combine leaf and stem if LAI is smaller than a minimum value
else if ( elai(p) < min_lai) then
combine_leaf_and_stem = .true.
else
combine_leaf_and_stem = .false.
end if
else
! Always combine leaf and stem if it isn't a tree or shrub
combine_leaf_and_stem = .true.
end if
```

I think this makes the code much more readable.

_Originally posted by @ekluzek in https://github.com/ESCOMP/CTSM/pull/3643#discussion_r2586186787_

Contributor guide

Open the contributing guide

Assessment

This issue has not been assessed yet.

Get new issues in your inbox

A short digest of beginner-friendly GitHub issues.