DEV Community

Tomaz Lemos
Tomaz Lemos

Posted on • Edited on

Keeping your code clean by sweeping out "if" statements

Mugging your way towards cleaner code

One of the most common things I see around that I think makes code more difficult to read is the overuse of "if" statements. It’s one of the first programming tools we learn, and it is usually when we learn that the computer can do pretty much anything we like, “if” we use those statements right. Following usually are long ours of printfs and debugging and trying to figure out why the program isn’t getting into that third nested "if" as we're sure it would do! That’s how many of us have approached programming, and that’s what many of us have grown used to.

As I studied more about code design and best practices I began noticing how using lots of if statements could be an anti-pattern, making the code worse to read, debug and maintain. And so out I went to find alternative patterns to those if statements, and I think the patterns I've found have improved my code’s readability and maintainability.

Of course there’s no silver bullet and any pattern should be used where it makes sense. I think it’s important for us developers to have options when attempting to write good quality code.

To illustrate this point I’ll share two simple examples, and I hope to hear your thoughts on the matter in the comments.

First let's see the example where we have to handle an incoming message from outside our application boundaries, and the object contains a string property specifying a type. It might be an error type from a mass email marketing, and we would have to translate that to our own domain’s error type.

Usually I see that implemented like this:



    private ErrorType translateErrorType(String errorString) {
        if ("Undetermined".equals(errorString)) {
            return UNKNOWN_ERROR;
        } else if ("NoEmail".equals(errorString)) {
            return INVALID_RECIPIENT;
        } else if ("MessageTooLarge".equals(errorString)) {
            return INVALID_CONTENT;
        } else if ("ContentRejected".equals(errorString)) {
            return INVALID_CONTENT;
        } else if ("AttachmentRejected".equals(errorString)) {
            return INVALID_CONTENT;
//      } else if (...)

        } else {
            throw new IllegalArgumentException("Error type not supported: " + errorTypeString);
        }
    }


Enter fullscreen mode Exit fullscreen mode

You see where this is going, right? It could be a switch statement, and it would be just as cluttered, with much more language specific words than actual business domain language.

