10 disciplines that Java programmers should follow _java

Source: Internet
Author: User
Tags prepare readable stringbuffer

What are the "disciplines" that Java programmers should follow?

1. Add a comment for the code (add comments to your code). – everyone knows this, but not everyone does. How many times have you "forgotten" to add a comment? Indeed, annotations do not add any function to your program. But how many times have you seen the code written 2 weeks ago and you can't remember what it's for? You are lucky that the annotated code is written by yourself, and there is a residual impression in your mind. Unfortunately, most of the time, the code is written by someone else, and that person is likely to have left the company. The saying is good: "Accumulate, mutual benefit", so programmers should be considerate to each other (and yourself) and annotate your code.

2. Don't complicate simple things (do not complicate things). -I've done this before, and I'm sure you are. Developers tend to use complex methods to solve simple problems. We introduce EJBS into a system of only 5 users, implementing a framework for applications that do not require a framework, using attribute files, object-oriented solutions, and threading, which are not needed at all. Why would you do that? Some people may not know there is a better solution, but others may deliberately do so to learn new knowledge, or simply because it is interesting. For those who don't know a better solution, listen to the advice of an experienced programmer. For those who complicate design for purely personal purposes, I suggest you be more professional.

3. Remember-"The less the better" is not always the case (Keep in mind– "Less are more" are not always better). -Efficient code is a good thing, but in many cases, it's not as if the number of lines of code is less efficient. Look at the following "simple" example:

if (Newstatuscode.equals ("SD") && (selloffdate = = NULL | |  
Todaydate.compareto (selloffdate) <0 | | (lastuseddate!= null && todaydate.compareto (lastuseddate) >0)) || (Newstatuscode.equals ("OBS") && (obsdate = = NULL | |  
Todaydate.compareto (obsdate) <0))) { 
    Newstatuscode = "NYP"; 
} 

How difficult is it to point out what this if condition is? Again, the person who wrote this code didn't follow 1th-add a comment for the code.

Is it easier to understand if the IF condition is broken down into 2 if statements? Now let's take a look at the modified code:

if (Newstatuscode.equals ("SD") && (selloffdate = = NULL | |  
Todaydate.compareto (selloffdate) <0 | | (lastuseddate!= null &&  
Todaydate.compareto (lastuseddate) >0))) { 
    Newstatuscode = "NYP"; 
} else  
if (newstatuscode.equals ("OBS") && (obsdate = = NULL | |  
Todaydate.compareto (obsdate) <0)) 
{ 
    Newstatuscode = "NYP"; 
} 

Isn't it better to be readable? Indeed, we wrote repeating statements; indeed, we wrote an IF and 2 curly braces, but the code is more readable and easier to understand!

4. Do not "hard code" (No hard coding please). -Due to time constraints, developers will always forget or deliberately ignore this one. Yet another possibility is that, following this commandment, we will not fall into the "time crunch" dilemma. How long does it take to define a static final variable and add one line of code? Such as:

public class A {public 
   
    static final String s_constant_abc = "ABC"; 
   
    public boolean MethodA (String sParam1) { 
       
      if (a.s_constant_abc.equalsignorecase (sParam1)) {return 
        true; 
      }     
      return false; 
    } 
} 

Now, each time you need to compare the string "ABC" with a variable, we simply reference a.s_constant_abc, without having to remember what it is. Modifications to this constant are also very handy, and you can change one place without having to look up all the code.

5. Don't invent your own frame (do not invent your own frameworks). -It's no exaggeration to say that there are already thousands of frameworks, most of them open source. Many frameworks are perfect solutions and have been used in thousands of systems. We just need to focus on the latest popular frame, at least superficially familiar. One of the most successful and widely used examples is the Struts framework, an OPEN-SOURCE web framework that is an excellent choice for building a web system, and not trying to build your own struts version will be exhausting. But you have to keep in mind the 2nd ("3rd", obviously not) commandment-don't complicate simple things. If you're developing a system that has only 3 interfaces, don't use struts. For such a system, there is not enough to be "controlled" things ("struts will be the interface to do MVC division, C is controller, so the author said there isn ' t much" controlling "required).

6. Say no to print line or string (Say No to print lines and string concatenations). -I know that for debugging purposes, programmers like to use System.out.println everywhere, and then tell themselves to delete them for a while. But we often forget to delete these lines or do not want to delete, we use SYSTEM.OUT.PRINTLN to do the test, why do we have to change the code after the completion of the measurement? This is likely to result in the deletion of the code we need in a row. Do not underestimate the harm of System.out.println, look at the following code:

