Category: Interview questions

State design patterns, when to use, pros and cons

The state design scheme is used to model changes in the state or state of an object by delegating the rules for such changes to individual objects representing each possible state.

When we should use the state model?

The state model is a good candidate to apply when you have an object with a relatively complex set of possible states, with many different business rules on how state transitions occur and what should happen when the state changes.

If the object is merely a state-owned property, at any time, any state can be updated with at least special logic, the State Schema increases needless complication. However, for the objects representing the real world concepts, with a compound workflow, the state structure can be a decent option.

What are the Advantages of using this model?

The state model minimizes conditional complexity, eliminating the need for if and switch statements on objects that have different behavioral requirements that are unique to different state transitions. If you can represent the state of the object using a finite state machine diagram, it is easy enough to convert the diagram into the types and methods of the state design model.

What are the Disadvantages of using this model?

The state schema requires a large amount of code to be written. Depending on the number of different defined state transition methods and how many possible states an object can have, you can quickly write dozens or more different methods. For N states with M transition methods, the total number of methods required will be (N + 1) * M. In the previous example for an insurance policy, there are 5 different states, each of which must define 5 methods (ignoring for the moment the ListValidOperations method), for a total of 25 methods in the state types. Thus, the type of policy context must also define the 5 methods of state transition, for a total of 30 methods to be written.


Domain model in Domain driven design

Hello everyone, In this article, we will focus on the Domain model an foundation of Domain Driven Design.

Domain Model is a term you will hear a ton of Domain Driven Design. I think Domain Model is a standout amongst the clearest cases of phrasing that implies literally nothing unless you comprehend the setting to which it applies.

In the present article, we will take a gander at what Domain Model really implies, why it is critical and how to utilize it in the setting of your improvement ventures.

The Domain is the problem

Domain Driven Design is predicated around taking care of the issues associations look through the code. This is accomplished by centering the speculation of assets into the core of the business rationale of the application.

The area in this way is the universe of the business. At whatever point you hear the expression “Area Driven Design”, you should consider it “Business Problem Driven Design”.

The area is the universe of the business you are working with and the issues they need to explain. This will ordinarily include standards, forms and existing frameworks that should be incorporated as a feature of your answer.

Space is the thoughts, information, and information on the issue you are attempting to settle. Most organizations will have terms that include particular significance inside the setting of their association. They will likewise likely have measurements, objectives, and destinations that are one of a kind to their business.

The Model is your solution

The Model of a Domain Driven Designed task is your answer to the issue.The Model more often than not speaks to a part of reality or something of intrigue. The Model is additionally frequently a disentanglement of the master plan thus the essential parts of the arrangement are focused on while everything else is disregarded.

This implies your Model ought to be engaged learning about a particular issue that is disentangled and organized to give an answer.

The Domain Model

So if the Domain is the world of the business, and the Model is your solution, what is the Domain, Model?

The Domain Model is your composed and organized information of the issue. The Domain Model ought to speak to the vocabulary and key ideas of the issue area and it ought to distinguish the connections among the greater part of the elements inside the extent of the space.

The Domain Model itself could be an outline, code cases or even composed documentation of the issue. The critical thing is, the Domain Model ought to be available and justifiable by everybody who is included in the venture.

The Domain Model ought to likewise characterize the vocabulary around the undertaking and should go about as a specialized instrument for everybody included. The Ubiquitous Language is a critical idea in Domain Driven Design thus it ought to be specifically gotten from the Domain Model.

One of the destructions of numerous product improvement ventures is the misconception of terms, targets and proposed arrangements that are checked toward the start of advancement.

The Domain Model should go about as a reasonable portrayal of the issue that is being comprehended and the proposed arrangement. It is critical that all partners of the task add to the Domain Model with the goal that everybody comprehends the key ideas and meanings of the vocabulary of the venture and how the issue is being handled and tackled.

Alternatives ORM for Entity Framework


Entity Framework has come a long way since version 1. So much that it leapfrogged every other version up to version 7.

With EF Core 2 out, I feel this gives us the performance and versatility we need for faster data access.

Keep in mind, I’m not saying all of these are recommended, I’m merely including them as top ORMs I’ve found in the .NET community as possible replacements for EF.


Dapper was built by the StackExchange group. This ORM delivers amazing results since it leverages ADO.NET.

