[Question] Completed Number Wizard Game. General Coding Practices

Hello, Not sure if this is the best place to ask this question, apologies if it’s not.

I’ve just recently finished the Number Wizard Section of this course and tried to make some of the changes suggested at the end of the video, I am quite new to programming in general, so the scripting was challenging,

The changes seem to be successful when playing the game through the console, however I ran into issues when it came to preventing the arrow or enter buttons from being pressed before a range is chosen at the beginning of the game. I tried to work around this by using a flag as suggested in another forum post, although admittedly there was a lot of trial and error to get it to work at my end, and it felt more like I got it to work by accident.

Just wanted to know if anybody can have a quick glance at my attached code and suggest if there are any better practices I should be following in this example or when writing code in general. As I am quite new to this, i’m not sure if the code I have written would be considered cluttered or if there are better methods to simplify what I have done.

Thanks, really enjoying the course so far!

NumberWizardCode

Hi @Hemal,

Well done on completing this section and for taking it a little further yourself.

Couple of items for you…

Naming Conventions - this is one of those topics that often stirs the emotions of a development community… :slight_smile:

	// Use this for initialization
	int max;
	int min;
	int guess;
	bool OptionRangeSelected; //flag for range selection
	bool ArrowKey; //flag for arrow and enter keys  

Here you start off introducing class level variables max, min and guess - note they are camelCase. After that you use two more variables for the bools but the case of these is different (Pascal Case). Minor changes like this can, at a glance, make it a little harder for another developer to understand easily whats going on.

Even if you are only working on your own, maintaining consistency throughout your code / project will invariably help you.

PascalCase / UpperCamelCase are normally used for Property names and Method names within a class, you will have most likely already seen Start() and Update() for example, both of these are methods.

camelCase / lowerCamelCase are normally used for variables.

It can (and often does) get more complicated when different conventions are used for the difference between public and private variables, you may also come across other people’s code which use m_myVaraible or _myVariable at a class level.

The one thing I would urge is consistency, if you have a strong desire to use a different naming convention, just be consistent with it, anyone else who looks at your code will get the idea :slight_smile:

With regards to your methods…

Update() - you want to try to keep methods in general quite small, responsible for as few things as possible, this will definitely come with time and practice. The Update() method, which you could say is fairly core to your game, could easily have more code added to it to do all sorts of things, as that grows it will become really difficult to read, similar/same name variables may get used and all manner of problems start to occur.

What you could do is break your difficulty setting code out into a new method, perhaps called “SetDifficulty” for example, and then call that from the Update() method.

With regards to layout of the code, this is again down to the developer, there are those who may prefer to see this;

		if (min == max){ Cheat(); }
		else { NextGuess(); }

over this;

		if (min == max){
			Cheat();
		}
		else{
			NextGuess();
		} 

Sure, it’s a few lines shorter, but I don’t personally find it any easier to read. Readability and maintainability for your code should be at the fore front of your mind when developing, so again, be consistent. If I open up one of your projects and see you with the second method above, this is how I may expect to see your logic written every time, so keep it consistent and easy for me (again you!).

Comments…

Another topic which will often cause debate… I have heard “only add a comment if it isn’t obvious what it’s doing” been said so many times… that’s fine, if everyone who is looking at the code is of the same familiarity and experience… if I pasted a chunk of code from one of the projects at the end of the course into this topic now, and stripped out all of the comments because I knew what it was doing… that doesn’t necessarily mean you would for example.

Coming from a team background I always wrote my code in such a way that I hoped that anyone looking at it would be able to understand it reasonably easily.

I’m not sure about MonoDevelop, but Visual Studio will help you with commenting your code, if you enter three consecutive comment characters in a row above a property or a method, for example;

