How do you handle huge if-conditions?

后端 未结 21 1735
一向
一向 2021-01-31 17:14

It\'s something that\'s bugged me in every language I\'ve used, I have an if statement but the conditional part has so many checks that I have to split it over multiple lines, u

21条回答
  •  挽巷
    挽巷 (楼主)
    2021-01-31 17:52

    Try looking at Functors and Predicates. The Apache Commons project has a great set of objects to allow you to encapsulate conditional logic into objects. Example of their use is available on O'reilly here. Excerpt of code example:

    import org.apache.commons.collections.ClosureUtils;
    import org.apache.commons.collections.CollectionUtils;
    import org.apache.commons.collections.functors.NOPClosure;
    
    Map predicateMap = new HashMap();
    
    predicateMap.put( isHonorRoll, addToHonorRoll );
    predicateMap.put( isProblem, flagForAttention );
    predicateMap.put( null, ClosureUtils.nopClosure() );
    
    Closure processStudents = 
        ClosureUtils.switchClosure( predicateMap );
    
    CollectionUtils.forAllDo( allStudents, processStudents );
    

    Now the details of all those isHonorRoll predicates and the closures used to evaluate them:

    import org.apache.commons.collections.Closure;
    import org.apache.commons.collections.Predicate;
    
    // Anonymous Predicate that decides if a student 
    // has made the honor roll.
    Predicate isHonorRoll = new Predicate() {
      public boolean evaluate(Object object) {
        Student s = (Student) object;
    
        return( ( s.getGrade().equals( "A" ) ) ||
                ( s.getGrade().equals( "B" ) && 
                  s.getAttendance() == PERFECT ) );
      }
    };
    
    // Anonymous Predicate that decides if a student
    // has a problem.
    Predicate isProblem = new Predicate() {
      public boolean evaluate(Object object) {
        Student s = (Student) object;
    
        return ( ( s.getGrade().equals( "D" ) || 
                   s.getGrade().equals( "F" ) ) ||
                 s.getStatus() == SUSPENDED );
      }
    };
    
    // Anonymous Closure that adds a student to the 
    // honor roll
    Closure addToHonorRoll = new Closure() {
      public void execute(Object object) {
        Student s = (Student) object;
    
        // Add an award to student record
        s.addAward( "honor roll", 2005 );
        Database.saveStudent( s );
      }
    };
    
    // Anonymous Closure flags a student for attention
    Closure flagForAttention = new Closure() {
      public void execute(Object object) {
        Student s = (Student) object;
    
        // Flag student for special attention
        s.addNote( "talk to student", 2005 );
        s.addNote( "meeting with parents", 2005 );
        Database.saveStudent( s );
      }
    };
    

提交回复
热议问题