Page 1 of 1

10 Common Programming Mistakes

#1 andrewsw  Icon User is offline

  • Speak up, I'm wearing a towel
  • member icon

Reputation: 5231
  • View blog
  • Posts: 20,235
  • Joined: 12-December 12

Post icon  Posted 11 November 2015 - 07:08 AM

*
POPULAR

I'm using C# to demonstrate common, beginner, programming mistakes but the same mistakes apply to most programming languages.

The examples are deliberately simplified, to concentrate on describing, and recognising, the mistakes. In fact, using Visual Studio, the first few mistakes are even more obvious because the editor will highlight them, and even suggest corrections.

  • Unmatched Brackets
  • Spelling Mistakes
  • Inconsistent Casing
  • Using = Instead of ==
  • Strings are Immutable
  • Not Instantiating Objects
  • Reading Past the End of an Array
  • Concatenating Rather Than Adding
  • Integer Division
  • Not Bracing Blocks
  • Bonus Mistake: Local Variables Hide Class-Level Variables

Unmatched Brackets

Attached Image

Every opening bracket (of any kind) must have a matching closing bracket. Visual Studio shows a red squiggly line at the last brace; pointing at this it displays "} expected". The closing brace is missing from line 15, not line 18. The editor parses the brackets but it is only at the last brace that it recognises there is an error, it doesn't know where you intended to put the missing brace.

Use a consistent indent style to make it easy for you to spot unmatched brackets. The coding standards for C# use an indent style more like this:

Attached Image

Different languages adopt different indent styles, and you may have company standards to follow. People debate which style to use or prefer; this is less important than following a standard consistently.

In Visual Studio, if you see a squiggly line, of any colour, point at it and a message will pop up. Sometimes a little button or icon will also then pop up. Click this and it will provide more information, sometimes suggesting a solution, and even offering to apply this solution for you. But don't just accept the proposed solution, make sure that it is the correct solution.

Spelling Mistakes

Attached Image

The variables are named firstNumber and secondNumber, not firstNo and secondNo.

The error message is "the name 'firstNo' does not exist in the current context". When you see this scroll back to where you defined the variable and check your spelling (and casing: see the next section). Instead though, it could mean that you are trying to refer to a variable that is defined in a different scope. That is, in a different method or code block (or namespace).

Inconsistent Casing

Attached Image

This creates the same error as a misspelling. It should be firstNumber not firstnumber.

Nearly all languages are case-sensitive. Even if your chosen language isn't case-sensitive, always assume that it is; this habit will stand you in good stead when you, eventually, work with other languages.

Consistently using camelCase for variable names (depending on your language) will eradicate this error, because firstnumber immediately just looks wrong.

Using = Instead of ==

Attached Image

= is the assignment operator, == is the equality comparison operator.

Visual Studio (VS) will not let us make this assignment, but it will allow it with a boolean variable:

Attached Image

Notice that VS issues a warning rather than an error. (In most cases, the assignment will be a mistake and == was intended.)

We should generally avoid nested assignments, but there are some common patterns that you will encounter such as this:
    while ((line = streamReader.ReadLine()) != null) {

    }


We can follow these patterns, just make sure that you understand them fully.

Strings are Immutable

Attached Image

