Encapsulate Field

From CSSEMediaWiki
(Difference between revisions)
Jump to: navigation, search
(make a new page)
 
m (Reverted edits by Ebybymic (Talk); changed back to last version by Johannes Pagwiwoko)
 
(2 intermediate revisions by 2 users not shown)
Line 1: Line 1:
Replace public fields (instance variables) with private fields and provide public accessors.
+
This is a common refactoring method suggested by [[Martin Fowler]]'s in his [[Refactoring]] book. Encapsulate Field states that we should ''Replace public fields (instance variables) with private fields and provide public accessors.''
  
Original code:
+
For instance, if we have a particular code/class like this:
  
 
   public class Person {
 
   public class Person {
Line 7: Line 7:
 
   }
 
   }
  
Refactored:
+
After we refactor the class using Encapsulate Field, we will have:
  
 
   public class Person {
 
   public class Person {

Latest revision as of 03:18, 25 November 2010

This is a common refactoring method suggested by Martin Fowler's in his Refactoring book. Encapsulate Field states that we should Replace public fields (instance variables) with private fields and provide public accessors.

For instance, if we have a particular code/class like this:

 public class Person {
   public String name;
 }

After we refactor the class using Encapsulate Field, we will have:

 public class Person {
   private String name;
   
   public void setName(String newName) {
       name = newName;
   }
   
   public String getName() {
       return name;
   }
 }
Personal tools