Search code examples
javaoopconventions

A real life example of public properties being bad


Countless times I've read that public properties on a class are a major faux pas, but I fail to see why on data that doesn't get transformed going in/out.

example of something I would write

public class Employee
{
    public String firstName;
    public String lastName;
    private int ssn = 0;
    public boolean setSsn(String s)
    {
        //makes perfect sense why something like an ssn would use a getter setter
        //some code to validate ssn
        if(!validSsn(s)){
            ssn = 0; 
            return false;
        }
        ssn = raw;
        return true;
    }
    public String getSsn()
    {
        return ssn;
    }
    private boolean validSsn(String s)
    {
        //validation goes here
        retrun val;
    }

    //I don't understand why I should make firstName private
    // and then write
    public void setFirstName(String s)
    {
        firstName = s;
    }
    public String getFirstName(String s)
    {
        return firstName;
    }       
}

please provide a scenario in which this would cause a problem and please be specific, not "because it causes issues when other people use your code" WHY? Why does it cause issues. Thanks in advance for constructive criticism and detailed answers :D


Solution

  • Imagine that your code has gone to production. I write a front-end that uses your Employee class that accesses firstName and lastName directly.

    6 months go by, and now there's a new business requirement that you add validation to the name fields.

    Where are you going to add it? You're going to have to make the fields private and add set methods, and this will force me and everyone else using your code to re-write our apps.

    If you had encapsulated that data properly in the first place, all we'd have to do is recompile using the new version of the library with your code.