Approaches for not complex conditions

by nodedotjs   Last Updated May 15, 2018 18:05 PM

I encountered code like this below. I was told its fine, and boilerplate is not always better. I agree boilerplate might be bad, but I am not sure about something like this:

    if (entity.isSomething && wasCheckedBefore(entity.name)) showSomeMessageToUser(entity.name) 
    if (entity.isSomethinElse && wasCheckedBefore(entity.name)) showSomeMessageToUser(entity.name) 
    if (entity.isSomethingSomethinElse && wasCheckedBefore(entity.name)) showSomeMessageToUser(entity.name) 

What would you recommend? (rather not CoR or Command pattern)



Answers 2


Why don't you just consolidate your messages inside the entities?

class SomethingEntity
{
    string name;
    bool isChecked;

    public string Message()
    {
        if (isChecked)
            return someMessage;
        else
            return someOtherMessage;
    }
}

You can then

showMessageToUser(anyEntity.Message());

There are many ways to skin this cat. You probably don't need a well-known software pattern.

Robert Harvey
Robert Harvey
May 15, 2018 17:49 PM

If there's a good domain term for what's being checked, you can convert each boolean expression to a method:

// This method name should explain what the boolean expression 
// means in terms of domain logic, i.e. why it is important
// to check both of these values.
private boolean someDomainConcept(entity) {
   return entity.isSomething && wasCheckedBefore(entity.name)
}

if (someDomainConcept(entity.name)) showSomeMessageToUser(entity.name);

This can add some documentation value to the code while making it a little more brief to use your boolean expressions and enabling reuse of those expressions. I wouldn't say that this is always a valuable pattern; it depends on your actual use case. Sometimes there isn't a better name for the boolean expression than just the sum of its parts.

Kyle McVay
Kyle McVay
May 15, 2018 17:59 PM

Related Questions


Refactoring Atrocious Java Code

Updated February 21, 2017 22:05 PM