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. Voting for the Unity Awards are OPEN! We’re looking to celebrate creators across games, industry, film, and many more categories. Cast your vote now for all categories
    Dismiss Notice
  3. Dismiss Notice

What's wrong with making all variables public ?

Discussion in 'Scripting' started by joefliss, Jul 7, 2018.

  1. joefliss

    joefliss

    Joined:
    Jun 13, 2018
    Posts:
    16
    Hello everyone. I'm new to Unity and Game Developping and i'm making my first game.

    I have a simple question, as i'm testing the variables and how they change when i play the scene to test if the game works or not. I almost all variables public so i can see how they change. But is there anything wrong with leaving them all public ?
     
  2. neoshaman

    neoshaman

    Joined:
    Feb 11, 2011
    Posts:
    6,466
    Not if you are "alone", but it's discipline, it forces you to think about what need to be accessed outside and not. It prevent you from making silly mistakes by making it public and accessing them without checks.

    Yes if you are in a team, it's basically a way to communicate about the design and what's off limit.

    And generally you are never alone, there is at least your past self and your future self. While they generally know each other very well, you will never know if one days one will make dumb thing or forget stuff due to fatigue, can save hunting bugs when you have a deep shortcut call to a variable that should be private in a function that should have been internal only, especially when the project grew in complexity, and you start having a lot of dependency everywhere due to patching exception in the code.
     
    Last edited: Jul 7, 2018
    Ryiah likes this.
  3. lordofduct

    lordofduct

    Joined:
    Oct 3, 2011
    Posts:
    8,378
    First and foremost, your desire for using public so they show up in the inspector really has nothing to do with the discipline of public vs private (vs internal/protected). That has to do with serialization.

    See Unity serializes all public fields by default (if they can be). And this is why/how they show up in the inspector, so you can see them. Note that you can serialize private fields, you just add the 'SerializeField' attribute:
    https://docs.unity3d.com/ScriptReference/SerializeField.html

    And yes, there are implications with having them all public/serialized. It means they're serialized. The serializing of data takes up space, it adds time to the deserializing, and it means data might be set to values you might not otherwise want it to be. These are some of the things you should be aware of when allowing them to show up in the inspector.

    ...

    Now to the other side of the conversation. That being public vs private,internal,protected.

    Outside of the fact unity implies serialization from your access modifer. Access modifiers have a completely different purpose in the sense of the C# language.

    Access modifiers are use in the manner neoshaman is talking about. It's to communicate the purpose or intent of the class member, and has completely to do with the design principal of encapsulation.

    A public member implies that outside objects should be able to mutate that field/property/method (mutate means to modify/change the state of). The class should be written in a manner where that mutation of that field/property shouldn't break the object (by putting it in an invalid state). This is why things like properties exist, so you can validate inputs before setting the state of the object (fields/variables are the state).

    Private members on the other hand imply that outside objects shouldn't be mutating it. It's upto the class itself to do so. This may be because mutating that field could break the state of the object.

    I'll give an example.

    Lets say you have a script that when it's enabled it increments an integer field counting the number of times it has been enabled:
    Code (csharp):
    1.  
    2. public class CountTimesEnabled : MonoBehaviour
    3. {
    4.  
    5.     private int _count = 0;
    6.    
    7.     private void OnEnable()
    8.     {
    9.         _count++;
    10.     }
    11.    
    12.     public int Count
    13.     {
    14.         get { return _count; }
    15.     }
    16.  
    17. }
    18.  
    Note that in this case '_count' should always reflect the number of times OnEnable has been called. If we expect that to be valid we don't want anything else modifying it.

    Now, in my class I ensure this by only incrementing it during OnEnable.

    BUT what about other classes out there. If '_count' were public anyone could modify it. So by setting it private I've conveyed to anyone who reads this class that no one should be mutating '_count' all willy nilly. To remain valid it should only be mutated by CountTimesEnabled.OnEnable. If you want to retrieve said value, just call the 'Count' property and it'll return it.

    And the compiler helps enforce this rule for you.

    Now as neoshaman points out, this might not seem obviously helpful on a one man team. If you're alone why bother with this? You wrote the code, so you aught to know how to access it.

    So you may be inclined to think this is only useful when in a team.

    Well... I put to you... say you go off and write 100,000 other lines of code over several weeks/months, and then you come back to this class. Is it so obvious then? Do you even remember writing this class?

    Sure you could leave comments in.

    But really it's nice to have a language that conveys what it means in and of itself.

    Comments would be like leaving little notes in between the lines of a novel you wrote. If you written language can't convey what you want it to say... maybe your language needs to be more 'expressive'. Of course... the expressiveness of a language is a hot topic amongst programmers/engineers. So I'm not saying this is necessarily a good thing depending on the school of thought you come from... but there is a large group who prefer a language that is expressive. Expressive languages are very nice from a long term maintenance perspective, and C# was designed for the enterprise space where long term maintenance is king.
     
  4. unity_lfdIHSb2LvaWEA

    unity_lfdIHSb2LvaWEA

    Joined:
    Apr 28, 2019
    Posts:
    4
    Might be bad manners to resurrect such post but I just wanted to say this was very insightful. Thank you.
     
    DouglasAsted likes this.