On one hand, I know that the advisable usage of Properties is to have a backing field, like in the following example:
private int m_Capacity;
public int Capacity
{
get { return m_Capacity > 0 ? m_Capacity : -666; }
set { m_Capacity = value; }
}
On the other hand, what benefit do I get from using the above example over discarding the field and using only the property for all purposes, like in the following example:
public int Capacity
{
get { return Capacity > 0 ? Capacity : -666; }
set { Capacity = value; }
}
What is good about using a backing field for regular (non-auto-implemented) properties?
A Backing Field is just a field that will be generated for a property in a class only if it uses the default implementation of at least one of the accessors. Backing field is generated only if a property uses the default implementation of getter/setter. If you see the following code with perspective of Java.
The backing fields feature allows us to access a field of a property only in a scope of getter and setter.
Properties have the primary advantage of allowing you to change the way data on an object is accessed without breaking it's public interface. For example, if you need to add extra validation, or to change a stored field into a calculated you can do so easily if you initially exposed the field as a property.
As shown above, when a property needs its backing field, Kotlin provides it automatically. Moreover, we can reference the backing field inside custom accessors via the field identifier. Put simply, the backing field is where the value for a property will be stored.
If you do this:
public int Capacity
{
get { return Capacity > 0 ? Capacity : -666; }
set { Capacity = value; }
}
then your code will have an infinite recursion. It will never work. That's because the getter for Capacity is referencing itself. Same thing goes for the setter.
Unless you are using automatic properties, you need a backing field
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With