There are a number of approaches to getting rid of this kind of “if” entanglement, but I guess the simplest one is the use of a map.



    public class ErrorTypeTranslator {

        private final static Map<String, ErrorType> errorTypeMap;

        static {
            errorTypeMap = Map.of(
            "Undetermined", UNKNOWN_ERROR,
            "NoEmail", INVALID_RECIPIENT,
            "MessageTooLarge", INVALID_CONTENT,
            "ContentRejected", INVALID_CONTENT,
            "AttachmentRejected", INVALID_CONTENT
//          (…)
            );
        }

        public ErrorType translateErrorType(String errorTypeString) {
            return requireNonNull(errorTypeMap.get(errorTypeString),
                    () -> "Error type not supported: " + errorTypeString 
        }
    }


Enter fullscreen mode Exit fullscreen mode

See the difference? Now the business logic is front and center, and any developer approaching this class should be able to very easily understand what it does and change it should it be needed. Lots of language specific words and symbols have disappeared making way for a much nicer, cleaner and less error prone code.

This kind of pattern is also very good for simple factories, where you can have a map of singletons, or even suppliers as values. For example, let’s say you have to return a handler bean based on an enum retrieved from the database.

What I usually see is something like:



    public class IntegrationHandlerFactory {

        private final EmailIntegrationHandler emailHandler;
        private final SMSIntegrationHandler smsHandler;
        private final PushIntegrationHandler pushHandler;

        public IntegrationHandlerFactory(EmailIntegrationHandler emailHandler,
                              SMSIntegrationHandler smsHandler,
                              PushIntegrationHandler pushHandler) {
            this.emailHandler = emailHandler;
            this.smsHandler = smsHandler;
            this.pushHandler = pushHandler;
        }

        public IntegrationHandler getHandlerFor(Integration integration) {
            if (EMAIL.equals(integration)) {
                return emailHandler;
            } else if (SMS.equals(integration)) {
                return smsHandler
            } else if (PUSH.equals(integration)) {
                return pushHandler
            } else {
                throw new IllegalArgumentException("No handler found for integration: " + integration);
            }

        }
    }


Enter fullscreen mode Exit fullscreen mode

Let´s try using a Map instead:



    public class IntegrationHandlerFactory {

        private final Map<Integration, IntegrationHandler> handlerMap;

        public IntegrationHandlerFactory(EmailIntegrationHandler emailHandler,
                              SMSIntegrationHandler smsHandler,
                              PushIntegrationHandler pushHandler) {

            handlerMap = Map.of(
                        EMAIL, emailHandler,
                        SMS, smsHandler,
                        PUSH, pushHandler
            );
        }

        public IntegrationHandler getHandlerFor(Integration integration) {
            return requireNonNull(handlerMap.get(integration),
                            () -> "No handler found for integration: " + integration);
        }

    }


Enter fullscreen mode Exit fullscreen mode

Much neater, isn’t it? Once again a very simple design that gets rid of many if / else if statements and makes it very easy to add new options.

There are many other patterns such as this, and I might do a post about those soon.

So, what do you think about this kind of patterns? Have you ever used a pattern like this? Are you more comfortable dealing with "if" statements?

Please let me know in the comments, I'd love to hear your feedback!

I made a post about another pattern that helps avoiding repetitive ifs, want to check it out?

Top comments (122)

Collapse
 
tomazfernandes profile image
Tomaz Lemos • Edited

Thanks for the reply Andy!

I think the discussion in this case could be about what's more important for the reader to know, whether it's understanding "what" a piece of code does or "how" it does it.

I tend to prefer the solutions that are about making the business rules as clear as possible, in a declarative style, because I usually want to understand quickly "what" a piece of code does, and then evaluate whether or not I should spend time understanding "how" it does it.

So in this case, I think it's obviously easier to figure out "how" the "if" version works, but I think it does make a lot more obscure "what" it does.

What do you think, do you agree with this "what" vs "how" analogy?

Thanks again!

Collapse
 
thomasjunkos profile image
Thomas Junkツ • Edited

My feelings towards this topic are ambivalent. When I first had this revelation that if statements could be avoided with different techniques (some of them even through polymorphism) I was very sensible when I ever wrote an if statement again. But let's be honest: How many cases are there which are really improved by avoiding ifs?

They are dead simple to write. And simple to debug. Then there is the switch statement and there are OTOH languages like python who do not have a switch statement at all - so you are left with if and elif else.

Of course writing the dictionary / object-form is pleasing to read because it appeals to you - the reader - that you feel someone has put a bit of thought into that - and what makes us more comfortable than feeling smart when reading "smart code"?

The if version feels dirty because everybody could have written it.

But when or why do we read the code anyways? For fun and profit - sometimes: But most of the times one reads code, because it is somehow broken.

And coming back to the factory example: The question I would have as a "Debugger" is

Why is the object I am getting not the one I was expecting

And I would start to scan the cascade of ifs as I would the dictionary approach and I would assume very little difference in the time taken to make the code work again.

So on a "poetic level" I would agree that the cleanup is well spent time. OTOH hand it's like cleaning your house: It would be nice if everthing was 100 percent tidy. But most of the time when dealing with unexpected visitors, it is sufficient to keep a tidy facade even though you know there might be corners where it is a bit dusty.

Thread Thread
 
tomazfernandes profile image
Tomaz Lemos • Edited

Hi Thomas, thank you very much for sharing your thoughts!

I relate to that "if" sensibility, I have spent over a year not writing ifs, and that's how I came up with these patterns. Nowadays I do write ifs when I think they will lead to simpler solutions. OTOH, in my experience more often than not what started as a simple and innocent if will grow to a bizarre logic with lots of nested ifs and whatnot, and so I think it's a valid approach to enforce some constraints by providing a well defined interface for the developer to work on, so at least the mess is a bit organised.

"The if version feels dirty because everybody could have written it." - I don't really feel that way... I think the if version feels dirty because there are so many unimportant words concealing the important information, which is the business logic the class is implementing.

I think that the cleaner way has a huge benefit of making it as clear as possible what is the correlation between the two values. In the end, I think programming is all about business rules, and the implementation details should be concealed when possible.

In your debugging example, specially in a more complex situation, I think you could spend a lot more time on the if version if your eyes just didn't catch that one word that's out of place in that sea of words. Or at least it will require a lot more attention than the cleaner version.

But of course it's a matter of opinion, I actually had the word "polemic" in my first draft... And my intention here is to get this kind of feedback so we can all keep reasoning about what good code is, so thank you again!

Thread Thread
 
thomasjunkos profile image
Thomas Junkツ • Edited

I think we share a lot. Mostly avoidance of nasty convoluted code. That said it follows that when we both would encounter "a more complex situation" we would do our best to deconstruct it into much more digestible parts.

But I do not share your implicit bias that an if-free version were implicitly clean. Especially when I read

I think that the cleaner way has a huge benefit

Which anticipates which solution is cleaner 😉

Good code is code which does what it should nothing more.

Thread Thread
 
tomazfernandes profile image
Tomaz Lemos

I do think we share a lot, and it seems like this “if” matter is sooner or later part of the journey of developers who want to get better at writing good quality code.

I think that perhaps the main lesson here is that we should be able to choose how we’re going to write a particular piece of code, and this anti-if crusade is a way of discovering patterns that can be really useful, when many developers never question the “if” status quo and hence could have less tools to address good code requirements.

That said, the post is completely biased in that the if-less examples are cleaner, so it should really come at no surprise that I anticipated which solution I think is cleaner...

And last but not least, I do question your last phrase. I think most developers are really focused in making code do what they want, when the focus should be in writing code that tells you “what” it does.

So many times I have wasted precious time deciphering code only to realize it wasn’t the right place to work in.

I don’t really want to understand how the code works, unless I have to. I just want to take a look at it, understand what business rules it addresses, and see whether it’s the right piece of code to work with or not... If it is, then I’ll spend the necessary time understanding “how” it does it.

And I think the dictionary examples do make a better job at communicating the business rules.

I appreciate a lot being able to discuss this topic here, thanks 🙏🏼

Thread Thread
 
thomasjunkos profile image
Thomas Junkツ

I appreciate a lot being able to discuss this topic here

Yes. This discussion is good. And I find it is so on different levels. What I find mostly valuable is that it shows to others not being for so long in the industry that we aren't dealing with truths: We do things for reasons; and taking one or the other way has its own right. And that we both agree to disagree helps others to form their opinion on this topic.

Collapse
 
iulianbojinca profile image
iulian-bojinca

I can't believe the comments I'm reading. The 'if' discussion is part of a bigger subject: declarative vs imperative. And there are plenty of writings about this. The general consent is that you use imperative solutions as far away from your domain logic as possible. When you keep abstracting functions, you will end up will some mathematical and computational functions that underneath are maybe using ifs, switches or fors like map does. These functions are then easily packed in a lib of some sort and you just keep using the declarative style in the rest of your code. It's a longer discussion overall, but to see so many people defending the imperative style...makes me sad. I have seen so many bugs and hit so many problems because of the imperative approach used on the wrong levels and I still have to fight for this because people are unwilling to learn and move past the God damn 'if' chapter and approach my code as 'clever'. It is not clever, it is programming and this approach WILL clean your app for 90% of your bugs and WILL make you move faster when changes are required.

Collapse
 
binarydelight profile image
Binary Delight • Edited

Well said, these comments also make me sad. It means so many programmers still don’t get it.

Reducing Cyclomatic Complexity is vital to reduce bugs. Avoiding the use of a hash and rather using ifs is not clever. It’s short sighted.

Collapse
 
tomazfernandes profile image
Tomaz Lemos

Hi Roger, thanks for your feedback! I've written a blog post about another pattern, if you'd like to take a look I'd really appreciate your feedback on that as well.

Thanks again and happy new year!

Collapse
 
alwynschoeman profile image
Alwyn Schoeman

The problem is that people do not work with significantly large and/or complex programs with multiple developers.

The examples here are simple value mappings, but what happens when those if blocks perform logic? Different types of logic blatantly ignoring the single responsibility principle. The more complicated they get the bigger the chance that there are unmatched use cases.

But that's a code smell? Yes, but if statements are like candy to children who just want to plug some code in somewhere to finish a ticket. Code they don't understand and that gets more complicated with each if statement.

Apart from functional declarative solutions there is also the proper use of OOP which is really what design patterns are all about.

All of these require reasoning about code, which apparently is too much too ask.

Thread Thread
 
binarydelight profile image
Binary Delight

Agreed. This is going to sound snobbish. Anyone can code; but not everyone can apply coding principles.

Collapse
 
laughingraven profile image
Laughing Raven

Bold statements, but dubious at best. Don't be clever. Use the if statement. Think about all the overhead you introduce and how much more difficult your code is to debug.

Collapse
 
binarydelight profile image
Comment marked as low quality/non-constructive by the community. View Code of Conduct
Binary Delight

Clearly you don’t get the difference between declarative programming and imperative and would rather stay “not clever”. It’s fine, I hire clever declarative programmers over imperative programmers . Clever programmers who write smart code, less code, which leads to less bugs. The reason you prefer using the if statement is because you find it easier to debug, which obviously is very important to you because that’s what you do a lot of... because of your spaghetti if code. Now that’s dubious .

Thread Thread
 
lagerenas profile image
lagerenas

Hmm. Reading this article and reflecting on the times I have encountered the map pattern I initially did not like it. It separates the logic into two different places. That makes it harder to trace through the code and find the right place to modify. You are however right that I have to do it less often using this pattern.

Thread Thread
 
laughingraven profile image
Laughing Raven • Edited

As an electrical engineer, coding is only a small part of what I do. The rest of my day is spent in planning, documentation, testing for regulatory compliance and debugging. Then again, I write firmware for medical equipment. It must be correct or people die.

Thread Thread
 
skyl profile image
Skylar Saveland

Imperative style with lots of ifs takes a lot more unit tests to prove it works compared to declarative style. One shouldn’t be debugging, one should be testing and isolating complexity out of the main program. This thread is scary, frankly.

Don’t worry about cyclomatic complexity, just do a lot of debugging to make sure people don’t die? Hrm ...

If it has to work or people die, then you really should scrutinize every if statement carefully and see if you can get rid of it. Many ifs are bugs waiting to be discovered.

Collapse
 
brycebba profile image
brycebba

I have to say this being "cleaner" isn't necessarily true to me. I think it is more clever for sure but as someone who works professionally on a bug fixing team I would MUCH rather see the ifs in my codebase than someone trying to be clever but then again, people trying to be "clever" or write less lines is why I have the job fixing bugs that I have which I love. I'm not trying to insult your code, I'm simply saying the basics are something everyone understands and I have seen countless times where a refactoring to produce less lines or "simplify" something is the cause of a bug or difficult debugging to find a bug. Ultimately is all personal preference until performance is analyzed but when you work for an enterprise level company with tons of devs cranking out code it is better not to be "clever" and to be consistent and predictable.

Collapse
 
tomazfernandes profile image
Tomaz Lemos

Hi brycebba, thanks for replying!

I hear the complaints about it being
“clever” code. Normally clever code is when someone sacrifices readability or comprehension to create an one liner or to use a design pattern just for using it.

First of all, I don’t see where is the complexity of these solutions. They are just different from what we are used to, but it has one very simple line of code (map.get). One can change the requireNonNull to an “if” if he or she is not used to it.

What I don’t see people talking here is about how easy or hard it is understanding the business rules behind the logic, which is my main point.

I think code should be read like a business document, because in the end of the day that’s what we do: we code business rules.

So I really don’t see these patterns as “clever” code, because in my opinion they enhance the business rules readability.

As for the bug fixing, in my experience it’s really easy to debug such patterns because there’s really one place that can have a bug, which is the map, and it’s very easy to notice when something is wrong. Can’t say the same about those lots of ifs.

Cheers!

Collapse
 
mindplay profile image
Rasmus Schultz

One downside to the map version is it's less flexible.

Are you certain you'll never need to enhance one of those conditions?

Should you ever get to the point where you need more than a single, straight comparison for one of those conditions, you'll only end up having to factor the whole thing back to the original if-else ladder.

I think I would need more motivation to favor a map - for example, if you had a kind of registry where new items could be plugged into the map (say, via constructor or method injection) that would be a practical need for a map.

Personally, I tend to favor the simplest possible language constructs over data types or abstractions, until there's a demonstrated need for something more.

Just my perspective. 🙂

Happy New year!

Collapse
 
khtony profile image
Breton F • Edited

Just for testing the if version would have been way more difficult to write without any added value.

Map is an interface meaning more flexibility. Yes a little more complex.

The map in the example is static but could be a dynamic configuration or comes from anywhere.

Yes it depends on the context. But this pattern is relevant. I like it

Collapse
 
mindplay profile image
Rasmus Schultz

Just for testing the if version would have been way more difficult to write without any added value.

I'm not sure what you mean?

The test burden is the same - it has to cover every case.

If the map was somehow open to dependency injection, this would have been a different case, where you could inject a simpler map with mock values, leading to a simpler test case. But as it is now, the map is an implementation detail - your test needs to cover every supported case, so there's no difference in terms of testing. (Your test should not assume implementation details like a map or an if-else ladder, since these details could change; the subject of this post.)

Yes it depends on the context. But this pattern is relevant. I like it

I wasn't trying to say it isn't relevant or I didn't like it. 🙂

I'm just raising awareness of the limitations - when introducing an abstraction (whether it's one you design, or an existing one, in this case a map) there is always a trade-off in terms of flexibility.

