Tech Point Fundamentals

Friday, April 1, 2022

Design Patterns Interview Questions - Part 05

Design Patterns Interview Questions and Answers - Part 05


In Software Industry the Design Patterns and Principles are always followed. So this is the most common topic for the interview. In this article, we will see the most frequently asked 90+ Design Patterns and Principles Interview Questions with Answers

Please visit our YouTube Channel for Interviews and other videos by below link:

Please read the complete C# Interview Questions and Answers article series here.


This is the 5th part of this Design Patterns and Principles Interview Questions and Answers article series. Each part contains five Design Pattern Interview Questions. Please read all the Design Patterns and Principles Interview Questions list here.

I will highly recommend to please read the previous parts over here before continuing the current part:

Design Patterns Interview Questions - Part 05

Q33. What is CQRS or CQS Architectural Pattern?

CQRS stands for Command and Query Responsibility Segregation. CQRS is a pattern that separates read and update operations for a data store. The related term Command Query Separation (CQS) was originally defined by Bertrand Meyer in his book Object-Oriented Software Construction. 

CQRS is an architectural pattern that separates the models for reading and writing data. CQRS means having two objects for a read/write operation. CQRS separates reads and writes into different models, using commands to update data, and queries to read data. The basic idea is that you can divide a system's operations into two sharply separated categories:

  1. Queries: These queries return a result and do not change the state of the system, and they are free of side effects.
  2. Commands: These commands change the state of a system.

There are reasons to have a denormalized reads database. Implementing CQRS in your application can maximize its performance, scalability, and security. Having separate query and update models simplifies the design and implementation. For greater isolation, you can physically separate the read data from the write data. In that case, the read database can use its own data schema that is optimized for queries.

However, one disadvantage is that CQRS code can't automatically be generated from a database schema using scaffolding mechanisms such as O/RM tools. Separation of the read and write stores also allows each to be scaled appropriately to match the load. 

The flexibility created by migrating to CQRS allows a system to better evolve over time and prevents update commands from causing merge conflicts at the domain level. CQRS stands for Command Query Responsibility Segregation. 

Advantages of CQRS:

  1. CQRS allows the read and write workloads to scale independently, and may result in fewer lock contentions.
  2. CQRS optimized data schema because the read side can use a schema that is optimized for queries, while the write side uses a schema that is optimized for updates.
  3. CQRS also ensures better security because it is easier to ensure that only the right domain entities are performing writes on the data.
  4. CQRS follows the separation of concerns because segregating the read and write sides can result in models that are more maintainable and flexible.
  5. CQRS simplifies the SQL queries as well because by storing a materialized view in the read database, the application can avoid complex joins when querying.

Q34. What is Domain-Driven Design (DDD) Pattern?

In software, the term domain refers to business. The domain is the area of knowledge around which application logic revolves. The domain or business logic of an application is a set of rules and guidelines that explain how the business objects should interact with each other to process modeled data.

Domain-Driven Design is a concept introduced by Eric Evans in 2004 in his book "Domain-Driven Design: Tackling Complexity in Heart of Software". It is an approach for architecting software design by looking at software in a top-down approach.

Domain-Driven Design is an approach to software development that centers the development on programming a domain model that has a rich understanding of the processes and rules of a domain.

DDD talks about problems as domains. DDD patterns help you understand the complexity in the domain. Domain-driven design recognizes multiple kinds of models. In domain-driven design, the domain layer is one of the common layers in an object-oriented multilayered architecture.

A software's domain governs its context, the setting in which a word or statement appears that determines its meaning. From this, developers build a domain model: a system of abstractions that describes selected aspects of a domain and can be used to solve problems related to that domain. 

There are three layers in a DDD pattern:

Domain Model Layer: The domain model layer is where the business is expressed. It is responsible for representing concepts of the business, information about the business situation, and business rules. State that reflects the business situation is controlled and used here, even though the technical details of storing it are delegated to the infrastructure.

Application Layer: This layer defines the jobs the software is supposed to do and directs the expressive domain objects to work out problems. This layer is necessary for interaction with the application layers of other systems. It does not contain business rules or knowledge, but only coordinates tasks and delegates work to collaborations of domain objects in the next layer down. It does not have a state reflecting the business situation, but it can have a state that reflects the progress of a task for the user or the program.

Infrastructure Layer: The infrastructure layer is how the data that is initially held in domain entities (in memory) is persisted in databases or another persistent store. 

Q35. What is ORM Pattern? What are the different available ORM Patterns?

The ORM stands for Object Relational Mapping. The ORM in computer science is a programming technique for converting data between incompatible type systems using object-oriented programming languages. This creates a "virtual object database" that can be used from within the programming language.

So ORM is a design pattern for converting (wrapping) the data stored within a relational database into an object that can be used within an object-oriented language. ORM is a design pattern of accessing a relational database from an object-oriented language.

Compared to traditional techniques of exchange between an object-oriented language and a relational database, ORM often reduces the amount of code that needs to be written.

