Accessors and Mutators in Java- How it works?

Accessor & Mutator

Accessor & Mutator

Overview: In this article we will discuss about java accessors. Accessors are basically member functions which are used to access and manipulate field values. We will also discuss the advantages and disadvantages of using accessors in java application.








Introduction: Accessors in java makes it more robust and modular. The concept is simple but very powerful for any application development. As we know that accessors are basically member functions which are used to access and modify field values. At the same time accessors add a second layer on top of the field variables so it is a little overhead. But it helps to hide the implementation details of the classes and its components. So the flexibility is increased manifold and the design is also more efficient. Java accessor comes in two flavors, setter and getter. A setter is used to set field value and getter is used to get the field value.

Another important aspect is the visibility of accessors. Accessors can have different types of visibility based on the access specifier added to them. So it also helps the application to set different level of access as per the requirement of the application. As accessors are simple java member functions so it is important to assign proper visibility in an efficient way which will improve the design on the application as a whole. There are mainly four levels of visibility available like public, protected, private, and default and they are having different purpose.

Advantages of accessors: We have already discussed the purpose of accessors in java application. Now we will discuss in details about the advantages of accessors.

  • Single point of contact: Accessor provides single point of contact for each attribute in the application. It helps to modify and test the property more efficiently. From object oriented point of view, the application attributes are encapsulated.
  • Lazy initialization: The lazy initialization is an important concept in java application. The concept is to load the data when it is first accessed. So for example, your application might be running but you do not need some particular attribute value. In this situation populating the attribute value does not hold any meaning and it will not be used in the application. But these will unnecessary hold the memory. So if we apply lazy initialization technique then we are only loading the data when it is first accessed. By using the accessors, we can control lazy initialization efficiently and hence make the application more efficient. The disadvantage is, your application becomes complex because you need to check if the attribute holds any value or not and then obtain its value. Lazy initialization is helpful when there is some expensive calculation required to populate the attribute. But again the entire selection depends upon the requirement of the application.
  • Complete control: The developer has the complete control over the application attributes. So the access to these attributes can be changed at any point of time depending upon the requirement. Access control also helps in the design of the application.
  • Easy modification to business rules: If there is requirement to change the business rule then accessors are very helpful. As accessors are encapsulating the attributes, any change or modification to these attributes does not have any impact to the calling functions. So the new business rules can be implemented easily without affecting the associated components. The accessors make it more flexible.
  • Reduce coupling issue: In normal implementation coupling between super class and sub class is a major issue. If you change anything in the super class then it has a direct impact on the sub class. But if the sub class access the attributes by using the accessor methods then any changes to the implementation of super class attribute does not impact the sub class. So the coupling issue is reduced and hence increases the flexibility of the application design.
  • Encapsulation of validation logic: Some time we have a requirement to perform some validation before we update or save the data. So one of the best places to put this validation logic is inside accessor method (more specifically setter method). We can also take advantage of access modifier along with accessor methods to put some restricted access and check the validation logic.
  • Overcome name hiding issue: We have a common practice to give the local variables same name as the attributes. This solves a problem of different name conflict. But using accessors mitigate this issue as we do not have any chance to access the attributes directly. So what ever be the name of the local variable we do not need to worry about it. The accessors will set it automatically.
  • Hide undo and redo logic: If your application has a requirement of changing the value of some attribute and then return back to the old value then using accessors are very helpful.
  • Use of getter accessor for constants: In normal java programming, any constant is defined as static final. And then it is used in the application code as constant. But the disadvantage is that, if the value of constant changes then you needs to change it in every line where ever it is used. So the traditional approach is good in places where there is no chance to change the value of constant. But if the constant value depends on some calculation or business logic then the better way is to use static getter to access it. So applying encapsulation for constant value in static getter method gives more robust solution and the design is also more modular and loosely coupled. The advantage is that you do not need to change it in every line but only in the getter method. And it also follows the object oriented rule of information hiding. So this is a new way of using accessors like getter method which gives a lot of flexibility to the application development. And in this scenario you do not need to change the setter method.









Following is an example of java accessors. The code has implemented a bulk setter method to improve the performance of the accessor implementation.

Listing 1: The sample is showing a bulk accessors implementation

[code]

/* JavaAccessors.java

* Thsis is an example of bulk setter and a singe getter method.

*/

/**

* @author Kaushik Pal

*/

public class JavaAccessors {

// Local variables

String name;

String address;

String age;

String totalstring;

/** Creates a new instance of JavaAccessors */

public JavaAccessors() {

}

/**

* Returns the consolidated string value.

*/

public String getTitle()

{

if ( name != null && address != null && age!=null) {

// Build the total string

totalstring = “Name is :”+name+” Address is :”+address+” Age is :”+age;

}

return this.totalstring;

}

/**

* This is a bulk setter

* Sets the name, address and age

* @param name, address, age

*

**/

private void setTitle(String name,String address,String age)

{

this.name = name;

this.address = address;

this.age = age;

}

public static void main(String[]args)

{

// Create new instance

JavaAccessors jvaccessor = new JavaAccessors();

// Use bulk setter

jvaccessor.setTitle(“Jhon”,”USA”,”32″);

// Get the consolidated output

String newname = jvaccessor.getTitle();

System.out.println(“New string value is :”+ newname);

}

}

[/code]

When not to use accessors: We have already discussed the areas where accessors can be implemented. We have also explained that correct implementation of accessors make the application more robust, flexible and maintainable. Now we will discuss some areas where accessor is not a best fit. In some application, execution time is of highest importance and there usage of accessor might make the process slow and poor response time. But this scenario is rare and if arises then we should think of some alternative solution. The other way of making accessor efficient is to use bulk accessor. Bulk accessor can be defined as an accessor which works on multiple attributes rather one at a time. So the advantage is that the work is performed in one shot compared to calling several accessors and get/set attributes values. And another important point is that the accessors are not necessarily need to make public. Some time we can also make it private or protected if required.

Following are some rules to be followed when considering the access to the accessors

  • Always try to keep the accessors protected. It will only make it visible in sub classes
  • If subclass do not need to access the attributes then make accessors private
  • If some external classes need to access attributes then only use public

Conclusion: In this article we have introduces java accesors and their implementation. We have also discussed about the robustness and flexibility of java application while using accessors. But some time it might be a overhead when some complex calculation is performed and application needs quick response time. So we can conclude that the accessors are a powerful feature in java but its implementation should be done carefully.







Tagged on: , ,
============================================= ============================================== Buy best TechAlpine Books on Amazon
============================================== ---------------------------------------------------------------- electrician ct chestnutelectric
error

Enjoy this blog? Please spread the word :)

Follow by Email
LinkedIn
LinkedIn
Share