Blog for Junior Developers C#/.NET

Saturday, October 19, 2024

In today's article, I'll show you 16 popular mistakes that beginner programmers often make. Of course, there's nothing wrong with making mistakes. Every programmer took their first steps at some point, and many of us made the same mistakes back then. It's important to learn from them for the future. If you're learning programming or you're a beginner programmer, this article will definitely interest you.

16-common-beginner-programmer-mistakes-you-need-to-avoid.png

These errors apply to all programming languages, but the examples I will be showing will be written in C#. The order in which the errors are presented is not important, it is worth focusing on all the errors presented.


Mistake 1. Using the wrong types


This error is quite important, and what is more, very common. Remember that if you are creating any models, their properties or fields should be of the appropriate types. Not every property should be of the string type (which I often encounter). This type should store only text. If you are using numbers, then depending on whether you require an integer, a float, or an amount, you should also use the appropriate type.


public int Id { get; set; }
public string FirstName { get; set; }
public string LastName { get; set; }
public DateTime DateOfBirth { get; set; }
public decimal Salary { get; set; }
public float Height { get; set; }
public float Width { get; set; }
public bool IsDeleted { get; set; }
public string Position { get; set; }


For integers, it can be, depending on the size, e.g. byte, short, int or long. For floating-point numbers, float or double. For decimal amounts. For DateTime dates, and bool for logical values. Similarly, if you use components on the user interface, you will also find the right one for each of them, depending on the framework you are programming in. This means, for example, in WPF, you can use TextBox for strings, NumerUpDown for numbers, CheckBox for bools, and DateTimePicker for dates.


Mistake 2. Poor formatting


This is always a problem at the beginning. Of course, there is nothing strange about it, formatting can be unintuitive at the beginning, but over time, if you practice more, review other programmers' code, it will definitely be easier for you to use good formatting. Take a look at the code I prepared.

using System;

namespace App
{
    class Program
    {




        static void Main(string[] args)
        {
        var employee     =   new Employee( "Jan Kowalski"  );


                employee.Position   =    "Junior C# Developer" ;


    employee.Work();

    Console.ReadLine();
        }
    }
}


Fortunately, in C#, you can instantly fix the formatting in lines with the shortcut CTRL+K+D. Then the code will look like this:

using System;

namespace App
{
    class Program
    {




        static void Main(string[] args)
        {
            var employee = new Employee("Jan Kowalski");


            employee.Position = "Młodszy Programista C#";


            employee.Work();

            Console.ReadLine();
        }
    }
}


Also remember not to use too much space between lines, because it also reduces the readability of the code. More than one line of space is never needed. Our code could look like this:

using System;

namespace App
{
    class Program
    {
        static void Main(string[] args)
        {
            var employee = new Employee("Jan Kowalski");
            employee.Position = "Młodszy Programista C#";
            employee.Work();

            Console.ReadLine();
        }
    }
}


Notice that this code is now much more readable.


Mistake 3. Bad naming of variables / methods / classes


Here too, it is important to always stick to the same rules, of course, best in accordance with accepted conventions. See this example:

using System;

namespace App
{
    public class Employee
    {
        private string _firstName;
        private string lastName;
        private DateTime date_of_birth;

        public Employee(string name)
        {
            _firstName = name;
        }

        public int Id { get; set; }
        public string firstName { get; set; }
        public string Last_Name { get; set; }
        public DateTime DateOfBirth { get; set; }
        public decimal salary { get; set; }
        public float Height { get; set; }
        public float width { get; set; }
        public bool ISDELETED { get; set; }
        public string Position { get; set; }

        public void Work()
        {
            //
        }

        public void setname()
        {
            //
        }
    }
}


Notice that here we have 3 fields and in each of them the programmer uses different naming. Sometimes he uses camelCase, sometimes camelCase with underscore, sometimes he separates words with underscores. First of all, we should always stick to the same established rules in one project. Usually, underscore plus camelCase is used for fields.

private string _firstName;
private string _lastName;
private DateTime _dateOfBirth;


When it comes to properties, we use PascalCase naming here.

public int Id { get; set; }
public string FirstName { get; set; }
public string LastName { get; set; }
public DateTime DateOfBirth { get; set; }
public decimal Salary { get; set; }
public float Height { get; set; }
public float Width { get; set; }
public bool IsDeleted { get; set; }
public string Position { get; set; }


Same for methods, in C# we use PascalCase.

public void Work()
{
    //
}

