Abhi Jain's .NET Blog

This is a blog where I try to describe the lessons that I learn on my journey on .NET. My aim here is to spread the knowledge that I gain which will help all of us to be a better developer. In this blog I will explain the books, other articles as well as my own experiences which I go through everyday and hope everybody benefits from them.

Sunday, May 20, 2018

NON-NULLABLE Reference Types

In today's blog post, I will be discussing one of the new & exciting feature of upcoming C#8. The work is currently under way. This is more of a sneak preview :)

Currently, whenever we have a reference type, it's always nullable by default. If I don't assign any value to a reference type, it defaults to null. Furthermore, as a programmer, there is no way to specify that for this specific reference, I want to disallow nulls. As a result, these nulls do sneak into our applications and cause the famous Null reference exceptions. Tony Hoare, the guy who invented Null, called it his billion dollar mistake. I am pretty sure, it has costed more than that by now!

This feature attempt is to reduce these null reference exceptions. The biggest hurdle is, if C# 8 disallows nulls on reference types completely, then it's not backward compatible. So this feature is going to be an opt-in feature. The idea is that slowly people will adopt this feature and as more and more code becomes compatible to this feature, they can completely turn off the switch for default nulls sometime in future.

The feature will provide the ability to the programmer to make the decision consciously whether to allow nulls or not to reference types, similar to the way we do it for primitive types. For e.g. when I say

int? x; // explicitly nullable

If I don't put "?" then nulls are disallowed.

So using similar syntax, the plan is, if you opt in the feature for not allowing reference types to be null, then any code like this will throw a warning:

string str = null; //Warning

Now, to fix this, you have 2 options:
Either, you will have to explicitly make it nullable like this:

string? str = null;

OR

Assign it something other than null and expect that null will never be assigned to this reference.

string str = "text";

This way you are consciously making decision of allowing or disallowing nulls for these reference types too.

With that said, with the last syntax above, there are ways to still assign nulls to this reference indirectly at run time and still get Null reference exception. Not everything can be known at compile time. But the idea is that the exception will become less common.

CONCLUSION

I think this a great step by C# team to improve the code quality and reduce the number of run time exceptions. With each and every version, the C# language is moving towards better. Happy coding :)

Saturday, December 3, 2016

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 :)Follow @abhijain369

Thursday, November 10, 2016

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).

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.

Thursday, November 3, 2016

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.

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.

Thursday, October 27, 2016

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.

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 :)Follow @abhijain369

Thursday, October 20, 2016

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".

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.

Thursday, June 2, 2016

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.

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

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 :)Follow @abhijain369