关于LISt Process...
前2天听了熊老师的一个Session,关于List Process的,差点忘了总结,现记录如下:
从一个Story开始,现需求如下:(注:List中的每个元素都是都是整数)
(1)、给定一个List,把List中的每个元素+1,返回新的List;
(2)、给定一个List,把List中的每个元素*2,返回新的List;
(3)、给定一个List,取出其中的偶数,返回新的List;
以TDD的思维开发,先写Testcase
public class ListProcessTest { @Test public void test_every_element_in_list_add_one() throws Exception { List<Integer> inputList = Arrays.asList(1, 2, 3, 4); assertThat(ListProcess.addOne(inputList), is(Arrays.asList(2, 3, 4, 5))); } @Test public void test_every_element_in_list_multiply_two() throws Exception { List<Integer> inputList = Arrays.asList(1, 2, 3, 4); assertThat(ListProcess.multiplyTwo(inputList), is(Arrays.asList(2, 4, 6, 8))); } @Test public void test_get_even_from_input_list() throws Exception { List<Integer> inputList = Arrays.asList(1, 2, 3, 4); assertThat(ListProcess.getEvenList(inputList), is(Arrays.asList(2, 4))); }}
public class ListProcess { public static List<Integer> addOne(List<Integer> inputList) { List<Integer> result = new ArrayList<Integer>(); for (int input : inputList) { result.add(input + 1); } return result; } public static List<Integer> multiplyTwo(List<Integer> inputList) { List<Integer> result = new ArrayList<Integer>(); for (int input : inputList) { result.add(input * 2); } return result; } public static List<Integer> getEvenList(List<Integer> inputList) { List<Integer> result = new ArrayList<Integer>(); for (int input : inputList) { if (input % 2 == 0) { result.add(input); } } return result; }}功能完成,测试通过之后,马上就回发现这段代码的Bad Smell,一共才5,6行的函数,居然和其他函数有4句代码是重复的,然后熊老师就开始给我们讲这个Session的主要目的。
public class ListProcess { public static List<Integer> addOne(List<Integer> inputList) { return Lists.transform(inputList, new Function<Integer, Integer>() { @Override public Integer apply(@Nullable Integer integer) { return ++integer; } }); } public static List<Integer> multiplyTwo(List<Integer> inputList) { return Lists.transform(inputList, new Function<Integer, Integer>() { @Override public Integer apply(@Nullable Integer integer) { return integer * 2; } }); } public static List<Integer> getEvenList(List<Integer> inputList) { //注:不知为何,Google Collections没有把Filter也做在Lists里面,而是放到Collections2里面,返回一个Collection<E>,我们不得不自己转成List List<Integer> result = new ArrayList<Integer>(); result.addAll( Collections2.filter(inputList, new Predicate<Integer>() { @Override public boolean apply(@Nullable Integer integer) { return integer % 2 == 0; } })); return result; }}这样改完之后有什么好处呢?