Search Unity

  1. We are migrating the Unity Forums to Unity Discussions. On July 12, the Unity Forums will become read-only.

    Please, do not make any changes to your username or email addresses at id.unity.com during this transition time.

    It's still possible to reply to existing private message conversations during the migration, but any new replies you post will be missing after the main migration is complete. We'll do our best to migrate these messages in a follow-up step.

    On July 15, Unity Discussions will become read-only until July 18, when the new design and the migrated forum contents will go live.


    Read our full announcement for more information and let us know if you have any questions.

Question Coding Conventions

Discussion in 'Scripting' started by junior333istall, Feb 11, 2023.

  1. junior333istall

    junior333istall

    Joined:
    Jan 11, 2023
    Posts:
    101
    So, since im a complete beginner at C# should i learn all about coding conventions or just learn the basic ones like Pascal and Camel Case?
     
  2. Spy-Master

    Spy-Master

    Joined:
    Aug 4, 2022
    Posts:
    908
    It’s worth engraining generally accepted conventions in your mind as you go along, so you don’t need to adapt to things later. However, if you find that this is too difficult or distracting when you’re getting a handle on how to use the language in general, it’s fine to leave that to a later time. Proper reference materials should tell you what the accepted conventions are as you need them, anyway. Just know that for the most part, you’ll use pascal case for methods, properties, and classes, camel case for local variables, and start interfaces with “I”. For Unity specifically, you generally use camel case for fields.

    Also, it would be worth taking advantages of the automatic naming suggestions, auto-formatter, and other intelligent suggestions in Visual Studio or Jetbrains Rider.

    Some reference resources:
    https://unity.com/how-to/naming-and-code-style-tips-c-scripting-unity
    https://learn.microsoft.com/en-us/dotnet/csharp/fundamentals/coding-style/coding-conventions
     
  3. junior333istall

    junior333istall

    Joined:
    Jan 11, 2023
    Posts:
    101
    So would this be a good use of conventions? I used naming conventions and comments

    Code (CSharp):
    1. using System.Collections;
    2. using System.Collections.Generic;
    3. using UnityEngine;
    4.  
    5. public class LogicScript : MonoBehaviour
    6. {
    7.     // Variables to move the player.
    8.     public Rigidbody2D _rigidBody2DSpeed;
    9.     private Vector2 _moveDirection;
    10.  
    11.     void Update()
    12.     {
    13.         // The direction the player is moving.
    14.         _moveDirection.x = Input.GetAxisRaw("Horizontal");
    15.         _moveDirection.y = Input.GetAxisRaw("Vertical");
    16.  
    17.         // Log the direction the player is moving in.
    18.         Debug.Log(_moveDirection);
    19.     }
    20.  
    21.     void FixedUpdate()
    22.     {
    23.         // How fast the player is moving.
    24.         _rigidBody2DSpeed.velocity = _moveDirection * 5;
    25.     }
    26. }
     
  4. halley

    halley

    Joined:
    Aug 26, 2013
    Posts:
    2,661
    Good conventions are just conventions where you're consistent. Microsoft has their recommendations. Unity has their own style. It's just like how different newscaster channels have different spellings for some foreign dictator's name, but each newscaster is always consistent about it on their own sites. Writing style guides exist, like the Chicago Book of Style or the Strunk & Wagnalls' Elements of Style. You may have heard of the "Oxford Comma" which comes from another style guideline reference.

    Some people might wonder why you started
    _rigidBody2DSpeed
    with an underscore if it was public, or why you use a capital B when Unity's Rigidbody and Rigidbody2D classes both use a lowercase b.

    But whatever works for you.
     
  5. Spy-Master

    Spy-Master

    Joined:
    Aug 4, 2022
    Posts:
    908
    That looks pretty good. You may want to consider changing “_rigidBody2DSpeed” to “rigidBody2DSpeed” or “RigidBody2DSpeed.” Using camel case (rigidBody2DSpeed) would go with how a lot of first-party and legacy Unity-specific public serialized fields are named, while pascal case (RigidBody2DSpeed) would go with what Unity now appears to recommend in the resource I previously linked (and I believe Microsoft has generally gone this way as well).
    Note that whenever you change a serialized (for example public or marked with SerializeField) field’s name, any values you previously assigned in the Inspector or otherwise saved in asset files will be lost unless you use the FormerlySerializedAttribute attribute on the field.
    https://docs.unity3d.com/ScriptReference/Serialization.FormerlySerializedAsAttribute.html
    Besides that, nice looking code! :D
     
    Last edited: Feb 13, 2023
    SisusCo likes this.
  6. junior333istall

    junior333istall

    Joined:
    Jan 11, 2023
    Posts:
    101
    Oh yes sorry still getting used to it! thanks though.
     
  7. AngryProgrammer

    AngryProgrammer

    Joined:
    Jun 4, 2019
    Posts:
    490
    Looks very good. As it was written above, the underscore before the name is intended for private values (according to MS recommendations). Also, consider using abbreviations for extremely popular components (e.g. rb2d or just rb) most people familiar with Unity will understand this.
     
  8. Nad_B

    Nad_B

    Joined:
    Aug 1, 2021
    Posts:
    730
    Also don't bother with too much comments, naming your variables/fields/methods correctly and clearly will be more than enough (and I see that you're already doing this). Comments should explain why you did write a certain block of code, not what it does, something like:

    Code (CSharp):
    1. // Using Perlin Noise was causing some artifacts, so we switched to Wavelet Noise instead
    "Comments tell the why, not the how/what"
     
    Deleted User and Anthiese like this.
  9. chemicalcrux

    chemicalcrux

    Joined:
    Mar 16, 2017
    Posts:
    726
    Most of my comments are for fixes to things that surprised me.

    Code (CSharp):
    1.     public void Navigate()
    2.     {
    3.         // If we try to set the destination every frame, we'll never actually go anywhere
    4.         // if it takes too long to find a path!
    5.  
    6.         if (agent.pathPending)
    7.             return;
     
    Deleted User and Nad_B like this.
  10. tleylan

    tleylan

    Joined:
    Jun 17, 2020
    Posts:
    698
    As was pointed out consistency is slightly more important than the actual conventions used. You can modify your conventions over time (refactoring the existing code) as you develop your own style. When in doubt however use an established convention. BTW, don't get too hung up on the idea that every property needs to be some very long explanation. In a small class with what it does being obvious there is little benefit to naming something _rigidBody2DSpeed if it is controlling the speed. You didn't for instance name the other one _vector2Direction.

    And I would limit the use of the underscore to private properties. Oh... that _rigidBody2DSpeed isn't a speed at all. Be a little careful about obscuring what the property represents.
     
  11. Owen-Reynolds

    Owen-Reynolds

    Joined:
    Feb 15, 2012
    Posts:
    2,004
    I've found that thinking too much about every letter sucks time away from more important things. For example, naming your Vector2 moveDirection says what it is (since a Vector2 could stand for lots of things). But naming your rigidBody "speed" could be confusing if the script grows -- it's a rigidbody, not a speed.

    But one thing you can fix to make your code vastly easier to read is moving every { to the end of the line above it. VisualStudio has been trying to fix that bug for ages.
     
    Kurt-Dekker likes this.
  12. chemicalcrux

    chemicalcrux

    Joined:
    Mar 16, 2017
    Posts:
    726
    You can configure your editor to do this. It's not a "bug" :p
     
    mopthrow and halley like this.
  13. Yoreki

    Yoreki

    Joined:
    Apr 10, 2019
    Posts:
    2,606
    While i do agree that you can comment too much and that you shouldnt skip out on the "whys", i do respectfully disagree with the implications what descriptive comments should be avoided generally. I do love to use overview comments to segment longer pieces of code into logical sections. This helps immensely, especially in multi-coder projects. Done correctly, it lets you find the section of code you actually care to adjust without having to read through and understand the rest of it. In practice the latter can be especially helpful, if you have to adjust code written by another person, who just so happens to disagree with you on the subjective topic of what a good variable name looks like. A huge amount of time can be wasted on navigating code, as it becomes more complex. While classes and functions serve to segment code, in practice a lot of functions can grow large enough to make such "headline comments" a huge time saver. I personally use it for my own code as well, as it saves me way more time than not doing it. Especially if you work on code you didnt write yesterday.
     
  14. tleylan

    tleylan

    Joined:
    Jun 17, 2020
    Posts:
    698
    Planning ahead for something that will never happen is a complete waste of effort. If it needs to be renamed in the future you do it then when the "other thing" (which could be a similar object type right?) shows up.
     
  15. tleylan

    tleylan

    Joined:
    Jun 17, 2020
    Posts:
    698
    You are pointing out one of the other aspects about conventions. They are easier to follow if you are the sole developer or on a very small team. I've worked on huge projects that spanned a decade and most of the explanatory comments were no longer valid (if they ever were).
     
  16. SisusCo

    SisusCo

    Joined:
    Jan 29, 2019
    Posts:
    1,393
    Some practices to consider:
    1. Always use at least a top-level namespace. This helps avoid conflicts with type names in third party plugins. They can also be a great organizational tool, and help keep your class names shorter.
    2. Consider sealing all classes by default. This can help improve performance, give better static code analysis and makes a clear distinction between classes that are derived from (and are much more dangerous to modify!) and leaf classes.
    3. Consider if you want to prefer event-based programming over polling for changes every frame in Update.
    4. Consider whether or not you want to always explicitly specify access modifiers (private, internal...) or if you want to leave them out when it's the default one.
    5. Decide if you want to use expression-bodied members.
    6. Consider using the common
      -ing
      /
      -ed
      convention for event naming. For example event Scene.Opening would be invoked right before a scene opens, and Scene.Opened would be invoked right after it has opened.
    7. Consider using the single-responsibility principle to guide you when deciding how much stuff to put inside a single component. For example a Player class could easily grow to be thousands of lines long if it contains the logic for reading inputs, moving the GameObject, jumping, crouching, playing animations, etc. If this functionality is broken down into multiple classes, it can help make those classes more focused, and easier to comprehend and modify without introducing bugs. Components that only do one thing are also much more reusable.
    8. Comments can arguably sometimes be a sign of badly named variables and methods or methods that are doing too many things and should be broken into smaller pieces. When you want to add a comment, consider if you could improve readability by refactoring the code instead.
    9. Consider adding XML documentation comments to your code. These can be handy because the IDE shows them as tooltips when hovering over type and member references. Having a general overview of what a component does can help save a lot of time, because you can quickly get a good understanding of its use cases without having to read through the code. Listing out what happens in more exceptional cases (if player does not exist, will PlayerManager.PlayerName be null or empty or throw an exception?) in method/property summaries can be really useful in avoiding bugs in places where they are called. Sometimes you can also realize ways you can improve your code while writing these summaries (Maybe I should add
      bool TryGetPlayerName(out string name)
      instead or returning null).
    10. If you have multiple instances of the Enemy prefab, and they all share some of the same stats like Speed and MaxHp, consider extracting the shared values into a ScriptableObject asset. This can help reduce memory use, loading times and makes it easier to change values for multiple objects in one place. It can also make it easer to try out different values in play mode, and have the changes affect all instances on-the-fly.
    11. Consider using properties instead of public fields, and only exposing a public get-accessor and making set private (or not adding one at all) when possible. The less places there are that can change the state of an object, the easier it is to keep track of it all and have it not break in some edge cases.
    12. Consider specifying exact units used in variable names (e.g. ElapsedSeconds, DurationSeconds), summaries and / or by creating unique types for different units instead of using the same primitive types for everything. Ambiguity in code is bad, and bugs can be introduced when you think something is in in pixels but it's in viewport space units instead.
    13. Consider if you want to explicitly specify numeric types with their suffix (
      60f
      ,
      60d
      ), or rely on implicit conversions.
    14. Consider if you want to prefer using
      var
      over explicit types. If so, are there exceptions? Using var can have benefits like reducing noise/repetition and making it easier to change types of variables later on.
    15. Consider if you want to always organize your members in some particular order (for example events always first, then fields, then properties, then constructors, then methods, then nested types...).
    16. Consider how you want to approach null-handling. Do you want to guard against null everywhere? Do you want to do this at edit time (OnValidate), at runtime (Awake) or both? Do you want to mark variables that don't need to be null checked with [NotNull]? Or maybe you only null-check variables with the [MaybeNull] attribute.
    17. Consider avoiding abbreviations. How much benefit are you really gaining from writing
      dbg
      ,
      rb
      and
      mr
      instead of
      debug
      ,
      rigidbody
      and
      meshRenderer
      ? Abbreviations can introduce additional mental overhead when reading code that would not be needed if plain English was used. An exception to this rule would be abbreviation that are so common they can be used even more than the non-abbreviated form (GUI, HUD, ID, FBI...).
    Example:

    Code (CSharp):
    1. namespace MyGame.Components
    2. {
    3.     /// <summary>
    4.     /// Component that moves a <see cref="Movable"/> component based on the player's movement inputs.
    5.     /// </summary>
    6.     public sealed class InputProvider : MonoBehaviour
    7.     {
    8.         [SerializeField] private Movable movable;
    9.  
    10.         private void OnEnable() => InputManager.MoveInputGiven += OnMoveInputGiven;
    11.         private void OnDisable() => InputManager.MoveInputGiven -= OnMoveInputGiven;
    12.  
    13.         private void OnMoveInputGiven(Vector2 moveInput) => movable.MoveDirection = moveInput;
    14.     }
    15. }
    Code (CSharp):
    1. namespace MyGame.Components
    2. {
    3.     /// <summary>
    4.     /// Component that enables objects to be moved.
    5.     /// </summary>
    6.     [RequireComponent(typeof(Rigidbody2D))]
    7.     public sealed class Movable : MonoBehaviour
    8.     {
    9.         [SerializeField] private Rigidbody2D rigidbody;
    10.         [SerializeField] private MovableSettings settings;
    11.  
    12.         /// <summary>
    13.         /// Gets or sets the direction in which this object is currently moving.
    14.         /// <para>
    15.         /// Magnitude of the vector is clamped between 0 and 1.
    16.         /// </para>
    17.         /// </summary>
    18.         public Vector2 MoveDirection
    19.         {
    20.             get => rigidbody.velocity.normalized;
    21.             set => rigidbody.velocity = value.normalized * settings.Speed;
    22.         }
    23.  
    24.         private void OnValidate() => rigidbody = GetComponent<Rigidbody2D>();
    25.     }
    26. }
    Code (CSharp):
    1. namespace MyGame.Settings
    2. {
    3.     /// <summary>
    4.     /// Specifies the settings for a <see cref="Movable"/> component.
    5.     /// </summary>
    6.     [CreateAssetMenu]
    7.     public sealed class MovableSettings : ScriptableObject
    8.     {
    9.         [SerializeField, Min(0f), Tooltip(
    10.         "The constant speed at which the object travels when it is moving.\n\n" +
    11.         "In units per second.")]
    12.         private float speed;
    13.  
    14.         /// <summary>
    15.         /// The constant speed at which the object travels when moving.
    16.         /// <para>
    17.         /// In units per second.
    18.         /// </para>
    19.         /// </summary>
    20.         public float Speed => speed;
    21.     }
    22. }
     
    Last edited: Feb 14, 2023
  17. tleylan

    tleylan

    Joined:
    Jun 17, 2020
    Posts:
    698
    I tend to recommend "practical" conventions over what might be termed enterprise conventions. I don't think the person who posted the question is part of a large team.

    I suggest one adapt over time like one might learn a foreign language. Rules are great but adherence to rigid rules when starting out can take the fun out of things.
     
  18. junior333istall

    junior333istall

    Joined:
    Jan 11, 2023
    Posts:
    101
    Yes, i'm not part of a big team i'm solo. I'm really trying to focus primarly on the naming conventions and layout conventions by microsoft.
     
  19. junior333istall

    junior333istall

    Joined:
    Jan 11, 2023
    Posts:
    101
    Ive wrote code before and its really messy and hard to read so thats why im trying to write neat clean code thats easier to mantain
     
  20. TzuriTeshuba

    TzuriTeshuba

    Joined:
    Aug 6, 2019
    Posts:
    186
    so naming conventions will help quite a bit, because even as a solo dev, you may find yourself posting your here or other places looking for help, in which case well-thought names will get you a lot more help.

    something else that may help you is using constants for magic numbers. like at the top of a file having DECK_SIZE = 52, rather than having a '52' sitting in the middle of your code.
     
  21. spiney199

    spiney199

    Joined:
    Feb 11, 2021
    Posts:
    8,647
    There's a stickied post on this very sub-forum from Unity staff that has a download link for Unity's proposed 'base' style guide. That's generally been my preferred coding style, being very straight-forward, clean and readable.
     
    SisusCo, Yoreki and Anthiese like this.
  22. Yoreki

    Yoreki

    Joined:
    Apr 10, 2019
    Posts:
    2,606
    The only Unity C# convention im really not a fan of is the member leading underscore.

    Keep in mind that conventions serve to make code more uniform among different developers, so they can more quickly understand what's what. Following the most basic conventions of whatever environment you work in is a good practice for that purpose, but you dont have to follow every last one of them. Beyond the most basic layer, people will heavily disagree on what good conventions are anyways, based on what programming language / environment they come from. In python, for example, you more often than not dont use camelCase, but instead underscore_separation. Thus someone who is heavily used to that may adopt it for C# aswell, which would look weird to other C# developers, but technically there is nothing wrong with it. And vice versa, of course.

    I personally stick to camelCase, UpperCamelCase and CAPS_UNDERSCORE for C# naming, which i find sufficient to communicate what's a variable, class, method, ... and so on. As for the leading underscore, i find it a really annoying convention. It's hard to type out quickly, as it's a Shift+Key combination (at least in my keyboard layout), and it adds an unnecessary symbol at the start which means one more symbol to type before the first possible distinction can be made to allow your IDE to autocomplete the rest of the identifier.
     
    Ryiah and SisusCo like this.
  23. Owen-Reynolds

    Owen-Reynolds

    Joined:
    Feb 15, 2012
    Posts:
    2,004
    Think of a leading underscore as part of the name instead of some style rule. It means "more private". That an underscore is more work to type-out is a feature. You think "I don't want to type that character -- I'd have to put my donut down" and then you think "wait, do I even want to use that function?"

    Back when we didn't even have
    private
    we used an underscore to mark "if you're an outsider be careful using these"'s. Of course now you just make it private -- style rules saying to put underscore in front of privates are either super-outdated or for non-private-having languages. But now underscore can be repurposed to funny private-seeming cases.

    Maybe you have to expose a cleanUp() function for some special case. Naming it
    _cleanUp()
    is an easy way to let users know they don't have to always call it. Or name it
    _specialCaseCleanUp()
    . The underscore is still an extra heads-up. Or sometimes you've got a large class with lots of private functions and a few very-special-case ones. Maybe
    private rejustify()
    gets called a lot, while
    private _rejustifyWithOutKerning()
    is called rarely. The underscore warns other member functions "this is probably not the one you want".
     
  24. tleylan

    tleylan

    Joined:
    Jun 17, 2020
    Posts:
    698
    Coding conventions are not a substitute for well-written code. Conventions exist on a number of planes from none to enforced by the enterprise and include "that's how all the code in that 10 year old app is written". One typically has a personal set of preferences (regardless of what some random individual thinks) and adjusts according to the situation. Someone posted on this forum a few weeks ago that

    Code (CSharp):
    1. using TMPro;
    was "confusing" or at least inconsistent and thought it should be moved so we could write
    Code (CSharp):
    1. using UnityEngine.TMPro;
    I suggested that if that bothered him he isn't going to make it as a developer on larger enterprise-level projects with dozens of developers from around the world.

    Take recommendations in stride, consider them, use the ones you like ignore the ones you don't. I use underscores for private properties. :)
     
  25. chemicalcrux

    chemicalcrux

    Joined:
    Mar 16, 2017
    Posts:
    726
    Coding conventions facilitate the creation of well-written code -- and the understanding of that code by others.

    There is absolutely nothing wrong with thinking that this is inconsistent. I think it looks weird, since I'm so used to things being namespaced under UnityEngine.

    Chastising someone for that is unreasonable.
     
  26. tleylan

    tleylan

    Joined:
    Jun 17, 2020
    Posts:
    698
    I seem to have hit a nerve, sorry about that. But the reality (if we are into that) is that it isn't going to be changed in the short-term but then I really don't know, perhaps it will be. I didn't see it as chastisement BTW.

    Generally speaking I'll bet we all understand the value of coding conventions. I'm simply stating facts having worked for several billion dollar companies. The world of software is not always so tidy and there were many projects with 3 or 4 "conventions" as they changed over a decade.

    The code was not "understandable" by most people but it worked and while I could personally get away with "fixing" large parts, the junior programmers didn't understand the impact that making fundamental changes could have on all the other services running. Breaking it could mean the loss of a million dollars a day.

    I hope the original poster and everyone else adopts coding conventions that work for them but they may not always be to their liking.
     
  27. SF_FrankvHoof

    SF_FrankvHoof

    Joined:
    Apr 1, 2022
    Posts:
    780
    Backwards-Compatibility would state that it never will be, because if the namespace is changed, all projects would need to update this everywhere.
    It's a result of TMP having been a completely seperate 'entity' from Unity in the past (Unity bought it from the developer).
     
    chemicalcrux likes this.
  28. tleylan

    tleylan

    Joined:
    Jun 17, 2020
    Posts:
    698
    Frankly that was my point :) Still most changes could be automated with an editor script. It was a silly thing to be bugged about.
     
  29. Owen-Reynolds

    Owen-Reynolds

    Joined:
    Feb 15, 2012
    Posts:
    2,004
    Since C# is microsoft's language it's fun to look at their history of coding styles. In the 90's, according to "ShowStoppers", BG and the group around him thought standards were bad; coders were geniuses and lesser minds shouldn't tell them what to do. Later when they hired people to write the new Windows there were arguments about starting all member variables with
    m_
    (which distinguishes them from parameters) or prefixing all vars with the type (such as
    i_
    for integers; called Hungarian notation).

    As best I can tell, their current rules came about when they realized they had none and customers were asking. Not-BG (he was gone by then, so maybe Ballmer or probably an underling) had people ask the Excel team, the Word team ... about style, and took the average.
     
  30. SisusCo

    SisusCo

    Joined:
    Jan 29, 2019
    Posts:
    1,393
    So that means if Microsoft's guidelines are a great match for you, you must be a pretty average programmer.
     
    SF_FrankvHoof likes this.
  31. tleylan

    tleylan

    Joined:
    Jun 17, 2020
    Posts:
    698
    Why would anything mean that? Which conventions do you follow, if we follow them we are above average?

    Seriously these threads can get pretty depressing.
     
  32. SisusCo

    SisusCo

    Joined:
    Jan 29, 2019
    Posts:
    1,393
    @tleylan I was just trying to make a dad joke :p

    One must be an "average" programmer if the style guide that was created for the "average" Microsoft employee fits them well.

    And yeah, I must be a pretty average programmer myself, since I do follow the guidelines pretty closely (except for the
    _
    ,
    s_
    and
    t_
    prefixes).
     
    Last edited: Feb 15, 2023
    Yoreki likes this.
  33. halley

    halley

    Joined:
    Aug 26, 2013
    Posts:
    2,661
    The history here is a little off.

    The Hungarian Notation (named after Charles Simonyi) borrowed from older languages like FORTRAN which identified default types for variables by their initial letter. It was adopted by the MFC (Microsoft Foundation Classes) team for use in MS's first C++ compiler and companion C++ class library, which wrapped the Win32 API. The type prefixes stacked, so m_ for member, m_nCount or m_sName, etc.

    At the time, obviously, nobody else at Microsoft used MFC or C++, and kept doing their C thing however they wanted. Even a decade later, Microsoft's Apps division barely used C++ and surely didn't rewrite their whole apps like Excel or Word. However, as time went on, pretty much any of the smaller apps evaluated C++ and the approach caught some traction. The outside world used it more than Microsoft internal teams.
     
  34. tleylan

    tleylan

    Joined:
    Jun 17, 2020
    Posts:
    698
    I get it now. Guffaw :)
     
    SisusCo likes this.
  35. Owen-Reynolds

    Owen-Reynolds

    Joined:
    Feb 15, 2012
    Posts:
    2,004
    Sorry I wasn't clear, the part about Hungarian notation was from the book, written in 1994 by someone who talked to the WindowsNT team. They were definitely arguing about
    i_cats
    vs. just
    cats
    or
    m_cats
    . I don't know how it ties in with how other people used HungN. The book is pretty good but not super-easy to find. I think I borrowed mine from the huge University Library.

    As for the last part, that was my point -- microsoft's person _asked_ the teams about style, but never told them what to do. As best I can tell, the C# style guide is like UnityLearn -- outsiders kept asking "do you have this?" and they didn't see a need until finally they were like "fine, will this make you happy?". But I merely spent about 2 hours a few years ago googling about it.

    Onto FORTRAN, which is a real point. IMHO more important than style is naming conventions. One I still use from FORTRAN, which C stole, is super-short names for very local vars: i,i,k for nested loops; w or s for strings; n for ints; f for floats; and n1, n2, n3 or f1, f2, f3 or w1, w2, w3 for several. For longer super-local I still keep it short: iCat for the catIndex, d1, d2, d3 for various distances, gap for "the horizontal gap between cats in the current row".

    Then there's a whole thing with good longer names. The last thing I did I had variables "stage" and "level" and a different level and I think "rank" and I kept getting tangled up which was which. Finally I renamed the main one "era" (since it kind of stood for progress through time) and I could remember that, and I think one became "upgradeLevel" which I could also remember. Naming variables or writing comments is almost like writing a solid short sentence, a weak skill with many coders.
     
    SisusCo likes this.
  36. tleylan

    tleylan

    Joined:
    Jun 17, 2020
    Posts:
    698
    Q: What did they name object-oriented COBOL

    A: add one to COBOL
     
  37. halley

    halley

    Joined:
    Aug 26, 2013
    Posts:
    2,661
    Sorry, I wasn't clear. I was on the MFC team from 1991 to 1993. ;)


    As for short names, if you can see ALL of the instances of that variable on one screenful, say an 80x25 screen, then go for it. Otherwise, we have Intellisense and completions and macros in our editor for a reason. Never give up readability to save keystrokes.
     
  38. Owen-Reynolds

    Owen-Reynolds

    Joined:
    Feb 15, 2012
    Posts:
    2,004
    And if I have this right, you thought/think they were the only group at MS to use "Hungarian notation". And that's more of what my point was, since it turns out the team from Digital Equipment hired to write WindowsNT was also partly using "Hungarian" from the late 1980's and you didn't know and no one especially cared to ask. It just wasn't a big deal.

    Did you like it? I can't see the point, even before nice IDE's. I mean, I already have to remember that cats stands for how many cats I have. Obviously it's an integer. Naming it i_cats seems pointless. Same seems to go for most variables. Maybe some people think Hungarian also means adding conceptual type information, such as meters_height, but then almost everything is technically Hungarian. I suppose I can see it for things like unsigned long int and so on, but intense use of those is rare.

    As for m_myMember, Python (I think) basically does that when they say all member variables must use this-dot. Things like
    setCats(cats) { this.cats=cats; }
    . But we can do the same thing in C# and choose not to.
     
  39. tleylan

    tleylan

    Joined:
    Jun 17, 2020
    Posts:
    698
    Back in the '90s I wrote articles extolling the virtue of HN. It served a purpose at the time but its time has passed. Specifically I was using it with languages that had no type enforcement at all.

    Code (CSharp):
    1. var = 5
    2. var = "hello"
    3. var = .t.
    The prefix didn't have to represent actual datatypes. I could prefix something with bx_ as in bx_menu to represent that it was a "box" definition, i.e. an array with a given structure related to something I declared as a box.

    I found it very helpful at the time.
     
  40. halley

    halley

    Joined:
    Aug 26, 2013
    Posts:
    2,661
    No, if you read back to what I wrote, I didn't imply that. Simonyi was a big name at Microsoft, but was not a part of the C/C++ team nor MFC, so of course the concept was wider-known throughout the company of 10,000 people at that time. Microsoft was still busy scrubbing the serial numbers off the codebase from their partnership with IBM on OS/2 recycling as much as possible into Windows NT [something they repeated in Java>C#], and looking for new coding conventions for that work. Unlike MFC, the Windows NT rarely showed off the Hungarian in exposed APIs, but used it in its internal structures a fair amount.

    This is the end of my interest in the conversation, as it's a distraction from OP's questions about Unity, C# conventions, and writing games.
     
  41. Owen-Reynolds

    Owen-Reynolds

    Joined:
    Feb 15, 2012
    Posts:
    2,004
    Right, to me we were realizing that with longer variable names allowed we can start making them more descriptive, which includes what they relate to or units and so on. At first people figured maybe we needed a system, but I think we do it informally now. So your bx_menu today might be simply boxMenu, or redBoxMenu or boxAppearanceMenu, or menuBox1 (if it's in the menu section). If I'm playing with cat and dog arrays I want index variables to tell me that, and to say which array they go to, but ci, di1 and di2 are just fine (instead of, ummm, idx_cats_n and idx_dogs_n1).

    I feel like the early bx_ attempts were thinking we could plan everything in advance -- sort of the waterfall vs. agile thing. Today we think that level of planning is a waste and figure to pick decent names as we go, fixing them when we know more. So maybe we went nuts and had "milesCity1ToCity2", and later find we don't need to be told that stuff, but we do need to know it's by road, not straight-line, and it's not the final distance, so we rename it bestDistByroad.
     
  42. Owen-Reynolds

    Owen-Reynolds

    Joined:
    Feb 15, 2012
    Posts:
    2,004
    Obviously I think this is important. OP wrote one sentence "should i learn all about coding conventions or just learn the basic ones like Pascal and Camel Case?" We get asked that a lot and there are pages and pages written, which isn't wrong but reading all that is going to kill anyone's desire to write programs. I say the answer is "no -- spend your time on other stuff".

    But the answer has to be "no, and here's why". And the "why" is that the people who own C# tried to make rules, then gave up. They don't even use the rules on their own web site now.
     
  43. tleylan

    tleylan

    Joined:
    Jun 17, 2020
    Posts:
    698
    Pardon me but I think you are overanalyzing it a bit. You need to be back in that decade reading the code that followed no convention at all. It was a workable solution that worked for many people (myself included). I think you were there but perhaps working with people who understood the value of consistency in code.

    I had an application that took 1 hour to compile. There was no editor to tell me whether it would or wouldn't compile I started the compiler and went to lunch. If it didn't build then it couldn't go for testing.

    Anything that helped was by definition helpful. I also wrote in my article words to the effect of "if this doesn't work for you then don't use it".
     
  44. tleylan

    tleylan

    Joined:
    Jun 17, 2020
    Posts:
    698
    Again you probably have your reasons but I can't understand why the answer to learning/using coding conventions would be "no". You would be fired from the team if you couldn't follow our basic conventions. Why would the new guy get to decide that whatever they felt like doing was as good as what the people who a) wrote the app and b) have worked there for 10 years, have standardized on?

    I think the thread has just about died now. :)
     
  45. Owen-Reynolds

    Owen-Reynolds

    Joined:
    Feb 15, 2012
    Posts:
    2,004
    Why would they refuse to follow your coding conventions? Why would they be unable to? The question is what someone just starting to learn programming should spend time on. Should it be to "learn all about coding conventions" or can they just start coding and pick up the style from Unity examples?

    I get that you don't want to encourage people to write ugly code on purpose, and you want to say some decent-looking style is important, but saying "yes" to their Q is pretty much telling them to research the Hungarian Notation Wikipedia page before writing their first IF statement. Maybe I'm being extreme, but can you think of some style rules specifically they should read about first? I suppose end-line comments, but those are in Unity examples.
     
    Yoreki likes this.
  46. tleylan

    tleylan

    Joined:
    Jun 17, 2020
    Posts:
    698
    Well I can only guess but I'm pretty certain that nobody has suggested that person learning C# stop everything and bone up on Hungarian Notation. And (I assume you checked the page) you will see there are lots of disadvantages to using it these days with type-safe compilers and modern editors.

    If a novice has a very busy schedule they can spend an hour watching a video and/or reading an online document any time after they have written their first IF statement. Following conventions is an option, not a requirement.
     
  47. lordofduct

    lordofduct

    Joined:
    Oct 3, 2011
    Posts:
    8,633
    This thread is a starter guide on why I think the conversation about coding conventions are ridiculous because it usually boils down to "my way is the best way" arguments.

    This isn't to say coding conventions are bad, but I generally find the conversations just devolve into pitched battles defending one's own camp.

    Take this hungarian notation nonsense. The arguments, taken from wikipedia, basically just boil down to "its unnecessary/cluttered/redundant". And yeah, sure, if I named my public facing class members with it, it's cluttered. And if I put it in a class name it's... really really redundant. But whose doing that? And who cares if it's kind of redundant for simpler things?

    I've seen this criticism lobbed at simple things like "sName" and "iCount" cause "it's implied a name would be a string anyways". OK, yeah, sure. But so what? It's not hurting anything. "Oh, but what if you need to translate it, now you gotta rename it!" Are you telling me if I port to Java from C# it's not going to have an int or a string? Or even if I ended up in a language that doesn't necessarily call it a string it's not going to be pretty obvious and NOT confusing what is meant?

    And then I see it get lobbed at stuff like this in many arguments:
    Code (csharp):
    1. public static string Pad(string str, char c) ...
    Sorry, but that is descriptive. It's way more descriptive than "value". Who cares that it breaks some anti-HN rule. (this isn't to say anyone here explicitly said that... just mentioning the devolved arguments I've seen spawned out of such things).

    Or more hilariously at things like the i,j,k for indexers because "they're short and non-descriptive" (not really a HN argument... but in the same space). Pfff... if you're a programmer and don't know what i,j,k means... you're not a programmer!

    And lastly... I love the anti-HN argument that "the compiler takes care of that". OK... tell that to my javascript/python/other interpreted language's compi... oh, that's right.

    ...

    Here's my simple list of rules for coding conventions.

    1) recognize that they exist and that you should probably use something that resembles a convention

    2) use a convention consistently through out a specific codebase

    3) when joining an existing codebase be able to recognize the conventions used and maintain the same for consistency sake

    4) if writing a public facing API that is intended to be consumed by 3rd parties one should select a very well known and popular convention relative to that products user space. For example a distributed C# library should probably use the MSDN/Microsoft C# coding conventions:
    https://learn.microsoft.com/en-us/dotnet/csharp/fundamentals/coding-style/coding-conventions

    Though this really only severely matters for the publicly facing aspects of your library. If internally/privately you break these standards it's not a deal breaker. Though this would break rule 2 of consistency. But then again if the code base was originally closed and a public api was attached on later... maintaining rule 3 is also important. There's no need to rewrite all the internal code just cause it doesn't abide by the rules of the publicly facing conventions.

    5) If you're writing your own privately used codebase and you find certain conventions help you... may that include hungarian... have at it bro! Just don't over do it. As with anything... too much of anything can be a bad thing. Flamboyant ignorance of the law is bad, ardent adherence can also be bad. And as long as you can adapt your conventions to the required context when you leave your private space... you're good.
     
    Last edited: Feb 20, 2023
    spiney199 and Ryiah like this.
  48. tleylan

    tleylan

    Joined:
    Jun 17, 2020
    Posts:
    698
    This thread is a starter guide on why I think the conversation about coding conventions are ridiculous because it usually boils down to "my way is the best way" arguments.

    Just about all conversations come down to "what I believe is right", humans are generally irrational. The upside is those that think conventions are dumb are reassured and those that think they should use them confirm their belief.

    And for perhaps 3rd or 4th time absolutely nobody suggested that one should standardize on Hungarian Notation with C# in 2023.

    I think this quote sums it up.
    Charles Simonyi was trying to bring clarity to an issue he dealt with in his craft.

    Now we can move onto the Option Explicit statement in Visual Basic.
     
  49. Owen-Reynolds

    Owen-Reynolds

    Joined:
    Feb 15, 2012
    Posts:
    2,004
    But technically, technically, if we're so old-fashioned as to read the 1st post, this thread wasn't supposed to be about coding conventions. For a few minutes it was about when a complete beginner should worry about them. And take SisusCo's perfectly fine list (near the top) -- most of those involve advanced topics (namespaces, sealing classes, event-handling ... ); not beginner stuff. Even your first "you should probably use something that resembles a convention" is fine, but ... then a beginner is going to want to know what's a convention to resemble, and then search, and get sucked back into namespaces and sealing classes.
     
  50. tleylan

    tleylan

    Joined:
    Jun 17, 2020
    Posts:
    698
    "if we're so old-fashioned" what does that even mean?

    So, since im a complete beginner at C# should i learn all about coding conventions or just learn the basic ones like Pascal and Camel Case?

    He doesn't appeared worried to me. It reads as though he was wondering whether coding conventions were important enough to study. What would be the purpose of leaning "the basic ones like Pascal and Camel Case"? Should I learn about nouns or just verbs and adverbs?

    He now has material that should convince him either to read more or to ignore them and he will live with his decision. He could read a little and see if the topic interests him to read more.

    SisusCo should have cited where he got that list from. If he wrote it then it is not unlike you stating something like most people don't use conventions or my stating everybody uses conventions. There is nothing with which anyone (who doesn't understand conventions) can vet the information. They are almost universally not simple introductory examples of conventions.

    There are books, articles and videos all over the Internet that deal with the pros and cons. Leveraging existing material is good idea.