如何从我的代码中删除重复项 [英] How to remove duplication from my code
本文介绍了如何从我的代码中删除重复项的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!
问题描述
我有两种类似的方法.其中一个打印一些东西,其中一个保存一些东西.如您所见,有很多重复的代码.我应该如何重构它并删除此重复项?
I have two similar methods. One of them prints something and one of them save somethings. As you can see there are a lot of duplicate code. How should I refactor it and remove this duplication ?
public static void printSomething(List<String> list) {
for (String item : list) {
if (item.contains("aaa")) {
System.out.println("aaa" + item);
}
if (item.contains("bbb")) {
System.out.println("bbb" + item);
} else {
System.out.println(item);
}
}
}
public static Map<String, String> getSomething(List<String> list) {
Map<String, String> map = new HashMap<String, String>();
for (String item : list) {
if (item.contains("aaa")) {
map.put("aaa", item);
}
if (item.contains("bbb")) {
map.put("bbb", item);
} else {
//do nothing
}
}
return map;
}
更新:
更新代码以解决方法不完全相似时的问题
Code was updated to solve problem when method are not exactly similar
推荐答案
具有方法 action(T t) 的通用接口 Action 可以减少代码.
A generic Interface Action that have a method action(T t) can reduce the code.
public interface Action<E> {
void action(E e);
}
示例:
public static void forEach(List<String> list, Action <String> action) {
for(String s : list){
action.action(s);
}
现在您只需要 2 种不同的 Action 实现.
Now you just need 2 different implementations of Action.
如果您不想创建类,可以使用匿名类型.
You can use annonymous types if you don't want to create a class.
如果您了解 c#,这与 lambdas 类似.
使用匿名类型:
public static Map<String, String> getSomething(List<String> list) {
final Map<String, String> map = new HashMap<String, String>();
forEach(list, new Action<String>() {
@Override
public void action(String e) {
if (e.contains("aaa")) {
map.put("aaa", e);
}
if (e.contains("bbb")) {
map.put("bbb", e);
} else {
// do nothing
}
}
});
return map;
}
创建类:
public static Map<String, String> getSomething2(List<String> list) {
final Map<String, String> map = new HashMap<String, String>();
forEach(list, new ListToMapAction(map));
return map;
}
public class ListToMapAction implements Action<String> {
Map<String, String> map;
public ListToMapAction(Map<String, String> map) {
this.map = map;
}
@Override
public void action(String e) {
if (e.contains("aaa")) {
map.put("aaa", e);
}
if (e.contains("bbb")) {
map.put("bbb", e);
} else {
// do nothing
}
}
}
这篇关于如何从我的代码中删除重复项的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!
查看全文