Getters and setters are
not going away. Deal with it.

Don’t believe what
wannabe pundits and OO purists tell you. At the end of the day, every object becomes a primitive type.

Unfortunately, Java doesn’t have the prettiest way to handle getters and setters, which leads up to a lot of code obfuscation. Granted, we are now very much used to visually identify the pattern:

  private String m_firstName;
  public String getFirstName() {
    return m_firstName;
  }
  public void setFirstName(String fn) {
    m_firstName = fn;
  }

  private Integer m_socialSecurityNumber;
  public Integer getFirstName() {
    return m_socialSecurityNumber;
  }

Note that in the above example, I declared the field right next to its getters and setters, which improves readability and locality, in my opinion, but it’s a technique that is pretty much never used, making it even harder to find which fields are exposed with getters and setters and which ones are stricly part of the private implementation of the class.

Compare this to the terse but to-the-point pseudo-code:

  property String name;
  property readonly Integer socialSecurityNumber;

In order to support the most flexibility for attributes, a language needs to offer the three functionalities. Here is how Ruby, C# and Java address these three problems:

Java Ruby C#
Concise notation for read-write attributes N/A attr_accessor :first_name public string FirstName {
  get; set;
}
Concise notation for read-only attributes N/A attr_reader :first_name public string FirstName { get; }
Full definition of accessors for additional logic public String getFirstName() {
  /* code */
}
public void setFirstName(String s ) {
  /* code */
}
def first_name
  /* code */
end
def first_name=
 /* code */
end
public string FirstName {
  get {/* code */}
  set { /* code */}
}

Note that another important feature supported by both Ruby and C# — but unfortunately not Java — is that of “Universal Access”. Regardless of how you choose to define your properties, they all end up going through the same code line when executed. In other words, you can start by define “attr_accessor first_name” and then later use more complex logic by defining “def first_name=”. In either cases, assigning this attribute will always end up calling the assignment method.

It’s too bad that properties didn’t make it in Tiger.