Search Unity

  1. Welcome to the Unity Forums! Please take the time to read our Code of Conduct to familiarize yourself with the forum rules and how to post constructively.
  2. We have updated the language to the Editor Terms based on feedback from our employees and community. Learn more.
    Dismiss Notice
  3. Join us on November 16th, 2023, between 1 pm and 9 pm CET for Ask the Experts Online on Discord and on Unity Discussions.
    Dismiss Notice

Should I use both back fields and properties, or just keep my code as simple as possible?

Discussion in 'Scripting' started by colin299, Dec 16, 2015.

  1. colin299

    colin299

    Joined:
    Sep 2, 2013
    Posts:
    176
    hello,
    while the most basic code is clean & easy to read,
    Code (CSharp):
    1.  
    2. //codeA
    3. public MyClass variableName;
    4.  
    a private back field & public get set property can provide more functionality like checking null
    Code (CSharp):
    1.  
    2. //codeB
    3. private MyClass _variableName;
    4. public MyClass variableName
    5. {
    6.      get { return _variableName; }
    7.      set
    8.      {
    9.          Assert.IsNotNull(value);
    10.          _variableName= value;
    11.      }
    12. }
    but if I have many these kind of back fields and properties, my code is really long & hard to read, as they are very repetitive.

    My question is:
    Should I use both back fields and properties(case 2),
    or just keep my code as simple as possible(case 1)?
     
  2. Patico

    Patico

    Joined:
    May 21, 2013
    Posts:
    886
    There's a trick, you can use a shorter notation like this one:
    Code (csharp):
    1.  
    2. public int MySupaProperty { get; set; }
    3.  
    and compiler will make a backfield for you.

    upd: In my opinion, using of backfield only is enough for prototyping, but for production I prefer to use properties it makes code more maintainable
     
  3. Kiwasi

    Kiwasi

    Joined:
    Dec 5, 2013
    Posts:
    16,860
    Does it matter?

    I start off with everything as fields. If I need data validation then I make it into a property. It's trivial to convert between a field and a property.
     
    JasonBricco likes this.
  4. CloudKid

    CloudKid

    Joined:
    Dec 13, 2015
    Posts:
    207
    Also, I tend to go for a code that is clean & easy to read (this will save your skin when you revisit your code later). Don't use getter and setter unless you need them.
     
  5. Baste

    Baste

    Joined:
    Jan 24, 2013
    Posts:
    6,199
    Keep your code as simple as possible. If you need to do something when variableName is set, case 2 is as simple as possible. Case 1 doesn't do what you need to do.

    The difference between these two:
    Code (csharp):
    1. public MyClass variableName;
    2. public MyClass variableName { get; set; }
    Is that the second one makes reflection a bit of a pain in the butt, but is necessary for some tools (like the automatic YamlDotNet serializers and deserializers).
     
  6. OrSi333

    OrSi333

    Joined:
    Jan 5, 2014
    Posts:
    5
    Accessing a field of a class outside the class is bad practice. The object-oriented approach is that every interaction between classes will be done using methods (properties are methods). Here are some of the benefits you gain from using properties:
    1. Different access modifiers for get and set.
    2. Internal checking for setting the variable.
    3. Polymorphism
     
  7. Kiwasi

    Kiwasi

    Joined:
    Dec 5, 2013
    Posts:
    16,860
    Yes in the .Net world.

    However the properties are not serialized in the Unity world. Which makes a big argument in favor of using fields. If you are a purist you can serialize the backing variable and then make properties public. It works, but I'm not sure its worth it. Again the way Unity works you loose the internal checking with this approach.
     
  8. OrSi333

    OrSi333

    Joined:
    Jan 5, 2014
    Posts:
    5
    But you don't need to serialize the properties, only the backing variable.
     
  9. Kiwasi

    Kiwasi

    Joined:
    Dec 5, 2013
    Posts:
    16,860
    True. It's just never proven worth the effort for me. It may be a big project small project thing, most of my work has been on small projects.

    Edit: Don't get me wrong. I use properties all the time when there is a need for them. I've just never seen the benefit of making everything a property.
     
  10. Fajlworks

    Fajlworks

    Joined:
    Sep 8, 2014
    Posts:
    344
    Since properties are methods behind the scenes, in performance bottleneck scenarios, it can be helpful to call fields directly to save off some extra ms. As well as serialisation. :)
     
    Kiwasi likes this.
  11. passerbycmc

    passerbycmc

    Joined:
    Feb 12, 2015
    Posts:
    1,739
    If you are accessing a field on a object so often that it becomes a issue you should cache the result anyways.

    For big project with multiple people, I tend to always use properties and just explicitly use the SerializeField Attribute, on the backing field if it needs to be serialized.

    If your are the lone developer and the scope isn't huge this inst much of a issue since you know how your objects will be used. But in the case of multiple developers working on it, you wont always know how it will be used so it is good to isolate the internal logic of the object.
     
    Fajlworks likes this.
  12. colin299

    colin299

    Joined:
    Sep 2, 2013
    Posts:
    176
    I read all the replies, and I have the following conclusion,
    - only use a more complex one when absolutely needed.
    - never allow public set
    - if we need logic in setter, "type3" is a must

    Code (CSharp):
    1.     //type1, most basic field without breaking OOP rules.
    2.     private MyClass field; //most basic
    3.  
    4.     //type2, allow public get.
    5.     public MyClass autoProperty { get; private set; }
    6.  
    7.     //type3, full get set logic
    8.     private MyClass _backfield;
    9.     public MyClass customProperty
    10.     {
    11.         get { return _backfield; }
    12.         set
    13.         {
    14.             //setter logic
    15.             if(value != null)
    16.                 _backfield = value;
    17.         }
    18.     }
    because I need assertion in most of my properts's setter, I will keep using type3 as long as I need assertion or any setter logic.
    thanks everyone!
     
  13. Xarbrough

    Xarbrough

    Joined:
    Dec 11, 2014
    Posts:
    1,184
    What's the benefit of using an Assert over just not setting the variable, if it is null? I could also throw and exception or log to the console, that something is going wrong, but that would need to be stripped out for a final build and might be a nightmare to maintain during development, because you might be getting a hundred log statements. Is the Assert method more useful?

    The property and field question totally depends on the scope of the project. If you're working with other people it can be very helpful to use typical conventions to give other developers insight into how your code is supposed to be used. A private backing field with [SerializeField] clearly says, that this is a Unity inspector variable. Whereas a private field a public setter with data validation tells everyone "this field needs to have certain data in it". Properties also give you a good place to put xml summary comments for others and yourself, explaining things like "this float field is meant to be used in a range between zero and one."
     
  14. kru

    kru

    Joined:
    Jan 19, 2013
    Posts:
    452
    An Assert method can place all of the logic required to handle asserts in one place where the responsibility should lie. The basic thing is that the property method itself is not responsible for handling the assert, it just invokes something that knows what to do. The property method is responsible only for setting the property. Assert handles asserting that some condition is true.
     
  15. lordofduct

    lordofduct

    Joined:
    Oct 3, 2011
    Posts:
    8,380
    I still use private fields backed public properties.

    It's a habit I've maintained for a long time.

    And I find it more readable, but that's me. I just organize it in a way that makes sense to me.

    Code (csharp):
    1.  
    2. public class Example
    3. {
    4.  
    5.     #region Fields
    6.    
    7.     //i can come here and see all the fields that exist
    8.    
    9.     #endregion
    10.    
    11.     #region CONSTRUCTOR
    12.    
    13.     //i can come here to see how those fields may be initialized
    14.    
    15.     #endregion
    16.    
    17.     #region Properties
    18.    
    19.     //i can come here to see what properties are actually publicly available from my class
    20.    
    21.     #endregion
    22.    
    23.     //.. so on, so forth
    24.  
    25. }
    26.  
    And of course, my IDE has a Class View so I can see the general shape of the interface of my class.