Login | Register   
LinkedIn
Google+
Twitter
RSS Feed
Download our iPhone app
TODAY'S HEADLINES  |   ARTICLE ARCHIVE  |   FORUMS  |   TIP BANK
Browse DevX
Sign up for e-mail newsletters from DevX


Tip of the Day
Language: Java
Expertise: Beginner
Sep 23, 1997

Increase Code Reusability

Instead of exposing fields of a Java class, such as in this code:
 public class Person
{
   public String firstName;
   public String lastName;
}
use private fields and provide access to the information through "Getter" and "Setter" methods. The re-written class is:
 public class Person
{
   private String firstName;
   private String lastName;

   public String getFirstName()
   {
      return firstName;
   }
   public void setFirstName( String fistName )
   {
      this.firstName = firstName;
   }
   public String getLastName()
   {
      return lastName;
   }
   public void setLastName( String lastName )
   {
      this.lastName = lastName;
   }
}
There are two advantages to this. First, if you make changes to the class that affect the way you store information, you can hide the changes behind the getter and setting methods. Your class would still look the same to the users of the class as they would continue to use the getter and setter methods. Second, getter and setter methods is the coding pattern for JavaBeans. The re-written class is a JavaBean while the first one is not.
Randy Kahle
 
Comment and Contribute

 

 

 

 

 


(Maximum characters: 1200). You have 1200 characters left.

 

 

Sitemap
Thanks for your registration, follow us on our social networks to keep up-to-date