Four harmful Java coding habits

Source: Internet
Author: User
Tags coding standards

For programming languages, a good coding style can not only generate effective framework encoding at the beginning of programming, but also make our coding clearer and more standardized. However, as mentioned by the author in this article, although the coding style of some Java programs is widely used, it will have a negative impact on the maintainability of coding and will be harmful to our programming. This article tells you how to break this style, rewrite these four harmful encoding styles, optimize the encoding, and improve maintainability.

The encoding style in the program makes our programming work easier, especially the program maintainer. They often need to read the coding compiled by others, which is particularly prominent. Coding standards fundamentally solve the difficulties of program maintainers. It is easier to read and understand the codes, and you can quickly learn from others' codes without any effort. For those who will maintain your code in the future, the more optimized your code, the more they will like your code and the faster they will understand it.

Similarly, high-level coding styles (such as fixed closed structures) aim to improve design and make coding easier to understand. In fact, some people may think that it is one thing to improve the design and improve the coding.

In this article, you will see that some popular encoding styles are replaced by more acceptable styles for readers. Some people argue that these styles have been widely used and should not be simply discarded to meet the reader's expectations. However, the reader's expectation is only one of the reasons, and it cannot be above all factors. List four common problems:

1.Local variables and parameters (method arguments), Field (fields)The names of these three variables are not differentiated:

For those who look at the code, first of all, we need to understand how the data is defined? When looking at a class, you have to figure out that each entry is a local variable? Field? Or parameter? It is necessary to use a simple naming convention to define these variables and add yi.

Many authorities regulate field variables to distinguish them from other variables, but this is far from enough. The rational naming convention logic for fields can also be applied to parameters. First, let's look at Example 1: There is no class definition to distinguish these three variables, as shown below:

Example 1:
1 public boolean equals (Object arg) {2   if (! (arg instanceof Range)) return false;3   Range other = (Range) arg;4   return start.equals(other.start) && end.equals(other.end);5 }

In this method, Arg uses the abbreviation of argument. Although you can see it as a parameter, this naming method loses the meaning of the object represented by the parameter. You know that this is a parameter, but you do not know what it is. If there are more parameters in the method, they are all named in the arg1 or arg2 format. It is a headache to read the code. The other two field variables, start and end, suddenly come out of thin air, think about it to know that this should be a field. Of course, this method is very short, causing little difficulty. If this method is relatively long, you will suddenly see the start and end changes. Generally, you will first check whether it is a local variable, then you can determine the field variable of the class.

This question seems insignificant, but why do you need to let the code reader spend extra time on these trivial issues? If there is a solution that allows the code reader to clearly understand the variables, why not use them? As Steve McConnell said in "code Daquan": "it's okay to worry about the mysterious killer, but you don't need to worry about the program code. The code is used for reading.

Next, let's take a look at Example 2. Use the naming conventions and rewrite the code in Example 1. The naming conventions used include:
  • ParametersDefinitionWhen the name is prefixed with
  • Prefix F for field Definition
  • When defining a local variable, no prefix is added.
Example 2: differentiate variable types
1 public boolean equals (Object aOther) {2   if (! (aOther instanceof Range)) return false;3   Range other = (Range) aOther;4   return fStart.equals(other.fStart) && fEnd.equals(other.fEnd);5 }
You may oppose the style in example 2 and the obsolete Hungarian symbol, but I think it is wrong because the Hungarian symbol can describe the type of information in detail.
The naming conventions above distinguish between types. In addition, fields, variables, and local variables are distinguished in this way, which are two completely different concepts.
This naming convention is not as trivial as it looks: when these conventions are used in program coding, it will greatly reduce the difficulty of understanding, because you do not need
You need to identify these variables first, saving a lot of time.

2. Package partitioning by Hierarchy
Instead of dividing by features or functions

The most common application order is hierarchical naming packages:
  • com.blah.action
  • com.blah.dao
  • com.blah.model
  • com.blah.util
That is to say, classes with the same features or functions are divided into different packages. Because the attributes of members should be visible to other Members, this means that almost all classes in the application are public. In fact, this hierarchical packet division method completely discards the private content in the Java package. Private in the package should be completely unavailable. Now, private in the package is the default scope of designers in the Java programming language. This classification habit of packages also violates the core principles of object-oriented programming-keep private as much as possible to reduce the impact, because this habit forces you to expand the scope of the class. For some strange reason, it seems unfair that some java organizations do not approve of such naming. Another style is naming by feature:
  • com.blah.painting
  • com.blah.buyer
  • com.blah.seller
  • com.blah.auction
  • com.blah.webmaster
  • com.blah.useraccess
  • com.blah.util
Here, Members are not divided by behavior, but by class of different features. Each member is associated with different features. In this method, the package is defined at the beginning. For example, in a web application, com.blah.paintingThe package may consist of the following members:
  • Painting. Java: A model object
  • Paintingdao. Java: a data access object Dao
  • Paintingaction. Java: A control or behavior object
  • Statements. SQL: SQL file used by the DaO object
  • View. jsp: JSP file
