Use with caution! – Getters Setters in JAVA and Properties in C#


A lot of programmers and gurus on the internet talk about Getters and setters in Java and (almost similar to Properties in C#) and most of them seem to love these constructs. The claim that “they hide the private implementation” is very valid and it is root cause of this evil.

Let us take the case of a simple class sitting in JAR, coming from a 3rd party library:

public class BankAccount {
public double getBalance() {
}


}

The innocent programmer sees that getBalance() is a method on a BankAccount object, starts calling it, and the programs starts dragging its feet. The problem is that the getBalance() does a DB query under the hood and therefore is slow. The method name should have been getCurrentBalanceByLiveQuery() and any semi-witted programmer would have guessed “Ah! that would be slow”.

I have mandated that in the teams that I (try to) control, Getters and Setters should purely get or set the variable and just that. No extra validations, or whatever else, and if you are already doing this, then why not just expose the fields directly? Some code generation tools “depend” upon Getters and Setters, so my rule is to keep Getters and Setters do only what their names suggest.

If there is a method setBalance(double qMoney) and it does a DB update, I would call it setBalanceAndUpdateDB()…

This discussion applies to Object Properties in C#.


Leave a Reply

Your email address will not be published. Required fields are marked *