Download as docx, pdf, or txt
Download as docx, pdf, or txt
You are on page 1of 36

Explain Cohesion and coupling ( .

NET and C# Architecture


level interview question) ?

If you look at the dictionary meaning of cohesion it means sticking things together which are of
the same types or substance.

Cohesion in software is a measure which tells how strongly related the responsibilities of a class
or module is.

For example below is a class diagram of a simple “customer” class. In this class diagram
“CustomerName” and “CustomerCode” are very much related to the “Customer” class but
watch the “SupplierCode” property it’s not related directly.

Because this class has unrelated elements it has LOW.

Cohesion can be at any level class level, module level etc. For example below is a simple
package diagram which groups classes in a “Customer” package.

Now Customers buy products and have multiple addresses. So it’s logical to have “Customer” ,
“Product” and “Address” in this namespace but look at “Exception” and “Logger” classes they
are needed but they are not logically the part of “Customer” namespace.
So below grouping would look more logical and appropriate.

Coupling is a contrast to cohesion. Coupling says how much the classes and modules directly
depend on each other. A good architecture is that architecture where change in one place
should not lead to changes all over the places. If classes are directly connected with each other,
then change in one class leads to changes in other class as well, so a loose coupling is more
desirable.

Below is a simple class diagram which shows “Customer” and “Address” relationship. In the first
section of the diagram “Customer” and “Address” classes are directly connected. In other
words changes in “Address” class will lead to change in “Customer” class as well. So rather than
these classes talk with each other directly they can talk via interfaces which the next section of
the diagram shows. This is termed as decoupling.
Coupling and cohesion are measured using ordinal measurement: – LOW and HIGH. So we have
low cohesion, high cohesion, low coupling and high coupling. Below table explains the same in
detail.

High Low

Classes and modules have related and logical elements Elements are unrelated
Cohesion
together. This is a desirable situation. and are not desirable.

This means that classes


are not tightly coupled
This means the classes are tightly coupled with each other and and changes in one place
Coupling
will make the software more difficult to maintain will not affect the other
section. This is a
desirable situation.

In other words, good software architectures have high cohesion and low coupling.
Inversion of Control
C# Indexer

https://www.youtube.com/watch?v=HdtEQqu0yOY

Indexer help us to l simplify the way we are getting collection from the class

To create Index we have to use this keyword


String and StringBuilder

https://www.youtube.com/watch?v=hF-6eudOD0M

Strings are immutable

String always creates the new object and assign value.

String Builder will always append value in a single memory.


OUT and Ref

https://www.youtube.com/watch?v=lYdcY5zulXA

 OUT and REF helps to pass variables BY REFERENCE.

 In OUT we need to compulsorily initialize variables inside the function for REF we do not need to do the
same.

 REF helps to pass data two ways i.e. from caller to callee and back. While OUT is one way it just passes
data from callee to caller.

OUT: we need to initialize the variable in the calling function.


IS and AS Keyword

http://www.dotnetinterviewquestions.in/article_what-is-the-difference-between-out-and-ref-c-
interview-questions_255.html#.VgpKBaKrySA.facebook
//IS str1 variable type of string

//Can we convert str1 string AS a object

IS keyword is useful for checking variables are same type or not.

AS keyword used for type cast

Const and Read only

https://www.youtube.com/watch?v=vNPBWNNlDwM&feature=player_embedded

Const: Compile time Constant, value will be assigned at the time of declaration itself.

ReadOnly: We can assign the value at runtime or in the constructor.

Extension Methods

https://www.youtube.com/watch?v=Iu7OrL6vCOw&feature=player_embedded

Extension Methods: Help you to create a methods without changing the source code
Anonymous Methods

https://www.youtube.com/watch?v=drgsIO5M8ok

Delegate:
Anonymous Method: Method which can be coded inline

It avoids the writing a separate method for simple code and need to point
delegate to that method

If we are looking performance aspect we can use anonymous method.

Delegate:

Dictionary meaning of delegate:

Main use of delegate is communication between two parties

Main use of delegate is Callbacks.

https://www.youtube.com/watch?v=ifbYA8hyvjc

What is the benefit of calling method in directly using delegate (via pointer)?

We can do the call back using delegate


What is Lambda expressions , Action , Func and Predicate

https://www.youtube.com/watch?v=8o0O-vBS8W0

FUNC<>(Generic delegate): Func is a readymade delegate we can pass input and get output.
Action<>: Action Delegate used when we want to pass the input and no output expected.

Predicate<>: it is a extension to the Func<> it is used for checking purpose. Return type is always
Boolean type by taking any input type.
Expression tree

Simple LinQ Query


When we will see the x value in quick was it is translated as below.

 What is the use of Yield keyword in c# ?

