Getters, Setters, and Properties Best Practices. Java VS. C#

Getters, setters, and properties best practices. Java vs. C#

Pre-C# 6

I'd use the last of these, for a trivial property. Note that I'd call this a public property as both the getters and setters are public.

Immutability is a bit of a pain with automatically implemented properties - you can't write an auto-property which only has a getter; the closest you can come is:

public string Foo { get; private set; }

which isn't really immutable... just immutable outside your class. So you may wish to use a real read-only property instead:

private readonly string foo;
public string Foo { get { return foo; } }

You definitely don't want to write getName() and setName(). In some cases it makes sense to write Get/Set methods rather than using properties, particularly if they could be expensive and you wish to emphasize that. However, you'd want to follow the .NET naming convention of PascalCase for methods, and you wouldn't want a trivial property like this to be implemented with normal methods anyway - a property is much more idiomatic here.

C# 6

Hooray, we finally have proper read-only automatically implemented properties:

// This can only be assigned to within the constructor
public string Foo { get; }

Likewise for read-only properties which do need to do some work, you can use member-bodied properties:

public double Area => height * width;

Getters and Setters versus class method

Getters and setters are just syntactic sugar. The compiler will compile your getters and setters into getter and setter methods eventually. So by writing getter and setter methods yourself, you are kind of doing the job of the compiler.

Therefore, I recommend you to use getters and setters, because one of their main purposes is to replace getter and setter methods.

Here are some other advantages of using getters and setters:

  • Getters and setters can save you a lot of time if you only need getters and setters without any logic:

    public int Property { get; set; }
  • In my opinion, the aesthetic of getters and setters look better. Compare:

    obj1.Property += obj2.Property;

    with

    obj1.SetProperty(obj1.GetProperty() + obj2.GetProperty());

    I feel like the latter just has too many parentheses.

  • Keep the setters and getters close to the property declaration. If you use getter and setter methods, you could accidentally write other methods between the property declaration and the getter/setter methods, causing the getter/setter methods to slowly "drift away" from the property declaration. Next time you want to find it, you need to scroll up and down. With getters and setters, they will always be below the property declaration.

Why doesn't Swift use getter and setter for properties as much as Java or C#?

Java historically had different syntax for direct property access versus a method call that gets the value (a "getter"). Since you might someday want to override a property with a method, for consistency it is common to create a method in all cases.

Swift avoids this problem by having the same syntax for direct property access and "getters" (computed properties). This means you can change your mind later without impacting callers, and so there is no reason to create a method "just in case."

A computed property is defined as one with a "getter" (a get method) in Swift.

C# - Getters/Setters different from other languages

public string PersonName { get; set; }

is actually equivalent to

private string personName;

public string PersonName
{
get { return personName; }
set { personName = value; }
}

Auto-Implemented Properties were introduced in C# 3.0 to make the code more readable/concise.

Best practice for getters and setters for collection properties and object properties in a java class

The second implementation guards against returning null, right? So if there's a chance this object could return null (because what constructors there are permit this or it otherwise could come to pass) and that would be a Bad Thing for your intended use case, then use the second implementation.

C# private variable & java private variable getter & setter - Difference?

It is exactly the same.

The automatic property you defined in C# will compile down to getter and setter methods anyway. They are classified as "syntactic sugar".

This:

public int Test { get; set; }

..is compiled to this:

private int <>k____BackingFieldWithRandomName;

public int get_Test() {
return <>k____BackingFieldWithRandomName;
}

public void set_Test(int value) {
<>k____BackingFieldWithRandomName = value;
}

What is the point of getters and setters?

Multiple reasons:

  • If you allow field access like

    shape.x = 90

then you cannot add any logic in future to validate the data.

say if x cannot be less than 100 you cannot do it, however if you had setters like

public void setShapeValue(int shapeValue){
if(shapeValue < 100){
//do something here like throw exception.
}
}
  • You cannot add something like copy on write logic (see CopyOnWriteArrayList)
  • Another reason is for accessing fields outside your class you will have to mark them public, protected or default, and thus you loose control. When data is very much internal to the class breaking Encapsulation and in general OOPS methodology.

Though for constants like

public final String SOMETHING = "SOMETHING";

you will allow field access as they cannot be changed, for instance variable you will place them with getters, setters.

  • Another scenario is when you want your Class to be immutable, if you allow field access then you are breaking the immutability of your class since values can be changed. But if you carefully design your class with getters and no setters you keep the immutability intact.

Though in such cases you have to be careful in getter method to ensure you don't give out reference of objects(in case your class have object as instances).

We can use the private variables in any package using getters and setters.



Related Topics



Leave a reply



Submit