Getter & Setter: Use or Discard

Source: Internet
Author: User
Getter & Setter: Use or Discard


Private variables

Why do we use private instance variables?

Because we don't want other classes to be directly dependent on these variables. And in the whim, we can also flexibly modify the variable type and implementation.

However, why are programmers automatically adding getter and setter methods to objects to expose private variables as if the variables were public.

Access method

Access Methods (also known as getters and setters) are methods that can be used to read and write object instance variable values.

Why use the Access method.

It is justified to use access methods in a class rather than exposing properties directly.

Getter and setter make the API more stable.

For example, suppose a class has a public property that can be accessed directly by other classes. After a while, you want to add extra logic when reading or saving this public property. This will affect the classes that already use the API. So any change to this public property will result in changes to other classes that reference this property.

Instead, using the access method, we can then easily add some other logic, such as caching data and delaying loading. Also, if the new property value differs from the old property value, we can also trigger the property change event.

All of these are transparent to classes that get values by using access methods.

Whether to use the access method for all properties.

Properties can be declared as either package-level private or private nested classes visible. In these classes, the direct exposure of attribute fields to external exposures can reduce visual clutter in class definitions and calling code, relative to the use of access methods.

If a class is a package-level private or a private nested class is visible, assuming that its attribute fields well describe the data provided by the class, exposing these attribute fields externally is inherently non-problematic.

Such classes are limited to the packages declared by the class, and the calling code is limited to the internal representation of the class. We can modify this class without changing any of the out-of-package code. Also, for private nested classes, the scope of the changes is further narrowed to the nested class.

Another example of using public properties is the Javaspace request object. Ken Arnold the experience of their decision to use public properties rather than private attributes with access methods (details)

People are told not to use public properties, public property is bad, sometimes it makes people uncomfortable, and often people use the indisputable tone to discuss. But we are not very religious people. There is a reason for making the rules. The reason for the private property rule does not apply to this special case. This is a special exception, and I also tell people not to use public properties in their classes, but there are exceptions. This is an exception to this rule, because it is simpler and more secure to simply say that it is a property. Let's take a step back and think: In that case, why do you want this rule? Does it apply? In this exception, it does not apply.

Private attribute + Public access method = = Encapsulation.

Consider the following example

We generally think that this is a bad code style because it destroys encapsulation. The workaround is:

Some people think this encapsulates the attribute. Does this really implement encapsulation?

In fact, Getter/setter does not have any relationship with encapsulation.

Data is not more subtle or encapsulated than using public properties.

Other classes still know the inner details of the class.

Class changes can spread, forcing other classes that depend on it to make the appropriate modifications. Getter and setter used in this way often break the encapsulation.

A truly complete package class is not a setter method, and it is best not to have getter methods. Instead of getting the data from a class and calculating the data, the class should be responsible for calculating and returning the results using its own data.

Look at the following example

If we need to get a special page, we'll write the following code,

It is worth noting here:

And, even worse, any client code of map can empty this map, which is usually not what we want.

The client code needs to get an object from the map and convert it to the appropriate type.

The alternative implementation of the same logic is:

This hides the map instance and the Interaction Interface (map).

Excessive use of getters and setters

Creating a private property, and then automatically generating the getters and setters methods for all of these properties through the IDE, is just as bad as using public properties directly.

One reason for overuse is that these access methods can now be created in the IDE with just a few click events. These completely meaningless Getter/setter code can sometimes be longer than the logic of the class itself, and you will read the code many times, although you don't want to do it.

All attributes should remain private, but only the setter method is added to the immutable property. Adding an unnecessary getter exposes the internal structure, which also increases the chance of code coupling. The avoidance scenario is that each time an access method is added, we should analyze whether the encapsulation behavior can replace the access method.

Let's look at another example

Based on the above logic, suppose we subsequently assume that the data type double is not appropriate, but rather that we should use BigDecimal, so that the client code that has already used this class will be invalidated.

Let's rebuild the example above

Unlike the previous direct request data, the class is responsible for increasing its own value. In this way, any future request to change the data type does not need to change any client code. This not only encapsulates the data, but also encapsulates the fact that the data is preserved and even the data exists.

Conclusion

Using access methods to restrict access to property variables is preferable to using public property variables directly.

However, creating getter and setter methods for each property is a bit extreme. And it has to be based on specific circumstances, sometimes you just want to have a simple data object. You should add access methods for the properties you really need.

A class should use its own properties and provide powerful capabilities to the outside, rather than just as a storage pool of storage state properties that are manipulated by other 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.