Below is a simple query written in C# code to execute in SQL using a database engine:

var sqlQuery = "SELECT id, first_name, last_name, phone FROM persons WHERE id = 101";
var result = context.Persons.FromSqlRaw(sql).ToList();
var firstName = result[0]["first_name"];

You can write the same query using ORM in one line:

var person = repository.GetPerson(101);
var firstName = person.GetFirstName();

Anatomy Features of ORM:

The ORM usually follows some useful patterns internally which provide a lot of benefits:

Table Data Gateway:  It is an object that represents a table of the database. It is usually built as a generic class that can be subclassed or instantiated for any physical table.

Active Record: It transforms a row of a table into an object. It strictly couples the object structures to the database tables by making the domain object subclassing an abstract implementation.

Data Mapper: A real ORM is an instance of a Data Mapper, a tool that stores objects which are ignorant of the environment where they will be kept, thus decoupling them from persistence concerns.

Unit Of Work: UoW maintains a list of dirty objects and writes out the changeset. The purpose of this object is to keep track of modified data on the entity object that it knows and its flushing capabilities substitute the save() method of the Active Record implementations. 

Repository: The persistent-ignorant equivalent of the Table Data Gateway. While a single repository implementation is aware of the database backend, a generic interface is placed between service classes and object retrieval mechanisms to aid decoupling.

Identity Map: A map of objects organized by class and primary key. It is a first-level cache that contains every initialized object, so it can be used to prepare a changeset of database queries on flushing.

Lazy Loading: Substituting a domain object or collection with a subclass that loads data on the fly when methods are requested, before forwarding the original call.

Query Object: A class that represents a query for retrieving objects, encapsulating SQL or other high-level languages.

Criteria Object: A class that represents a set of criteria for the selection of objects of a particular model.

Table Inheritance: A pattern implemented to represent class inheritance in relational tables. 

ORM Pattern Example:

  1. Entity Framework for .Net
  2. Hibernate for Java
  3. Ruby on Rails
  4. Doctrine for PHP
  5. Laravel’s Eloquent
  6. Symfony (Propel)
  7. Django’s ORM
  8. Sqlalchemy for Python
  9. Yii Active Record

Disadvantages of ORM Pattern:

Disadvantages of ORM tools generally stem from the high level of abstraction obscuring what is actually happening in the implementation code.  

However, some critics say that ORM is an anti-pattern as well because it violates all principles of object-oriented programming.

Q36. What is the Unit of Work  (UoW) Pattern?

The Unit of Work Pattern is a pattern that handles the transactions during data manipulation using the Repository Pattern. Unit of Work is referred to as a single transaction that involves multiple operations.

An UoW pattern maintains a list of objects affected by a business transaction and coordinates the writing out of changes and the resolution of concurrency problems. It prevents too many DB connections and transactions, instead, all the operations of a transaction are executed at once.

When you're pulling data in and out of a database, it's important to keep track of what you've changed; otherwise, that data won't be written back into the database. Similarly, you have to insert new objects you create and remove any objects you delete.

You can change the database with each change to your object model, but this can lead to lots of very small database calls, which end up being very slow. Furthermore, it requires you to have a transaction open for the whole interaction, which is impractical if you have a business transaction that spans multiple requests. The situation is even worse if you need to keep track of the objects you've read so you can avoid inconsistent reads.

A Unit of Work keeps track of everything you do during a business transaction that can affect the database. When you're done, it figures out everything that needs to be done to alter the database as a result of your work.

Q37. What is the ADO.Net? What is the limitation of this framework?

ADO.NET stands for ActiveX Data Object. It provides a bridge between relational and non-relational systems. It is a great technology after traditional ADO, which gives the advantage to create everything from scratch and have full access control of a database in the application. You can get data from ADO.NET in disconnected mode and can serve a large number of connections without compromising the performance of an application.

Entity Framework is an object-relational mapping framework for ADO.Net which is open-source, that enables developers to work with data in the form of domain-specific objects and it reduces the time of development so that we can easily be focused on production instead of development.

In ADO.NET, you can access and modify data stored in different data sources such as Oracle, MS SQL Server, MySQL, and XML. It has a set of classes and data providers that are equivalent to OLE DB, ODBC, and JDBC drivers. It mainly uses two namespaces i.e. System.Data.dll and System.Xml.dll that support the interaction between client and database. 

ADO.NET uses a multilayer architecture that has different .NET components to interact with the database and process the query result using Connection, Reader, Command, Adapter, and DataSet/DataTable objects.

Q38. What is the Entity Framework (EF)? What is the difference between ADO and Entity Framework?

Microsoft introduced Entity Framework with .NET Framework 3.5 in 2008, to enable developers to focus on business domain objects instead of working with underlying database stored data, and it eliminates the need of writing code for writing and reading data from data sources.  

