Accessors and Mutators in Java- How it works?

Accessor & Mutator

Accessor & Mutator

Trosolwg: 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.








Cyflwyniad: 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, preifat, and default and they are having different purpose.

Advantages of accessors: We have already discussed the purpose of accessors in java application. Nawr byddwn yn trafod yn y manylion am fanteision accessors.

  • Un pwynt cyswllt: Accessor yn darparu un pwynt cyswllt ar gyfer pob priodoledd yn y cais. Mae'n helpu i addasu a phrofi yr eiddo yn fwy effeithlon. O bwynt gwrthrych oriented o farn, priodoleddau cais yn cael eu crynhoi.
  • initialization Lazy: Mae'r initialization ddiog yn gysyniad pwysig yn y cais java. Mae'r cysyniad yn llwytho'r data pan gaiff ei gafael yn gyntaf. Felly, er enghraifft, gallai eich cais yn cael ei rhedeg, ond nid oes angen i chi rhywfaint o werth priodoledd penodol. Yn y sefyllfa hon poblogi'r gwerth priodoledd nid yw'n dal unrhyw ystyr ac ni fydd yn cael ei ddefnyddio yn y cais. Ond bydd y rhain yn ddiangen yn dal y cof. Felly, os ydym yn gwneud cais techneg initialization ddiog, yna rydym yn unig yn llwytho data pan gaiff ei gafael yn gyntaf. Drwy ddefnyddio'r accessors, gallwn reoli initialization ddiog yn effeithlon ac felly yn gwneud y cais yn fwy effeithlon. Yr anfantais yw, eich cais yn mynd yn gymhleth oherwydd bod angen i chi wirio a yw'r priodoledd yn dal unrhyw werth neu beidio, ac yna chael ei werth. initialization Lazy yn ddefnyddiol pan mae rhywfaint o gyfrifiad drud sy'n ofynnol i boblogi y priodoledd. Ond unwaith eto y dewis cyfan yn dibynnu ar ofynion y cais.
  • rheolaeth lwyr: Mae'r datblygwr mae gan y reolaeth lwyr dros y priodoleddau cais. Felly gall y mynediad i'r priodoleddau hyn gael ei newid ar unrhyw bwynt o amser yn dibynnu ar y gofyniad. rheoli mynediad hefyd yn helpu yn y dyluniad y cais.
  • addasiad Hawdd i'w rheolau busnes: Os oes angen newid y rheol busnes, yna accessors yn ddefnyddiol iawn. Gan accessors yn crynhoi nodweddion, Nid yw unrhyw newid neu addasiad i priodoleddau rhain yn cael unrhyw effaith ar y swyddogaethau galw. Felly, gall y rheolau busnes newydd yn cael ei weithredu yn hawdd heb effeithio ar y cydrannau cysylltiedig. Mae'r accessors wneud yn fwy hyblyg.
  • Lleihau mater coupling: Yn coupling gweithredu arferol rhwng dosbarth super ac is-ddosbarth yn fater o bwys. Os byddwch yn newid unrhyw beth yn y dosbarth super yna mae'n cael effaith uniongyrchol ar yr is dosbarth. Ond os bydd y fynedfa is-ddosbarth nid priodoleddau trwy ddefnyddio'r dulliau accessor yna unrhyw newidiadau i o briodoledd dosbarth super gweithredu yn effeithio yr is dosbarth. 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. Ond os bydd y gwerth cyson yn dibynnu ar rai cyfrifiad neu fusnes rhesymeg yna mae'r ffordd well yw defnyddio benderfynol statig i gael gafael arno. Felly gwneud cais amgįu am werth cyson mewn dull benderfynol statig yn rhoi ateb mwy cadarn a dyluniad hefyd yn fwy modiwlaidd ac ynghyd llac. Y fantais yw nad oes angen i chi ei newid ym mhob llinell, ond dim ond yn y dull benderfynol. Ac mae hefyd yn dilyn y rheol gwrthrych oriented o wybodaeth cuddio. Felly, mae hyn yn ffordd newydd o ddefnyddio accessors fel dull benderfynol sy'n rhoi llawer o hyblygrwydd i'r datblygiad cais. Ac yn y sefyllfa hon nid oes angen i chi newid y dull Rhai sy'n Cynnau.









Canlynol yn enghraifft o accessors java. 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

[cod]

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

{

os ( enw != null && address != null && oedran!=null) {

// Build the total string

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

}

return this.totalstring;

}

/**

* This is a bulk setter

* Sets the name, address and age

* @param name, address, oedran

*

**/

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

{

this.name = name;

this.address = address;

this.age = age;

}

gwag statig gyhoeddus prif(Llinyn[]args)

{

// Create new instance

JavaAccessors jvaccessor = new JavaAccessors();

// Use bulk setter

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

// Get the consolidated output

String newname = jvaccessor.getTitle();

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

}

}

[/cod]

Pryd i beidio â defnyddio accessors: Rydym eisoes wedi trafod y meysydd lle gellir accessors cael eu gweithredu. Rydym hefyd wedi esbonio bod y gweithredu cywir o accessors wneud y cais yn fwy cadarn, hyblyg ac y gellir ei chynnal. Nawr byddwn yn trafod rhai meysydd lle nad yw accessor yn cyd-fynd orau. Mewn rhai cais, amser gweithredu o bwysigrwydd uchaf ac efallai y defnydd o'r accessor yn gwneud yr amser ymateb araf a thlawd broses. Ond y sefyllfa hon yn brin ac os cyfyd yna dylem feddwl am rai ateb arall. Y ffordd arall o wneud accessor effeithlon yw defnyddio accessor swmp. Gellir Swmp accessor cael ei ddiffinio fel accessor sy'n gweithio ar briodoleddau lluosog yn hytrach un ar y tro. 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

Casgliad: 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