\\\
void Start() {

as soon as I hit space after that, Visual Studio will create this above the method

\\\ <Summary>
\\\ 
\\\ </Summary>
void Start() {

} 

If you have methods that taken parameters then it will also cater for these and fill in some of the information for you also.

You can then provide a brief explanation as to what the method is responsible for, or what value it returns etc.

There are tools/plugins that you can use which will use this format of comments to construct full documentation for your project, which can be handy.

Personally, I do not worry about / fear the use of white space or comments in my code, the compiler will strip both of these out completing when building anyway.

It looks like you are probably using MonoDevelop as I can see spaces before the brackets for two of the methods, Start () and Update (), Visual Studio doesn’t tend to do this, again, it doesn’t make any significant difference, but having two styles mixed together is, well, annoying! :wink: again, consistency. :slight_smile:

There’s a little bit of feedback anyway, I hope it is of use :slight_smile:

2 Likes

Thank you for your response @Rob . This was the kind of thing I was looking for, and it definitely helps. Being new to programming in general I want to make sure I start with good practices from the beginning rather than picking up bad ones.

Just a question regarding methods you spoke of. Is it ever a bad thing to have too many methods in your code? and as the number of methods increase, Is there a certain way I should be organizing these. At the moment I have them all listed below update in no particular order, although I do realize that this a relatively simple program, should I be organizing them differently?

Thanks Again.

Hi @Hemal,

I’m glad my post was of use to you.

Is it ever a bad thing to have too many methods in your code? and as the number of methods increase, Is there a certain way I should be organizing these.

This is still very early on in the course and as you mentioned you are new to programming I don’t want to swamp you with information, however, one of the things that you should consider is what behaviour (functionality) belongs to what in your design, a separation of concerns.

So, rather than having one class that does everything and knows all of the inner workings of everything, you can break this down into specific classes that are responsible for specific things. The relevant fields, properties and methods would go into the relevant classes. Each classes only exposing publicly what it really needs to in order to work.

You will move into more of this as the course progresses.

At the moment I have them all listed below update in no particular order, although I do realize that this a relatively simple program, should I be organizing them differently?

With something so small as Number Wizard it isn’t really a problem, you can scroll up and down and find what you are looking for very easily, but developing around a consistent structure will help you in the long term.

For the time being I would probably suggest you look at laying out the structure along these lines;

  • class level variables (fields)
  • properties
  • methods (behaviour)

Then for a little organisation;

Separate private and public class level variables, e.g. keeping each type together. The same for properties, although you will probably find yourself mainly using public properties anyway.

With regards to methods, when a class is small it’s fairly straight forward, you may for example have them in the order of execution, perhaps;

  • Start()
  • Update()
  • YourMethod()

When you start including more logic which may change the flow of execution of the methods that gets a little harder to persist. You could opt for alphabetical ordering, the intellisense in modern IDEs will do this by default, so it’s not unusual, also, you can often simply select a method name being called, right-click and choose “Go to definition” (or equivalent) and the IDE will take you to the method anyway.

Whether it’s worth grouping the methods for both private and public would really depend on the scenario, but again, something worth considering perhaps from the outset, it’s a choice you can make.

One thing that will help you enormously is consistency, when you start organising the structure of your classes, use that structure across all of your classes, then when ever you are flitting from one to another trying to either follow the code, or a debug a problem, it will be a lot easy.


Below is an example class to show the structure I’ve talked about in the above;

using UnityEngine;

public class Example : MonoBehaviour {

    // private fields

    // public fields

    // properties


    // methods

    /// <summary>
    /// Initialise
    /// </summary>
    private void Start() {
        // do something
    }

    /// <summary>
    /// Update is called once every frame
    /// </summary>
    private void Update() {
        // do something
    }

}
2 Likes

Thank you again @Rob, more useful information I will try to keep in mind as a progress through the course.

Thanks for taking the time to answer my questions. :slight_smile:

2 Likes

You are more than welcome @Hemal :slight_smile:

Feel free to post about anything else and of course, share what you create! There’s a great community here with lots of friendly and helpful people :slight_smile:

1 Like