Accessors and Mutators in Java- How it works?

Accessor & Mutator

Accessor & Mutator

Преглед: Во оваа статија ние ќе разговараме за Java accessors. Accessors се во основа член функции кои се користат за пристап и манипулираат величините. Исто така, ќе се дискутира за предностите и недостатоците на користење accessors во Java апликација.








Вовед: 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, приватни, 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. Значи прашањето за спојување се намалува, а со тоа се зголемува флексибилноста на дизајнот на апликацијата.
  • Херметичка на логика валидација: По некое време имаме услов за извршување на некои проверка пред да се ажурира или да ги зачувате податоците. Така, еден од најдобрите места за да се стави оваа логика валидација е внатре метод accessor (поконкретно словослагател метод). Ние исто така може да ги искористат предностите на модификатор пристап, заедно со accessor методи да се стави некои ограничено пристапот и да се провери логика валидација.
  • Надминување на прашањето за името се крие: Имаме вообичаена практика да се даде на локални променливи истото име како и атрибути. Со ова се решава проблемот на различни конфликтни име. Но со користење на accessors се ублажи овој проблем, како што немаат можност да пристапите директно атрибути. 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. Но, ако на константна вредност зависи од некои пресметка или бизнис логика тогаш подобар начин е да се користи статични копач за пристап до неа. Значи примена херметичка за константна вредност во статички метод копач дава повеќе робустен решение и дизајн е исто така повеќе модуларен и лабаво заедно. Предноста е во тоа што вие не треба да се смени во секој ред, но само во начинот на копач. И тоа, исто така, го следи објектно ориентирано владеењето на информации крие. Значи ова е нов начин на користење accessors како метод копач кој дава многу флексибилност за развој на апликации. И во овој случај не треба да се промени начинот на сетер.









Следниве е пример на 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

[код]

/* 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()

{

ако ( име != 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(Стринг[]аргументи)

{

// Create new instance

JavaAccessors jvaccessor = new JavaAccessors();

// Use bulk setter

jvaccessor.setTitle(“Jhon”,”САД”,”32″);

// Get the consolidated output

String newname = jvaccessor.getTitle();

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

}

}

[/код]

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. Во некои апликации, 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. Па така предност е тоа што работата се врши во еден истрел во споредба со повик неколку accessors и / да поставиш атрибути вредности. И уште една важна поента е дека accessors не мора да значи треба да се направи јавна. По некое време ние исто така може да ја направат приватни или заштитени ако е потребно.

Следниве се некои правила за да се следат кога станува збор за пристап до accessors

  • Секогаш обидувајте се да се задржи на accessors заштитени. Тоа само ќе го направи видливо во под класи
  • Ако подкласа не треба да пристапите на атрибути, тогаш бидете accessors приватни
  • Ако некој надворешен класи треба пристап до атрибути потоа ги користат само јавните

Заклучок: Во оваа статија ние имаме воведува Јава accesors и нивна имплементација. Ние сме, исто така, разговараа и за стабилноста и флексибилност на Java апликација, додека со користење 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