How to simplify your code

package simple.code;

/**
 * simplify if-elif-elif-else when return is boolean
 * @author weijun.zou
 * Create on 2017/12/6
 */
public class Loader {

    private boolean load1(String args) {
        if (args == null) {
            return false;
        } else if (args.equals("")) {
            return defaultLoad();
        } else if (args.startsWith("a")) {
            return aLoad(args);
        } else if (args.startsWith("b")) {
            return bLoad(args);
        } else if (args.startsWith("c")) {
            return cLoad(args);
        } else {
            return false;
        }
    }

    // warn : it is not equals load1 ,so you need think carefully
    // if change method, such as load1(T t),load2(T t)
    // if t meet the conditions 'a' and t also meet conditions 'b',but aLoad(t) is false,bLoad(t) is true
    // the method load1(T t) is false,the method load2(T t) is true;
    // where t is a String,so t could not startWith 'a' and 'b'
    private boolean load2(String args) {
        return args != null && (
                (args.equals("") && defaultLoad())
                || (args.startsWith("a") && aLoad(args))
                || (args.startsWith("b") && bLoad(args))
                || (args.startsWith("c") && cLoad(args))
        );
    }

    private boolean defaultLoad() {
        // do something
        return true;
    }

    private boolean aLoad(String args) {
        // do something
        return true;
    }

    private boolean bLoad(String args) {
        // do something
        return true;
    }

    private boolean cLoad(String args) {
        // do something
        return true;
    }

}
package simple.code;

import java.util.HashMap;
import java.util.Map;
import java.util.function.BiFunction;

/**
 * simplify if-elif-elif-else when you need mapping
 * @author weijun.zou
 * Create on 2017/12/6
 */
public class Calculator {

    public int compute1(int a, char f, int b) {
        if (f == '+') {
            return a + b;
        } else if (f == '-') {
            return a - b;
        } else if (f == '*') {
            return a * b;
        } else if (f == '/') {
            return a / b;
        } else {
            return a % b;
        }
    }

    //use switch
    public int compute2(int a, char f, int b) {
        switch (f) {
            case '+':
                return a + b;
            case '-':
                return a - b;
            case '*':
                return a * b;
            case '/':
                return a / b;
            default:
                return a % b;
        }
    }

    //use '? :' , it's so simple
    public int compute3(int a, char f, int b) {
        int res = f == '+' ? a + b
                : f == '-' ? a - b
                : f == '*' ? a * b
                : f == '/' ? a / b
                : a % b;
        return res;
    }

    private Map<Character, BiFunction<Integer, Integer, Integer>> computeMap = new HashMap<>();

    {
        computeMap.put('+', (a, b) -> a + b);
        computeMap.put('-', (a, b) -> a - b);
        computeMap.put('*', (a, b) -> a * b);
        computeMap.put('/', (a, b) -> a / b);
        computeMap.put('%', (a, b) -> a % b);
    }
    //use map,you can dynamic increase expression,such as 'a^b','max(a,b)',...
    public int compute4(int a, char f, int b) {
        return computeMap.getOrDefault(f, computeMap.get('%')).apply(a, b);
    }

}
package simple.code;

import java.util.List;

/**
 * simplify 'for'
 *
 * @author weijun.zou
 * Create on 2017/12/6
 */
public class Sum {

    //this is a bad demo, time complexity is O(n^2) when you use LinkedList
    //so never use "for(i=0;i<size;i++)" when not necessary
    public long rangeSum1(List<Integer> list, int minLimit, int maxLimit) {
        long sum = 0;
        for (int i = 0; i < list.size(); i++) {
            if (list.get(i) >= minLimit && list.get(i) <= maxLimit) {
                sum += list.get(i);
            }
        }
        return sum;
    }

    //foreach
    public long rangeSum2(List<Integer> list, int minLimit, int maxLimit) {
        long sum = 0;
        for (int e : list) {
            sum += (e >= minLimit && e <= maxLimit) ? e : 0;
        }
        return sum;
    }

    //stream and lambda,I love this style of coding
    public long rangeSum3(List<Integer> list, int minLimit, int maxLimit) {
        return list.stream()
                .mapToInt(Integer::intValue)
                .filter(e -> e >= minLimit)
                .filter(e -> e <= maxLimit)
                .asLongStream()
                .sum();
    }
}
package simple.code;

import java.util.*;

import static java.util.stream.Collectors.groupingBy;

/**
 * @author weijun.zou
 * Create on 2017/12/6
 */
public class WordUtils {

    //In the past, you need to do this
    public static String mostWord1(String... words) {
        Map<String, Integer> wordMap = new HashMap<>();
        for (String word : words) {
            if (wordMap.containsKey(word)) {
                wordMap.put(word, wordMap.get(word) + 1);
            } else {
                wordMap.put(word, 1);
            }
        }
        String mostWord = null;
        int most = 0;
        for (Map.Entry<String, Integer> entry : wordMap.entrySet()) {
            if (entry.getValue()>most){
                mostWord = entry.getKey();
                most = entry.getValue();
            }
        }
        return mostWord;
    }

    //now you can do this
    public static String mostWord2(String...words){
        return Arrays.stream(words)
                .collect(groupingBy(String::toString))
                .entrySet()
                .stream()
                .map(Map.Entry::getValue)
                .max(Comparator.comparingInt(List::size))
                .orElse(Collections.singletonList(null))
                .get(0);
    }
}
發表評論
所有評論
還沒有人評論,想成為第一個評論的人麼? 請在上方評論欄輸入並且點擊發布.
相關文章