Skip to content

Refactor a complex if statement into a logical function #3644

@ekluzek

Description

@ekluzek

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:

         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 #3643 (comment)

Metadata

Metadata

Assignees

No one assigned

    Labels

    bfbbit-for-bitcode healthimproving internal code structure to make easier to maintain (sustainability)enhancementnew capability or improved behavior of existing capabilitymodernizationE.g., for improving ability to perform on new computing architecturessize: small

    Projects

    No projects

    Milestone

    Relationships

    None yet

    Development

    No branches or pull requests

    Issue actions