Saturday, December 3, 2016

Entities vs Value Objects in Domain Driven Design

In today's blog post, we will be discussing the differences between entities and value objects in Domain Driven Design.

Entities

When two objects are deemed equal on the basis of their identity, they are considered "Entities". Suppose, you have two Employee objects in your system i.e. employee1 and employee2. The only way your code determines that the two objects are equal is by comparing the employee ids of the two objects. If the two ids match, these objects are considered equal.

Entity objects are mutable. We should be able to change specific properties of the entity object and be able to save it.

In terms of database storage, an entity should be stored in its own table.

Value Objects

Value Objects have no conceptual identity. When two objects are deemed equal only if all their members match, they are considered "Value Objects". For example, you have two addresses i.e. address1 and address2. In order to determine whether the two addresses are equal, we will have to compare all the fields inside the address object i.e. Street Name, City, State, Country, etc. If all the fields match then only they are considered equal otherwise not.

Value Objects should be immutable. If we need to change some part of it, we should be creating a new instance of value object instead of updating the existing one.

For database storage, the value object data should be stored with the entity object itself instead of storing in a separate table. For example, for employee address, it's preferable to store the address fields in the employee table itself rather than a separate Address table.

Context Dependency

The same thing can be a value object in one application and and entity in another. For example, the dollar bill might be a value object in a casino application, however, it might be an entity in federal bank application. The bank might want to keep each bill based on it's identity, according to their application needs.

Conclusion

Using Value objects can simplify the design in instances where we can reuse the same object instead of creating multiple copies of the same thing. This might be more efficient in terms of memory as only one object might be used instead of creating multiple copies of the same value object again and again. Making it immutable might be extra work initially but it helps in communicating the design decisions more clearly to future code readers.

For future updates to my weekly blog, please subscribe to my blog via the "Subscribe To Weekly Post" feature at the right and follow me on Twitter. Until then Happy Coding :)


Thursday, November 10, 2016

Anti Corruption Layer and Shared Kernel in Domain Driven Design

In today's blog post, I will be discussing few more key terms in Domain Driven Design i.e. Anti Corruption Layer and Shared Kernel. Last week we discussed Ubiquitous Language and Context Maps here.

Anti Corruption Layer

If I am creating a model for a sub-system that communicates with other sub-systems, I might have to interface with other models created by different teams. Since other models are part of different bounded contexts, they might be expressed very differently using their own ubiquitous language. If we use them as is, they might cause corruption in the model in our bounded context.

So in order to avoid this problem, we can have an isolation layer in the middle which takes care of adapting and translating the model from one bounded context to another. This isolation layer is called the anti-corruption layer (ACL).

Anti Corruption Layer in Domain Driven Design


If you have a big, messy and legacy code application to which you need to add more features, usually people think of two options. Either, add to the existing mess which is not a good idea as we are increasing the maintenance nightmare and might introduce bugs in the existing functionality. Or, rewrite the whole application which might not be possible given the time constraints and can also lead to lots of bugs. The third, and most feasible one is to create a new bounded context and anti corruption layer, transform the models you need for your new bounded context and implement the functionality needed. This way your new bounded context is isolated from the existing messy code. This will not only help you avoid creating new bugs in existing application but also will be easier to maintain.

Shared Kernel

If two teams want to collaborate closely and have a lot of cross over in terms of domain logic and concepts, the overhead of translating from one bounded context to another might be too much. So they might decide to share that part of the model, which is known as shared kernel.

Shared kernel introduces risk in terms of one team can break the code of the other team. This also requires the two teams to align their Ubiquitous Languages. It's highly important to have strict coordinating rules around the shared kernel. Any changes to be made to shared kernel should be in consent with the sharing teams. If coordination seems expensive and might not be possible going forward, it might be better to not put anything in shared kernel.


Conclusion

So we saw the importance of anti corruption layer and understood what shared kernel is in Domain Driven Design.

References:
http://softwareengineering.stackexchange.com/questions/184464/what-is-an-anti-corruption-layer-and-how-is-it-used

Thursday, November 3, 2016

Ubiquitous Language and Context Maps in Domain Driven Design

In today's blog post, I will be covering a few more key terms in Domain Driven Design. We will be discussing Ubiquitous Language and Context Maps. This is is continuation with last week's blog post about Domain, Sub-Domain and Bounded Context which we discussed here.

Ubiquitous Language

Some people call it the language of the business. Some people call it the language of domain experts. In reality, it is a language shared by the team i.e. domain experts and developers alike. The domain experts do have a high influence on the language but they don't decide everything. It's dependent on how the business thinks and operates. If you have multiple domain experts on the same team, they themselves might have different terminologies. So the domain experts and other team members all need to be on the same page.
Also, there might be scenarios which the domain experts have not even considered. Developers and QAs s are good at finding such scenarios ;) In such cases, the language & terminologies might not even exist and the team might have to come up with some new terms. All these become part of the ubiquitous language.
Lastly, it's not a one-time thing. It grows and changes over time. As the understanding of the domain improves for domain experts and other team members, new terms are added and existing terms are updated with time.

Ubiquitous Language and Context Maps in DDD

Context Maps

A context map can capture the technical and organizational relationships between various bounded contexts. It shows the boundaries of the bounded contexts and the contact points of these contexts among each other.
Also, it shows how various bounded contexts communicate with each other and what type of relationships exist among them. It represents the holistic view of the application. This is helpful in informing the teams their own communication points and how they can communicate with other teams.
A context map need to be updated whenever there is any change in the boundaries of the bounded contexts or change in how they talk to each other.


Conclusion

So we defined some more key terms in the Domain Driven Design this week. We will be continuing with our journey by learning more about context maps and what it contains next week.


References:
i)  Domain Driven Design By Eric Evans;
ii) Patterns Principles and Practices of Domain Driven Design By Scott Millet

Thursday, October 27, 2016

Domain vs Sub Domain vs Bounded Context in DDD

In today's blog post, I will be discussing some of the key terms in Domain Driven Design. There is a lot of confusion around these terms especially when one starts reading about Domain Driven Design.