https://www.youtube.com/watch?v=4fju3xcm21M
What is Tuple in C#?
Basically, a tuple (Tuple in C#) is an ordered sequence, immutable, fixed-size and of heterogeneous
objects, i.e., each object being of a specific type. The tuples are not new in programming

http://www.codeproject.com/Articles/193537/C-Tuples
Difference between IEnumerable and IEnumerator.
https://www.youtube.com/watch?v=jd3yUjGc9M0

IEnumerable and IEnumerator help to loop through the collection (list, array list)

IEnumerable actually uses the IEnumerator

Biggest difference is IEnumerator remembers the state where as IEnumerable not remembers the state.

IEnumerable used when we want to loop in the sequentially and we don’t want to remember where the
current cursor and we are going to use IEnumerable.

IEnumerator is useful when you want to pass the value from one function to other function and we want
to remember in t=what position cursor is then we are going to use the IEnumerator.

IEnumerable we are going to use ForEach

IEnumerator we are going to use While with MoveNext

Difference between IEnumerable and IQueryablIe

IEnumerable IQueryable
Namespace System.Collections Namespace Syste.LINQ
Derives from No base interface Derives from IEnumerable
Deferred
Supported Supported
Execution
Lazy Loading Not Supported Supported
While querying data from database, While querying data from database, IQueryable
How does it work
IEnumerable execute select query on execute select query on server side with all
server side, load data in-memory on
client side and then filter data. Hence filters. Hence does less work and becomes fast.
does more work and becomes slow.
LINQ to Object and LINQ to XML
Suitable for LINQ to SQL queries.
queries.
Supports using CreateQuery and Execute
Custom Query Doesn’t supports.
methods.
Extension mehtod Extension methods supported in Extension methods supported in IEnumerable
parameter IEnumerable takes functional objects. takes expression objects i.e. expression tree.
when querying data from in-memory when querying data from out-memory (like
When to use
collections like List, Array etc. remote database, service) collections.
Best Uses In-memory traversal Paging

What is the use of "VAR" keyword in .NET and c# ?


https://www.youtube.com/watch?v=VnlCmxBuqFE

VAR type will be decided by the type assigned by the value in the right hand side at compile time.

Ex:

Var I=123

In the above scenario I is a integer type

If we try to assign I=”Shiva” we will get compile error already I is Integer type.

Var Keyword is statically type

VAR keywords used when class names are big and to make readable and shorter code

Var keyword is used in Linq and anonymous type methods.

LINQ
Var vs Dynamic in c#

https://www.youtube.com/watch?v=SsvJY33vc5g

Dynamic keyword uses reflection.

In the above example VAR x at compile time only we comes to know it is a string type and we can find
length of string.
When we use the dynamic key we won’t get the compile time error and build succeds, but in run time
we will get error because we are given length instead of “Length”

 Difference between == VS .Equals()


https://www.youtube.com/watch?v=3IReFdq5d7o

Difference between String and string


String is a just alias name for String
What is the difference between Abstraction and Encapsulation ?
https://www.youtube.com/watch?v=1Q4I63-hKcY
What are Generics?
https://www.youtube.com/watch?v=7bKhAJpY9ho
its separates the logic from data type

What is the use of checked and unchecked keyword ?


https://www.youtube.com/watch?v=JNwvVrK_y-I
What is covariance and contravariance in c# ?
https://www.youtube.com/watch?v=jtzPBYBub5Y

What is TPL ( Task Parallel Library) and how it differs from threads (c#
interview questions) ?
https://www.youtube.com/watch?v=No7QqSc5cl8

Prove that only 1 instance of the object is created for static classes?
https://www.youtube.com/watch?v=N9xwjZ4mMvw

static class always creates the only one instance


Can we implement interfaces with same method names in c# ?
https://www.youtube.com/watch?v=6ZxVx93wa7Q

What is Garbage Collector, Gen 0, 1 & 2?


https://www.youtube.com/watch?v=gC8NdlOeNEs

What is thread,background thread and foreground thread ?


https://www.youtube.com/watch?v=Fzckqczmgd0
Fore Ground Threads: fore ground threads will execute , even though mail application exist.

Back Ground Thread: Background thread will exit, when the main application will quit.
 Multithreading and thread safe objects.
https://www.youtube.com/watch?v=J-jNcUhi9xw

Thread Safe:

Lock: will lock the code and make sure only one thread can execute the Locked code.
What is AutoResetEvent and ManualResetEvent 
https://www.youtube.com/watch?v=xaaRBh07N34
What are Async and Await
https://www.youtube.com/watch?v=V2sMXJnDEjM
What is the use of private constructor ?
https://www.youtube.com/watch?v=8xyXjdUtmfQ&list=PL5753E1DFB675A268&index=2

What is the Aggregation, Association and Composition?


https://www.youtube.com/watch?v=0po_wmSEW1Q

Association: Both the objects used each other, but they can have own life style. (has a Relation)

Aggregation: is a single owner of the object (There is a single owner of child object)
Composition: both the objects depend each other, one goes off and other goes off.

What is Abstraction and Encapsulation

https://www.youtube.com/watch?v=1Q4I63-hKcY

Difference between Abstract Method and Virtual


Abstract Functions can not have any body or implementation while virtual Functions can
have body or implementation ,abstract functions must be implementation by derived classes
and virtual not must implementation by derived classes,both are override in derived classes

Difference between Temp table and table variable

What is Boyce-Codd Normal Form(BCNF)?

Boyce-Codd Normal Form (BCNF) is one of the forms of database normalization. A database table is in
BCNF if and only if there are no non-trivial functional dependencies of attributes on anything other than a
superset of a candidate key. BCNF is also sometimes referred to as 3.5NF, or 3.5 Normal Form.
SQL SERVER – Stored Procedure
Optimization Tips – Best Practices
We will go over how to optimize Stored Procedure with making simple changes in the code. Please
note there are many more other tips, which we will cover in future articles.

 Include SET NOCOUNT ON statement: With every SELECT and DML statement, the SQL
server returns a message that indicates the number of affected rows by that statement. This
information is mostly helpful in debugging the code, but it is useless after that. By setting
SET NOCOUNT ON, we can disable the feature of returning this extra information. For
stored procedures that contain several statements or contain Transact-SQL loops, setting
SET NOCOUNT to ON can provide a significant performance boost because network traffic
is greatly reduced.

CREATE PROC dbo.ProcName

AS

SET NOCOUNT ON;

--Procedure code here

SELECT column1 FROMdbo.TblTable1

-- Reset SET NOCOUNT to OFF

SET NOCOUNT OFF;

GO

 Use schema name with object name: The object name is qualified if used with schema
name. Schema name should be used with the stored procedure name and with all objects
referenced inside the stored procedure. This help in directly finding the complied plan
instead of searching the objects in other possible schema before finally deciding to use a
cached plan, if available. This process of searching and deciding a schema for an object
leads to COMPILE lock on stored procedure and decreases the stored procedure’s
performance. Therefore, always refer the objects with qualified name in the stored procedure
like

SELECT * FROM dbo.MyTable -- Preferred method

-- Instead of

SELECT * FROM MyTable -- Avoid this method
--And finally call the stored procedure with qualified name like:

EXEC dbo.MyProc -- Preferred method

--Instead of

EXEC MyProc -- Avoid this method

 Do not use the prefix “sp_” in the stored procedure name: If a stored procedure name
begins with “SP_,” then SQL server first searches in the master database and then in the
current session database. Searching in the master database causes extra overhead and
even a wrong result if another stored procedure with the same name is found in master
database.

 Use IF EXISTS (SELECT 1) instead of (SELECT *): To check the existence of a record in
another table, we uses the IF EXISTS clause. The IF EXISTS clause returns True if any
value is returned from an internal statement, either a single value “1” or all columns of a
record or complete recordset. The output of the internal statement is not used. Hence, to
minimize the data for processing and network transferring, we should use “1” in the SELECT
clause of an internal statement, as shown below:

IF EXISTS (SELECT 1 FROM sysobjects

WHERE name = 'MyTable' AND type ='U')

 Use the sp_executesql stored procedure instead of the EXECUTE statement.


The sp_executesql stored procedure supports parameters. So, using the sp_executesql
stored procedure instead of the EXECUTE statement improve the re-usability of your code.
The execution plan of a dynamic statement can be reused only if each and every character,
including case, space, comments and parameter, is same for two statements. For example, if
we execute the below batch:

DECLARE @Query VARCHAR(100)

DECLARE @Age INT

SET @Age = 25

SET @Query = 'SELECT * FROM dbo.tblPerson WHERE Age = ' +CONVERT(VARCHAR(3),@Age)

EXEC (@Query)

If we again execute the above batch using different @Age value, then the execution plan for
SELECT statement created for @Age =25 would not be reused. However, if we write the above
batch as given below,
DECLARE @Query NVARCHAR(100)

SET @Query =N'SELECT * FROM dbo.tblPerson WHERE Age = @Age'

EXECUTE sp_executesql @Query, N'@Age int', @Age = 25

the compiled plan of this SELECT statement will be reused for different value of @Age parameter.
The reuse of the existing complied plan will result in improved performance.

 Try to avoid using SQL Server cursors whenever possible: Cursor uses a lot of
resources for overhead processing to maintain current record position in a recordset and this
decreases the performance. If we need to process records one-by-one in a loop, then we
should use the WHILE clause. Wherever possible, we should replace the cursor-based
approach with SET-based approach. Because the SQL Server engine is designed and
optimized to perform SET-based operation very fast. Again, please note cursor is also a kind
of WHILE Loop.
 Keep the Transaction as short as possible: The length of transaction affects blocking and
deadlocking. Exclusive lock is not released until the end of transaction. In higher isolation
level, the shared locks are also aged with transaction. Therefore, lengthy transaction means
locks for longer time and locks for longer time turns into blocking. In some cases, blocking
also converts into deadlocks. So, for faster execution and less blocking, the transaction
should be kept as short as possible.
 Use TRY-Catch for error handling: Prior to SQL server 2005 version code for error
handling, there was a big portion of actual code because an error check statement was
written after every t-sql statement. More code always consumes more resources and time. In
SQL Server 2005, a new simple way is introduced for the same purpose. The syntax is as
follows:

BEGIN TRY

--Your t-sql code goes here

END TRY

BEGIN CATCH

--Your error handling code goes here

END CATCH

You might also like