Map is an interface meaning more flexibility.

Once you adopt an abstraction, you're limited to whatever that abstraction defines as being the responsibility, which means less flexibility.

Unless you have some other definition of flexibility.

But I think I was clear with my example on what I define as flexibility: the freedom to add another condition that doesn't conform to a precise pattern, in this case the map abstraction.

Of course, you could abstract further to cover use-cases with new conditions, but at that point you're taking on more complexity.

So you have to weigh the pros and cons. Introducing an abstraction is always less flexible and can always lead to more complexity - I think that's definitely demonstrated by the example I gave here.

And the author agrees with me:

Your point is a valid one, in that the map version is a lot less flexible than using ifs.

Again, that doesn't mean this pattern isn't relevant. It doesn't mean I don't like it. It just means you shouldn't make decisions like these without understanding the trade-offs. You should have a practical reason, which, in my opinion, should go beyond implementation details - if you add abstraction, it should be because there's a practical reason to do so.

For example, a need for dependency injection, which would allow different message handlers to be plugged in, would allow testing with mock message handlers, and so on.

There are plenty of valid reasons to choose maps or other abstractions - this wasn't a criticism of the post, just an addendum. 🙂

Thread Thread
 
tomazfernandes profile image
Tomaz Lemos

Hi Rasmus!

