I think rigor is essential to every programmer, and writing elegant and efficient code is a lifelong pursuit.
preface
I always review the code developed by several members of my team before submitting it. In the past, I passed a lot of unsatisfied code fragments, either written by interns or colleagues with years of development experience. Today, I have a sudden impulse to share some code snippets with you, hoping to bring you some inspiration and inspiration.
The theme
Due to the influence of our stereotypical thinking, we write code, in many cases without others to remind us, it is difficult to find something wrong.
Poor command of MAP
Student Student =new Student(" 新 Student "); Map<String, Object> map3 = new HashMap<String, Object>(); Map3. put("k", "k"); map3.put("v", student.getCollogeName()); resultlist.add( map3); Map<String, Object> map4 = new HashMap<String, Object>(); Map4. put("k", "professional "); map4.put("v", student.getMajorName()); resultlist.add( map4); Map<String, Object> map5 = new HashMap<String, Object>(); Map5. put("k", "class "); map5.put("v", student.getBjmc()); resultlist.add(map5);Copy the code
As you can see from the above code, this developer probably started with a single map and found that all maps after list.add were the last one. The initial code looks like this
Student Student =new Student(" 新 Student "); Map<String, Object> map = new HashMap<String, Object>(); Map. Put ("k", "college "); map.put("v", student.getCollogeName()); resultlist.add( map3); Map. Put ("k", "professional "); map.put("v", student.getMajorName()); resultlist.add( map);Copy the code
Such code causes the map to be overwritten because the key is the same. So what’s wrong with changing to his code? Mainly is the problem that the variable name, according to this logic, for example, the next time you need map6, map7, map8, this variable to maintain a few times, delete, increase is elegant, might as well to:
Student Student =new Student(" 新 Student "); Map<String, Object> map = new HashMap<String, Object>(); Map. Put ("k", "college "); map.put("v", student.getCollogeName()); resultlist.add( map3); map = new HashMap<String, Object>(); Map. Put ("k", "professional "); map.put("v", student.getMajorName()); resultlist.add( map);Copy the code
This way, every time you create a new HashMap, you can eliminate the problem of having an inelegant name. Add k and v keys to map.
Student Student =new Student(" 新 Student "); Resultlist. add(new MapKV(" college ", student.getcollogename ())); Resultlist. add(new MapKV(" professional ", student.getmajorName ()));Copy the code
And this MapKV, I don’t need to tell you anything, just has two strings, k and v.
I am not sure about mybatis
public interface QuestionDao {
List<Question> getQuestionList();
}
Copy the code
Corresponding map file questionmapper.xml
List<Question> questionList = QuestionDao.findBy(params); If (mexamList == null) {// Throw exception}Copy the code
The dao layer of Mybatis cannot return a null list, even if size()=0 only returns a new list, so there is no need to determine the list is null
The equals are not ripe
If (user.get("sl").equals(" sl")) {Copy the code
Many people say that this error is impossible, if the front is null, it will report an error, but I have searched the previous project globally, it is inevitable to find one or two, after all, there are historical legacy problems, intern problems and so on. Because we know null can’t change.equals to:
If (" equals ".equals(user.get("sl"))) {Copy the code
The abuse of the toString
user.get("sl").toString();Copy the code
An error is reported if the preceding value is null. Null cannot have any methods.
On the return are not ripe
Public String getResult() {if (" condition ") {// return "result "; }else {// a bunch of code return "result "; }}Copy the code
Now that there is a return to make sure that the following code does not go, you can rest assured that the bold release
Public String getResult() {if (" condition ") {// return "result "; } // a bunch of code return "result "; }Copy the code
Will not use continue, break, if too long
For example, when searching for a name in a list, break the name in time to save CPU.
for (int i = list.size() - 1; i >= 0; I -) {if (" Shao Lei ". The equals (list) get (I)) getName ())) {user = list. Get (I); }}Copy the code
Instead of
for (int i = list.size() - 1; i >= 0; I -) {if (" Shao Lei ". The equals (list) get (I)) getName ())) {user = list. Get (I); break; }}Copy the code
Suppose that no operation is performed except for a named person, the code looks like this:
for (int i = list.size() - 1; i >= 0; I -) {if (" Shao Lei ". The equals (list) get (I)) getName ())) {/ / there are only two things. user=list.get(i); }else{// do a lot of things here}}Copy the code
In this case, we can drop the if and use the continue
for (int i = list.size() - 1; i >= 0; I -) {if (" Shao Lei ". The equals (list) get (I)) getName ())) {/ / there are only two things. user=list.get(i); continue; } // Do a lot of things here}Copy the code
Continue: exits the current loop and continues with the next loop break: exits the body of the function and continues with the body of the function outside the loop return: exits the entire body of the function and the rest of the body is not executed
Not familiar with the for loop
if (list.size()==0) { for (int i = list.size() - 1; i >= 0; I --) {// do something}}Copy the code
And we know that even list.size()==0 doesn’t affect the code, so let’s just do it
for (int i = list.size() - 1; i >= 0; I --) {// do something}Copy the code
Wrong with try catch
Try catch wrap a chunk
} catch (Exception e) {// error}Copy the code
As to
Try {// this code may be abnormal} catch (Exception e) {// this code is not abnormal // this code is not abnormalCopy the code
This is more readable and elegant, and of course throws can also be used to catch exceptions. Try catch is in the for loop
for (int i = list.size() - 1; i >= 0; I --) {try {catch (Exception e) {catch (Exception e) {Copy the code
We know that a trycatch is going to wrap the whole code around it, and it’s going to be an expensive, frequent trycatch, and except for special cases, you can extract the method and wrap it around it.
Duplicate code snippets
For example, if a method is called multiple times in a class, and only some variables are different, you can extract methods and variables to make the code concise
Don’t use case
If (type = = 1) {} else if (type = = 2) {} else if (type = = 3) {} else if (type = = 4) {}.....................Copy the code
This would be a very long if, and we know that string matching can also be solved using case. In Java 7 and above, case strings are supported.
Switch (argument) {case constant expression 1: break; Case constant expression 2: break; . default: break; }Copy the code
Lazy loading is not used
Such as
String STR = "STR "; if (i == 1){ list.add(str); }Copy the code
Can be changed to
If (I == 1){String STR = "STR "; list.add(str); }Copy the code
Keep creating object references
for (int i = 1; i <= 100; i++) { Object obj = new Object(); // Other code}Copy the code
This will only open up many Object references in memory
Object obj; for (int i = 1; i <= 100; i++) { obj = new Object(); // Other code}Copy the code
conclusion
We solve the problem, may have many kinds of ideas, but also can write many kinds of code, but the code to write elegant is a skill, of course, the first part of the introduction, attention is high, I continue to update. Finally, I’d like to add that I’m not actually a Virgo, but that’s what people call me, so I’ll take it.
If you feel good, remember to pay attention to me! The Denver nuggets: juejin. Cn/user / 272334…