Domain Driven Design is both a way of thinking and a set of priorities, aimed at accelerating software projects that have to deal with complicated patterns.  -Eric Evans

Domain

The terms domain refers to the problem space that we are trying to create the software for. This refers to the way actual business works. Understanding the domain is the most important constituent of Domain Driven Design. For example, if you are creating software for managing performance reviews of employees, then understanding how the performance reviews actually work, the whole end to end workflow, the needs and expectations of the customers, how it affects compensation, etc is what refers to the Domain. The domain will include employees, managers and performance reviews, etc.


Core Domain

By breaking the complex domain into multiple sub-domains, we follow the divide and conquer approach to understand the domain better. The core domain refers to the key differentiator for the customer's business - something they must do well and cannot outsource. It's important to separate the core domain from other sub-domains. This helps us to focus our effort on one thing at a time. So in our example of employee performance review, our core domain is the performance review itself. The core domain affects other domains like compensation or affected by badges awarded to employees in the system. Those sub-domains are outside the core domain.


Domain Sub Domain Core Domain Bounded Context

Sub-Domain

These refer to the sub-domains that our core domain must interact with. They can be other applications or features our application must support or interact with. So in our example above, compensation management and badges management are the sub-domains with which our performance review application interacts. The relationships between the sub domains reflect how various components of the organization interact with each other.

Domain Model

Domain Model refers to the abstraction of the domain. It is an interpretation of reality. Not every aspect of domain can be part of the model. It's the aspects chosen for implementation that constitute the model. The diagrams (e.g. UML Diagrams) and even English sentences can present various views of the model. For us developers, the code represent the model. The model doesn't necessarily mean the classes, it can be anyway the code is written. Domain model consists of analysis model, code model and the language. The domain model shows how the user interacts with the application for a sub-domain.

Bounded Context

Whenever we discuss model, it's within a context. For example, a person might be called a user in one context and employee in the other. Every domain model lives in one bounded context and a bounded context contains one domain model. The bounded context defines the application boundary that separates it from other parts of the system. Bounded context includes not only how the users interact with the part of the application (as represented by domain model) but also how other parts of the application interact with it. These might include files, messages, API calls, etc. So by defining these boundaries, we get to know that we might have to translate the concepts from one sub domain to another.
Ideally, there should be a bounded context for a sub-domain. However, in reality, that's not the case all the time. Bounded context is more technical in nature. For example, in our performance review management application, if we have sub domain of how admin interacts with the application. Within this sub domain, how admin searches for a performance review can in itself be a bounded context along with other bounded contexts.


Conclusion

So in today's post, we saw some of the key terms of Domain Driven Design. It's important to understand them well before going deep into DDD. We will be looking at some more of these terms in next week's post as well.
For future updates to my weekly blog, please subscribe to my blog via the "Subscribe To Weekly Post" feature at the right and follow me on Twitter. Until then Happy Coding :)


Thursday, October 20, 2016

Domain Driven Design Advantages and Disadvantages

In today's blog post, I will be discussing what domain driven design is along with it's advantages and disadvantages.

Domain Driven Design

The term "Domain Driven Design" was coined by Eric Evans in 2003 in his book titled "Domain Driven Design".


Domain Driven Design


The Domain Driven Design (DDD) is an approach to software design which makes us focus on the heart of the application i.e. complexity of the business domain rather than technical details. DDD contains a set of patterns for building enterprise applications from the domain model out.

Advantages of DDD

Here are the advantages of using Domain Driven Design:

i) Patterns

DDD gives us the principles and patterns to solve difficult problems in software as well as sometimes in business. These patterns have been successfully used to solve complex problems.

ii) History of Success

It has a history of success with complex projects. It aligns very well with the experience of developers and successful software applications already built.

iii) Clear Code

It helps us write clear and testable code that represents the domain. The code is more focused and concise

iv) Better Understanding

It helps us understand client needs better.

What It Involves

To look at the Domain Driven Design from a high level, here are a few critical pieces which are important for us to successfully follow DDD methodologies:

i) Interaction with Domain Experts 

There is a lot of back and forth interaction with Domain Experts. The communication between the developers and domain experts is critical to the success of this methodology and our software. We as developers need to understand their terminologies, how they want to use the system and their pain points.

ii) Focus on part of Domain

Since the domain is complex, we need to divide it into sub-domains. By doing this, we are keeping the conversation focused to a specific sub-domain at a time. This leads to better understanding on both sides.

iii) Focus on part of Domain (again;)

During development too, the focus is on one sub-domain at a time. It helps the modeling and implementing of sub-domain efficiently and directly ties into separation of concerns principles.

Advantages of DDD to Code

If we follow Domain Driven Design, the resultant code also has a few advantages:

i) Supple

By following DDD, the code is very flexible and will be easier to change and extend.

ii) Solving Customer Problem

The resultant code is generally much more close to customer's vision and perspective of the problem.

iii) Divide and Conquer

Since we are breaking the complex problem into smaller pieces, the resultant code is also easier to write and read. It is much better organized and it should have fewer issues and should be easier to test.

iv) Patterns to Leverage

Even if we don't use DDD by the word, it still helps us to see many great patterns to leverage.

Disadvantages of DDD

DDD comes with a lot of advantages. However, there are a few disadvantages as well:

i) Only if Domain is Complex

The real benefit of DDD shows up only if the domain is complex. If the domain is simple, then DDD might be an overkill.

ii) Time Consuming Upfront

The developers have to spend a lot of time with domain experts to understand the domain thoroughly. This can be time consuming on both ends. Also, deciding the sub domains and system boundaries can also take lot of time.

iii) High Learning Curve

DDD has a high learning curve initially. Getting used to this new way of thinking might be painful at first but I think we as developers do like to give ourselves pain :P

Conclusion

Domain Driven Design helps us focus on the client problem and guides us in the direction of solving it using divide and conquer technique. We will be delving deeper into DDD in subsequent blog posts.

References:
Domain Driven Design book By Eric Evans

Thursday, June 2, 2016

