Comments

[Q&A]: What is the difference between junior and senior developers?

I’m excited to announce that I just published the first episode of my Q&A shows on YouTube. In this episode, I’ve answered Kyle’s question:

What is the difference between junior and senior developers?

If you enjoy this video, please like and share it. If you want me to include your question in my upcoming shows, please use the comments section on YouTube. You can ask me anything, technical or non-technical.

Tags:
Comments

Ask me anything in my YouTube shows

I’ve been thinking about producing weekly YouTube shows to help you with what is stopping you from achieving your aspirations. These shows are in the form of questions and answers. You send me your questions (by filling out the form below), and in each show I’ll pick a few questions and talk about them.

You can ask me ANYTHING (technical or non-technical), except the following:

  • Code not compiling or ​running on your machine
  • Exceptions you get at run-time

I don’t answer questions like that because I believe a programmer must be able to isolate and troubleshoot such issues on their machine themselves.

If you don’t learn the skills to troubleshoot such problems yourself, you’re going to have a difficult time working as a full-time software developer. Every single day you’re going to face such issues and I’m not there to help you. You cannot ask your colleagues for help every single time either. Your only resource is Google and try and error.

When I was a junior programmer, I didn’t even have Google. I used to stay up till 4am troubleshooting these problems. I had to comment out the code line by line, and look into exact locations of memory (talking about C++ and assembly back then) to find out what was happening. These days, you don’t have to do that. If you spend only 2 minutes, most of the time, you’ll find your answer on the first link on the first page of Google search results.

So, feel free to ask me any technical or non-technical questions. Your non-technical questions can be on topics such as getting a job, or if you have a job, you may have some challenges at work (e.g. collaborating with others especially strongly-opinionated developers in the team, etc). You may suffer from RSI (repetitive strain injuries), etc.

So, if you like me to answer your questions as part of my weekly shows, simply feel out the following form.

I love to hear about you, your aspirations and your challenges. Feel free to write as much detail as you want. This helps me better understand you and come up with proper advice in my shows.

http://goo.gl/forms/9b8lsyYJOX​​​

Thanks,
Mosh

Comments

My upcoming courses in this year

Just wanted to say a quick thank you to every one who filled out my little survey. The top most voted courses are:

  • Design Patterns
  • Building iOS and Android Apps with Xamarin
  • Advanced Angular 2

So these are the courses that I’ll be focusing on for the next few months. Of course, this is not a definite plan and sometimes unexpected things happen and I may have to focus on a different topic.

I don’t have a firm decision about which course I’ll be publishing next, but for the moment, I’m leaning more on Xamarin. 

 

Comments

Update on my Pluralsight course

I’ve been getting a lot of emails lately, almost on a daily basis, people asking me when my Pluralsight course (Building a Real-world App with ASP.NET MVC) is going to get published and how it is different from my upcoming ASP.NET MVC course on Udemy.

So, I’m going to answer these two questions in this post.

Udemy course

This course will teach you the fundamentals of building web apps with ASP.NET MVC 5. I’m aiming to publish it in 2 weeks or less. Here is a sneak peak of what you’re going to get.

Is this the same as the Pluralsight course? Yes and no. There are some overlaps, but they have differences. In the Pluralsight course, I don’t really teach much of the ASP.NET MVC framework. I’m assuming you have some basic familiarity and want to learn how to build a real-world app end to end.

In the Udemy course, I assume you know nothing about ASP.NET MVC and I teach you all the details step-by-step.

And here is more about the Pluralsight course.

 

Pluralsight course

This course is about 15 hours long, distributed over 3 parts. Almost 95% of the course is reviewed and approved by Pluralsight and we’re aiming to finish it off in less than 2 weeks. But I can’t promise anything because once I fully hand it off to Pluralsight, it’s up to them to decide when they’ll publish it, but I can’t think of a reason why they would want to hold on to that.

By the way, I decided to rename the course from “Building a Real-world App with ASP.NET MVC” to “Become a Full-stack .NET Developer“, because I realized that is really the core of what I teach in this course. It covers a wide range of front-end and back-end skills.

The application I’ve built over these three parts is a simplified social networking app for live gigs. Artists can sign up and list their upcoming gigs. Users can follow artists and get upcoming gigs in their gig feed. If a gig is updated or removed, they’ll receive a notification, similar to Facebook notifications.

Here are more details about each part.

Part 1: Fundamentals

Part 1 is for junior developers who have basic familiarity with ASP.NET MVC and Entity Framework. This is mostly for people who know a little bit of these technologies but don’t know how to put them together and build a real-world application. I’ve received tons of emails from students telling me they don’t know how to start from the requirements document, how to go from one step to the next, how to version their code, etc. So, that’s the essence of this part.

I’ll also talk about security, usability and building beautiful user interfaces using HTML and CSS.

Part 2: Advanced Concepts

Part 2 is for the intermediate developer and includes more advanced use cases. This is where I’ve implemented the Facebook-like notification system. There is a lot of emphasis on domain modelling and object-oriented design in this part. You’ll also learn about refactoring an anaemic domain model (which is a common issue in design of many applications out there) into a behaviour-rich domain model.

Part 3: Architecture and Unit Testing

Part 3 is what takes you from an intermediate developer to an advanced developer. In this part I talk about

  • Refactoring spaghetti JavaScript code
  • Repository and unit of work patterns
  • Programming against interfaces
  • Dependency injection
  • Clean architecture
  • Unit testing
  • Integration testing

This course is packed with concepts, best practices and keyboard shortcuts and I’m sure you’re going to love it.

Pluralsight’s feedback

This morning I woke up with a sweet email from Pluralsight giving me feedback about my course. I was in bed reading the email with one eye and within a few seconds both my eyes were big open and I couldn’t not smile. So I thought to share the feedback with you.

You are a meticulous coder! The spacing, alignment, various conventions, even alphabetical order of things–all awesome

Nice sample app. It’s simple enough to be approachable, but still robust enough to show important concepts, and it feels like a real-world app that I might build.

Clean, crisp audio, good volume. Nice work on recording/editing.

I like your approach of implementing things in an “ugly” way, then showing how to make them better. I think this is a great way to learn; it’s much more effective than showing only the “correct” way up front.

You did a nice job talking through the keyboard shortcuts you were using throughout the demos. Very helpful.

Loved your story about John throwing code wherever with a 5-second approach, then realizing it’s a mess, then implementing with a shiny new framework. I can’t tell you how often I’ve seen this happen!!!

I like that you acknowledged that some developers find testing to be painful and time-consuming. I think this gives you credibility, and shows that you aren’t selling some unrealistic “rainbows and butterflies” view on testing.

Great explanations of IIFE/revealing module pattern.

As much as you’ve been excited to watch this course, I’ve been excited to share all this with you and can’t wait until it goes live. So, if you’ve not joined my mailing list, be sure to join now and I’ll send out an announcement once the course is live.

Tags: , ,
Comments

Angular 2 Tutorial: Angular 2.0 in 20 minutes

This article is outdated. Check out my brand new Angular 4 tutorial on YouTube.

Angular 2 has been getting a lot of momentum lately. The number of tweets and posts have been increasing as Angular team have been preparing the release candidate. So, I’m planing to write a series of hands-on blog posts to help you get started with Angular 2.0. If you have any questions as you read this article, please drop a comment below. I’ll answer every question and update the post if required.

Whether you’re familiar with Angular 1 or not, it doesn’t matter. You just need to have basic familiarity with HTML, CSS and Javascript.

Let’s start by a few beginners’ questions.

Beginners’ questions

If you’re already familiar with Angular 1, feel free to skip this section.

What is Angular? 

Angular is one of the leading frameworks for building well-structured, testable and maintainable front-end applications. It’s often (but not necessarily) used in building single page applications (SPAs).

Why do I have to learn Angular?

Angular is not the only framework for building modular, testable and maintainable front-end applications. There are many other frameworks and libraries out there, including but not limited to React, Ember, Backbone, etc. Do you have to learn them all? If you have time and passion, why not! But if you have limited time, you may better invest your time in learning Angular 2.0 and React as these are the leading frameworks in this space.

Angular is developed by Google and has a huge community support. Google trends shows that the demand for Angular developers is increasing constantly.

angular developer

So, whether you’re an aspiring or an established front-end or full-stack developer, knowing how to build applications with Angular can definitely increase your options when it comes to finding that ideal job.

Is Angular better than “…”?

The problem with this kind of question is that it’s hard to define “better”. Every framework has certain strengths and weaknesses. Religious debates about which framework is “better” than the others are really useless and don’t give you any values.

So, instead of wasting your time researching the best framework out there, spend some time and learn the top 2 – 3 leading frameworks. Then, you can pick the one that works best for you.

Getting the tools

If you don’t have Node on your machine, first, head over to http://nodejs.org and download and install the latest version of Node.

Once you install Node, open up Command Prompt on Windows or Terminal on Mac, and run:


npm install -g typescript

If you are a Mac user, you need to put sudo before npm to run this command with administrative privileges.

This will install TypeScript globally on your machine. TypeScript is a superset of Javascript and is the language we will be using in this tutorial. Why TypeScript? Because it brings many useful features to Javascript that are missing in the current version of Javascript, including classes, interfaces, access modifiers (e.g. public, private), IntelliSense and more importantly compile-time checking. So, we can catch many programming errors during compile time. Angular 2.0 itself has been written with TypeScript.

Just note that browsers don’t understand TypeScript. We use TypeScript compiler to compile or more accurately transpile TypeScript into Javascript. More on this later.

Next, run:


npm install -g typings

Typings is another Node module that we use to reference existing Javascript libraries in TypeScript.

Finally, you need an editor. You can use any editors that support TypeScript, including VSCode, Sublime, Atom, IntelliJ IDEA, Visual Studio and etc.

Your first Angular 2 app

Download the seed project and extract it somewhere on your machine. Inside this project, you’ll find a few  configuration files, an index.html and an app folder, which includes the source files for our application.

Inside the app folder, we have a couple of TypeScript files: boot.ts, which is the main or starting module of our application, and app.component.ts, which is the root component of our application. Every Angular 2 app has at least one component, which we call root component.

tsconfig.json is the configuration file TypeScript compiler uses to determine how to transpile our TypeScript code into Javascript.

typings.json is another configuration file for Typescript. When using external Javascript libraries in TypeScript, we need to import a typescript definition file. A type definition file gives us static type checking and IntelliSense for that Javascript library.

Next to that, we have package.json, which is a standard Node package configuration file, where we define the dependencies of our app.


{
  "name": "angular2-quickstart",
  "version": "1.0.0",
  "scripts": {
    "start": "concurrent \"npm run tsc:w\" \"npm run lite\" ",    
    "tsc": "tsc",
    "tsc:w": "tsc -w",
    "lite": "lite-server",
    "typings": "typings",
    "postinstall": "typings install" 
  },  
  "license": "ISC",
  "dependencies": {
    "angular2": "2.0.0-beta.7",
    "systemjs": "0.19.22",
    "es6-promise": "^3.0.2",
    "es6-shim": "^0.33.3",
    "reflect-metadata": "0.1.2",
    "rxjs": "5.0.0-beta.2",
    "zone.js": "0.5.15"
  },
  "devDependencies": {
    "concurrently": "^2.0.0",
    "lite-server": "^2.1.0",
    "typescript": "^1.7.5"
  }
}

Now, we need to install these dependencies. So, open up Command Prompt on Windows or Terminal on Mac, and go to the folder where you’ve extracted the seed project. Then, run:


npm install 

This is going to take several minutes for the first time, so be patient. If you get several errors, that’s most likely due to administrative privileges. So, on Mac, be sure to add sudo before npm. 

Once these dependencies are installed, you’ll see a new folder called node_modules. All our application dependencies will be stored there.

Now, have one more look at package.json. Under the scripts section, we can have a few custom node commands:


"scripts": {
    "start": "concurrent \"npm run tsc:w\" \"npm run lite\" ",    
    "tsc": "tsc",
    "tsc:w": "tsc -w",
    "lite": "lite-server",
    "typings": "typings",
    "postinstall": "typings install" 
  }

The one we’ll be using a lot is start.


    "start": "concurrent \"npm run tsc:w\" \"npm run lite\" ",  

 

It’s a shortcut for concurrently running two commands:

  • npm run tsc:w: which runs TypeScript compiler in the watch mode. When we save a TypeScript file, TypeScript compiler will automatically detect the changes and transpile our TypeScript code into Javascript. We never have to view or modify these Javascript files. So we code purely in TypeScript.
  • npm run lite: this will run the lite web server for our Angular app.

Now, back in the terminal and run the following command from the project folder:


npm start

When the lite web server starts, it’ll launch your default browser navigating to http://localhost:3000. This is our first Angular 2.0 app.

angular2-tutorial

What is a component?

A component is one of the most fundamental building blocks in Angular 2 apps. Every app consists of at least one component, which we call the root component. A component can include other components, which we call child components. A real-world app is essentially a tree of components.

But what are these components really? A component is a TypeScript class that encapsulates the template, data and behaviour for a view. So, it’s more accurate to call it a view component. That’s what they’re called in React.

As an example, think of Twitter. If you want to build a similar app in Angular 2, you may model your application components like this:

  • app
    • navbar
    • sidebar
    • content
      • tweets
        • tweet

Root component

Open up app/app.component.ts. This is the root component of our app:


import {Component} from 'angular2/core';

@Component({
    selector: 'my-app',
    template: '<h1>My First Angular 2 App</h1>' 
}) 
export class AppComponent { }

As you see, a component is a TypeScript class decorated with @Component decorator. We use decorators (also called annotations) to add metadata to a class. This @Component decorator tells Angular that AppComponent is a component. Note that these decorators are actually functions. So, here, @Component is called and given an object which includes metadata about AppComponent:


@Component({
    selector: 'my-app',
    template: '<h1>My First Angular 2 App</h1>' 
})

This object has two properties: template, which specifies the markup that should be rendered when this component is used, and selector, which tells Angular where in the DOM it should render this component. This is a CSS selector. So, my-app here represents an element with the name my-app.

When Angular sees an element like that in the DOM, it’ll create an instance of AppComponent and render it (according to its template) inside that element. Open up index.html and scroll down a bit. Note the my-app element.

Rendering data

Back in app.component.ts, let’s define a field in this class:


export class AppComponent { 
	title = "Hello World";
}

So, as I explained earlier, a component encapsulates the template, data and the behaviour for a view. We use fields to store data. Now, let’s render the value of this field in the template. Modify the template as follows:


    template: 'Hello {{title}}' 

We use double curly braces syntax, called interpolation, to render data.

Now, save the file. Since TypeScript compiler is running in the background, it will re-compile our AppComponent. Our lite web server uses a module called BrowserSync, which automatically refreshes the browser when it detects a change in the source files. So, if you switch back to your browser, you should see the new content.

Handling events

Let’s extend our component and add a button. First, replace the single quote character in the template with backtick. That’s the character to the left of number 1 on your keyboard. By using backtick, we can break up our template into multiple lines and make it more readable.


@Component({
    selector: 'my-app',
    template: `
<h1>Hello {{title}}</h1>
` 
})

Now, add a button and a span to the template:


<h1>Hello {{title}}</h1>
<span><span>
<button>Click me</button>

We want to display a counter on this view. Every time we click the button, the counter will be increased by one. So, first declare a new field in the component:


export class AppComponent { 
        count = 0;
        title = "Hello World";
}

Then, modify the span and use interpolation to render the value of count:


<span>Clicks: {{count}}<span>

Finally, to handle the click event, we need to bind it to a method in our component. When we click the button, the corresponding method in the component will be called.

Change the button declaration as follows:


<button (click)="increaseCount()">Click me</button>

Note the syntax. This is called event binding. So, we put the event name in parentheses and then set to a method in the component.

Now, let’s create this method:


export class AppComponent { 
	count = 0;
	title = "Hello World";

	increaseCount(){
		this.count++;
	}
}

Save the file and switch back to your browser. Click the button a few times and note the counter.

So, in this article, you learned the basics of components in Angular 2.0 apps. A component encapsulates the template, data and behaviour of a view. We used interpolation to render data and event binding to handle events raised from DOM elements.

In the next part, we’ll look at services and dependency injection. If you want to be notified when I publish the next part, subscribe to my blog below.

If you enjoyed this tutorial, please drop a comment below and share it with others.

You can also check out my comprehensive Angular 2 course here.

logo draft 2_3_2048

Tags:
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”.

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.

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!

 

 

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.

 

Tags: , ,
Comments

Response to Students’ Feedback for My Next ASP.NET MVC Course

First of all, thank you so much for filling out the questionnaire about my next ASP.NET MVC course.

Thank You

Unfortunately, due to large number of responses and their anonymity, I can’t give a direct feedback to each of you. But I wanted to assure you that I’ve read every single comment and will do my best to include most of the topics you requested in my next course.

Most of you wanted to see me build an application end-to-end. I’ll definitely do that as part of the course. And no, it’s not going to be yet another toy app like a blog or todo list!

I’ll cover all the core topics as well as most of the advanced ones that you need to know. Some of the key things that many of you struggle with that I’ll definitely include in my course include:

  • Programming against interfaces: why and how
  • Dependency injection: what it is, why and when it’s required and how to do it
  • Repository pattern
  • Integration with front-end JS frameworks: Angular, Backbone and React
  • Real-time notifications with SignalR
  • Layered architecture and best practices
  • Security best practices 
  • Authentication and authorization
  • View Models: what they are, why we use them and when

Paul from UK wrote:

You get straight to the point: explaining concepts, evaluating and justifying design decisions and providing relevant, concise, clean and understandable example code, allowing the student to maxmise their time and learning. You help existing software developers to improve their skills and new software developers to learn the best practices from the very beginning. I think you’re quite unique in doing this

Thanks so much Paul for your beautiful words. Really appreciate it! 🙂

Another ASP.NET MVC course

In the meantime, I’ve been working on another ASP.NET MVC course but that’s not for beginners. It’s still under production and is going to be about 15 hours long. You’ll see me build a real-world application (a mini social network) end-to-end. This course is different from the one I’m going to create specifically for you and you can read more about it here.

Next course is going to be better!

I’ve learned a lot about course production since my first course: Double Your Coding Speed. There are many things I could have done better, in terms of delivery and audio/video production. So, I can guarantee that my next course is going to be better than all courses you’ve taken so far! So, stay tuned!

Can you do me a favour?

Many of you wrote me beautiful messages in the questionnaire about how much you love my teaching style, but you could support me on this journey a lot more by writing a genuine review on Udemy. Your reviews help my courses rank better in search results and potentially get more students. And if I get more students, I can rely more on this journey as a source of income and spend more time creating more and better courses for you.

So, could you please write a review for my courses you’ve watched and enjoyed? It takes only 30 seconds. Thanks!

Tags: ,