The primary concern by far when writing code is to write readable, maintainable code.
Such code is also “more debuggable” because the debugger lets you step over code line by line, not statement by statement (or at least it makes it more complicated).
The main thing to keep in mind is to trade vertical space for horizontal space. In other words: write more lines but each line is short.
Perhaps you are still used to write trainwreck code like this:
if (GameObject.Find(“Player”).GetComponent<PlayerController>().Stats.Strength.Min > 0 && GameObject.Find(“Player”).GetComponent<PlayerController>().Stats.Strength.Max <= 15)
// do something
if (GameObject.Find(“Player”).GetComponent<PlayerController>().Stats.Charisma.Min > 0 && GameObject.Find(“Player”).GetComponent<PlayerController>().Stats.Charisma.Max <= 13)
// do something
Let it go! This is not code, it’s copypasta!
Change it to something more readable and debuggable like this:
var playerObj = GameObject.Find(“Player”);
var playerCtrl = playerObj.GetComponent<PlayerController>()
var stats = playerCtrl.Stats;
if (stats.Strength.Min > 0 && stats.Strength.Max <= 15)
// do something
if (stats.Charisma.Min > 0 && stats.Charisma.Max <= 13)
// do something
And why is that more readable? Because not just the debugger, you yourself also step over individual lines! We simply cannot efficiently process long lines the same way we can scan short, concise lines rather quickly.
One statement per line is a good rule to follow in general as it lets you focus on a particular statement rather than a long blob of text. A statement is either an assignment or a method call or both combined.
The refactored code is also more efficient. It keep the things it found or got once in a variable, rather than finding or getting it all over again repeatedly.
Improve Conditionals
This code still has the condition awkwardly AND-ed together and it’s not perfectly readable what the intent is:
if (stats.Strength.Min > 0 && stats.Strength.Max <= 15)
// do something
Again, variables help to provide meaning and context:
var isWithinStrengthThreshold = stats.Strength.Min > 0 && stats.Strength.Max <= 15;
if (isWithinStrengthThreshold)
// do something
This may seem like overkill but it has the great benefit that now the if statement is very, very readable. As in: “if (the thing) is within strength threshold (then) …”. You get the point. It’s also crucial to not repeat yourself - if you need that condition multiple times, you write it once and assign it to a variable!