Thread: Can you convert this code to not use an IF statement?

Page 1 of 3 123 LastLast
Results 1 to 10 of 29
  1. #1 Can you convert this code to not use an IF statement? 
    Registered Member
    Join Date
    Dec 2013
    Posts
    419
    Thanks given
    127
    Thanks received
    85
    Rep Power
    349
    This is out of pure curiosity. A senior developer at work expressed his opinion to be regarding IF statements and said that we should write code that doesn't use IF statements.
    His reason being that you write better code and have a direct app flows over conditional flows.

    It was his opinion and nothing to be taken literal however I want to know, is the following code possible without an IF statement?

    Code:
    int input = getUserInput();
    if(input > 10) {
     handleHigh();
    } else {
      handleLow();
    }
    Be as creative as you want. I tried, I couldn't think of anyway on how to do it.


    Edit;

    Update! Just found one excellent way to do this!

    Code:
    NavigableMap<Integer, InputHandler> messages = new TreeMap<>();
            messages.put(Integer.MIN_VALUE, new DefaultInputHandler()); //everything
            messages.put(1, new LowInputHandler()); //values from 1..9
            messages.put(10, new HighInputHandler()); //values after 10 
            messages.put(15, new DefaultInputHandler()); //everything
            
            System.out.println(messages.floorEntry(7).getValue().getMessage()); //LowInputHandler.getMessage()
            System.out.println(messages.floorEntry(11).getValue().getMessage()); //DefaultInputHandler.getMessage()
            System.out.println(messages.floorEntry(15).getValue().getMessage()); //DefaultInputHandler.getMessage()
    In this case it would be:

    Code:
    messages.floorEntry(input).getValue()
    Update again: Try without any sort of conditional such as x > y!
    Reply With Quote  
     

  2. #2  
    Registered Member HarrySnow's Avatar
    Join Date
    Jan 2021
    Posts
    12
    Thanks given
    7
    Thanks received
    15
    Rep Power
    50
    You're taking his advice too literally. Any pattern you would use ultimately will contain conditional logic.

    I think the suggestion he was ultimately trying to point to you was that you should be mindful of how you design your software. Leverage common software design patterns to make your code more robust.

    But to answer your question:

    Code:
    switch(input) { case 0,1,2,3,4,5,6,7,8,9 -> handleLow() default-> handleHigh() }
    would technically answer your question.
    Reply With Quote  
     

  3. Thankful users:


  4. #3  
    Registered Member
    Join Date
    Dec 2013
    Posts
    419
    Thanks given
    127
    Thanks received
    85
    Rep Power
    349
    Quote Originally Posted by HarrySnow View Post
    You're taking his advice too literally. Any pattern you would use ultimately will contain conditional logic.

    I think the suggestion he was ultimately trying to point to you was that you should be mindful of how you design your software.

    But to answer your question:

    Code:
    switch(input) { case 0,1,2,3,4,5,6,7,8,9 -> handleLow() default-> handleHigh() }
    would technically answer your question.
    Re-read the original thread, it was pure curiosity. I'm most likely not personally ever going to follow this advice however there are actually some people that passionately hate IF statements. Arguably, intelligent ones too.

    There's supposedly campaigns that express death to if statements "anti if'ers".

    As for your code, that's one way! Not sure it would be feasible if the condition was if (n > 100)

    Just updated the thread with my solution!


    Code:
    NavigableMap<Integer, InputHandler> messages = new TreeMap<>();
            messages.put(Integer.MIN_VALUE, new DefaultInputHandler()); //everything
            messages.put(1, new LowInputHandler()); //values from 1..9
            messages.put(10, new HighInputHandler()); //values after 10 
            messages.put(15, new DefaultInputHandler()); //everything
            
            System.out.println(messages.floorEntry(7).getValue().getMessage()); //LowInputHandler.getMessage()
            System.out.println(messages.floorEntry(11).getValue().getMessage()); //DefaultInputHandler.getMessage()
            System.out.println(messages.floorEntry(15).getValue().getMessage()); //DefaultInputHandler.getMessage()
    Reply With Quote  
     

  5. #4  
    nice


    Join Date
    Jul 2014
    Posts
    740
    Thanks given
    382
    Thanks received
    562
    Rep Power
    4239
    'excellent way'
    Attached image
    Reply With Quote  
     

  6. Thankful user:


  7. #5  
    Registered Member
    Dread's Avatar
    Join Date
    Nov 2013
    Posts
    49
    Thanks given
    17
    Thanks received
    116
    Rep Power
    503
    Let's go for real hacky:

    Code:
    import java.util.function.IntConsumer;
    
    public class Test {
    
        private static final int HIGH_VALUE = 10;
    
        public static void main(String... args) {
            int input = 9;
            operate(input);
        }
    
        private static void operate(int input) {
            IntConsumer lowInput = (int i) -> System.out.println("The low number is: " + i);
            IntConsumer highInput = (int i) -> System.out.println("The high number is: " + i);
            IntConsumer[] consumers = {lowInput, highInput};
            consumers[(~(input - HIGH_VALUE) & 0x80000000) >>> 31].accept(input);
        }
    }
    Just for fun, I reimplemented this in x86
    Code:
    HIGH_VALUE equ 10
    
    global  _main
    extern  _printf
    
    section .text
    _main:
        mov eax,3 ; Input value
        mov edi,eax
        sub eax,HIGH_VALUE
        neg eax
        and eax,0x80000000
        shr eax,31
        mov ecx,[jmp_table+eax*4]
        push edi
        jmp ecx
        retn
    is_low:
        push low
        jmp operate
    is_high:
        push high
    operate:
        push message
        call _printf
        add esp,12
        retn
    jmp_table:
        dd is_low
        dd is_high
    low:
        db 'low', 0
    high:
        db 'high', 0
    message:
        db 'The %s input is %d.', 10, 0
    Reply With Quote  
     


  8. #6  
    Registered Member
    Join Date
    Dec 2013
    Posts
    419
    Thanks given
    127
    Thanks received
    85
    Rep Power
    349
    Quote Originally Posted by Dread View Post
    Let's go for real hacky:

    Code:
    import java.util.function.IntConsumer;
    
    public class Test {
    
        private static final int HIGH_VALUE = 10;
    
        public static void main(String... args) {
            int input = 9;
            operate(input);
        }
    
        private static void operate(int input) {
            IntConsumer lowInput = (int i) -> System.out.println("The low number is: " + i);
            IntConsumer highInput = (int i) -> System.out.println("The high number is: " + i);
            IntConsumer[] consumers = {lowInput, highInput};
            consumers[(~(input - HIGH_VALUE) & 0x80000000) >>> 31].accept(input);
        }
    }
    I love it

    Quote Originally Posted by Suic View Post
    'excellent way'
    It's essentially a hashmap but with range. Hopefully switch statements will soon support ranges though.
    Reply With Quote  
     

  9. #7  
    (Official) Thanksgiver

    Arham's Avatar
    Join Date
    Jan 2013
    Age
    23
    Posts
    3,415
    Thanks given
    7,254
    Thanks received
    1,938
    Rep Power
    3905
    Code:
    Map<Boolean, Runnable> actionMap = new HashMap<>();
    actionMap.put(true, () -> handleHigh());
    actionMap.put(false, () -> handleLow());
    actionMap.get(input > 10).run();
    Attached image
    Attached image
    Quote Originally Posted by MrClassic View Post
    Arham is the official thanker!
    List of my work here!
    Reply With Quote  
     

  10. #8  
    Registered Member
    Join Date
    Dec 2013
    Posts
    419
    Thanks given
    127
    Thanks received
    85
    Rep Power
    349
    Quote Originally Posted by Arham View Post
    Code:
    Map<Boolean, Runnable> actionMap = new HashMap<>();
    actionMap.put(true, () -> handleHigh());
    actionMap.put(false, () -> handleLow());
    actionMap.get(input > 10).run();
    Still using a conditional statement!
    Reply With Quote  
     

  11. #9  
    Registered Member

    Join Date
    Dec 2015
    Posts
    166
    Thanks given
    77
    Thanks received
    87
    Rep Power
    404
    Code:
    val result = Option(getUserInput())
      .filter(n => n > 10)
      .map(n => handleHigh())
      .orElse(handleLow())
    "It's all a matter of perspective. There is no single path in life that is right and fair and does no harm."
    Reply With Quote  
     

  12. Thankful users:


  13. #10  
    (Official) Thanksgiver

    Arham's Avatar
    Join Date
    Jan 2013
    Age
    23
    Posts
    3,415
    Thanks given
    7,254
    Thanks received
    1,938
    Rep Power
    3905
    Quote Originally Posted by Kiissmyswagb View Post
    Still using a conditional statement!
    You said without if-statements, not conditionals. Moreover, it isn't a statement, it's an expression.
    Attached image
    Attached image
    Quote Originally Posted by MrClassic View Post
    Arham is the official thanker!
    List of my work here!
    Reply With Quote  
     

  14. Thankful users:


Page 1 of 3 123 LastLast

Thread Information
Users Browsing this Thread

There are currently 1 users browsing this thread. (0 members and 1 guests)


User Tag List

Similar Threads

  1. Convert this code to PI
    By Eclipser in forum Help
    Replies: 7
    Last Post: 06-29-2012, 12:35 AM
  2. Replies: 1
    Last Post: 12-07-2011, 03:34 AM
  3. Replies: 4
    Last Post: 06-22-2010, 09:07 PM
  4. Can someone explain this code to me?
    By jordan641 in forum Help
    Replies: 3
    Last Post: 04-24-2010, 07:52 AM
  5. Can anyone convert this to espeon (508) Repp++
    By massacre215 in forum Requests
    Replies: 2
    Last Post: 08-02-2009, 01:39 PM
Posting Permissions
  • You may not post new threads
  • You may not post replies
  • You may not post attachments
  • You may not edit your posts
  •