To give you an idea of the performance, Matthew Jones from conducted a performance benchmark between Dapper, Entity Framework, and ADO.NET. His benchmark shows Dapper delivering exceptional performance over Entity Framework and narrowly edges out even ADO.NET.

While the performance is worthy, the technique of getting the data reminds me of the old days of retrieving data.

Here is a code example from their GitHub page:

public class Dog
     public int? Age { get; set; }
     public Guid Id { get; set; }
     public string Name { get; set; }
     public float? Weight { get; set; }
     public int IgnoredProperty { get { return 1; } }

var guid = Guid.NewGuid();
var dog = connection.Query("
                    select Age = @Age, Id = @Id", 
                          new { Age = (int?)null, Id = guid });
Assert.Equal(guid, dog.First().Id);

As you can see, it uses inline SQL to pull back the record and map it. The only thing missing is the left-to-right assignment.

Their GitHub page has a lot of examples like this.


nHibernate (introduced in 2007) is one of the oldest and most stable ORMs around and has been around longer than Entity Framework (introduced in 2008).

Most companies run their entire data access on NHibernate and are one of the most stable ORM frameworks around.

I’ve heard tales of woe and tales of wonder with this product. It has a number of ways to configure your mappings whether it be in code or through XML.

While I’ve never worked with the product, it’s definitely vast in its configuration settings making it quite versatile.

Example Code:

//Add a Customer to the datastore

//'sessionFactory' is a thread-safe object 
  built once per application lifetime (can take seconds to build)

//based on configuration files which control 
       how database tables are mapped to C# objects

//(e.g. which property maps to which column in a database table)


//'session' is not thread safe and fast to obtain 
      and can be thought of as a connection to the database