Strings (in C# and most languages) are immutable, they cannot be changed in place. name.ToUpper(); will return the name converted to uppercase, but the returned value isn't stored anywhere, so 'name' hasn't changed at all. Notice that VS doesn't offer an error or warning for the discarded value.

You need to store the returned value:
    name = name.ToUpper();


This is how you change the value of a string. You apply some method that returns a changed value of the original string, and assign this new value to the (original) variable.

Not Instantiating Objects

Attached Image

The code
    Person pers;


declares a variable of type Person, it does not create, instantiate, a Person. It is simply a variable that can/will refer to an instance of Person.

The code
    Person pers = new Person();


declares a variable of type Person but, at the same time, instantiates a Person and makes pers refer to this new instance.

It is a common misunderstanding to assume that an array of a (reference) type will, somehow, create all the instances of the type.

Attached Image
    Person[] pers = new Person[4];


This creates an array of 4 Person references. That is, an array with the capacity to refer to 4 Persons. The 4 people do not yet exist, they need to be instantiated individually:
    pers[0] = new Person();
    pers[0].FirstName = "Bob";


Notice the different error message: "Object reference not set to an instance of an object". This error (which you will see often) confuses people. If you (now) understand what it is saying then you are making progress!

Reading Past the End of an Array

Attached Image

The array has Length 4, there are 4 elements. These elements are indexed from 0 to 3; that is, one less than the Length (the size) of the array, so attempting nos[4] causes the error. The solution is to change <= to just <
    for (int i = 0; i < nos.Length; i++)
        Console.WriteLine(nos[i].ToString());


If you declare an array to hold 10 integers using
    int[] numbers = new int[10];  // numbers is a 10-element array


the number 10 is the size of the array, the elements are indexed 0..9.

Using foreach instead of a for-loop to iterate all array elements avoids this (reading past) possibility. Arrays Tutorial :MSDN.

The Exception is System.IndexOutOfRangeException and the additional information "Index was outside the bounds of the array". I am encouraging you to look up, study, and understand errors as you encounter them. There are many possible Exceptions, but around 10 that you will encounter more than any others.

Concatenating Rather Than Adding

In most languages the plus sign + is used both for arithmetic addition and to concatenate, to join, text. 3 + 4 is clearly 7, and "hello " + "there" is clearly "hello there", but what about "hello " + 7? The 7 is typically coerced to a string to obtain "hello 7". (This is clearer written as "hello " + "7".)

Consider this slightly less obvious example:
    static void Main(string[] args) {
        int x = 4;
        string y = "12";

        Console.WriteLine(string.Format("{0}", x + y)); // 412

        Console.ReadKey();
    }


x is 4 and you may have expected "12" to be coerced into an integer, so that the result would be 16. This doesn't happen. Although 4 is an integer, a primitive, integers still have a ToString() method which is used when a number is used in the context of a string.

Basically, if you intend to add numbers, then ensure that ALL of the values are numbers. (If you are storing the result then this is not an issue, because we cannot store a string in a numeric variable.)

You could, if you like, be very explicit when concatenating text, with methods string.Concat() and string.Format(). Using Concat() is a bit excessive in my opinion, just be aware of the possibility of a mistake. string.Format() however, should be used in preference to concatenating with +. Format() is a very powerful method and provides much neater code than concatenating with +.

Another sensible approach is to perform all arithmetic as separate statements, before outputting a concatenated result/string.

Integer Division

This is a very common mistake (a misunderstanding) and everyone is caught out by it at some point. Consider this code:
    static void Main(string[] args) {
        int x = 4;

        Console.WriteLine(string.Format("4 / 10 is {0}", x / 10)); // 0

        Console.ReadKey();
    }


When we divide one integer by another the result is always an integer, the remainder is discarded. / Operator.

To correct this we give either 4 or 10 the type of float or double. This can be achieved by appending .0 to the value. So 4 / 10.0 or 4.0 / 10 (my preference), or (float)4/ 10. For a variable we could write x * 1.0 to obtain a decimal value.

(VB.NET is an exception, / doesn't result in integer division, \ is used if integer division is required.)

Not Bracing Blocks

Consider this code:
    int x = 4;
    bool doubleItTwice = true;

    if (doubleItTwice)
        x *= 2;
        x *= 2;

    Console.WriteLine("New value {0}", x); // 16


This behaves as expected, but only the first x *= 2; is optionally executed, depending on the value of doubleItTwice. The second version will ALWAYS be executed. Compare to this version, with doubleItTwice set to false:
    int x = 4;
    bool doubleItTwice = false;

    if (doubleItTwice)
        x *= 2;
        x *= 2;

    Console.WriteLine("New value {0}", x); // 8


You may have expected the result to be 4, with neither multiplication occurring, but the second multiplication will always take place.

Block statements (if, for, while, etc.) will conditionally execute only the line that follows it. If you wish several statements to be conditionally executed then you must surround the block of statements with braces {}. What is actually happening is made clearer if you reduce the indenting of the second multiplication:
    if (doubleItTwice)
        x *= 2;
    x *= 2;


It is a far better practice, and strongly recommended, to always follow a block statement with braces, even if the block only consists of a single statement.
    if (doubleItTwice) {
        x *= 2;
        x *= 2;
    }

    // or
    if (doubleItOnce) {
        x *= 2;
    }
    // the rest of the code




Bonus Mistake: Local Variables Hide Class-Level Variables

Consider this code:
    class Program {
        static void Main(string[] args) {

            Person pers = new Person();
            pers.SetAge(4);

            Console.WriteLine(string.Format("Person has age {0}", pers.GetAge()));
            // Person has age 0
            Console.ReadKey();
        }
    }

    class Person {
        private int Age = 0;

        public string FirstName { get; set; }
        public string LastName { get; set; }

        public void SetAge(int age) {
            int Age;        // new, local, variable
            Age = age;
        }
        public int GetAge() {
            return Age;
        }
    }


The variable Age declared in the method SetAge hides (takes precedence over) the class-level variable also named Age. The problem could be avoided by explicitly using this.Age = age; within the method. It is far more preferable to NOT use the same identifier Age.

A common approach is to name private, class-level variables (fields) beginning with an underscore. This is not part of the C# Coding Conventions but many people, myself included, do this.



You might want to continue with this tutorial:

Understanding the most frequently asked about errors

which covers some similar ground but also introduces debugging features, which you can pursue further with my debugging tutorial.

This post has been edited by andrewsw: 13 November 2015 - 05:00 AM


Is This A Good Question/Topic? 7
  • +

Replies To: 10 Common Programming Mistakes

#2 alishawalter  Icon User is offline

  • New D.I.C Head

Reputation: -1
  • View blog
  • Posts: 16
  • Joined: 09-November 15

Posted 13 November 2015 - 12:03 AM

very informative tutorials... These are obvious mistakes that everybody make. Thanks a lot for sharing it.
Was This Post Helpful? 0
  • +
  • -

#3 chering  Icon User is offline

  • New D.I.C Head

Reputation: 1
  • View blog
  • Posts: 21
  • Joined: 11-October 15

Posted 13 November 2015 - 03:57 AM

andrewsw thank you very much for this! :)/> For the effort and the time spent to help others ! Keep up the wonderful work !


The information was long but the way that you have wrote it I have read and understand it with ease ! You have given great examples with just the right amount of text and amazing explanations!

This post has been edited by chering: 13 November 2015 - 04:01 AM

Was This Post Helpful? 1
  • +
  • -

#4 andrewsw  Icon User is offline

  • Speak up, I'm wearing a towel
  • member icon

Reputation: 5231
  • View blog
  • Posts: 20,235
  • Joined: 12-December 12

Posted 13 November 2015 - 09:42 AM

Thank you very much both, and you are welcome!
Was This Post Helpful? 0
  • +
  • -

#5 mirrorshades  Icon User is offline

  • New D.I.C Head

Reputation: 0
  • View blog
  • Posts: 1
  • Joined: 16-November 15

Posted 16 November 2015 - 04:14 PM

I'm a pretty novice programmer, but it's amazing to me how basic a lot of these mistakes are, and yet they continue to occur. I usually do multiple read-throughs of any code I've written, but sometimes some of these mistakes get past me. Guess I gotta work on those goalkeeping skills. I'm learning C, and the most common mistake I make is omitting a semicolon to terminate a statement. It's a fairly small issue, but it can be quite annoying.
Was This Post Helpful? 0
  • +
  • -

#6 andrewsw  Icon User is offline

  • Speak up, I'm wearing a towel
  • member icon

Reputation: 5231
  • View blog
  • Posts: 20,235
  • Joined: 12-December 12

Posted 17 November 2015 - 05:56 AM

Yes, I could have included omitting semi-colons. I'm happy not to include it though because, firstly, there isn't much to say about it ;). But also, it's something that everyone does in the beginning and, hopefully, will quickly overcome.

As you progress it will become second nature to include the semi-colons (so much so that people moving to a language like Python cannot resist the temptation to type them!).
Was This Post Helpful? 1
  • +
  • -

#7 Saloo  Icon User is offline

  • New D.I.C Head

Reputation: 0
  • View blog
  • Posts: 20
  • Joined: 02-January 16

Posted 03 January 2016 - 12:09 AM

Very Informative . The most mistakes which I do are :
Unmatched Brackets
Inconsistent Casing
Using = Instead of == .


Thank you for sharing .
Was This Post Helpful? 0
  • +
  • -

Page 1 of 1