One thing I’ve learned from this post and all the discussion around it is that it should have been more about tradeoffs. I wrote a new post, about a different pattern, based more around the tradeoffs, and I think it’s a far better approach.

About the flexibility, one thing that came to mind is that this pattern is just as flexible as a switch statements, isn’t it? If something coded as a switch statement has to embrace a more complex condition you’d have to refactor it anyway. And yet I’ve never seen anyone argue that this should be taken into consideration when using switches.

I’m writing a new post with some more examples of pattens such as this, and in my experience once you have a minimal toolset of these patterns you can change pretty much any repetitive-if situation into a declarative one, without much effort.

As for the valid reasons for using the pattern, my point is that it makes the business rules a lot more readable, which in my experience leads to easier maintenance and less bugs.

I’d have preferred that the discussion gravitated more towards the business rules clarity than to the if or not if part, but again that’s on me for the way I’ve written the post.

I do appreciate your feedback a lot, thanks!

Thread Thread
 
khtony profile image
Breton F

@Rasmus

We may not see the problem with the same lens. I ll just try to make my points clearer. Hope we could agree later.

A map is a contract and practically a function. You give it a key it does some magic and return back to you a value. Your map implementation is up to you. So by providing a specific map and boom you can do stuff of your imagination. This for me is flexibility as you pick your map based on your requirements.