public class Badcode {public 
  static void Calculationwithprint () { 
    double somevalue = 0 D; 
    for (int i = 0; I < 10000 i++) { 
      System.out.println (somevalue = somevalue + i); 
    } 
  public static void Calculationwithoutprint () { 
 
      double somevalue = 0 D; 
      for (int i = 0; I < 10000 i++) { 
        somevalue = somevalue + i; 
      } 
     
  } 
  public static void Main (String [] n) { 
    badcode.calculationwithprint (); 
    Badcode.calculationwithoutprint (); 
  } 
 

The following table shows that the Calculationwithoutprint () method execution time is 0.001204 s. As a contrast, the Calculationwithprint () method actually requires an incredible 10.52 s to execute!

(If you want to know how to make a table like this, please read another article "Java Profiling with WSAD" Java Profiling with WSAD)

In order to avoid CPU waste, the best approach is to introduce a packaging method, as follows:

public class Badcode {public 
   
    static final int debug_mode = 1; 
    public static final int production_mode = 2; 
   
  public static void Calculationwithprint (int logmode) {   
    double somevalue = 0 D; 
    for (int i = 0; I < 10000 i++) { 
      somevalue = somevalue + i; 
      Myprintmethod (LogMode, somevalue); 
    } 
       
  public static void Myprintmethod (int logmode, double value) { 
    if (LogMode > Badcode.debug_mode) {return  ;} 
    System.out.println (value);   
  } 
  public static void Main (String [] n) { 
    badcode.calculationwithprint (badcode.production_mode); 
    } 

String concatenation is another way of wasting CPU, look at the following example:

public static void Concatenatestrings (String startingstring) {for 
    (int i = 0; i < i++) { 
      startingstring = Startingstring + startingstring; 
    } 
  } 
   
  public static void Concatenatestringsusingstringbuffer ( 
String startingstring) { 
    StringBuffer sb = new StringBuffer (); 
    Sb.append (startingstring); 
      for (int i = 0; i < i++) {sb.append ( 
        sb.tostring ()); 
      } 
} 

From the table below you can see that using StringBuffer as long as it takes 0.01 s to use string connections requires 0.08 s, which should be obvious.

7. Note The graphical user interface (Pay attention to the GUI). -No matter how absurd it may sound, one thing I've noticed many times: the graphical user interface (GUI) is as important to business users as the program function and execution efficiency. The GUI is critical for the success of your application. IT managers are often ignoring the importance of GUI, and many companies are not hiring web designers to save money, and these designers have enough experience to design "user-friendly" applications, management. Java programmers have to rely on their limited hmtl knowledge. I've seen a lot of "computer-friendly" and not "user-friendly" apps, and developers proficient in software development and user interface development are rare. If you are a Java programmer who has unfortunately been assigned to do interface development, you should follow the following 3 rules:

A. Don't reinvent the wheel. Look at the interfaces that are similar to application systems.
B. Establish a prototype first. This is a crucial step. Customers like to see what they want in advance. Also you can get their feedback instead of having to make a lot of things that a customer doesn't like.
C. Try to wear a user's hat. In other words, stand in the user's perspective to see the requirements. For example, a statistical interface can be paginated or paginated. As a developer, it is likely that paging will be overlooked because it can reduce a lot of hassle, and it's not a good plan to stand on the customer's side because the data can be as many as hundreds of rows.
8. Prepare requirements documentation in advance (Always Prepare document Requirements). – Each business requirement is recorded in the document. This can be achieved in fairy tales, and it's hard to do in reality. No matter how tight your time is, no matter how close the deadline is, you have to make sure that your business needs are recorded. This is a clearly contrary to the concept of agile development, we have to think independently, screening right and wrong.

9. Unit test, Unit Test, Unit Test (unit-test). Unit-test. Unit-test). – I'm not going to discuss the details of unit testing, I just want to say that it has to be done. This is the most basic rule in programming, especially not to be ignored. If your co-workers can create a test plan for your code, that's great; if not, do it yourself. When making a unit test plan, follow these guidelines:

A. Write unit tests before coding
B. Retention notes for unit tests
C. Unit testing of any "interesting" public method ("interesting" means a method other than the most common getter/setter such as a method, but containing a getter/setter method with its own content)
10. Remember: Quality, not quantity (remember–quality, not quantity). -Don't stay too late (unless necessary). I know that sometimes due to product problems, deadlines or other unexpected events, can not work on time. But managers will not appreciate or reward you for being too late for a general problem; they will be grateful to you for a quality job. If you follow the principles listed above, you will write more robust, less bug-prone programs. That's the best you could do.

This article summarizes 10 of the best practices that Java programmers should pay attention to. Just knowing is not enough, but also follow them. Hopefully, these codes will allow us to be more professional programmers.

Related Article

Contact Us

The content source of this page is from Internet, which doesn't represent Alibaba Cloud's opinion; products and services mentioned on that page don't have any relationship with Alibaba Cloud. If the content of the page makes you feel confusing, please write us an email, we will handle the problem within 5 days after receiving your email.

If you find any instances of plagiarism from the community, please send an email to: info-contact@alibabacloud.com and provide relevant evidence. A staff member will contact you within 5 working days.

A Free Trial That Lets You Build Big!

Start building with 50+ products and up to 12 months usage for Elastic Compute Service

  • Sales Support

    1 on 1 presale consultation

  • After-Sales Support

    24/7 Technical Support 6 Free Tickets per Quarter Faster Response

  • Alibaba Cloud offers highly flexible support services tailored to meet your exact needs.