informa
/
7 MIN READ
Featured Blog

Coding guidelines for a debuggable code base

The coding style guidelines helped us to make our code base more debuggable, easier to read and maintain.

Maintaining a code base for six years is a hard task when you don't start early on to create conventions and paradigms for your coding guidelines, especially if you have fluctuations in your programmers (working students, retirements, freelancers,...). Over the years, about 12 different programmers of various experience contributed to our code base. While doing code reviews with colleagues is a good opportunity to teach other (junior) programmers your coding guidelines, it is also important to listen to your coworkers. In fact in my 10 years of coding I've never experienced a single guideline which wasn't broken at least once, but always with good reason. And you should know the reasons and maybe even adjust your guidelines then.

Coding style

The main reason for our guidelines is to create readable and easy to debug code, i.e. no too complex instructions or equations and trying not to hide variables in instructions which could be important for debugging. This of course didn't produce always the best or most optimized code, but that was most times better than having someone not understanding how to fix a bug or even introduce a new one.

A thing which irritated me many times when I got applications for an open programmer position was finding code in a non-english language. One thing was that it was sometimes nearly impossible to read some of the code (no, I can't read chinese, russian,... variable names). The other thing we stumbled upon in our team was that it was merely confusing if people talked about the same thing, but named it differently in their own language (our company is located in Germany). So english were forced to be used in code, comments and (technical) documentation all the time to avoid that confusion.

I've split the guidelines into three categories:

  1. General, general guidelines to consider before actually writing code.
  2. C# specific, which were the guidelines to write any C# code.
  3. Unity specific, which were to avoid some pitfalls in writing for Unity3D.

Again, all the guidelines were not set into stone! If there was a good reason to break one, all had to know why and it was okay for everyone. The most important thing was that all programmers were fine with the guidelines and that they worked for the whole team.

 

So let's take a look at the guidelines:

General

  1. The coding language is english. Class, variable, function and method names are all in english, as well as all written comments or header information.
  2. Use spaces instead of tabs (that way the code looks the same on every other machine). A tab is 4 spaces.
  3. Names of variables and functions should be descriptive. Long names are no problem, undescriptive names are. Only use abbreviations if they are very clear and commonly known.
  4. No hungarian notation.
  5. Every comma follows a space (e.g. myFunction(int a, int b, int c)).
  6. Use comma to improve readability, but keep it to one comma (e.g. add(1 + 2) instead of add(1+2)).
  7. Avoid making large classes. Extract generic functionality to helper classes. A single class file should not exceed more than 500 lines.
  8. Write short functions, preferably no longer that 100 lines.
  9. Don't write lines that are longer than what fits on a normal 1920*1080 screen.
  10. Produce DRY code. (https://en.wikipedia.org/wiki/Don%27t_repeat_yourself)
  11. Keep a loose coupling of classes. (https://en.wikipedia.org/wiki/Law_of_Demeter)
  12. Write functions as functional as possible. (http://www.gamasutra.com/view/news/169296/Indepth_Functional_programming_in_C.php). Writing functional will make it also easier to separate logic and keep classes smaller.
  13. Use code comments only if needed (e.g. when breaking one of the coding convention rules). Code should speak for itself and commenting it mostly means, that it is written too difficult to understand.
  14. When adding comments for later work, write "TODO:" and end it with your initials in brackets (e.g. "TODO: clean up later (PH)")
  15. Don't disable error and warning messages.
  16. When working with callback delegates, try to include both a successful and failed outcome.
  17. Avoid "magic numbers" (https://en.wikipedia.org/wiki/Magic_number_(programming)#Unnamed_numerical_constants). If constant values are needed, they have to be declared at top of a class.
  18. When working on own branches, update your branch frequently from the master/developer branch to stay up to date and avoid large merge conflicts.
  19. Commit small chunks of changes instead of huge commits. Makes it easier to review and revert.

C# specific

  1. Every class, interface, struct, enum is implemented in its own file. Only class intern private structs, classes, enums are allowed inside the same file (use within reasons).
  2. Actions and events are declared below, after properties and fields.
  3. Delegate function declaration and constant values are declared right after class declaration.
  4. Functions and methods start with entry functions: Constructor (and for MonoBehaviours: Awake, OnEnable, Start) with an optional Initialize function. Following exit functions: Destructor (OnDisable, OnDestroy).
  5. Class, enumeration and function names are starting with a capital (UpperCamelCase).
  6. Constants are all capital letters.
  7. For private fields which are used for temporary data storage (e.g. between 3rd party plugin callbacks), use "_" before the variable name to display its special usage.
  8. The order for variable declarations is: as SerializedField annotated variables, public and internal properties and fields (first properties, then fields), protected and private properties and fields (first properties, then fields).
  9. Avoid partial classes.
  10. Use extension methods if needed.
  11. Use correct visibility for classes and functions: private, protected, internal, public.
  12. Always add visibility classifier. So instead of "void myFunc()" write "private void myFunc()".
  13. Do not use regions, as long as it doesn't contain code which don't surprise other developers. (e.g. our lazy property pattern is widely used and doesn't contain any surprises).
  14. Avoid flag booleans to describe states of objects if possible. States of objects can most often be checked by other, already present, variables (e.g. "if(joinedTournament != null) playerJoined = true" introduces the redundant flag "playerJoined" as you can simply ask if "joinedTournament != null")
  15. Put curly brackets into extra lines. They may never be left out, except for trivial checks (e.g. if(callback != null) callback() ).
  16. Use curly brackets for switch cases to open and close case implementation.
  17. Use precompiler definitions as less as possible.
  18. Avoid LINQ.
  19. Don't use aliases.
  20. Use implicit namespaces. I.e. "var myGameObject = new GameObject();" instead of "var myGameObject = new UnityEngine.GameObject();"
  21. Ternary operator ( ? : ) may be used in trivial cases. Never nest it though, like:
    var exceptionSupport = exceptionLevel == 0 ? WebGLExceptionSupport.None : exceptionLevel == 1 ? WebGLExceptionSupport.ExplicitlyThrownExceptionsOnly : WebGLExceptionSupport.FullWithoutStacktrace;
  22. Avoid nesting variable declarations in functions. That makes them hard to debug. So instead of: add(multiply(a, b), c); write:
    var ab = multiply(a, b);
    add(ab, c);
  23. Use explicit null checks (e.g. if(myObject != null) instead of if(myObject))
  24. Use object pooling when it makes sense.
  25. Try to avoid Lambda and closure functions. Instead use reusable delegate functions.
  26. Use for loops whenever possible. Store list variable before using it.
  27. Use "var" when type initializer explicitly defines type (i.e. "var myFloat = 1f;" instead of "float myFloat = 1f;")

Unity3d specific

  1. Use cached references to Unitys components: transform, gameObject,... by using lazy properties.
  2. Avoid Unitys build in properties to get components. Especially in Update() loops! They are always calling GetComponent<>().
  3. Avoid Camera.main.
  4. Avoid GameObject.Find().
  5. Use Time.timeScale with care. It has many side effects (wanted and unwanted).
  6. Remove Start, Awake, Update,... functions used by Unity. They are called even if they are empty.

 

These guidelines are meant to be an inspiration for other developers. You can agree and disagree with lots of them, they worked for us but that doesn't mean that they will also work for you. Think about what you want to achieve with the guidelines and where they can help you and your team to avoid problems.

Feel free to write your experience with code guidelines into the comments section. You can also write me on twitter if you want to discuss our guidelines with me.

Also take a look at other very good blog posts from other developers, which inspired me:

- Joost Van Dongen from Ronimo: https://www.gamasutra.com/blogs/JoostVanDongen/20170711/301454/The_Ronimo_coding_style_guide.php

- John Romero from id Software: https://www.gamasutra.com/view/news/279357/Programming_principles_from_the_early_days_of_id_Software.php

- Jessica Baker from Rare: https://jessicabaker.co.uk/2018/09/10/comment-free-coding/

Latest Jobs

Treyarch

Playa Vista, Los Angeles, CA, USA
2.03.23
Senior Physics Gameplay Engineer - Treyarch

High Moon Studios

Carlsbad, CA, USA
2.03.23
VFX Artist - High Moon Studios

Anne Arundel Community College

Arnold, MD, USA
1.30.23
Instructor/Assistant Professor, Game Art

Treyarch Vancouver

Vancouver, BC, Canada
2.02.23
Producer - Treyarch Vancouver
More Jobs   

CONNECT WITH US

Explore the
Subscribe to
Follow us

Game Developer Job Board

Game Developer Newsletter

@gamedevdotcom

Explore the

Game Developer Job Board

Browse open positions across the game industry or recruit new talent for your studio

Browse
Subscribe to

Game Developer Newsletter

Get daily Game Developer top stories every morning straight into your inbox

Subscribe
Follow us

@gamedevdotcom

Follow us @gamedevdotcom to stay up-to-date with the latest news & insider information about events & more