Lambda expressions in C#

In today's blog post, I will be discussing lambda expressions in C#. They are pretty useful for writing shorthand methods and were introduced in C# 3.

Lambda Expressions

Lambda expressions are methods that appear in line and do not have a name. Lambda expressions are simply more concise syntax of anonymous methods. At compile time all lambda expressions are converted to anonymous methods. Lambda expressions are denoted using lambda operator " => ". To the left of the operator are method arguments and right side denotes the method definition.


Lambda Expressions in C#



Let's look at an example. Suppose we have a method to find multiples of five like this:

public static List<int> GetMultiplesOfFive(List<int> numbers)
{
       var multiples = new List<int>();
       foreach (var num in numbers)
       {
           if (num % 5 == 0)
           {
                multiples.Add(num);
            }
       }
       return multiples;
 }

And then we simply use this method like this:

var numbers = new List<int>() { 1, 2, 3, 4, 5, 6, 7, 8, 9 };

var multiples = GetMultiplesOfFive(numbers);

Now, that's a lot of work to create a method especially if it's being used only once in the code. Instead of creating doing all that, we can simply use lambda expression like this:

var numbers = new List<int>() { 1, 2, 3, 4, 5, 6, 7, 8, 9 };

var multiples = numbers.Where(x => x % 5 == 0).ToList();

This way we didn't have to create a separate method. As I mentioned this is good for any short operation that we want to accomplish without going through the overhead of creating a separate method. The compiler will do it for us :)

The variable referred inside lambda expression (i.e. "x") is not available outside the lambda expression. Also, we can have lambda expressions with multiple parameters or with no parameter. Most of the times compiler can infer the variable type in use in lambda expression, but if not, we can also provide it explicitly. For example,

(int x) => x % 5 == 0

Conclusion

So we saw how lambda expressions can be useful and help us save some time and extra code. They are more of syntactic sugar for writing methods with short definition that are not used more than once (generally).

For future updates to my weekly blog, please subscribe to my blog via the "Subscribe To Weekly Post" feature at the right and follow me on Twitter. Until then Happy Coding :)

Thursday, May 26, 2016

Indexers in C#

In today's blog post, we will understand the indexers in C#. Indexers are a useful and less-known feature of C#.

Indexers in C#

An indexer is a way to overload the indexing operator (just like we access array's elements). By defining an indexer on a class, we can access it's properties using an index. Let's take a look at an example to understand how it's done.




Indexers in C#


Suppose we have a Vector class like this:

public class Vector
{
    public int X { get; set; }
    public int Y { get; set; }

    public int this[int index]
    {
        get
        {
            switch (index)
           {
                 case 0: return X;
                 case 1: return Y;
                 default: throw new IndexOutOfRangeException();
           }
        }

        set
        {
            switch (index)
            {
                case 0: X = value;
                    break;
                case 1: Y = value;
                    break;
                default: throw new IndexOutOfRangeException();
            }
        }

    }

}

So here we defined integer indexer in the class. Please note the syntax how we used the "this" keyword with "int index" parameter. Inside the method definition we have the get and set, so we can get the property as well as set the property using integer index.

We are not just limited to integer index. We can even have string indexer like this:


public int this[string index]
{
     get
     {
        switch (index)
        {
              case "x": return X;
              case "X": return X;
              case "y": return Y;
              case "Y": return Y;
              default: throw new IndexOutOfRangeException();
        }

     }

     set
     {
          switch (index)
          {
              case "x":
              case "X":
                  X = value;
                  break;
              case "y":
              case "Y":
                   Y = value;
                   break;
              default: throw new IndexOutOfRangeException();
          }
     }

Please note the "string index" parameter this time. Inside it we define what to do in case of "x" or "X" and "y" or "Y".
Now, let's take a look at how we can use these integer as well as string indexers:

static void Main(string[] args)
{
      var vector1 = new Vector();
      vector1[0] = 2; // integer indexer
      vector1[1] = 3;

      //string indexer
      Console.WriteLine("Vector 1: X = {0}, Y = {1}",
                   vector1["X"], vector1["Y"]);
      Console.ReadLine();
}

So we saw how they can add to readability of the code. Using indexers, we can access each of the property like we are accessing the array elements.

Conclusion

So we saw how to define integer as well as string indexers on a class. Just because we can define indexers doesn't mean it's always the right solution. If it increases the readability of the code and makes sense then only we should use them. In our example, for Vector class it makes it easy to read the code.

For future updates to my weekly blog, please subscribe to my blog via the "Subscribe To Weekly Post" feature at the right and follow me on Twitter. Until then Happy Coding :)


Thursday, May 19, 2016

Operator Overloading in C#

In today's post, I will be discussing operator overloading in C# with an example.

Operator Overloading

In general, operators like "+", "-", etc have pre-defined functionalities. They can be used for mathematical operations for add, subtract, etc. Using operator overloading, we can have our own implementations for operations where one or both the operands are of a user defined class or struct type.

Operator Overloading in C#



Many operators can be overloaded and some of the operators cannot be overloaded. And some of the operators can be overloaded only in pairs. Here is the table from MSDN that shows the complete list of operators that can be overloaded.


OperatorsOverloadability
+, -, !, ~, ++, --, true, false
These unary operators can be overloaded.
+, -, *, /, %, &, |, ^, <<, >>
These binary operators can be overloaded.
==, !=, <, >, <=, >=
The comparison operators can be overloaded. However, they can be overloaded only in corresponding pairs.
&&, ||
The conditional logical operators cannot be overloaded, but they are evaluated using & and |, which can be overloaded.
[]
The array indexing operator cannot be overloaded, but you can define indexers.
(T)x
The cast operator cannot be overloaded, but you can define new conversion operators.
+=, -=, *=, /=, %=, &=, |=, ^=, <<=,>>=
Assignment operators cannot be overloaded, but +=, for example, is evaluated using +, which can be overloaded.
=, ., ?:, ??, ->, =>, f(x), as, checked,unchecked, default, delegate, is, new,sizeof, typeof
These operators cannot be overloaded.

Let's take a look at an example of how operator overloading is done. Suppose, we have a Vector class and we want to overload the "+" operator. In order to overload any operator, we need to use "static" keyword and "operator" keyword like this:

public class Vector
{
    public int X { get; set; }
    public int Y { get; set; }

    public static Vector operator +(Vector A, Vector B)
    {
       return new Vector() 
        { X = A.X + B.X, Y = A.Y + B.Y };
    }

}

So now we can simply use "+" operator to add two vectors. So when we add two vectors, it adds their corresponding X and Y values and returns the new vector.

static void Main(string[] args)

{
       var vector1 = new Vector() { X = 2, Y = 3 };
       var vector2 = new Vector() { X = 4, Y = 5 };
       var vector3 = vector1 + vector2;
       Console.WriteLine("The new vector is: X = {0}, Y = {1}.", 
           vector3.X, vector3.Y);
       Console.ReadLine();
}

The result is: The new vector is: X = 6, Y = 8.

Conclusion

We need to use operator overloading very carefully. It's easy to abuse it which can make the application hard to understand and maintain. If the operator overloading is not necessary to use and might make the code look bad, we should avoid it.

For future updates to my weekly blog, please subscribe to my blog via the "Subscribe To Weekly Post" feature at the right and follow me on Twitter. Until then Happy Coding :)


