Java review 2-objects and classes

Source: Internet
Author: User

Review the knowledge that is encountered in the process of basic knowledge and needs to be recorded.

Packaging

We design the class should be as high as possible cohesion, reflected in the degree of encapsulation. A class attribute should only be modified on its own, and the other classes are only communicating with this class and should not be able to modify it. One of the more common problems is the date property.

In business development, it is often necessary to design class date attributes, such as birthday, createdate, etc.

public class User {    private String name;    private Date birth;        public Date getBirth() {        return this.birth;    }}

I often design an entity, fill in the field, and then directly getter, setter out, especially after the use of Lombok, but also accretion Chengdu to change automatically. In accordance with the requirements of encapsulation, such an approach is inappropriate. Because the other class can get the date object, the Date object is mutable. Then there is a possibility that the date will be modified.

If the project has a scan that introduces FindBugs, this class will definitely be scanned and should not return a mutable object. So, what can be done to avoid this problem? We really need to expose date.

The answer is to expose an immutable object. Java8 introduced a new date API, where Localdate is immutable. Replace date with Localdate. Localdate, like a string, does not provide any way to change the internal properties, and all the modifications and the like will create a new object. This way, the modification operation will not affect the original class.

The Date object can be resolved, but many are the objects of their own definition, what about this? For example, user has a property that is role.

public class User {    private String name;    private LocalDate birth;    private Role role;        public Role getRole() {        return this.role;    }}

Similar to date, when called getRole , if the outside world can modify the properties of role, such as changing role to admin, then this object has the admin permission. This is what we don't want to see. You can imitate localdate and turn off all the methods that modify the internal properties of the role. This way, the role cannot be modified externally, and the user is not affected. However, we need to render the object as JSON in the Web, and Jackson will do the serialization and deserialization operations based on the Getter Setter. The setter cannot be closed yet.

Then you can only deal with the user himself. The only place where the user is at risk is to expose their own internal attributes after getrole. We can give a new one when we are getrole and let the other classes change without affecting ourselves.

public class User {    private String name;    private LocalDate birth;    private Role role;        public Role getRole() {        return (Role) this.role.clone();    }}

The reality is that we seldom pay attention to such practices, all of which are returned directly. Also, there are few errors encountered. FindBugs exceptions can be ignored at this time. But, best of all, it is recommended to make such modifications.

Call by value for method pass parameter

The easiest way to learn Java is to pass the parameters in the end.

In the programming language, there are some specialized terms for passing parameters to methods (or functions). Call by Value (call by value) means that the method receives the value provided by the caller. The call is reference, by reference, means that the method receives the variable address provided by the caller. A method can modify the value of the variable that corresponds to the passed reference, and cannot modify the value of the variable that corresponds to the pass-through value invocation. Press ... Invocation is a standard computer science term used to describe how method parameters are passed in various programming languages (not just Java).

Java programming languages are always called by value . That is, the method obtains a copy of all the parameter values, in particular, the method cannot modify the contents of any parameter variables passed to it.

int a = 10;addOne(a)

No matter how the AddOne method is implemented, a eventually remains 10. Because when a is passed to the AddOne method, it copies a value of a to the parameter, and the method runs in a copy, without affecting the original variable.

There are two methods of method parameters:

    • Basic data type (numeric, Boolean)
    • Object reference

The demo above shows that a method cannot modify a parameter of a base data type. What about the object reference?

StringBuilder sb = new StringBuilder();appendOne(sb);

Does Appendone have an impact on SB during execution?

This depends on the specific method content. Like what

public void appendOne(StringBuilder sb) {    sb.append("1");}

So, we end up with the result that we've added 1 to the SB content. And in a different way,

public void appendOne2(StringBuilder s){    s = new StringBuilder();    s.append("a");}

So, what does the content of the SB outside of the method become?

The first thing to remember is that the Java method pass-through is simply a passing copy. Then, understand the meaning of passing copies

Because S points to the same address and SB, so when S.append, the content of SB will also change. This also starts with the reason that the wrapper should not return a mutable variable. Any method that gets the address of the variable variable can directly modify the attributes in the variable. What is the difference between the method 2?

In Method 2, the parameter S is pointed to the new address, and any subsequent modifications will not affect the old address. The address space of SB corresponding to the method is not changed. This can be understood as Java passes the object reference only when the address of the object reference is copied.

Class Design Tips
    1. Must ensure that the data private, that is, encapsulation;
    2. Be sure to initialize the data, it is best not to rely on the default value of the system, given an initial value;
    3. Do not use too many basic types in the class, can be related to a number of variables to synthesize a class, to reference class, in addition, can be used in the wrapper class without the basic type;
    4. Not all member variables should provide external access methods, such as the creation date can not be modified;
    5. Decomposition of classes with excessive responsibilities;
    6. The class name and method name should be able to reflect their responsibilities;
    7. Use immutable classes first.

Java review 2-objects and classes

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.