Accessors and Mutators in Java- How it works?

Accessor & Mutator

Accessor & Mutator

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








Uvođenje: 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. Dakle, to također pomaže zahtjev postaviti različite razine pristupa kao i po zahtjevu primjene,,en,Kao pristupnici su jednostavne funkcije članice Java tako da je važno da se dodijeliti odgovarajuće vidljivost na učinkovit način koji će poboljšati dizajn o zahtjevu u cjelini,,en,Postoje uglavnom četiri razine vidljivosti na raspolaganju kao javna,,en,a zadana i oni imaju drugačiju svrhu,,en,Prednosti Pristupnici,,en,Već smo raspravljali o svrsi Pristupnici u Java aplikacije,,en,Sada ćemo raspraviti u detalje o prednostima Pristupnici,,en,Jedna točka kontakta,,en,Pristupnik nudi jednu točku kontakta za svako svojstvo u primjeni,,en,To pomaže da se mijenjaju i testirati imovine učinkovitije,,en,Od objektno orijentiranog gledišta,,en,atributi aplikacija su kapsulirane,,en. 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, privatan, 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.
  • lijen inicijalizacije,,en,Lijeni inicijalizacije je važan koncept u Java aplikacije,,en,Koncept je učitati podatke kada je prvi put pristupa,,en,Tako na primjer,,en,vaša aplikacija može biti pokrenut, ali ne treba neki poseban vrijednost atributa,,en,U ovoj situaciji popunjavanje vrijednosti atributa ne drži nikakvo značenje i neće se koristiti u primjeni,,en,No, to će se nepotrebno držati memorije,,en,Jednostavno izmjena poslovnim pravilima,,en,Ako postoji zahtjev za promjenu poslovnog pravilo onda pristupnici su vrlo korisne,,en,Kao što su pristupnici encapsulating atribute,,en,bilo koja promjena ili izmjena tih atributa nema utjecaj na funkcije poziva,,en,Dakle, nova pravila poslovanja može se provesti lako bez utjecaja na povezane komponente,,en,U pristupnici čine ga fleksibilnijim,,en: 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.
  • Smanjite problem spojke,,en,U normalnom provedbe spajanja super klasa i pod klase je veliki problem,,en,Ako promijenite nešto u super razred onda ima izravan utjecaj na sub klase,,en,No, ako je sub pristup klase atribute pomoću metode pristupnik tada bilo kakve promjene u provedbi super klasa atributa ne utječe na pod klasu,,en,Pa je pitanje spajanja se smanjuje, a time i povećava fleksibilnost dizajna aplikacije,,en,Enkapsulaciju validacije logike,,en,Neko vrijeme smo zahtjev za obavljanje neke valjanosti prije nego što smo se ažurirati ili spremanje podataka,,en,Dakle, jedan od najboljih mjesta da se stavi taj valjanosti logiku unutar metoda pristupnik,,en,točnije dizač metoda,,en,svaki konstanta je definiran kao konačni statički,,en: 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. A onda se koristi u programskom kodu, kao konstanta,,en,No, nedostatak je da,,en,ako je vrijednost stalnih promjena onda ti treba ga promijeniti u svakom retku, gdje god se koristi,,en,Dakle, tradicionalni pristup je dobar na mjestima gdje ne postoji mogućnost za promjenu vrijednosti konstante,,en,Šifra je implementirao bulk seter metodu za poboljšanje performansi provedbe pristupatelja,,en,Uzorak pokazuje provedbu rasuti Pristupnici,,en,JavaAccessors.java,,en,Thsis primjer rasutog dizač i postupak opaliti dobavljač,,en,@author Kaushik Pal,,en,public class JavaAccessors,,en,lokalne varijable,,en,Gudački dob,,en,Gudački totalstring,,en,Stvara novu instancu JavaAccessors,,en,javne JavaAccessors,,en,Vraća konsolidirani vrijednost niza,,en,javni Gudački getTitle,,en,adresa,,en,= null,,en,Izgradite ukupan niz,,en,totalstring =,,en,Ime je,,en,naziv ,,en,adresa je,,en. 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

[kod]

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

{

ako ( ime != null && address != null && godine!=null) {

// Build the total string

totalstring = “Name is :”+name ” Address is :”+pošte ,,en,dob je,,en,povratak this.totalstring,,en,To je većina dizač,,en,Postavlja ime,,en,adresu i dob,,en,naziv param,,en,privatni praznina setTitle,,en,this.age = dobi,,en,Stvori novu instancu,,en,JavaAccessors jvaccessor = novi JavaAccessors,,en,Korištenje skupnu seter,,en,jvaccessor.setTitle,,en,Dobiti konsolidirani izlaz,,en,Niz NEWNAME = jvaccessor.getTitle,,en,Novi niz vrijednost,,en,NEWNAME,,en,Kada ne koristiti Pristupnici,,en,Već smo razgovarali o područjima u kojima pristupnici mogu provoditi,,en,Također smo objasnili da je ispravna provedba Pristupnici bi primjena robusniji,,en,fleksibilan i održivi,,en,Sada ćemo raspraviti neka područja u kojima pristupnik nije najbolje odgovara,,en,Vrijeme izvođenja je od najveće važnosti, a tu korištenje pristupnika može učiniti proces spor i slab odziv,,en” Age is :”+godine;

}

return this.totalstring;

}

/**

* This is a bulk setter

* Sets the name, address and age

* @param name, address, godine

*

**/

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

{

this.name = name;

this.address = address;

this.age = age;

}

public static void main(Gudački[]args)

{

// Create new instance

JavaAccessors jvaccessor = new JavaAccessors();

// Use bulk setter

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

// Get the consolidated output

String newname = jvaccessor.getTitle();

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

}

}

[/kod]

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. U nekim prijave, execution time is of highest importance and there usage of accessor might make the process slow and poor response time. No, ovaj scenarij je rijetka, a ako se javlja onda bismo trebali razmišljati o nekom alternativnom rješenju,,en,Drugi način da pristupnik učinkovit je za korištenje skupnu Accessor,,en,Bulk pristupnik može definirati kao pristupnika koji radi na više atributa radije jednu po jednu,,en,Dakle, prednost je da se rad obavlja u jednom kadru u odnosu na pozivanje nekoliko Pristupnici i dobiti / set atributa vrijednosti,,en,I još jedna važna stvar je da su pristupnici nisu nužno potrebno kako bi javni,,en,Neko vrijeme možemo učiniti privatnim ili zaštićeni ako je potrebno,,en,Evo nekih pravila koje treba slijediti pri razmatranju pristup Pristupnici,,en,Uvijek pokušati zadržati Pristupnici zaštićene,,en,To će samo učiniti vidljivim u sub klase,,en. 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
  • Ako podrazred ne moraju pristupiti atribute onda bi pristupnici privatni,,en,Ako neki vanjski klase je potrebno za pristup atribute onda koristiti samo javno,,en,U ovom članku smo se uvodi java accesors i njihovu provedbu,,en,Također smo razgovarali o robusnosti i fleksibilnosti java aplikacija dok koristite Pristupnici,,en
  • If some external classes need to access attributes then only use public

Zaključak: 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