using (var session = sessionFactory.OpenSession()) 
   //transaction represents a db transaction
   using (ITransaction transaction = session.BeginTransaction()) 

       //The line below adds the customer to NHibernate's list 
              of objects to insert to the database

       //but it doesn't execute SQL insert command at this stage*.

      //*if the Id field is generated by the database 
         (e.g. an auto-incremented number)

      //then NHibernate will execute SQL INSERT when .Save is called

      session.Save(new Customer 
                    Id = Guid.NewGuid(), 
                    FirstName = "Boss", 
                    Age = 50 

     //The call below will execute the 
          SQL INSERT and commit the transaction



//Retrieve the Customer from the database, modify 
       the record and update the database

using (var session = sessionFactory.OpenSession())
   using (ITransaction transaction = session.BeginTransaction()) 
       //session's Query returns IQueryable.
       //Only when .FirstOrDefault is called will NHibernate 
           execute the SQL query
       Customer customer = session.Query()
                                   .Where(c =>c.Token == token )
       //Now the customer is 'part of' the 'session' object 
            and NHibernate keeps track of changes
       //made to it
        if( customer != null ) 
           //Changing a property of an object does NOT cause SQL 
              to be executed
            customer.TokenVerified = true;
            //Committing the transaction results in an SQL UPDATE 
            //NHibernate kept track of the fact that 'customer' 
               has been changed since loading


Replacing the SQL statements with LINQ makes this example better in my opinion.

Why just two?

When examining the landscape of ORMs, I referred to a wiki page listing of object-relational mapping software for.NET.

Now, I don’t want to alarm anyone, but after looking through this list of ORMs, I realized that 75% of them were names I’ve never heard of, don’t exist, or aren’t active.

I tried to remember some ORMs my colleagues used in the past. I remember the majority mentioning Entity Framework and NHibernate as their tool of choice with Dapper being the new guy on the block. In that order.

Even though Dapper is new, I couldn’t find any other mature, solid, stable, or popular ORMs

Multiple Ways to Build Routing in ASP.NET Core


Routing in Microsoft MVC or WebAPI applications serves as a map to define the routes for all incoming requests. There are three basic components of routing in MVC , WebAPI applications Controller, Action method, and parameters.


In the provided link account is a controller, login is action method and 24 is parameter or query string.

Let’s review the different ways to build routing in ASP.NET CORE.

Creating Default Routes

By convention in your project’startup class, the default route can be defined.

public class Startup
   public void ConfigureServices(IServiceCollection services)

   public void Configure(IApplicationBuilder app, 
                         IHostingEnvironment env, 
                         ILoggerFactory loggerFactory)

      app.UseMvc(routes =>

                         name: "default",
                         template: "



We need to be sure that essential configuration for MVC pattern of Controller + Action + ID route, exist in our project. Routing pattern can also be declared like: 

    name: "default_route",
    template: "{controller}/{action}/{id?}",
    defaults: new { controller = "Home", action = "Index" }

Extending Default Routes

On specific needs, Default Route can be extended by adding customized routes. By MapRoute() method, configurations can be added:

app.UseMvc(routes =>
    //New Route
       name: "about-route",
       template: "about",
       defaults: new { controller = "Home", action = "About" }

       name: "default",
       template: "{controller=Home}/{action=Index}/{id?}");

On the Home controller, Adding extra route allows access to About action with an/about the route. About page can be still accessed with conventional /home/about the route, as the default pattern route is still present.

Using Attributes

Using attributes in controller and actions, you can also configure routes.

public class AnalyticsController: Controller

    public IActionResult Index()
        return View();

    public IActionResult Charts()
        return View();

Now, controller actions can be accessed through the following routes:

  • /Analytics/Dashboard
  • /Analytics/Charts

Two tokens [controller] and [action] indicate that we have to refer to the controller and action name that has been declared. In this case, “Analytics” is the name of the controller, and “Charts” the name of the action, therefore it the name of the route.

Building RESTful Routes

We need to use the following route configuration, to declare a RESTful controller. 

public class ValuesController : Controller
    // GET api/values
    public IEnumerable Get()
        return new string[] {"hello", "world!"};

    // POST api/values
    public void PostCreate([FromBody] string value)



Here, RESTful service is told to accept calls under the /api/values route. Now, we do not use the Route attribute for actions. Instead, we decorate it with HttpGet, HttpPost, HttpPut, HttpDelete attributes

LINQ Standard Query Operators


LINQ standard query operators are the methods which help you to write LINQ query. Most of these query methods operate on sequences or collection whose implement the IEnumerable interface or the IQueryable interface. These operators provide query capabilities including filtering, projection, aggregation, sorting and much more.

LINQ Standard Query Operators Sets

LINQ provides two sets of standard query operators, one set operates on objects of type IEnumerable and the other set operates on objects of type IQueryable. Also, these query methods (standard query operators) are static members of the Enumerable and Queryable static classes They are defined as extension methods of the type on which they operate. Hence, they are called either by using static method syntax or instance method syntax.

The query methods which are extended from IEnumerable, operate on in-memory collections. The query methods which are extended from IQueryable, operate on out-of-process memory collections and build an expression tree that represents the query to be performed.

Example for LINQ Query Method Where() Sets

In LINQ to Objects (in-memory collection), LINQ query methods would be used as an anonymous method, like Where():

public static IEnumerable Where(

this IEnumerable source, Func<TSource, bool> predicate)

While in LINQ to SQL (out-memory collection), mostly LINQ query methods would be used as the expression tree, like Where():

LINQ Query Method Execution

public static IQueryable Where(

this IQueryable source, Expression<Func<TSource, bool>> predicate)

The standard query operators are executed based on the value they return. The query methods that return a singleton value (like Average, Sum, Min, Max etc.) then execute immediately. The query methods that return a sequence or collection defer the query execution. The query methods can be chained together in one query.

Writing LINQ Query with the help of Standard Query Operators (LINQ Query Methods)

string sentence = "The quick brown fox jumps over the lazy dog";


// Split the string into individual words to create a collection.

string[] words = sentence.Split(' ');


// Using query expression syntax.

var query = from word in words

group word.ToUpper() by word.Length into gr

orderby gr.Key

select new { Length = gr.Key, Words = gr };


//You can also write above query by using method-based query syntax.

var query1 = words.

GroupBy(w => w.Length, w => w.ToUpper()).

Select(g => new { Length = g.Key, Words = g }).

OrderBy(o => o.Length);


//use either query or query1 variable to get result

foreach (var obj in query)


Console.WriteLine("\n Words of length {0}:", obj.Length);

foreach (string word in obj.Words)


  1. Words of length 3:

  2. THE

  3. FOX

  4. THE

  5. DOG

  6. Words of length 4:

  7. OVER

  8. LAZY

  9. Words of length 5:

  10. QUICK

  11. BROWN

  12. JUMPS

  13. */