0

Question: Is it better to have more variables to allow a conditional to be "more readable" or is it cleaner to have less variables but a harder to read conditional?

I read this which says less variables. I think their solutions look LESS readable ( https://techbeacon.com/why-unnecessary-variables-are-bad-your-code ) This SO sounds slightly different though: Introducing variables only for readability?

Example:

I have the following statement:

if ((memberIDandLNIsValid) || (memberIDandDOBIsValid && memberDOBFormatIsValid))

To get memberIDandLNIsValid I have:

if (!string.IsNullOrEmpty(Search_MemberID) && !string.IsNullOrEmpty(Search_MemberLastName))

Notice that Search_MemberID and Search_MemberLastName are two separate variables. I thought it was easier to read to have a combined variable. But I have been told there are too many variables in my code.

I'm guessing the solution is to just leave it as :

if( (Search_MemberID && Search_MemberLastName) || ((Search_MemberID && Search_DOB) && memberDOBFormatIsValid) )

To me, this conditional is MUCH less readable now.

Thoughts?

seesharp
  • 101
  • 1
  • 14
  • I'm sure its all personal preference, but when getting into a complex mess of both multiple truth and multiple logical NOTs, I would be totally fine to prequalify some into a simplified variable. – DRapp Oct 05 '18 at 17:07

1 Answers1

1

I think it's fine as is, but one technique you can use is to refactor your booleans to methods with more readable names.

(Search_MemberID && Search_MemberLastName)|| ((Search_MemberID && Search_DOB)

becomes:

SearchMemberHasIdAndLastName() || SearchMemberHasIdAndDOB()

You don't need to do that here, but it is a technique to keep in the back of your mind.

Ryan Bennett
  • 3,404
  • 19
  • 32