Ref: MSDN

Thursday, May 12, 2016

EventHandler with Generics in C#

In previous post, we saw the basic usage of EventHandler in C# here. In this post, we will see how to use EventHandler with generics in C#.

EventHandler With Generics

The EventHandler<TEventArgs> is a predefined delegate that represents an event handler method for event with data. We can use an object of class derived from EventArgs with such an EventHandler. This is essentially useful when we have an event where we want to use some data.


Event With Generics in C#


If we look at the implementation of EventHandler with generics, this is how it's defined:


public delegate void EventHandler<TEventArgs>(object sender, 
            TEventArgs e);

Suppose, we have a User class where we want to trigger an event whenever the user's name is updated. We want the event arguments to have the old user name and the new user name. On user name update, we want to print the old and new user name.

We will first create a new UserNameUpdatedEventArgs derived from EventArgs class.


public class UserNameUpdatedEventArgs : EventArgs
{
    public string OldUserName { get; set; }
    public string NewUserName { get; set; }
}

Next, here is the User class:

public class User {     public int userId;     public string name;     public User(int id, string username)     {         userId = id;         name = username;     }
    public void UpdateUserName(string username)     {         UserNameUpdatedEventArgs args = new            UserNameUpdatedEventArgs();         args.OldUserName = name;         args.NewUserName = username;         OnUserNameUpdated(args);     //event          name = username;     }
    protected virtual void OnUserNameUpdated(           UserNameUpdatedEventArgs e)     {         EventHandler<UserNameUpdatedEventArgs> handler =                 UserNameUpdated;         if (handler != null)         {             handler(this, e);         }     }
    public event EventHandler<UserNameUpdatedEventArgs>        UserNameUpdated; }

Please note how the event args are set in the UpdateUserName method. We set the old and new user names in the UserNameUpdatedEventArgs object and pass it to the event. 

In order to use it in the main method, we simply create a handler and use it like this:

static void Main(string[] args) {       User user = new User(1, "Abhi");       user.UserNameUpdated += program_UserNameUpdated;       user.UpdateUserName("Abhi Jain");       Console.ReadLine(); }
static void program_UserNameUpdated(object sender,       UserNameUpdatedEventArgs e) {     Console.WriteLine("The user name was updated from           {0} to {1}.", e.OldUserName, e.NewUserName); }

The output looks like this:

The user name was updated from Abhi to Abhi Jain

Conclusion

So we saw how to use EventHandler with generics in this post. This is pretty useful when we need to pass in special data.
For future updates to my weekly blog, please subscribe to my blog via the "Subscribe To Weekly Post" feature at the right and follow me on Twitter. Until then Happy Coding :)

Thursday, April 21, 2016

Events using EventHandler in C#

In today's post, I will be discussing Events using Event Handler in C#. This is in continuation with the previous week post here.

Events without using Delegates keyword explicitly

Last week we discussed what events are and how to use them in our application. We saw how to use events using delegates here. That post was more to show what's going on behind the scenes. The .NET framework has special guidelines on the delegates that can be used for events. The delegate type should have an object parameter and EventArgs parameter and should return void. So the .NET framework has defined a special delegate type called EventHandler for this purpose.

So the last week's example, if we were using EventHandler, will be as follows:


public class ListWithChangedEvent : ArrayList
{
    public event EventHandler Changed;
    protected virtual void OnChanged(EventArgs e)
    {
            if (Changed != null)
                Changed(this, e);
     }

    public override int Add(object value)
    {
        int i = base.Add(value);
         OnChanged(EventArgs.Empty);
        return i;
    }

    public override void Clear()
    {
        base.Clear();
        OnChanged(EventArgs.Empty);
    }

    public override object this[int index]
    {
        set
        {
            base[index] = value;
            OnChanged(EventArgs.Empty);
        }
    }
}

There is no delegate keyword being used explicitly and we just used EventHandler.

Internally, the EventHandler looks like as follows:

public delegate void EventHandler(object sender, EventArgs e);

So, to use the list we can do it the same way as previous post mentioned above:

static void Main(string[] args)
{
     ListWithChangedEvent list = new ListWithChangedEvent();
     list.Changed += ListChanged;
     list.Add("item 1");
     list.Clear();
     Console.ReadLine();
}

private static void ListChanged(object sender, EventArgs e)
{
     Console.WriteLine("This is called when the event fires without delegate.");
}

The list triggers event anytime the list items are changed.

Conclusion

So we saw a simple example of delegates usage using EventHandler. Using EventHandler helps us follow the .NET framework guidelines and adhere to the standard. It's good to know how the delegates work behind the scenes.

For future updates to my weekly blog, please subscribe to my blog via the "Subscribe To Weekly Post" feature at the right and follow me on Twitter. Until then Happy Coding :)


