Comments

5 Tips for Junior C# Developers to Write Cleaner C# Code

Many students of my C# Basics course submit their code in the discussion area, and when I get a chance, I review their code and give them hints to improve their code. I’ve noticed quite a few common patterns in the code submitted by junior C# developers. In this post, I’m going to explore these areas and share a few tips to write cleaner and more maintainable code.

1. Validate the input “first”!

Look at this code snippet:

public void Draw(Shape shape)
{
   if (shape != null)
   {
      Console.WriteLine("Drawing " + shape.ToString()); 
      Console.WriteLine("---");     
   }
   else 
   {
      throw new ArgumentNullException("shape");
   }

We have to read all this code to find the last line that throws an exception if the argument is null. By convention, we often validate the input first. This tells the reader of the code how a given method should be used.

So, let’s reverse the order of if and else here:

public void Draw(Shape shape)
{
   if (shape == null)
   {
      throw new ArgumentNullException("shape");
   }
   else    
   {
      Console.WriteLine("Drawing " + shape.ToString()); 
      Console.WriteLine("---");     
   }

Now, you can immediately tell what is a valid argument for this method. You don’t have to scroll down to the end of the body of the method to figure that out.

2. You don’t always need an “else”!

Continuing from the last example, if shape is null, we throw an exception and the rest of the method will not be executed. So, there is really no need to add that “else” block, which increases the indentation of the code. Here is a cleaner way to write this code:

public void Draw(Shape shape)
{
   if (shape == null)
   {
      throw new ArgumentNullException("shape");
   }
      
   Console.WriteLine("Drawing " + shape.ToString());
   Console.WriteLine("---");
}

Note that the rest of the code after the “if” statement is not indented.

3. Curly braces?

This one is subjective. Some developers love their curly braces, some don’t. I’ve gone through different phases. There is really no right or wrong here. Do your own judgment when looking at the code. Let’s remove the curly braces in the precious code and see what it looks like:

public void Draw(Shape shape)
{
   if (shape == null)
      throw new ArgumentNullException("shape");
 
   Console.WriteLine("Drawing " + shape.ToString());
   Console.WriteLine("---");
}

I think this code is cleaner. What do you think?

4. Pay attention to the name of your identifiers

Name of your identifiers is as important as the name of your children. I’m dead serious. No one wants to read someone else’s code with the following identifiers:

  • od: What is od? Oh Damn? Obsessive Disorder? Overdue Days?
  • Button1_Click(): What is Button1? How is it different from Button2?
  • thisAs: What’s that even supposed to mean?!

Use a name that clearly communicates the intent.

5. Avoid unnecessary variables

Back in 80s, programming books used to teach use to declare a variable for nearly everything! Look at this piece of code that reads two numbers from the console and prints the maximum:

var firstInput = Console.ReadLine();
var firstNumber = Convert.ToInt32(firstInput);
var secondInput = Console.Readline();
var secondNumber = Convert.ToInt32(secondInput);
var max = (firstNumber > secondNumber) ? firstNumber : secondNumber;
Console.WriteLine(max);

My eyes are popping out as I’m declaring all these variables! What is the focus of this code? Two numbers and their maximum. So, firstInput and secondInput, which are strings read from the input, are not the focus of the code. All we care about is a number read from the console. The temporary string we receive from the console is not the focus here. So, these two variables are not adding any value to this code in terms of readability. They’re just creating noise in the code.

We can read an input from the console and convert it to a number in one line:

var firstNumber = Convert.ToInt32(Console.ReadLine());
var secondNumber = Convert.ToInt32(Console.Readline());
var max = (firstNumber > secondNumber) ? firstNumber : secondNumber;
Console.WriteLine(max);

So, avoid declaring unnecessary variables. Use variables to increase the readability of the code.

If you enjoyed this post, please drop a comment and also share it with your peers. If you’d like to learn more tips for writing cleaner code, check out my course: “Clean Code: The Art of Writing Beautiful C# Code”.

Hi, my name is Mosh Hamedani and I am the author of several best-selling courses on Udemy and Pluralsight with more than 130,000 students in 196 countries. You can see the list of all my web and mobile development courses on this website.
Tags: , ,
Comments

Why I don’t like IEntity interfaces

One comment that keeps popping up in regards to my YouTube video about repositories (Repository Pattern, Done Right) is why I don’t like IEntity interfaces. So, let’s see.

The case for IEntity is to apply a constraint in the repository interfaces.

public interface IRepository<T> where T : IEntity 

I need to write another post about why you should avoid generic repositories. But for now, let’s just ignore it and focus on IEntity.

So, what’s the value of this constraint here? Does this force a developer from accidentally creating a repository for an integer?

public class IntRepository : IRepository<int>

Probably not! Those familiar with domain-driven design (DDD) argue that repositories are should be created for aggregate roots. So, this will stop a developer from creating a repository for an entity that is not an aggregate root, or a value object. So, perhaps it’s more accurate to call this interface IAggregateRoot (which is even worse than IEntity, as you’ll find out shortly).

With either IEntity or IAggregateRoot, a junior developer can bypass this “constraint” in just a second:

public class Money : IEntity
{
}

So, these marker interfaces don’t really stop anyone from creating a repository for the wrong type!

With these interfaces, every time you want to create a class, you need to write some additional code (noise) to mark it as an entity or aggregate. What is the value of this? I’ve never seen it! Hopefully, you can drop a comment and enlighten me.

What is an interface really?

An interface is a contract. When you declare an interface and implement it, all those implementations follow that contract. This gives you two benefits: extensibility and testability.

Think of the classic polymorphism example you read in your first object-oriented book.

IEnumerable<IShape> shapes = GetShapes();
foreach (var shape in shapes)
    shape.Draw(); 

Here, the type of the actual objects in our enumerable doesn’t really matter. We can “extend” this design, and define new shapes that implement this contract (IShape). At a minimum, they all will have a Draw method.

Another benefit of these contracts is that they help us mock dependencies of objects during unit testing. For example, we can unit test a controller or a service by providing a mock or fake repository. This way, we don’t need a database up and running to test the controller / service.

The case for IEntity

Look at this IEntity declaration. This is what I call a hollow interface.

public interface IEntity // or IAggregateRoot
{
}

What is the point of this interface? It’s an empty contract. What’s that supposed to mean “conceptually”? A contract that doesn’t enforce anything?! Really? Again, back to the first example, if you think by using these interfaces you prevent an inexperienced developer creating the wrong repository, you’re just fooling yourself.

Wait, I have a better solution!

Ok, Mosh, how about this interface?

public interface IEntity // or IAggregateRoot
{
    int Id { get; set; }
}

Not a hollow interface anymore! At least it enforces that every entity or aggregate root should have an Id, and that Id should be integer.

Wait… what if one of our entities needs a Guid as an Id?

Ok, what about IEntity<T>?

Here is another form of IEntity:

public interface IEntity<T> // or IAggregateRoot<T>
{
    T Id { get; set; }
}

This interface is even worse. Why? Look at how we use it:

public class Student : IEntity<int>

Read the code in plain English: class Student which is an entity of integer. What?! Entity of integer? (*my head spinning*).

Nonetheless, what value do you get from an interface like that? That every entity or aggregate root follows a contract? Would you be working with those IEntity or IAggregateRoot instances without caring what object is actually under the interface at runtime (like the polymorphism example I showed earlier)? Most likely not! You work with concrete types, like Student, Course, etc.

So, one more time, what’s the point of creating these contracts? To the best of my knowledge, nothing but extra noise in your code.

Unfortunately, interfaces are one of the least understood constructs of object-oriented programming languages. If you want to learn more about interfaces, check out my C# course: Classes, Interfaces and Object-0riented programming.

Hi, my name is Mosh Hamedani and I am the author of several best-selling courses on Udemy and Pluralsight with more than 130,000 students in 196 countries. You can see the list of all my web and mobile development courses on this website.
Tags: , , ,
Comments

Repositories or Command / Query Objects?

This is a follow up post to my YouTube video Repository Pattern, Done Right. If you haven’t seen this video, it’s best to watch it first, before continuing reading.

There have been many interesting questions in the discussion area and I’ve replied to most (if not all) of them. One that has come up a few times is:

Should we favour command/query objects over repositories?

A few have referred me to Jimmy Bogard’s post. So, in this post, I’ll be comparing these two approaches and pros / cons of each.

Before I get started, I need to emphasise: neither the repository pattern, nor command / query objects, are silver-bullets. Just because these architectural patterns exist, doesn’t mean you should use them in every single application. If your queries are simple enough (one or two lines), don’t worry about creating an abstraction over them. There is nothing wrong with writing them in your controllers (assuming a web application).

If you do, however, have fat queries that have bloated your controllers, you might want to consider one of these patterns to achieve “better separation of concerns”.

Repository vs Command / Query object

In a repository, we often have many methods, all related to a specific entity:

GetUpcomingGigs()
GetGigsIAmAttending()
GetMyGigs()
GetPopularGigs()

When you promote one of these methods to a class, you’ll end up with what we call a query object.


public class GetPopularGigsQuery
{
     private GigsContext _context;

     public GetPopularGigsQuery(GigsContext context) 
     {
          _context = context;
     }

     public IEnumerable<Gig> Execute() 
     {
          return _context.Gigs
                      .Where(...)
                      .Include(...)
                      .Include(...)
                      .Include(...)
                      .OrderByDescending(...)
                      .Take(10)
                      .ToList();
     }
}

So, what you see in the Execute() method here, used to be one of the methods of a class like GigsRepository. Now, we’ve promoted that to a class. Have we gained anything here? Absolutely not!

With this approach, if you have a repository with 5 methods, you’ll end up with 5 new classes in your application. Now, take into account how many repository classes you have and eventually how many command / query classes you’ll end up with. You’ll end up with an explosion of classes that don’t provide any additional value than a simple method.

When Command / Query objects provide value

When you want to execute some operation before and / or after the execution of the command / query. Sometimes, in large enterprise applications, you may want to check that the current user has permission to execute a given query (or command), and additionally you may want to log that somewhere.

Without using command / query classes, your repository methods would end up with a lot of duplicate logic:

public IEnumerable<Gig> GetPopularGigs()
{
     // authorisation logic 

     // logging logic 
     
     return _context.Gigs.......
}

public IEnumerable<Gig> GetUpcomingGigs()
{
     // authorisation logic 

     // logging logic 
     
     return _context.Gigs.......
}

At this point, by promoting a method to a class, you’ll have at least a couple of options in front of you to implement the same behaviour in a more elegant way. You can use the template or strategy pattern.

With the template pattern, you would define a base class for your commands or queries like this:

public abstract class Query 
{
      public void Execute()
      {
           // authorisation logic 

           // logging logic
 
           DoExecute();
      }

      abstract void DoExecute();
}

So, you write the authorization and logging logic only once, in the base Query or Command class. Then, when implementing an actual command or query, you override the DoExecute method:

public abstract class GetPopularGigsQuery : Query 
{
      public override DoExecute()
      {
           return _context.Gigs....
      }
}

With the strategy pattern, instead of using inheritance, you’d use composition to achieve the same thing. If you need more understanding of inheritance vs composition, check out my C# course: Classes, Interfaces and Object-oriented programming.

What about ASP.NET MVC action filters?

Mosh, aren’t action filters exactly for that? To execute some custom logic (e.g. like authorisation or logging) before each action? True! Then, why bother using the command / query pattern?

Good question! First, you don’t have to use the pattern, if you prefer to use ASP.NET MVC action filters. But what if, in the future, you decide to use a different web presentation framework that doesn’t have the concept of MVC filters? Tools and frameworks come and go. What is popular now, is not going to be popular in a few years time. There was a time we thought ASP.NET WebForms was so cool. Now, it’s almost a dead technology!

If you want to protect your application architecture from change of external tools and framework, you need to decouple it from them by creating your own abstractions. Command / query pattern is one of the ways to create such abstraction. If you switch over to a different presentation framework, you can take all your existing code and re-use it without modifying a single line, and more importantly, without breaking things along the way!

What if…

What if you’re not too concerned about decoupling your application architecture from external tools / libraries? What if you think this is overkill? That’s a perfectly valid argument. Then, don’t use these patterns. As I always say to my students: “Keep it simple”. Use MVC filters to achieve the same result, and if they won’t help you in the future, then you’d spend time solving that new problem, not now.

What if you don’t have such requirements like authorisation and logging before each query? Then, command / query objects don’t give you any additional value. You’ll just waste your time and energy writing more and more code.

What if you don’t have complex queries in the first place? Don’t bother with the repository pattern either!

Every pattern is designed to solve a specific problem. Don’t solve a problem that does not exist!

Till my next post, all the best my friends!

 

 

Hi, my name is Mosh Hamedani and I am the author of several best-selling courses on Udemy and Pluralsight with more than 130,000 students in 196 countries. You can see the list of all my web and mobile development courses on this website.
Tags: , , , ,
Comments

Critical stuff that every junior C# developer must know

A common question I often get from my students at Udemy is:

Mosh, I just got my first junior level C# job. What advice do you have for me? What are some critical stuff I need to learn?

So, whether you’re looking for your first junior C# job, or you just got one, this post will give you an overview of the kind of skills that you need to be familiar with as a junior C# developer. I’ve tried to put it in a “learning path” that would give you direction, whether you want to build web or desktop applications.

Before getting into details, I need to clarify something: as a junior, you’re not expected to know everything! No one does, even many senior developers! The world of programming is so big and it’s constantly getting bigger. So, every developer has strengths in some specific areas based on the projects they have worked on.

For each skill, I’ve added one or more links to good resources I have found. If you know better resources, please let me know and I’ll update the post.

Core Skills

Whether you want to focus on building desktop or windows apps, here are a few key things that you must know.

path2.001

Data Structures and Algorithms

If you don’t have a computer science degree, I strongly recommend you to spend only one month and study data structures and algorithms. These are the alphabets of programming. Sure you can skip this and jump straight into web development stuff, but trust me, there is a difference between a programmer who has been exposed to data structures and algorithms and one who hasn’t. This stuff help you think like a programmer.

You may be surprised that most big companies like Microsoft, Apple and Amazon dedicate a significant part (if not all) of their technical interviews to data structures and algorithms, not ASP.NET 5 or WPF! Because they just want to see if you can think like a programmer or not.

This is a good book to get you started:
Data Structures and Algorithms Made Easy

If you get stuck on some parts, don’t get discouraged. Move on. Just make sure you understand the basics of lists, stacks, queues, trees and hashtables. Try to implement each of these data structures using plain C# (arrays, loops, conditionals) without using LINQ or .NET collections. Implement a couple of search and sort algorithms.

Databases

SQL Server is the most commonly used Relational Database Management System (DBMS) amongst .NET developers. Make sure you’re familiar with the basics of relational databases and how to create tables, views and stored procedures in SQL Server.

T-SQL is the query language we use to query or modify data in a SQL Server database. Make sure you know your SELECT, INSERT, UPDATE, DELETE, JOIN and GROUP BY.

Zero to Hero with Microsoft SQL Server 2014
T-SQL Step by Step

O/RMs

When using a relational database, we often use an Object/Relational Mapper (O/RM) to save or load objects in a database. There are many O/RMs out there including Entity Framework, nHibernate, Dapper, PetaPoco, etc, but Entity Framework is the most commonly used amongst many teams.

Getting Started with Entity Framework 7

I also have a comprehensive 6-hour Entity Framework course on Udemy.

For Web Development

Building web applications is fundamentally different from building desktop applications. A web application at a minimum includes two parts: one that runs in the user’s browser (front-end), and one that runs on the server (back-end). As you view web pages in your browser, click on buttons and links, a request is sent from your browser to the server. The request is processed on the server, some data fetched from or written to the database and results are returned to your browser.

Web developers are often classified in three groups:

  • Front-end developers
  • Back-end developers
  • Full-stack developers: those who do both the front-end and the back-end

You should choose one of these paths depending on your interests. Full-stack developers often have more job opportunities because they can do both the front-end and the back-end.

As a front-end developer, you need to be familiar with basics of HTML, CSS and Javascript at a minimum.

HTML is the markup language we use to build structure for a web page. Unlike programming languages like C#, it doesn’t have logic.With the structure in place, we use CSS to make the page beautiful. CSS is all about styles (colors, padding, borders, fonts, etc). And finally we use Javascript to add behaviour to a webpage: what happens when you click a button or drag-and-drop an element.

HTML & CSS for Beginners
Learn to Code HTML & CSS
HTML5 & CSS Fundamentals on Channel9
Javascript on Code Academy

path3.001

ASP.NET MVC is the dominant framework (amongst C# developers) for building web applications on the server. As an ASP.NET MVC developer, you should still have some basic familiarity with HTML, CSS and Javascript. So, I’d suggest you to start with front-end development and then move to back-end development, which would make you a full-stack developer.

Here is a comprehensive tutorial I’ve published on Udemy blog to get you started. I’ll show you how to build a simple application with CRUD operations using ASP.NET MVC5 and Entity Framework6:

A Step-by-Step ASP.NET MVC Tutorial for Beginners

For Desktop Development

If you want to build desktop applications for Windows, you need a different set of skills than HTML, CSS and Javascript. Even though some are working on using HTML, CSS and Javascript to build desktop applications, it’s still new and 99% of the jobs out there require you to know XAML, WPF or Windows Forms.

 

path3.002

WPF: A Beginner’s Guide

 

If you’re a junior C# developer and have a question, drop a comment below and I’ll do my best to guide you in the right direction. If you’re an experienced C# developer and think I missed something to include in this post, or you know better resources for any of these topics, please let me know. I’ll update the post.

 

Hi, my name is Mosh Hamedani and I am the author of several best-selling courses on Udemy and Pluralsight with more than 130,000 students in 196 countries. You can see the list of all my web and mobile development courses on this website.
Tags: , ,
Comments

Top 3 Reads for C# Developers

I’ve had quite a few students of mine contacting me and asking:

Mosh, apart from your video courses, what books should I read to become a better developer?

If you want to become a kick-ass C# developer, you need to master the fundamentals. By fundamentals, I mean concepts that are always applicable. ASP.NET 5 is NOT one of them! Neither are Entity Framework, Xamarin, Azure, etc.

Frameworks and tools come and go. Becoming proficient in a framework may give you some career opportunities in the short term, but if you want to be ahead of the game, you need to understand the core principles. When you understand the fundamentals well, you can quickly learn a new framework or a new programming language. In fact, at that level, learning a new language is just a matter of getting used to a new syntax. Most of the concepts sound familiar to you.

Here are my 3 absolute favorite books. I’ve read each of these twice! Why only 3 books? I could list 30 books here, and chances are you wouldn’t read any of them because there would be too many too chose from! Less is more.

I handpicked the top 3 that I loved the most amongst all the other books I’ve read. And none of these books teach you the C# programming language. I’m assuming you’ve read one or more books on the topic or watched my courses. So, these books are “supplementary” materials to make you a better developer.

Agile Principles, Patterns and Practices (Robert C Martin)

Agile Principles, Patterns and PracticesRobert C Martin (Uncle Bob) is my guru! I’ve learned a lot from his books and videos. I’ve read most of his books twice and watched most of his videos. Even though the title has the word “agile”, the books is not much about agile. It’s mostly about SOLID principles of object-orientation and design patterns. The book is simple and easy to read and examples make sense.

 

Applying UML and Patterns (Craig Larman) 

51gVLEtrCNL._SX398_BO1,204,203,200_Shall I say the best or the only OOP book worth reading? There are many books on the topic but most of them are boring to death. Craig teaches you OOP in a real-world scenario. He walks you through the requirements of two applications and uses iterative development to build them. The book is around 900 pages, but I promise it’s worth reading. Prior to reading this book, I had read many books about OOP and used it for years. When I read this book, I realized I knew nothing about OOP!

Art of Unit Testing (Roy Osherove)

51VAZ9BwcvL._SX397_BO1,204,203,200_Great book if you want to learn all about automated testing and test-driven development. Roy has been very well respected in the area and he has been running workshops around the world teaching automated testing to C# developers. The book is just over 200 pages and you can easily read it.

 

 

What are your favorite C# books? Please drop a comment and share!

Hi, my name is Mosh Hamedani and I am the author of several best-selling courses on Udemy and Pluralsight with more than 130,000 students in 196 countries. You can see the list of all my web and mobile development courses on this website.
Tags: , ,
Comments

C# 6 features that help you write cleaner code

There have been many improvements to C# 6 that simplify your code. Unlike the features introduced in previous versions of C# (e.g. generics, LINQ, async programming, etc), these features are not revolutionary. But they’ll help you write cleaner and less-cluttered code.

In this post, I’ll delve into the details of these new features.

Auto-property Initializers

One of the things that always bugged me about properties in C# is that we couldn’t initialize them directly, like fields. We had to create a constructor to set them:

public class Post 
{
    public DateTime DateCreated { get; private set; }
    public Collection<Comment> Comments { get; private set; }

    public Post()
    {
        DateCreated = DateTime.Now;
        Comments = new Collection<Comment>();
    }
}

With C# 6, we can directly initialize a property without the need to create a constructor:

public class Post 
{
    public DateTime DateCreated { get; private set; } = DateTime.Now;

    public Collection<Comment> Comments { get; private set; }
       = new Collection<Comment>();
}

This is especially useful in initializing collections.

Dictionary Initializers

Before C# 6, we could initialize a Dictionary using the { key, value } syntax:

var dictionary = new Dictionary<string, string>
{
     { "LAX", "Los Angeles International Airport" },
     { "MEL", "Melbourne Tullamarine Airport" }
};

While this syntax works fine, if you’re initializing complex objects with nested structures, all these curly braces get in the way and you may easily lose track of them.

C# 6 introduces a new index-like syntax to initialize dictionaries:

var dictionary = new Dictionary<string, string>
{
     ["LAX"] = "Los Angeles International Airport",
     ["MEL"] = "Melbourne Tullamarine Airport" 
};

With this syntax, the extra noise due to curly braces is gone. Plus, keys stand out a bit more.

String Interpolation

This one is a simple but very effective improvement in C# 6 that I love. How many times have you used the String.Format() method like this:

var title = String.Format("{0} ({1})", post.Title, post.Comments.Count); 

While these placeholders make it easy to define a template, tracing them with their linked arguments causes a bit of distraction. Here, if you want to visualise the output, you have to look at the first placeholder ({0}), and then look at the first argument (post.Title). Then, you look at the second placeholder, and follow it up with the second argument. Your eyes keep moving from left to right.

C# 6 introduces a beautiful way to write the same code in a more direct way:

var title = $"{post.Title} ({post.Comments.Count})";

So, you need to prefix your string with $ and then you can replace placeholders with the actual arguments. Isn’t that cleaner?

Null-conditional Operator

This new syntax is my personal favorite and chances are it is going to be your favorite too! If you’ve been programming in C# for a little while, you should know that NullReferenceExpception is one of the most common exceptions that occur in .NET applications. Consider the following piece of code where we check for null:

var title = null;
if (post != null)
    title = post.Title;

How many times have you had to write code like this? We need to check an object for null before accessing one of its members. With C# 6, we can use the null-conditional operator to simplify this code as follows:

var title = post?.Title;

Here, if post is null, null will be returned and assigned to the title; otherwise, post.Title be assigned to the title variable.

So, what you put on the left side of the null-conditional operator will be evaluated for null. If it is null, null will be returned; otherwise, what you put on the right side of the null-conditional operator will be evaluated.

Here is another example of null-conditional operator using an indexer:

// Prior to C# 6
Post first = null;
if (posts != null)
    first = posts[0];

// C# 6
var first = posts?[0];

When using the null-conditional operator, we can access members in a chain:

// Prior to C# 6
if (post != null)
    body = post.Comments[0].Body.SubString(0, 100);

// C# 6
var body = post?.Comments[0].Body.SubString(0, 100);

We can also use the null-conditional operator multiple times in an expression:

// Prior to C# 6
var count = 0;

if (post != null)
{
    if (posts.Tags != null)
    {
        count = post.Tags.Count; 
    }
}

// C# 6
var count = post?.Tags?.Count;

There is something tricky about this last example. If either post or post.Tags is null, null will be returned; otherwise, post.Tags.Count will be returned. So, the data type for the count should be able to support both null and an int. So here, count is a nullable int (int?). If you want to define it as an int, you’ll need to add the null-coallescing operator at the end:

var count = post?.Tags?.Count ?? 0;

Another common use-case for the null-conditional operator is when triggering events. How many times have you seen code like this?

if (OnClick != null)
   OnClick(this, args);

We can re-write this code in C# 6 as follows:

OnClick?.Invoke(this, args);

So, if OnClick is null, nothing will happen; otherwise, the Invoke method will be called.

Getter-only Auto-Properties

How would you define a read-only auto-property in C#? Probably like this:

public class Post  
{
    public int Votes { get; private set; }
}

With this, you can only set the value of Votes from inside the Post class, but not from the outside. In C# 6, you can reduce the noise in your code by omitting the private set:

public class Post  
{
    public int Votes { get; }
}

Expression Bodied Members

Now we have a cleaner syntax for implementing properties or methods with a little bit of logic. Consider the following class:

public class Post  
{
    public int DaysOld 
    {
         return (DateCreated - DateTime.Today).TotalDays;
    }
}

In C# 6, we can use the => notation to immediately implement the getter for DaysOld property:

public class Post  
{
    public int DaysOld => (DateCreated - DateTime.Today).TotalDays;
}

So, no need for curly braces or the return keyword, which means less noise in the code.

You can use this syntax to implement simple methods as well:

public class Post  
{
    public int GetDaysOld() => (DateCreated - DateTime.Today).TotalDays;
}

Using Static

I’m not really a fan of this feature but thought to add it here to keep the post comprehensive. Consider this code snippet:

using System;

public class Program
{
    public static void Main()
    {
        Console.WriteLine("Hello World");
    }
}

With C# 6, you can import static classes into your using statements:

using static System.Console;

Note the use of static keyword after using.

With that, you can call the WriteLine method without prefixing it with its class name:

public class Program
{
    public static void Main()
    {
         WriteLine("Hello World");
    }
}

Is this code better? I let you be the judge of that. But personally, I see this as a backward step in C# 6. It is making it look more like Visual Basic, and I’m talking about the old Visual Basic, not even VB.NET! It can be a slight clean up if you have a static utility class and you’ve referenced its members in a file quite a few times. With this, yes for sure, you can remove the class name repeated a few times all over the place.

Summary

In case you love cheat sheets, I’ve put together all these tiny improvements in a simple PDF for you to remember and include in your programming toolbox. Some of these features, although useful, may require a little getting used to. But perfection comes with practice!

Download C# 6 Cheat Sheet

Hi, my name is Mosh Hamedani and I am the author of several best-selling courses on Udemy and Pluralsight with more than 130,000 students in 196 countries. You can see the list of all my web and mobile development courses on this website.
Tags: ,
Comments

What text books tell you about inheritance in OOP is wrong

I received an email from one of my students asking for a design advice. He is working on an application used by a sports team manager, where they can create, edit and delete players, teams and coaches. So, the design that my student had in mind is something like this UML diagram:

UML

So, a SoccerPlayer is a Player, which in turn is a Person. This is what many text books on object-orientation programming teach you:

When you can express the association between two concepts using IS-A, that’s an inheritance!

Many of these books claim that by creating these abstractions, in this example Person, you can “re-use” them in other projects. However, in 15 years of my professional experience, I have hardly seen many (or any) examples of such abstractions being used across projects in a useful manner.

At one point, I started creating a class library of these abstractions that I could share across projects. After a little while, that class library ended up being bloated with lots of unrelated abstractions and versioning it across different projects ended up being a nightmare. If you have done this before, you may relate to this story.

An extreme example of inheritance

Once I was engaged as a consultant for a greenfield project, and in the introductory session, the data architect of the project walked me through tons of UML class diagrams (more than 50 pages). Every class was inheriting from another class and eventually, they all led to a class that was called “Thing”! No joke!

Interestingly, there was not even one behavioural diagram expressing the behaviour of the system. So this huge inheritance hierarchy was only for inheriting “attributes”, not behaviour, which is what inheritance is all about!

Guess what? After spending more than a year and half a million dollars on that project, the company decided to shutdown the project. Nothing was produced, not even a beta version! They engaged various consultants and teams and no one could implement an application with such a large complex model.

Does this story sound familiar to you?

Don’t model the universe!

When building software, you should design a domain model for an application, based on the needs of that application and not the reality. The use cases that the application is going to fulfil will determine the angle at which you should look at the domain model.

In the real world, a SoccerPlayer is a Player and a Player is a Person. But just because you can express such relationship in English, doesn’t mean you should add such association between your classes. You’ll end up polluting your model with lots of unnecessary complexity that serves no purpose.

Inheritance increases coupling in your design

So what is wrong with inheritance? Well, before explaining, let me clarify something. I’m not anti-inheritance! Inheritance, just like every thing else, has its uses. When you use it in the right context, it works for you. But if you abuse it, it leads to increased complexity in your applications.

Inheritance creates tight coupling between your classes. If class Child derives from Parent, it is tightly coupled to the Parent. If you make any changes to the Parent, you may have to modify the Child as well. Or at a minimum, you need to re-compile it and re-deploy the assembly in which it is defined.

Now, when you have a small hierarchy with a few classes, that is not an issue. But as your hierarchy grows, the impact of change grows in your application. The further on top of the hierarchy you make changes, the more classes may be affected or at least need to be re-compiled.

When to use inheritance

So, when should you use inheritance? When re-using behaviour and potentially overriding it, which leads to polymorphism. But even then,  you could use composition to achieve the same thing with less coupling in your design. The famous saying favour composition over inheritance explains that. I’ll write a separate post on this topic soon.

Does this sound too abstract for you? Ok, continue reading for some simple pragmatic tips.

When not to use inheritance

I love theory in practice. If you’re the same, let me give you my super simple and pragmatic advice by showing you some code. If you have one or more of the following symptoms in your code, you probably don’t need inheritance. You can collapse your hierarchy, reduce the coupling and simplify your design.

When you have hollow classes

Do you have classes like this in your design?

public class Person 
{
     public int Id { get; set; }
     public string Name { get; set; }
}

public class Player : Person 
{
}

In case you’re not familiar with the C# syntax, here we have a Person class with two attributes: Id and Name. The Player class derives from Person.

The Player class here is what I call a hollow class. It serves no purpose. We could simply use the Person and reduce complexity in our design.

Here is a variation of this example:

public class Person 
{
}

public class Player : Person 
{
     public int Id { get; set; }
     public string Name { get; set; }
}

In this example, Person is a hollow class and is useless.

Here is the important part I want you to pay attention to: in the domain of this application, what matters is the Id and Name of each Player. The fact that a Player is a Person in the real-world does not matter in this application. And that’s what I meant by not modelling your applications based on the reality. Instead, you should model based on what the application needs and how it is going to behave.

When your inheritance hierarchy is all about attributes

Look at this example:

public class Person 
{
     public int Id { get; set; }
     public string Name { get; set; }
}

public class Player : Person 
{
     public byte Number { get; set; }
}

public class Coach : Person 
{
     public byte YearsOfExperience { get; set;
}

The argument behind this design is that we’re re-using the Id and Name properties in the Player and Coach classes. I used to have many classes like this before! The extreme example I mentioned earlier was exactly like this.

But re-using attributes is a poor way of thinking about inheritance. How much effort would be to duplicate these attributes in the derived classes? It would take only a second to copy/paste them. You may say but duplicating code is bad. Yes, but not always! It is bad if you’re going to change it and have to make the change in multiple places. But how often would these attributes “change”? Not often or never! How about the logic? Logic, algorithm and behaviour can change often.

That’s the reason that you should reserve inheritance for re-using behaviour, not attributes. But even then, you can use would better use composition.

Let’s sum it up

So, remember, inheritance increases coupling between your classes. Reserve it for situations when you want to implement polymorphism, not just for re-using code, especially attributes. If you have one or more of the following symptoms in your design, you probably don’t need inheritance:

  • Hollow classes that have no members
  • Base classes that include only attributes. They don’t have any methods for the derived classes to re-use or more importantly, override.

If you see this in your design, you can achieve a simpler, cleaner and more maintainable design by collapsing your inheritance hierarchy.

So, keep it simple!

 

If you enjoyed this post, please share it and leave your comments below.

 

Hi, my name is Mosh Hamedani and I am the author of several best-selling courses on Udemy and Pluralsight with more than 130,000 students in 196 countries. You can see the list of all my web and mobile development courses on this website.
Tags: , ,
Comments

IEnumerable and IEnumerator in C#

Many junior C# developers find the two IEnumerable and IEnumerator interfaces confusing. In fact, I was one of them when I first started learning C#! So, in this post, I’m going to explore these two interfaces in detail.

I’ll start by giving you a quick answer if you’re too busy to read the rest of the post, and then I’ll get into the details.

IEnumerable and IEnumerator in a Nutshell

IEnumerable and IEnumerator are implementation of the iterator pattern in .NET. I’ll explain the iterator pattern and the problem it aims to solve in detail shortly. But if you’re looking for a quick, pragmatic tip, remember that when a class implements IEnumerable, it can be enumerated. This means you can use a foreach block to iterate over that type.

In C#, all collections (eg lists, dictionaries, stacks, queues, etc) are enumerable because they implement the IEnumerable interface. So are strings. You can iterate over a string using a foreach block to get every character in the string.

Iterator Pattern

Consider the following implementation of a List class. (This is an over-simplified example and not a proper/full implementation of the List class).

public class List
{
    public object[] Objects;

    public List()
    {
        Objects = new object[100];
    }

    public void Add(object obj)
    {
        Objects[Objects.Count] = obj;
    }
}

The problem with this implementation is that the List class is exposing its internal structure (object[]) for storing data. This violates the information hiding principle of object-oriented programming. It gives the outside world intimate knowledge of the design of this class. If tomorrow we decide to replace the array with a binary search tree, all the code that directly reference the Objects array need to modified.

So, objects should not expose their internal structure. This means we need to modify our List class and make the Objects array private:

public class List
{
    private object[] _objects;

    public List()
    {
        _objects = new object[100];
    }

    public void Add(object obj)
    {
        _objects[_objects.Count] = obj;
    }
}

Note that I renamed Objects  to _objects because by convention private fields in C# should be named using camel notation prefixed with an underline.

So, with this change, we’re hiding the internal structure of this class from the outside. But this leads to a new different problem: how are we going to iterate over this list? We no longer have access to the Objects array, and we cannot use it in a loop.

That’s when the iterator pattern comes into the picture. It provides a mechanism to traverse an object irrespective of how it is internally represented.

IEnumerable and IEnumerator interfaces in .NET are implementations of the iterator pattern. So, let’s see how these interfaces work, and how to implement them in our List class here.

IEnumerable interface represents an object that can be enumerated, like the List class here. It has one method:

public interface IEnumerable
{
    IEnumerator GetEnumerator();
}

The GetEnumerator method here returns an IEnumerator object, which can be used to iterate (or enumerate) the given object. Here is the declaration of the IEnumerator interface:

public interface IEnumerator
{
    bool MoveNext();
    object Current { get; }
    void Reset();
}

With this, the client code can use the MoveNext() method to iterate the given object and use the Current property to access one element at a time. Here is an example:

var enumerator = list.GetEnumerator();
while (enumerator.MoveNext())
{
      Console.WriteLine(enumerator.Current);
}

Note that with this interface, the client of our class no longer knows about its internal structure. It doesn’t know if we have an array or a binary search tree or some other data structure in the List class. It simply calls GetEnumerator, receives an enumerator and uses that to enumerate the List. If we change the internal structure, this client code will not be affected whatsoever.

So, the iterator pattern provides a mechanism to iterate a class without being coupled to its internal structure.

Implementing IEnumerable and IEnumerator

So, now let’s see how we can implement the IEnumerable interface on our List class. First, we need to change our List class as follows:

public class List : IEnumerable
{
    private object[] _objects;

    public List()
    {
        _objects = new object[100];
    }

    public void Add(object obj)
    {
        _objects[_objects.Count] = obj;
    }

    public IEnumerator GetEnumerator()
    {
    } 
}

So I added the IEnumerable interface at the declaration of the class and also created the GetEnumerator method. This method should return an instance of a class that implements IEnumerator. So, we’re going to create a new class called ListEnumerator.

public class List : IEnumerable
{
    private object[] _objects;

    public List()
    {
        _objects = new object[100];
    }

    public void Add(object obj)
    {
        _objects[_objects.Count] = obj;
    }

    public IEnumerator GetEnumerator()
    {
        return new ListEnumerator();
    } 

    private class ListEnumerator : IEnumerator 
    {
    }
}

So, I modified the GetEnumerator method to return a new ListEnumerator. I also declared the ListEnumerator class, but I haven’t implemented the members of the IEnumerator interface yet. That will come shortly.

You might ask: “Mosh, why are you declaring ListEnumerator as a nested private class? Aren’t nested classes ugly?” The ListEnumerator class is part of the implementation of our List class. As you’ll see shortly, It’ll have intimate knowledge of the internal structure of the List class. If tomorrow I replace the array with a binary search tree, I need to modify ListEnumerator to support this. I don’t want anywhere else in the code to have a reference to the ListEnumerator; otherwise, the internals of the List class will be leaked to the outside again.

Alright, so let’s quickly recap up to this point. I implemented IEnumerable on our List class and defined the GetEnumerator method. This method returns a new ListEnumerator that the clients will use to iterate the List. I declared ListEnumerator as a private nested class inside List.

Now, it’s time to complete the implementation of ListEnumerator. It’s pretty easy:

public class ListEnumerator : IEnumerator
{
    private int _currentIndex = -1; 

    public bool MoveNext()
    {
        _currentIndex++;

        return (_currentIndex < _objects.Count); 
    }

    public object Current
    { 
        get 
        {
            try
            {
                return _objects[_currentIndex];
            }
            catch (IndexOutOfRangeException)
            {
                throw new InvalidOperationException();
            }
    }

    public void Reset()
    {
        _currentIndex = -1;
    }
}

Let’s examine this class bit by bit.

The _currentIndex field is used to maintain the position of the current element in the list. Initially, it is set to -1, which is before the first element in the list. As we call the MoveNext method, it is incremented by one.

The MoveNext method returns a boolean value to indicate if we’ve reached the end of the list or not. Note that here in the MoveNext method, we have a reference to _objects. This is why I told our ListEnumerator has intimate knowledge of the internal structure of the List. It knows we’re using an object[] there. If we replace the array with a binary search tree, we need to modify the MoveNext method. There are different traversal algorithms for trees.

The Current property returns the current element in the list. I’ve used a try/catch block here, incase the client of the List class tries to access the Current property before calling the MoveNext method. In this case, _currentIndex will be -1 and accessing _objects[-1] will throw IndexOutOfRangeException. I’ve caught this exception and re-thrown a more meaningful exception (InvalidOperationException). The reason for that is because I don’t want the clients of the list to know anything about the fact that we’re using an array with an index. So, IndexOutOfRange is too detailed for the clients of the List class to know and should be replaced with InvalidOperationException.

And finally, in the Reset method, we set _currentIndex back to -1, so we can re-iterate the List from the beginning, if we want.

So, let’s review. I modified our List class to hide its internal structure by making the object[] private. With this, I had to implement the IEnumerable interface so that the clients of the List could enumerate it without knowing about its internal structure. IEnumerable interface has only a single method: GetEnumerator, which is used by the clients to enumerate the List. I created another class called ListEnumerator that knows how to iterate the List. It implements a standard interface (IEnumerator) and hides the details of how the List is enumerated.

The beauty of IEnumerable and IEnumerator is that we’ll end up with a simple and consistent mechanism to iterate any objects, irrespective of their internal structure. All we need to is:

var enumerator = list.GetEnumerator();
while (enumerator.MoveNext())
{
      Console.WriteLine(enumerator.Current);
}

Any changes in the internals of our enumerable classes will be protected from leaking outside. So the client code will not be affected, and this means: more loosely-coupled software.

Generic IEnumerable<T> and IEnumerator<T>

In the examples in this post, I showed you the non-generic versions of these interfaces. These interfaces were originally added to .NET v1, but later Microsoft introduced the generic version of these interfaces to prevent the additional cost of boxing/unboxing. If you’re not familiar with generics, check out my video on YouTube.

Misconception about IEnumerable and Foreach

A common misconception about IEnumerable is that it is used so we can iterate over the underlying class using a foreach block. While this is true on the surface, the foreach block is simply a syntax sugar to make your code neater. IEnumerable, as I explained earlier, is the implementation of the iterator pattern and is used to give the ability to iterate a class without knowing its internal structure.

In the examples earlier in this post, we used IEnumerable/IEnumerator as follows:

var enumerator = list.GetEnumerator();
while (enumerator.MoveNext())
{
      Console.WriteLine(enumerator.Current);
}

So, as you see, we can still iterate the list using a while loop. But with a foreach block, our code looks cleaner:

foreach (var item in list)
{
     Console.WriteLine(item);
}

When you compile your code, the compiler translates your foreach block to a while loop like the earlier example. So, under the hood, it’ll use the IEnumerator object returned from GetEnumerator method.

So, while you can use the foreach block on any types that implements IEnumerable, IEnumerable is not designed for the foreach block!

Wrapping it Up

In this post, you learned that IEnumerable and IEnumerator are used to enumerate (or iterate) a class that has a collection nature. These interfaces are the implementation of the iterator pattern. They aim to provide a mechanism to iterate an object without knowing its internal structure.

If you enjoyed this post, please share it and leave your comment below. If you have any questions, feel free to post them here. I’ll answer every question.

Hi, my name is Mosh Hamedani and I am the author of several best-selling courses on Udemy and Pluralsight with more than 130,000 students in 196 countries. You can see the list of all my web and mobile development courses on this website.
Tags: , ,
%d bloggers like this: