Accessors and Mutators in Java- How it works?

Accessor & Mutator

Accessor & Mutator

Преглед: 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.








Увод: 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. Јава аццессор долази у две варијанте, сетер и човек који ствара. Техничар се користи за подешавање вредности поља и човек који ствара се користи да се вредност поља.

Још један важан аспект је видљивост Налози са приступом. Налози са приступом могу имати различите врсте видљивости на основу приступа додат им спецификатором. Тако да такође помаже захтев да постави други ниво приступа по захтеву апликације. Као Налози са приступом су једноставне функције чланице Јава, тако да је важно да се додели одговарајућа видљивост на ефикасан начин који ће побољшати дизајн на примени у целини. углавном постоје четири нивоа видљивости на располагању као јавна, protected, приватан, и подразумевани и они имају другу намену.

Предности Налози са приступом: Већ смо разговарали о сврси Налози са приступом у јава апплицатион. 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. Код је имплементирао булк метод техничар је да се побољша учинак имплементације аццессор.

Listing 1: Узорак показује имплементацију а булк Налози са приступом

[код]

/* ЈаваАццессорс.јава

* Тхсис је пример расуте техничара и метод опрљење Геттер.

*/

/**

* @аутхор Каусхик Пал

*/

публиц цласс ЈаваАццессорс {

// lokalne променљиве

String name;

String address;

стринг старост;

стринг тоталстринг;

/** Креира нову инстанцу ЈаваАццессорс */

публиц ЈаваАццессорс() {

}

/**

* Враћа консолидованог вредност ниске.

*/

Стринг гетТитле()

{

ако ( име != null && адреса != null && age!= нулл) {

// Изградити укупан стринг

тоталстринг = “Име је :”+ime ” Адреса је :”+адреса ” Старост је :”+age;

}

врати тхис.тоталстринг;

}

/**

* Ово је највећи сетер

* Поставља име, адреса и старост

* @парам име, адреса, age

*

**/

привате воид сетТитле(String name,String address,стринг старост)

{

this.name = name;

this.address = address;

тхис.аге = старост;

}

публиц статиц воид маин(Ниска[]аргс)

{

// Створити нову инстанцу

ЈаваАццессорс јваццессор = нев ЈаваАццессорс();

// Користе булк штампар

јваццессор.сетТитле(“Jhon”,”САД”,”32″);

// Добити консолидованог излаз

Стринг невнаме = јваццессор.гетТитле();

Систем.оут.принтлн(“Нови ниска вредност :”+ невнаме);

}

}

[/код]

Када се не користи Налози са приступом: Већ смо разговарали о области у којима се могу применити Налози са приступом. Такође смо објаснили да исправно спровођење Налози са приступом би се апликација више робустан, флексибилан и одржив. Сада ћемо размотрити неке области у којима купат није најбоље одговара. У неким апликацији, време извршења је од највећег значаја и тамо коришћење аццессор могла би се процес споро и лоше време одзива. Али овај сценарио је ретка и уколико се укаже онда треба да мислимо о алтернативним решењима. Други начин израде купат ефикасан је да користите булк Аццессор. Булк купат се може дефинисати као аццессор који ради на више атрибута радије једну по једну. Дакле, предност је да се рад обавља у једном потезу у односу на позивање неколико Налози са приступом и да се / скуп атрибута вредности. И још једна важна ствар је да се Налози са приступом не морају да се јавна. Неки пут можемо учинити приватним или заштићени уколико је потребно.

Након неколико правила која се примењују приликом разматрања приступ Налози са приступом

  • Увек се трудите да задржи Налози са приступом заштићеним. То ће само учинити видљивим у под класа
  • Ако поткласа не треба да приступе атрибуте онда би Налози са приступом приватним
  • Ако неки спољни класе треба да приступе атрибуте онда само користити јавни

Закључак: У овом чланку имамо уводи јава аццесорс и њихово спровођење. Такође смо разговарали о робусности и флексибилности Јава апликација уз коришћење Налози са приступом. 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.







Таггед на: , ,
============================================= ============================================== Buy best TechAlpine Books on Amazon
============================================== ---------------------------------------------------------------- electrician ct chestnutelectric
error

Enjoy this blog? Please spread the word :)

Follow by Email
LinkedIn
LinkedIn
Share