Reference: MSDN

Thursday, April 14, 2016

Events Using Delegates in C#

In today's blog post, I will be discussing a simple example of events in C#. We will be using delegates in this post to explain how events work.

Events

An event is a way to notify clients of the occurrence of something of interest to the clients. Events follow a publish-subscribe model. Any client that wants to listen to an event can subscribe to it and when the event occurs the client is notified.

Events in C#

Events Using Delegates

I discussed delegates some time back here. Let's look at an example of how we can implement events using delegates. Here we have an ArrayList which invokes an event called Changed whenever the contents of the list change.

public delegate void ChangedEventHandler(object sender, EventArgs e);

public class ListWithChangedEvent : ArrayList
{
    public event ChangedEventHandler Changed;
    protected virtual void OnChanged(EventArgs e)
    {
            if (Changed != null)
                Changed(this, e);
     }

    public override int Add(object value)
    {
        int i = base.Add(value);
         OnChanged(EventArgs.Empty);
        return i;
    }

    public override void Clear()
    {
        base.Clear();
        OnChanged(EventArgs.Empty);
    }

    public override object this[int index]
    {
        set
        {
            base[index] = value;
            OnChanged(EventArgs.Empty);
        }
    }
}

The delegate is declared first which decides the method signature which can be assigned to the delegate. Next, we declare the special type of list.
Inside the ListWithChangedEvent, first the event is declared. Next, the event is invoked. Inside the method, we check if Changed is not null to avoid null exception. That's a standard practice to avoid null exception while invoking events. Other than that, standard methods are exposed to interact with the List and change it's contents. Inside each of the method, note that the OnChanged event is fired.

Suppose, we want to output a line whenever the event is fired. So we simply have a method like this:

private static void ListChanged(object sender, EventArgs e)
{
      Console.WriteLine("Event Occurred. List Changed.");
}

And then in the Main method we create the list, add the handler to the Changed event. Then, we call the Add and Clear method on the list.

static void Main(string[] args)
{
       ListWithChangedEvent list = new ListWithChangedEvent();
       list.Changed += new ChangedEventHandler(ListChanged);
       list.Add("item 1");
       list.Clear();
       Console.ReadLine();
}

As a result, the event is fired twice, once each for Add and Clear methods.
So we get the output like this:

Event Occurred. List Changed.
Event Occurred. List Changed.


Conclusion

So we saw how to use events using delegates in this post. Events help us decouple our code so the invoking code doesn't need to know what happens when the event is occurred. The calling code itself (or any other part of the system) can decide what to do when the event is fired.  Next week, I will be discussing how to use events without using delegates explicitly.

For future updates to my weekly blog, please subscribe to my blog via the "Subscribe To Weekly Post" feature at the right and follow me on Twitter. Until then Happy Coding :)


Reference: MSDN

Thursday, April 7, 2016

Error & Exception Handling in C#

In today's blog post, I will be discussing error and exception handling in C#. We will also be discussing some new features of C# 6 for ways of exception handling.

Error & Exception Handling in C#

In order to make our application more resilient and robust, exception handling is inevitable. There could be several reasons for unforeseen errors in our application. Some times user might enter some bad data, some times some file may be missing, some times some server might be down, some times there might be division by zero and so on. If we don't have proper exception handling in place then our application might crash which certainly is not a nice user experience.

Try Catch Exception

If we have any potentially dangerous code which might throw exception, we can surround it by try block followed by a catch statement.
Here is a simple example:

try
{
       Console.WriteLine("Please Enter a number");
       var input = Console.ReadLine();
       var i = Convert.ToInt32(input);
       Console.WriteLine(String.Format("You entered number: {0}", i ));
}
catch (Exception e)
{
       Console.WriteLine("Number not valid.");
}
Console.ReadLine();

The code snippet asks user to input a number. If the number is valid then no exception is thrown. If the number is not valid, the code will throw an exception. Since we have a catch statement, we will get the output of number not being valid.

Here we had a generic exception handler which can handle any exception. If we want to have several exception handlers, each for several exception types, we can have those. We need to always have more specific exception type before less specific ones. These exception handlers are executed in order. As soon as the first match is found that catch block is executed.

Try Catch Finally

After the try block is executed, the catch exception block might be executed (if there was an exception), and then finally block is executed, if exists. The finally block is useful when we want to execute a block of code no matter if the exception occurred or not. This is useful if we open a file or database connection or something like that. We can close it as part of the finally block.

try
{
    //open connection
}
catch (Exception e)
{
    //handle exception
}
finally
{
    //close connection
}

Exception Filters

Suppose, we want to handle exception only if some specific condition satisfies. Otherwise, we don't want to handle the exception. Until C# 5, we had to do it this way:

try
{
      //Dangerous Code ;)
}
catch(Exception e)
{
     if(e.Message == "Message")
         //do something
     else
         throw;
}

So here we re-threw the exact same exception. The issue with this is that the stack trace is lost when we re-throw the exception. So we loose the information where the exception originally started.
In C# 6, we have exception filters which look like this:

try
{
      //Dangerous Code ;)
}
catch(Exception e) if(e.Message == "Message")
{
      //do something
}

This approach is much more cleaner and there is no re-throw of the exception, so no losing of stack trace.

Conclusion

Exception Handling is necessary for logging and better user experience. By examining these logs, we can improve the application performance too as exceptions generally slow down the application.

For future updates to my weekly blog, please subscribe to my blog via the "Subscribe To Weekly Post" feature at the right and follow me on Twitter. Until then Happy Coding :)

Thursday, March 31, 2016

Method Parameters in C#

In today's blog post, I will be discussing method parameters in C#. We will see the different ways in which parameters can be passed to methods in C#.

Method Parameters

Other than regular way in which we assign values to method parameters, there are a few tweaks which we can do to make our relationships with methods more useful.



Let's look at them one by one.

Optional Parameters

For any method, if we want the parameter(s) to have a default value, we can simply assign it like this:

public int Calc(int min, int max, int range = 100)
{
     \\...
}

So if any calling code passes a value for range, then that value is used. If we say Method1(1, 20, 200), then 200 is used for range's value. If we call Method1(1, 20) without any value for range, then range is used with value of 100.

This comes in handy when most of the time a default value is used but sometimes we need to pass in the value to be used for a specific parameter. We can have default values for any number of parameters, the only condition being that they come at the end after all non-default parameters.

Named Parameters

When we use our Calc() method in our code, every time we need to look at the method declaration to see the order of min, max and range. If we mess up the order while calling, we might get some wrong/ unexpected results. By using named parameters, we can assign the values for parameters based on their names instead of just the order.

So, for example, we can do:

Calc(max:20, range:80, min:1)

So this way we explicitly mention the variable name followed by the value assigned to each. This is useful to avoid any confusion which may happen when you have long list of parameters. Although, if you have a long list of parameters then you might have other issues with the code, but at least named parameters are easier to understand and less prone to error.
Another thing to keep in mind is that named arguments must appear after all fixed arguments have been specified.

Variable Number of parameters

When we want to give the caller code flexibility with the number of parameters to pass, we can use "params" keyword like this:

void VariableParamsMethod(params int[] array)
{
      foreach (var num in array)
      {
           Console.WriteLine(num);
      }
}

So here, I can call this method as :

VariableParamsMethod(1, 2);
OR

VariableParamsMethod(1, 2, 3);

I can pass in any number of int arguments and the method will work. Isn't it amazing? Internally, the compiler converts these values into array.
Also, I can pass in an integer array. That will also behave as expected.

var array = new int[4] { 1, 2, 3, 4 };

VariableParamsMethod(array);


This feature comes in handy when we want to have the flexibility of different number of parameters
to be passed.
Params can be combined with other parameters with the condition that it should be the last one and can be specified only once.

Out and Ref Parameters

When we call a method, the regular parameters are copied in the method. For value types (which I discussed here), the values are copied whereas for reference types the reference is copied, pointing to the same object in the heap.
If we want the called method to use the same variable instead of creating a separate copy, we can use the "ref" or "out" keyword.
Let's look at an example:

void OutRefMethod(out int i, ref int j)
{
     i = 5;
     j = 6;
}

So if we call the method:

int i = 1, j = 1;
OutRefMethod(out i, ref j);

At the caller side, "i" will be set to 5 and "j" will be set to 6.
This comes in handy when we want a single method to return multiple things. With ref and out parameters we can set them inside our method and retrieve at the calling side. The difference between ref and out parameter is that ref requires variable to be initialized before it is passed to the method whereas out requires the variable to be set some value inside the method. We need to mention the out and ref keywords both at method definition and method calling time to make sure that it's intentional.

Another thing to note is that if you see a lot of out and ref parameters then there might be other issues in the code (likely disobeying Single Responsibility Principle as discussed here).


Conclusion

With different types of parameters, methods can become more powerful. We can use these features as and when we need them.

For future updates to my weekly blog, please subscribe to my blog via the "Subscribe To Weekly Post" feature at the right and follow me on Twitter. Until then Happy Coding :)


Thursday, March 24, 2016

Namespaces in C#

In today's post, I will be discussing namespaces in C#. We will see how they are useful to us and some new features introduced in C# 6.

Namespace in C#

Namespaces are great for organizing classes into separate chunks. The .NET framework itself uses namespaces to organize it's huge number of classes. Even we can use namespaces to organize our classes in any fairly large project.

Namespace in C#


Using Directive

In order to access any class, we can use fully qualified name. For example,

System.Console.WriteLine("Hello World");

Or, we can access any namespace in our program using "using" directive. So if we have

using System;

at the top, then we can skip the word "System" and write our line as follows:

Console.WriteLine("Hello World");

Mostly, people prefer to write this way as it's shorter and less cluttered. In some cases, people like to write fully qualified names in order to avoid any confusion.


Namespace keyword

We can define namespace using "namespace" keyword.

namespace ns1
{
        public class cl1
        {
        }
}

namespace ns2
{
        public class cl2
        {
        }
}

In our main() method, we can use them like this:

   ns1.cl1 obj1 = new ns1.cl1();

   ns2.cl2 obj2 = new ns2.cl2();

Or use using keyword as explained above.

Namespace Alias

May times, if we have same class name in multiple namespaces and we are using both namespaces in the same file, the compiler might get confused which class are we trying to use. We can avoid such a scenario (called namespace collision) either by using fully qualified name as shown above or by using an alias like this:

using a1 = ns1.cl1;

So now we can use this alias to define our object like this:

a1 obj1 = new a1();

Static Using Directive

Since C# 6 onwards, we can use "using static" for static classes. This helps us to write only the method names directly. For example, if we use

using static System.Console;

I can directly use WriteLine() method like this:

WriteLine("Hello World");

instead of using Console.WriteLine() everywhere. So, this helps us write less cluttered code and quicker development :)

Conclusion

Namespaces are a great way for organizing our code into a more manageable manner. Having a good understanding of how to use it makes the code easy to read and understand.

For future updates to my weekly blog, please subscribe to my blog via the "Subscribe To Weekly Post" feature at the right and follow me on Twitter. Until then Happy Coding :)


Thursday, March 17, 2016

Properties in C#

In today's blog post, I will be discussing the properties in C#. We will see how properties are useful and are a great time saving feature for us.

Properties in C#

Properties are simply like the getters and setters methods which allow us to control the value being set/ read of a private variable in a class. They let you access the property as if it was a field but in reality they are special methods called accessors.

Properties in C#


In order to better understand their importance, let's look at the way we would have written some code if properties hadn't existed.


public class Employee 
{       private int employeeId;        public int GetEmployeeId()        {              return employeeId;        }        public void SetEmployeeID(int id)        {              employeeId = id;        }  }
If we had multiple properties, imagine how the lines of code would have grown.

Since properties exist, we can write it like this:

public class Employee 
{       private int employeeId;      public int EmloyeeId      {            get            {                  return employeeId;           }
          set            {                   employeeId = value;            }
      }  }


And since our accessors do not require any special logic for get and set, we can use auto-implemented properties like this:


public class Employee 
{            public int EmployeeId  {get; set;}  }

So all that lines of code are replaced by only one line as seen. This is so helpful to the developers and we use it all the time without even giving it much thought that how our task is made so much easier by the properties.

So there are two accessors: get and set. As expected, get is used to read the value of a variable and set is used to write the value. Both get and set can have different accessibility levels. If the property has only get accessor then it's a read-only property.
In the case of auto implemented properties, compiler creates a private and anonymous backing field that can be accessed only through property's get and set accessor.

Another thing worth mentioning is that from C# 6 onwards, auto-implemented properties can also have default values. Earlier, if we needed a default value, we had to manually write the code for properties accessors. But now it can be done like this:

public class Employee 
{ 
     public int EmployeeId {get; set;} = 1; 
}


So, here the default value is 1.

Conclusion

Properties help us developers to write our code quickly and efficiently. We should take full advantage of the properties instead of manually writing old style way of getters and setters. And we should thank the compiler for generating so much code for us when we use auto-implemented properties ;)

For future updates to my weekly blog, please subscribe to my blog via the "Subscribe To Weekly Post" feature at the right and follow me on Twitter. Until then Happy Coding :)


Thursday, March 10, 2016

Struct vs Class in C#

In today's blog post, we will be discussing the differences between struct and class in C#.

Struct Vs Class

Struct and Class are both constructs of the common type system in the .NET framework. Both are used to encapsulate data and behavior as a logical unit. While declaring, both look similar, except they keyword "struct" and "class" :)


Struct vs Class in C#

The major difference between struct and class is that class is a reference type and struct is a value type.  I have talked about reference vs value type before here.

A reference type is allocated on heap. It's garbage collected at frequent intervals (will cover garbage collection in another post). When a new variable is created pointing to such an existing object, no new object is created. The new reference points to the same object. So any changes made to the object using one reference is visible on the other because the underlying object is the same.

A value type is allocated on the stack. Value type is deallocated when the stack unwinds or when their containing type gets deallocated. The variable which defines the struct actually holds the data itself. When a new variable is assigned to an existing struct, a new copy of data is created and held by the new variable. So changes made to one copy are not reflected by the other.

In general, structs are limited as compared to classes. Here are some of the other differences:

  • In a struct, the fields cannot be initialized (except const or static).
  • There can be no default constructor (parameter-less constructor) or a destructor in a struct. However, structs can have constructor(s) with parameter(s).
  • Struct can be instantiated without the new operator.
  • A struct can not inherit from another struct or class. However, a struct can implement interfaces.

Conclusion

Although, most of the times, we lean towards classes as compared to structs. Classes give us more power and ease of use. Mostly people use structs for small and light-weight data.  However, it's still important to understand the difference between the two and use the right thing accordingly.

For future updates to my weekly blog, please subscribe to my blog via the "Subscribe To Weekly Post" feature at the right and follow me on Twitter. Until then Happy Coding :)


Thursday, March 3, 2016

Access Modifiers in C#

In today's blog post, I will be discussing the various access modifiers available in C#.

ACCESS MODIFIERS

The access modifiers help decide the accessibility levels of the members or types. They are the first step to learning object oriented programming. With appropriate access modifiers , we decide what is exposed and what is hidden from other parts of the code.

Access Modifiers in C#


There are 4 access modifiers:
i) Public: These is the one with least restriction. These are available for access from anywhere outside.

ii) Private: This makes sure that access is available only within the containing type. These are not available outside.

iii) Protected: Using this keyword, access is limited to containing class or any class inheriting from this.

iv) Internal: Access is limited to the current assembly. Within the assembly it can be accessed anywhere.


Protected Internal:
There is one more access modifier which is a combination of protected and internal. In my opinion, it's a little weird, because when I think of something as protected internal, I used to assume an "AND" condition between protected and internal. I thought that it should be accessible within the assembly and only containing type and derived types within the assembly should be able to access it.
But, the reality is, it's a more forgiving "OR" condition between protected and internal. So it can be accessed from anywhere within the assembly and also any derived class can also access it, even if it's outside the assembly.


Accessibility for Types

Depending on where the type or member is declared, it can be associated with different accessibility levels. If none is specified then there is a default accessibility associated.
i) Top level types: Top level types can only have internal or public accessibility. The default is internal for them.
ii) Enum: Enum members are always by default public. There is no access modifier allowed for enum members.

iii) Class: A class members can have any of the above five access modifiers associated. If no access modifiers is provided, by default, the class members are private.

iv) Interface: An interface members are always by default public. There is no access modifier allowed for interface members.

v) Struct: A struct members are by default private. They can also have public or internal access modifier.

Access modifiers are not allowed on namespaces. They are allowed only on the types mentioned above.

Conclusion

These access modifiers lay the foundation of our object oriented programming and therefore are very important to understand. Different accessibility levels allow us to expose the correct amount of functionality which is really important for security and maintainability of the application.

For future updates to my weekly blog, please subscribe to my blog via the "Subscribe To Weekly Post" feature at the right and follow me on Twitter. Until then Happy Coding :)

Thursday, February 18, 2016

Object Class in .NET

In today's blog post, we will be discussing the System.Object class in .NET framework.

Object Class

Object class is the ultimate base class of all classes in the .NET framework. Whether its a reference type or value type or any custom type we define, all types inherit from Object class.


Objects in .NET
Since Object class is the universal base class, the methods defined in the Object class are available in every object in the system.

Here are the methods in the object class:

i) public Object() Constructor: This method is called when an object is created.

ii) public static bool Equals(Object objA, Object objB): static method to compare two objects. This method determines whether the specified object instances are considered equal.

iii) protected Object MemberwiseClone(): creates a shallow copy of the current object.

iv) public static bool ReferenceEquals(Object objA, Object objB): static method to check whether specified object instances are the same instance.

v) public Type GetType(): gets the Type of the current object.

vi) protected Object MemberwiseClone(): returns a shallow copy of the object by copying its members.


