avoiding if statements

前端 未结 24 744
心在旅途
心在旅途 2021-01-30 08:39

I was thinking about object oriented design today, and I was wondering if you should avoid if statements. My thought is that in any case where you require an if statement you ca

24条回答
  •  走了就别回头了
    2021-01-30 09:24

    In answer to ifTrue's question:

    Well, if you have open classes and a sufficiently strong dependent type system, it's easy, if a bit silly. Informally and in no particular language:

    class Nat {
        def cond = {
            print this;
            return this;
        }
    }
    
    class NatLessThan<5:Nat> { // subclass of Nat
        override cond = {
            return 0;
        }
    }
    
    x = x.cond();
    

    (continued...)

    Or, with no open classes but assuming multiple dispatch and anonymous classes:

    class MyCondFunctor {
        function branch(Nat n) {
            print n;
            return n;
        }
    
        function branch(n:NatLessThan<5:Nat>) {
            return 0;
        }
    }
    
    x = new MyCondFunctor.branch(x);
    

    Or, as before but with anonymous classes:

    x = new {
        function branch(Nat n) {
            print n;
            return n;
        }
    
        function branch(n:NatLessThan<5:Nat>) {
            return 0;
        }
    }.branch(x);
    

    You'd have a much easier time if you refactored that logic, of course. Remember that there exist fully Turing-complete type systems.

提交回复
热议问题