In particular, in this division method, each package contains feature files related to all members, not just Java source files. This feature-based packet division method requires you to note that when deleting a feature, you must delete the entire directory of the feature and cannot store it in the source code. This method is better than the hierarchical packet division method, as shown in the following:
  • The package is highly cohesive and modular. The coupling between the package and the package is minimized.

  • The self-descriptive enhancement of the Code. The reader only needs to check the package name to make a general impression on some functions or features of the program. In code Daquan,Steve McConnell likes self-descriptive code to the Holy Grail of easy reading to express its ease of reading.

  • Separating classes from functional areas based on each feature makes it easy to implement hierarchical design.

  • The relevant members are in the same position. You do not need to browse the entire source code tree to edit a related member.

  • The member's scope is private in the package by default. Only when another package needs to access a member can it be changed to public. (it should be noted that modifying a class to public does not mean that all its class members should be changed to public. Public members and package-Private Members can coexist in the same class .)

  • To delete a function or feature, you only need to delete a folder.
  • Each package generally has only a few members, so that the package can naturally develop according to evolution. If the package grows too large, it can be subdivided into two or more new packages, similar to the evolution of species. However, there is no way to develop in an evolutionary manner based on the hierarchy, and restructuring is not easy.
For some frameworks, it is recommended to use the traditional method of defining packages at different layers.As the package naming method: because the traditional package naming method is used, developers can always know where to find the package.
These projects, but why do we avoid doing this? This monotonous operation is not required to use another feature-defined package style. Therefore,
Defined by feature
Beyond any other naming conventions. Joshua blohe wrote in "efficient Java" that the only important factor in distinguishing a good design is the module's internal hiding.
Data and the implementation process involved in other modules.

3. You are used to Using JavaBeans instead of immutable objects.

The immutable object does not change its status after being constructed. Martin odersky, the main creator of Scala, also recently praised this immutable object. In efficient Java
Joshua Bloch lists a large number of instances that support using immutable objects and summarizes many advantages. However, his opinion seems to be largely ignored. Most Processes
Use JavaBeans in sequence to replace immutable objects. Javabean is much more complex than an immutable object because of its huge declared space. Roughly speaking, you can
Think of JavaBean as the opposite of an immutable object: it allows maximum variability.
Javabean is often used to map database records. If you want to map a row from the database record set as an object without considering the existing persistence scheme and framework, you will
What is the design of this object? Is it similar to JavaBean?

I think it will be totally different, as described below:

  • It does not contain a non-parameter Constructor (this feature is essential for JavaBean .). The author believes that it makes no sense for a database record object to include no data. What are the optional fields of a database table?
  • It wowould likelyNotHave anything to say about events and listeners)

  • It does not force you to use mutable objects.
  • It has a data verification mechanism. Such a verification mechanism is very important to most database applications. (Remember the first principle of objects: an object should encapsulate data and operate on data at the same time. In this case, the operation is to verify the data .)

  • The data verification mechanism can report an error to the end user.

According to JavaBeans, JavaBeans are used to solve the problem in special fields: they act as widgets in the graphic interface program design. The description does not mention databases. However, JavaBean is usually used for database record ing. In practice, many widely used frameworks require applications to map database records Using JavaBeans (or other similar specifications. This abuse is not conducive to programmers to understand and use immutable objects.

4. Private Members are placed before other members.

The sort of Class Members is not arranged according to the size of the scope of the members, but the private is placed in front.
Old Hollywood films always start with long honors. Similarly, most Java classes place private members at the beginning. Example 3 provides a typical example of this style:

 1 public class OilWell implements EnergySource { 2    private Long id; 3    private String name; 4    private String location; 5    private Date discoveryDate; 6    private Long totalReserves; 7    private Long productionToDate; 8  9    public Long getId() {10       return id;11    }12    public void setId(Long id) {13       this.id = id;14    }15 16   //..elided17 }

However, it is easier for readers to read private member definitions. Because the general process of understanding a thing is from general to special, and from abstract level, it is from high-level to low level. If you do, you cannot grasp things as a whole, nor grasp the essence of things. You can only get lost in a bunch of specific fragments.

The overall abstraction allows you to ignore the details. The higher the abstraction level, the more details you can ignore. The more details a reader can ignore when reading a category, the more happy the reader will be. It is painful to fill your head with too many details, so the less details the better. Therefore, putting Private Members at the end is more compassionate, because this prevents unnecessary details from being exposed to readers.

Originally, the habit of C ++ programs is to put Private Members at the beginning Like java. However, the C ++ community quickly realized that this is a harmful specification, which has now been corrected. Here is a comment in the Classic C ++ style guide:

Similarly, in terms of C ++, the imperial college at the University of London also said: putting the public part in front will make readers more interested in reading and then the protection part, the last part is the private part.

Some people disagree that the reader can use the program documentation to understand the class, rather than directly looking at the source code. This reason does not seem to be true, because there is no relevant implementation details in the program documentation, it is necessary to look at the source code.

All technical documents usually start with hard-to-understand information, such as abstract academic papers. Why does Java not break this rule? Putting Private Members at the beginning seems to be a good habit of breaking the regular. This kind of habit seems to be caused by Sun's early coding specifications.

It is good to arrange the code in the order of javadoc: the first is the constructor, the second is the non-private method, and the last is the private part and the method. In this way, the reader naturally moves from the abstract level to the low level.

 

This article describes some bad Java habits and styles that need to be changed. The ultimate goal is to make our code easier to understand.

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.