And here are some of the methods that one can override:
vii) public virtual bool Equals(Object obj): specifies whether the specified object is equal to the current object.

viii) public virtual int GetHashCode(): it returns the hash using the default algorithm. It should be overridden if needed depending on object's contents.

ix) public virtual string ToString(): returns the string representation of the object. For an object, it just returns the type name by default. It should be overridden based on object contents and usage.

x) Finalize(): it can be used to perform clean up operations before it is reclaimed by garbage collection.

Another reason why Object base class matters

Since every class has a base class of Object, we can use the Object type in collections or method parameters to accept any object. For example, if we say:

List<Object> objList;

it can accept List of any object types.

OR

Method1(Object obj);

it can accept any object as the parameter.

In both the cases, any object can be used but there might be added cost of boxing and unboxing involved. That can lead to performance problems.
For the latter case, if we want a variety of objects to be handled by the method, we can create overloads of the method with specific object types while keeping the Object parameter overload as well. In that case, if an exact match is found, it's used, otherwise, the method with Object parameter is used.
Another way to avoid the boxing and unboxing performance issue is to use generics. I have talked about Generics previously here.

Conclusion

Since object class is a universal base class, it's important to understand the methods available to us. These methods are available to us in all the objects and we can override some of them to implement the functionality we need. Also, while using it in methods or collections can be useful to us, we need to consider the performance cost that might come along.

For future updates to my weekly blog, please subscribe to my blog via the "Subscribe To Weekly Post" feature at the right and follow me on Twitter. Until then Happy Coding :)



Thursday, January 14, 2016

Abstract Class Vs Interface in C#

In today's blog post, I will be discussing a very common interview question i.e. the difference between abstract class and interfaces in C#.

Abstract Class

Any class declared with abstract keyword becomes an abstract class. They are used  to define a contract but when we want to have some default behavior associated with the hierarchy.

Interface

An interface is defined using the interface keyword. Interfaces are used to define a contract and when we do not want to associate any default behavior with the hierarchy of classes.

Abstract Class Vs Interface in C#


So both of them are used to define contract and are important to understand in order for us to use them in our code properly. Let's look at the differences one by one.

Abstract Class can have implementation for some of its members which exists as the default behavior for the hierarchy. The interface can't have implementation for any of it's members. This is the most important difference between the two and guides our choice most of the time when deciding between the two.

The next difference is that interfaces are limited in terms of hierarchy in the sense that an interface  can inherit from interface only. As compared to that, abstract class can inherit from abstract class as well as interface.

Another difference is that abstract class can have fields whereas an interface can not have any fields. Interface can only have methods.

Another really important difference is that a class can inherit from multiple interfaces simultaneously whereas a class cannot inherit from multiple classes at same time.

And lastly, the interface members cannot have access modifiers. Everything is public by default.
Abstract class members can have access modifiers like public, private, etc.

Conclusion

It's one of the most common interview question and still I wonder why so many people get it wrong in their interviews. These differences are important to understand when to use which one. In general, when multiple entities in the system share common behavior then we might use abstract classes. If we just want the entities to follow a contract and not provide any default implementation then we are better with an interface.
For future updates to my weekly blog, please subscribe to my blog via the "Subscribe To Weekly Post" feature at the right and follow me on Twitter. Until then Happy Coding :)


Friday, January 1, 2016

var keyword in C#

In today's blog post we will be discussing the var keyword in C#.

var Keyword

var keyword was introduced in C# 3.0. It is used for implicitly typed local variables. In any statement, if the compiler can decide the data type of the variable with no confusion, we can use the var keyword.


var keyword C#


For example,

var i = 12;       // will work

var j;   // will not work
j = 12;  //implicitly typed variables must be initialized

Since data type of variable j cannot be determined at the time of declaration, it won't compile and we can't use var keyword.

Another thing to note is that with the usage of the var type, the data type is fixed in the initialization statement itself. If we hover the mouse on the var keyword, we can see the data type that compiler is assigning the variable. We should not confuse it thinking that it's a dynamic type. In the first statement itself, the data type is fixed and we can't change the data type dynamically for the variable.

These two statements below are completely equivalent.,

var i = 12;   //implicit declaration

int i = 12;    //explicit declaration

They both produce the exact same IL code. That means that there is no performance effect with the usage of var keyword.

Why use var

Usage of var is more of a syntactic sugar. It makes the code a little shorter and mostly easier to read. For example, if we have some code like this:

ImageThumbnail thumbnail = new ImageThumbnail();


We can write it as:

var thumbnail = new ImageThumbnail();


This helps us remove a small part of the redundant code from the statement and thus reduce code noise.

Another and more important benefit of the var keyword is with anonymous types. So when we want to use an object without going through the hassle of declaring it's class (might make sense if we need to use that object only once), we can use this. For example,

var anonymousObject = new { Id = 1, Name = "Abhi" };

Console.WriteLine(anonymousObject.Name);


So here usage of var prevented me the hassle of creating a new class with 2 properties i.e. Id, Name.

Similarly, another common place where we use anonymous types is while using LINQ:
For example,

var p = from employee in employees
             where employee.Id == 1
             select new { employee.FirstName, employee.LastName };

So here the variable p is IEnumerable<> of anonymous type. Again, usage of var prevented me the hassle of creating a new class which I might not need else where in the code.

When to avoid var

Personally, I prefer to use var when it let's me reduce a few words of redundant code as we discussed earlier in the post. However, I don't like to use it where the data type might be unclear. For example,

var t = SomeMethod();


Here the method name is not telling me what it's returning. So I need to look at the method signature to determine what the data type of my variable is, which makes it less favorable to me. The compiler won't stop you from using it like this, it's a matter of personal preference and readability of the code.

Conclusion

So we saw how var keyword is only a syntactic sugar and does not lead to any performance difference. I use var for anonymous types as well as reducing a few words in the code, wherever possible.

For future updates to my weekly blog, please subscribe to my blog via the "Subscribe To Weekly Post" feature at the right and follow me on Twitter. Until then Happy Coding :)