Unit tests burden
With the map/function version, I give a key and I get back a value. I do not need to go for all possible keys for my unit tests. Because what I m interesting in is the contract i.e ability here to translate an error code to something else.

Collapse
 
tomazfernandes profile image
Tomaz Lemos

Hi Breton, those are some very good points, thanks!

I’m in need of some feedback on this other pattern, if you care to take a look I’d really like to hear your thoughts:

dev.to/tomazlemos/implementing-a-s...

Happy New Year!

Collapse
 
tomazfernandes profile image
Tomaz Lemos

Hi Breton, thanks for your feedback!

Thread Thread
 
khtony profile image
Breton F

Thanks for sharing, I will read it..

Thread Thread
 
tomazfernandes profile image
Tomaz Lemos

I decided to rewrite that post based on your and other fellow DEV's feedback, if you'd care to read the new version I'd really appreciate!

dev.to/tomazlemos/let-s-talk-trade...

Collapse
 
schollii profile image
schollii

I don't agree you would have to refactor it back to sequence of ifs. Instead, you either have just one or 2 ifs before the call, better than 10 ifs! And when you get to the point where you have several ifs between the lookup and the call, it's time to refactor the special cases into the function calls themselves, then you're back to 0 ifs.

Collapse
 
mindplay profile image
Rasmus Schultz • Edited

In my opinion, now you have the mental burden of both approaches.

Personally, I'd want to choose one.

In my point of view, if you have to have a couple of if-statements before checking the map, that's a sure sign that the map is the wrong abstraction - for example, maybe the type inside the map is the wrong type and you may need to consider adding more abstraction, e.g. a type that covers all your cases; again, being aware of the complexity trade-off.

Maybe it's worth it, maybe it isn't. This is where the job gets hard 😉

Collapse
 
tomazfernandes profile image
Tomaz Lemos

Hi Rasmus! Thanks for bringing in your perspective. Your point is a valid one, in that the map version is a lot less flexible than using ifs. But I was reflecting on it and realised that it's exactly that what I like the most about it, and what frightens me more about those uncontrolled ifs.

I think that good code implies in enforcing constraints, and making intentions and interfaces clear, and it's something hard to achieve when solving everything with if statements.

