DEV Community

Discussion on: Avoid getters and setters whenever possible

Collapse
 
hussainakbar profile image
Hussain Akbar

(Darned cat walked over the keyboard and wiped my text)

I find Java programmers to be of the same cloth as Linux users; swearing by purity instead of concentrating on substance.

Case in point is the final declaration. It's my code. If I want to change a variable, I will. If not, not. So why use final?

This (and a boatload of similar posts) are because Java does have properties (public variables) but doesn't have any actual getters and setters. They're coincidental public methods that happen to set / read values of private variables.

I mean, just look at constructors that set multiple variables. Similarly, you can have a function for example:
public void setPerson(name, age, mobileNumber){...}

And another for:
public void setPersonAddresses(homeAddress, workAddress){...}

and not have individual setters for the above 5 variables. So, are they setters? They do the same work and the result is exactly the same. You can check for invalid values, copy arrays, etc. But, noooooo. Java purists would never deign to use them.

Now, have a look at DotNet. A VB.Net class would be:

Class Example
    Private _count As Integer

    Public Property Number() As Integer
        Get
            Return _count
        End Get
        Set(ByVal value As Integer)
            _count = value
        End Set
    End Property
End Class


`

That's a setter that's bound / fixed / glued to the property. You just use example.number = x and all the checks are carried out.

You get the ease of use with the needed functionality.

Purists: Go ahead and scream at me all you want. At the end of the day, Java still won't have any getters or setters.

Collapse
 
scottshipp profile image
scottshipp

It just sounds like you have your own brand of C# purism. In Java, the tools are there if you want to use them. "Final" keyword provides one ingredient towards immutable objects. The C# equivalent is the readonly keyword. If you want to use it, great, but if you don't, also great. I don't see anything to debate or any reason to compete Java against C#. Both have getters and setters, but different syntax for achieving the same result. C# properties are a little more compact and readable IMO which is nice. But Java is not missing anything.