public void SetName()
{
    //
}


Moreover, as for the names themselves, they should be self-descriptive, of course we can't exaggerate with the length of the names of variables, methods or classes, but remember that the names should be relatively short, but specific and immediately say what information they store. As you can see in the example below, the name of the variable "a" tells us nothing:

using System;

namespace App
{
    class Program
    {
        static void Main(string[] args)
        {
            var a = new Employee("Jan Kowalski");
            a.Position = "Junior C# Developer";
            a.Work();

            Console.ReadLine();
        }
    }
}


Here, depending on the situation, we should name it appropriately. Let's assume that in our case it will be simply employee. Of course, it does not have to be the same name as the class name. In our case, it is, because we do not know the whole context here.

using System;

namespace App
{
    class Program
    {
        static void Main(string[] args)
        {
            var employee = new Employee("Jan Kowalski");
            employee.Position = "Junior C# Developer";
            employee.Work();

            Console.ReadLine();
        }
    }
}


In any case, names like "a" or "a" with a number, e.g. "a1", are the worst. In such situations, it is not known what they mean and they reduce the readability of the code. Remember to give appropriate names, thanks to which this code will also be more readable not only for you, but also for other programmers.


Mistake 4. Excessive comments


While in projects you are learning on, you can safely add comments. Thanks to them, it will be easier for you to understand this code if you want to return to it in the future. However, in, say, production code, you should not use too many comments.

using System;

namespace App
{
    class Program
    {
        static void Main(string[] args)
        {
            //creating a new employee
            var employee = new Employee("Jan Kowalski");
            //setting his position
            employee.Position = "Junior C# Programmer";
            //call the work method
            employee.Work();

            Console.ReadLine();
        }
    }
}


Look at our code. Because of such comments, the code, instead of becoming more readable, actually becomes less transparent. I am an advocate of the smallest possible number of comments in such code. I assume that the code should be self-descriptive. If you use the appropriate naming of classes, methods, or variables, it will actually be so. You will not need to add additional comments. If I put comments in the code, it is only in situations when some code may not be understood for various reasons by other programmers, or by me in the future. In other words, these are some non-obvious solutions that had to be implemented in a given case. So the code above can definitely look like this:

using System;

namespace App
{
    class Program
    {
        static void Main(string[] args)
        {
            var employee = new Employee("Jan Kowalski");
            employee.Position = "Junior C# Programmer";
            employee.Work();

            Console.ReadLine();
        }
    }
}


Despite the lack of comments, it is now more readable.


Mistake 5. Large methods / classes


Beginner programmers like to create fewer classes, but more extensive ones. The same goes for methods. Unfortunately, this is quite a large mistake, which makes your application unreadable. If you need to find a fragment of code later, it takes a lot of time from you. You have to remember that programmers read code more often than they write. Therefore, you need to take care of the comfort of reading this code. If you create a so-called several thousand-line class, i.e. a class that has several thousand lines, then finding a given fragment of code later is very time-consuming. Similarly with methods. They should be at most a few, a dozen or so lines, but no more. Instead of creating huge classes and methods, create more smaller, appropriately named classes and methods.


Mistake 6. Code duplication


That is, creating the same code in several places in our application. Remember that if you have the same code in several places, then if you need to make any modifications or improve the code, you will have to make these changes in all places. It is much better to extract the common code, for example, into a separate class and use it in several places. Depending on the situation, you can also use inheritance.


Mistake 7. Not writing reusable code


Remember that programming often consists of similar functionalities. If you need to write a class to encrypt data, you can create it in a separate dll and use it in different projects. Thanks to this, you can save a lot of time in the future.


Mistake 8. Spaghetti code


Spaghetti code, or code that is difficult to understand, looks like spaghetti. There are references to different classes in different places. For example, database operations are sometimes in the model, sometimes in the repository, sometimes in the controller, or even in the view. There is no division into layers and it is difficult to find anything in such code. Changing the code in one place causes further errors in others. To avoid such code, you need to use the appropriate architecture in your application and, most importantly, stick to good patterns.


Mistake 9. Bad exception handling


In error-prone places, you absolutely must handle them properly. The best way to do this is to use a try catch construct.

public interface ILogger
{
    public void Error(string message, Exception exception);
}

public ILogger Logger { get; set; }

public void Work()
{
    try
    {
        //error-prone logic
    }
    catch (Exception ex)
    {
        Logger.Error("additional-information-about-error", ex);
        throw;
    }
}