To use your example, if you have lots of chained if statements and the one before the last is a little different due to an enhanced condition, or has a side effect the others don't, it can be really tricky to find it.

When you enforce the constraints, with a Map for example, you're saying that that's all there is about that logic, that's the contract.

Should the requirements change, perhaps that contract isn't useful anymore, and then you should have to design a new one. Or at least you would have to make it clear that that one condition is different than the others.

Coding for me is all about making intentions clear and stating what the business rules are, and I think this approach helps me in achieving it.

Thank you very much again for your perspective and a happy new year to you as well!

Collapse
 
lukemcar profile image
Luke Carpenter

I agree with you that overuse of "if/else" code can become hard to follow. Your simple case is a nice simple example how to get rid of "if/else". I've seen some terrible nested "if/else" that could cause one's head to explode.

Collapse
 
capellablue profile image
Amanda

Context context context context

Collapse
 
bhmckendrick profile image
Brian McKendrick

Exactly what's been ringing in my head reading almost every comment. Either pattern is suitably applicable depending on the context - the particulars of the codebase, project, target runtime environment, etc. I believe most commenters understand this simple truth, but most posts speak only in absolutes. Design patterns shouldn't be applied unilaterally in "real world" dev.

Philosophically... Yes, I believe the abstraction is preferable in most cases, but there are times when imperative code (conditional stmts) is a better solution.

Thread Thread
 
tomazfernandes profile image
Tomaz Lemos

Hi Brian and Amanda, I agree with you that context may change the applicability of one pattern or another. Most people seem to have liked the code examples, but perhaps I could have taken a better approach in presenting them, to generate less of an "us versus them" response. In the end we're all developers trying to write better code! It's been a really helpful and informative discussion though. Thanks for your feedback!

Collapse
 
tomazfernandes profile image
Tomaz Lemos

Hi Luke, thanks for your feedback! I've written a blog post about another pattern, if you'd like to take a look I'd really appreciate your feedback on that as well.

Thanks again and happy new year!

Collapse
 
spring_alfalfa profile image
Anonymous

Thanks for this Tomaz!

These are good examples of swapping out if statements with cleaner, safe alternatives.

I want to suggest another idea - To ask the question: "Why am I writing this code in the first place?" In other words - Is having my input come in as a string the right thing to do in this part of my code base?

If it's at all possible, having the input typed (as an enum, or better yet as a dedicated class) is so much better. Granted there are times when this is not possible (ex: coming in through serialization or user input), yet when it is possible, relying on the type system is superior to parsing strings even when efficiently done with a Map etc.

Happy new year,
@urig

Collapse
 
tomazfernandes profile image
Tomaz Lemos • Edited

Hi Uri!

As I have (perhaps poorly) tried to contextualize, in that case the response comes from an outside system, so I can’t really change it into an object. In fact the point of the class would be to do as you suggest so in the rest of the system I can use my own business’ enum.

If I used that enum to do the translation directly it would be an unnecessary coupling of my business object to the other system’s response.

Maybe a nicer solution would be to create another enum just for translating the string, and have the map correlate the two enums, might be a solution too.

What do you think?

Thanks for replying!

Collapse
 
wrldwzrd89 profile image
Eric Ahnell

I like the approach of coalescing a huge nest of if statements into a map lookup - it makes the code easier to read and understand! Like anything, though, you can overdo it - it doesn't help much for a 2-choice branch, and may use more resources than a simple if/else would have. Thanks for sharing!

Collapse
 
tomazfernandes profile image
Tomaz Lemos

Hi Eric! I’m glad you liked it, I like it a lot too! I’m in need of feedback for this other pattern, if you could take a look I’d really appreciate hearing your thoughts 😃

dev.to/tomazlemos/implementing-a-s...

Thanks for your kind reply, and Happy New Year!

Collapse
 
wrldwzrd89 profile image
Eric Ahnell

Done, glad to know it's useful.

Thread Thread
 
tomazfernandes profile image
Tomaz Lemos

Super useful Eric, thank you very much!

Collapse
 
tomazfernandes profile image
Tomaz Lemos

I decided to rewrite that post based on your and other fellow DEV's feedback, if you'd care to read the new version I'd really appreciate!

dev.to/tomazlemos/let-s-talk-trade...

Collapse
 
wrldwzrd89 profile image
Eric Ahnell

Done. This is why DEV is great - we help each other get better!

Thread Thread
 
tomazfernandes profile image
Tomaz Lemos

Thanks a lot Eric!

Collapse
 