Entity Framework is an Object Relational Mapper (ORM), built at the top of an ADO.NET, it creates the necessary code automatically for storing, and retrieving data, hence, developers only need to focus on creating the application, not dealing with databases and their problems. 

Now you can make an application in an Entity Framework with minimal knowledge of database, because the framework is doing most of the operations and commands, and it is easy to implement CRUD operations in it. Therefore, it reduces development time and you can easily focus on the production instead of the databases. 

There are three main components of the Entity Framework which create the architecture of EF:

Object Service: It is the top layer in the Entity Framework architecture. It maintains the session between the application and the database. It performs CRUD operations with the help of queries. It represents the model entities of an application.

Entity Client: Entity Client is the core layer in Entity Framework, which connects the data source layer to the Object Service layer with the help of providers. It allows developers to write LINQ queries and read or write data without generating classes of the conceptual schema. 

Data Providers: Data Provider layer is directly linked to the database. It is responsible to parse the query into a native SQL command expression in the database and then provide results back into domain objects of the application. 

ADO vs Entity Framework:

Both ADO.NET and Entity Framework are connectors between application and database and have a set of libraries that are used to access data services, and support the development needs of relational databases or XML in .NET applications such as console apps, desktop apps, web apps, and WCF/Web API services. They both are an integral part of the .NET framework having strong-typed .NET classes and objects. 

ADO.NET provides better performance as it is directly connected to the data source, which makes the processing faster than Entity Framework as it translates LINQ queries to SQL first then processes the query. The performance of ADO.Net is better than entity framework because ADO.Net is directly connected to the data source due to that it gives better performance than entity framework, whereas the performance of entity framework is less as compared to the ADO.Net as entity translate the LINQ queries to SQL first and then process the query.

ADO.Net provides a bridge between relational and non-relational database systems.  On the other hand Entity Framework is an ORM framework for ADO.NET which is an enhancement to the ADO.Net. In fact, the entity framework consists of the wrapper classes for ADO.Net.

In terms of raw SQL queries and procedures, ADO.Net provides more flexibility than the entity framework as provides full control over the database. 

Q39. What is the difference between LINQ-to-Entities and LINQ-to-Objects?

The term "LINQ to Objects" refers to the use of LINQ queries with any IEnumerable or IEnumerable<T> collection directly, without the use of an intermediate LINQ provider or API such as LINQ to SQL or LINQ to XML. 

You can use LINQ to query any Enumerable collections such as List<T>, Array, or Dictionary<TKey, TValue>. The collection may be user-defined or may be returned by a .NET Framework API. Linq to Objects is used for querying in-memory data (local objects).

LINQ to Entities provides Language-Integrated Query (LINQ) support that enables developers to write queries against the Entity Framework conceptual model using Visual Basic or Visual C#. 

LINQ to Entities converts Language-Integrated Queries (LINQ) queries to command tree queries, executes the queries against the Entity Framework, and returns objects that can be used by both the Entity Framework and LINQ. Linq to Entities is used for querying data via the ADO.NET Entity Framework (Database).

Q40. What is LINQ-To-SQL? What is the use of ADO.NET DataSet Designer?


LINQ to SQL is a component of .NET Framework version 3.5 that provides a run-time infrastructure for managing relational data as objects. In LINQ to SQL, the data model of a relational database is mapped to an object model expressed in the programming language of the developer.

When the application runs, LINQ to SQL translates into SQL the language-integrated queries in the object model and sends them to the database for execution. When the database returns the results, LINQ to SQL translates them back to objects that you can work with in your own programming language.

Developers using Visual Studio typically use the Object Relational Designer, which provides a user interface for implementing many of the features of LINQ to SQL.

ADO.Net Dataset Designer:

A dataset is a set of objects that store data from a database in memory and support change tracking to enable create, read, update, and delete (CRUD) operations on that data without the need to be always connected to the database. 

The ADO.NET DataSet is a memory-resident representation of data that provides a consistent relational programming model regardless of the source of the data it contains. A DataSet represents a complete set of data including the tables that contain, order, and constrain the data, as well as the relationships between the tables. The DataSet class and the classes contained in DataSet objects-Data­Table, DataColumn, DataRow, Constraint, and DataRelation-reside in the System.Data namespace.

The DataSet designer is useful even if you don't want to work with an external database. Datasets were designed for simple forms over data business applications. For new applications, consider using Entity Framework to store and model data in memory. 

The DataSet Designer can be used to create a strongly typed DataSet class that can contain as many tables as you like without ever having to reference a database that exists elsewhere in the system. It can also be used to create suitable classes to work with data provided by any ADO.NET adaptor even if they don't correspond to database tables stored on a disk. Put simply the DataSet Designer lets you create a data structure that is an in-memory database.

To Be Continued Part-06...

Recommended Articles

Thanks for visiting this page. Please follow and join us on LinkedInFacebookTelegramQuoraYouTubeTwitterPinterestTumbler, and VK, for regular updates.


No comments:

Post a Comment

Please do not enter any HTML. JavaScript or spam link in the comment box.