Take a look at our example. As you can see, we have our call in try catch, thanks to which our application will continue to work correctly despite a possible unexpected exception. Importantly, you cannot leave an empty catch and thus suppress errors, but it is worth saving information about a possible error, e.g. to a file. This will make it easier for you to diagnose what really went wrong later. Additionally, you can also implement catching all unhandled exceptions in the entire application and handle them appropriately. In each framework, such an implementation looks a bit different, but usually it only requires writing a few lines of code.


Mistake 10. Trying to implement everything from scratch


I made this mistake myself at the beginning, when I started learning programming. When you are already developing business applications, it is not worth implementing everything from scratch, if there are already other free solutions, libraries that you can use. If you need to save data to a file, it is not worth writing your own library that will do it. It is better to use existing solutions such as nlog, serilog, or log4net. Any of these solutions will be better than writing your own library from scratch. Such writing from scratch can only be useful in one case, when you are writing a project to develop your programming skills. However, in applications that you are already writing for your clients, do not waste your time on it. There is no point in reinventing the wheel. Since the libraries are tested and made available, we can safely use them.


Mistake 11. Lack of unit tests


I wondered whether to raise this point here as well, because not writing unit tests is not only a mistake of novice programmers, but also sometimes of programmers with more experience. It is worth knowing from the very beginning what they are and why we write such tests. Thanks to them, we write better quality code and it has fewer potential errors. And this is always very important for our clients. In addition, thanks to them, it is easier to refactor the code. The code must also be of better quality, we have to focus on good patterns, it is easier to maintain the code, and we also have immediate documentation of the code that we create.


Mistake 12. No validation of user input


You can never trust a user and should protect yourself in various ways where you collect data from them. Always verify that what the user has provided is correct first, and only then perform operations.


Mistake 13. Not focusing on the end user


When writing applications, it is worth putting yourself in the shoes of the end user who will use your application. Try to make it as easy as possible for them to use the application. Depending on the application you are writing, users can use it even several hours a day, and it is worth it for it to be time well spent. It is worth finding out how users use the application, listening to their opinions and constantly improving it. Therefore, also focus on the user interface and the so-called UX, or User Experience.


Mistake 14. Assuming that if something works, it is good


If you copy some code and want to use it in your application, always try to analyze it carefully line by line. It often happens that solutions proposed by other people, despite the fact that they are plus-rated, may work, but it also happens that they contain bugs. So you can definitely be guided by the solutions of others, but always analyze the code anyway. Yes, to protect yourself from potential errors in your application. The fact that some code works does not always mean that it is good, does not contain any bugs and is the most optimal.


Mistake 15. Not knowing the basics


Also try to learn the basics very well. It is worth knowing what static and abstract classes are, what reference and value types are, what polymorphism, inheritance, abstraction, encapsulation, composition, constructors, delegates, events, constants and many other basic issues are. These basics will accompany you throughout your programming career, so it is worth knowing them well to avoid making any basic mistakes.


Mistake 16. Not knowing the principles of clean code


Also try to focus on the principles of clean code, thanks to which your code will be of good quality. It will be easier for you to develop applications in the future. It is worth knowing what SOLID is and following its basic assumptions. Of course, this is not knowledge that you have to learn at the very beginning, but after a few months of learning, it is worth starting to think about it. It's good to learn popular design patterns and always stick to good principles.


SUMMARY


This is what I think is the list of 16 most popular mistakes made by beginner programmers. Among other things, I try to draw the attention of participants in my training Become a .NET Programmer to all of these mistakes, in which I show participants the entire programming path from the basics to working as a C#/.NET programmer. If you are interested in learning programming under my supervision, I also invite you to join. Link to sign up: BecomeSoftwareDeveloper.com.

If you liked this article, be sure to join my community. Sign up for the free newsletter, where every week I share valuable materials, especially regarding C# and the .NET platform (free subscription - newsletter).

Author of the article:
Kazimierz Szpin

KAZIMIERZ SZPIN
Software Developer C#/.NET, Freelancer. Specializes in ASP.NET Core, ASP.NET MVC, ASP.NET Web API, Blazor, WPF and Windows Forms.
Author of the blog CodeWithKazik.com

Previous article - How to Quickly Change to a Programmer from Another Profession?
Dodaj komentarz

Search engine

© Copyright 2024 CodeWithKazik.com. All rights reserved. Privacy policy.
Design by Code With Kazik