enthusiastio profile image
En • Edited

So which approach is faster? Did anyone test that? It's just another aspect to look at it, which might be relevant in some cases. I used write assembly and when I read code like this I compile it to machine code in my brain. One of greatest performance tweaks can be done with ugly ifs. End user will thank you. Next person taking over your code - not so much

Collapse
 
cklellie profile image
cklellie

I ran the tests out of curiosity using Java 11 and jmh looking at throughput...

Three implementation, if else if..., map (hashmap) and a switch.

With one notable exception, the results were as I had expected:

  • The if else if... approach became slower for matches against the "later" input options i.e. proportional to the number of comparisons performed before a match was found.
  • The map approach provided constant performance for all input options,
  • The switch approach also provided constant performance for all input options, not expected but I'll assume some compiler optimisations there.
  • The switch approach was slightly faster than the map approach.
  • The switch and map approaches were both slower than the if else if... until you test the 3rd or 4th input options respectively.
  • The if else if... approach degraded in performance until the 11th input when it improved slightly and then continued to degrade again. (I can't explain this).

In general, I prefer the map approach over a large if else if... block and 3 or 4 branches seems like a nice rule of thumb for when you might want to look at moving to the map or switch approach, both in terms of performance and readability, IMHO.

Code:
https://github.com/c-19/dev-to-if-tests

Setup:
Java: 11 
JMH: Fork=1, Warmup iterations=2, Benchmark mode=Throughput.
16 input options value0...value15 (coded sequentially)

Result:

Benchmark               (input)   Mode  Cnt          Score         Error  Units
MapperTests.ifImpl       value0  thrpt    5  225391654.785 ± 3290306.715  ops/s
MapperTests.ifImpl       value1  thrpt    5  137626847.272 ±  368944.076  ops/s
MapperTests.ifImpl       value2  thrpt    5  108679300.029 ± 3299310.284  ops/s
MapperTests.ifImpl       value3  thrpt    5   86237514.251 ± 1052735.135  ops/s
MapperTests.ifImpl       value4  thrpt    5   69846500.397 ±   96096.744  ops/s
MapperTests.ifImpl       value5  thrpt    5   61801196.907 ±  447615.691  ops/s
MapperTests.ifImpl       value6  thrpt    5   45586366.536 ± 1311782.917  ops/s
MapperTests.ifImpl       value7  thrpt    5   40547835.196 ±  601046.774  ops/s
MapperTests.ifImpl       value8  thrpt    5   36543064.119 ±  360208.524  ops/s
MapperTests.ifImpl       value9  thrpt    5   33102331.522 ± 1508720.970  ops/s
MapperTests.ifImpl      value10  thrpt    5   79657826.043 ± 3917631.998  ops/s
MapperTests.ifImpl      value11  thrpt    5   69926632.944 ± 2298541.222  ops/s
MapperTests.ifImpl      value12  thrpt    5   57850585.050 ±  298264.430  ops/s
MapperTests.ifImpl      value13  thrpt    5   49052412.415 ±  684120.388  ops/s
MapperTests.ifImpl      value14  thrpt    5   42669844.467 ±  389865.530  ops/s
MapperTests.ifImpl      value15  thrpt    5   37628886.485 ± 1017955.318  ops/s
MapperTests.mapImpl      value0  thrpt    5  113958609.374 ± 1134282.617  ops/s
MapperTests.mapImpl      value1  thrpt    5  113985273.332 ± 1214821.373  ops/s
MapperTests.mapImpl      value2  thrpt    5  113480216.182 ± 1600608.326  ops/s
MapperTests.mapImpl      value3  thrpt    5  113649067.777 ± 1565823.964  ops/s
MapperTests.mapImpl      value4  thrpt    5  113898990.164 ± 1402779.208  ops/s
MapperTests.mapImpl      value5  thrpt    5  113637571.320 ±  505975.224  ops/s
MapperTests.mapImpl      value6  thrpt    5  113355138.316 ±  479705.282  ops/s
MapperTests.mapImpl      value7  thrpt    5  113968525.926 ± 2417268.956  ops/s
MapperTests.mapImpl      value8  thrpt    5  116975067.618 ± 3477953.993  ops/s
MapperTests.mapImpl      value9  thrpt    5  113566437.305 ± 2096013.205  ops/s
MapperTests.mapImpl     value10  thrpt    5  109748822.972 ± 1803152.916  ops/s
MapperTests.mapImpl     value11  thrpt    5  113741818.520 ± 1331202.350  ops/s
MapperTests.mapImpl     value12  thrpt    5  109164776.582 ± 3809473.640  ops/s
MapperTests.mapImpl     value13  thrpt    5  110408351.205 ±  587733.025  ops/s
MapperTests.mapImpl     value14  thrpt    5  113899863.382 ± 2163418.194  ops/s
MapperTests.mapImpl     value15  thrpt    5  110488695.855 ±  909644.752  ops/s
MapperTests.switchImpl   value0  thrpt    5  147313906.613 ± 4442483.745  ops/s
MapperTests.switchImpl   value1  thrpt    5  147812229.197 ± 1241026.620  ops/s
MapperTests.switchImpl   value2  thrpt    5  141179106.457 ± 1744724.525  ops/s
MapperTests.switchImpl   value3  thrpt    5  140898884.244 ± 1072571.789  ops/s
MapperTests.switchImpl   value4  thrpt    5  140553087.462 ± 1153754.158  ops/s
MapperTests.switchImpl   value5  thrpt    5  147244206.471 ± 3327814.038  ops/s
MapperTests.switchImpl   value6  thrpt    5  141019484.294 ± 1173909.237  ops/s
MapperTests.switchImpl   value7  thrpt    5  147887831.522 ± 1508045.545  ops/s
MapperTests.switchImpl   value8  thrpt    5  148146866.817 ± 2328535.276  ops/s
MapperTests.switchImpl   value9  thrpt    5  147108615.588 ± 5732294.730  ops/s
MapperTests.switchImpl  value10  thrpt    5  133949614.842 ± 1199268.891  ops/s
MapperTests.switchImpl  value11  thrpt    5  139758382.256 ± 2345725.444  ops/s
MapperTests.switchImpl  value12  thrpt    5  141110898.690 ± 2514375.445  ops/s
MapperTests.switchImpl  value13  thrpt    5  140177616.112 ± 5352625.890  ops/s
MapperTests.switchImpl  value14  thrpt    5  134449800.546 ±  649498.406  ops/s
MapperTests.switchImpl  value15  thrpt    5  140783657.921 ± 1503688.188  ops/s
Collapse
 
tomazfernandes profile image
Tomaz Lemos

Just to add some clarification, this Map.of method returns an immutable map of defined size, so there’s not a great deal of heap allocation.

Besides that I usually try to optimize code for readability, even if it’s at the expense of a few microseconds.

I also think that being a static content Map the compiler would probably do some kind of optimizations, but that’s only my guess and trust in the bright JDK engineers.

But I’d like to see that kind of performance comparison, always good to put theory to practice!

Collapse
 
december1981 profile image
Stephen Brown

Fair points. I guess it also depends what you're trying to do.

If you're writing kernel code, or stuff for embedded systems, the issue of lots of branches can itself be an issue - from a performance point of view. Data oriented approaches might focus on removing branches in the first place by organising the layout of data and making the code run better by processing on 'chunks of stuff'.

Collapse
 
december1981 profile image
Stephen Brown

A map or associative array of some kind probably makes heap allocations and has plenty of ifs in its internal implementation. So I would hazard a guess it is probably a lot slower than just using ugly ifs.

Collapse
 
abdnkhan profile image
Abdullah

I second that.

Collapse
 
kaydubyew profile image
kaydubyew • Edited

I quite enjoyed this article.

While some may consider several years programming at university, then several more afterward, somewhat experienced, I consider myself a beginner. You can always be better.

Full disclosure I would have clung to the familiar if or switch approaches, that is until I read this article. There's always next time.

I like being able to look at my code and appreciate something well-crafted. It's a matter of personal bias, yes, but it's always helped me when reviewing code especially later.

I recently worked on a small project and would have really loved being able to clear up what was a nightmarish daisy chain of if-else statements.

I was able to clean it up quite well and eliminate many errors but I can see where it would have been great to use this approach. It would also make changing the values in a future version a snap.

In other words, thank you for helping a newbie see things in a different way.

Collapse
 
tomazfernandes profile image
Tomaz Lemos

Thank you for your feedback kaydubyew, I really appreciate it!

Collapse
 
mfp22 profile image
Mike Pearson

I love this post. This is an underappreciated application of DRY.

"if" blocks can become magnets for repeated code that often increases unnecessary coupling to APIs---all kinds of APIs. One example is when you have an if-else statement that both contain the same function call but pass in a different parameter. Instead you can use a ternary to make a simple conditional assignment and then a single function call. It's easier to follow the logic, and if you decide to refactor to a pure function, you only need to change one line to a "return" statement.

Some comments may only be visible to logged-in visitors. Sign in to view all comments.