Thursday, April 28, 2022

The Most Important Design Patterns

Why Design Patterns?

Design Patterns have become an object of some controversy in the programming world in recent times, largely due to their perceived ‘over-use’ leading to code that can be harder to understand and manage.

It’s important to understand that Design Patterns were never meant to be hacked together shortcuts to be applied in a haphazard, ‘one-size-fits-all’ manner to your code. There is ultimately no substitute for genuine problem-solving ability in software engineering.

The fact remains, however, that Design Patterns can be incredibly useful if used in the right situations and for the right reasons. When used strategically, they can make a programmer significantly more efficient by allowing them to avoid reinventing the proverbial wheel, instead of using methods refined by others already. They also provide a useful common language to conceptualize repeated problems and solutions when discussing with others or managing code in larger teams.

That being said, an important caveat is to ensure that the how and the why behind each pattern are also understood by the developer.

Without further ado (in general order of importance, from most to least):

The Most Important Design Patterns

  1. Singleton

The singleton pattern is used to limit the creation of a class to only one object. This is beneficial when one (and only one) object is needed to coordinate actions across the system. There are several examples where only a single instance of a class should exist, including caches, thread pools, and registries.

It’s trivial to initiate an object of a class — but how do we ensure that only one object ever gets created? The answer is to make the constructor ‘private’ to the class we intend to define as a singleton. That way, only the members of the class can access the private constructor and no one else.

Important consideration: It’s possible to subclass a singleton by making the constructor protected instead of private. This might be suitable under some circumstances. One approach taken in these scenarios is to create a register of singletons of the subclasses and the getInstance method can take in a parameter or use an environment variable to return the desired singleton. The registry then maintains a mapping of string names to singleton objects, which can be accessed as needed.

2. Factory Method

A normal factory produces goods; a software factory produces objects. And not just that — it does so without specifying the exact class of the object to be created. To accomplish this, objects are created by calling a factory method instead of calling a constructor.

Usually, object creation in Java and C# takes place like so:

SomeClass someClassObject = new SomeClass();

The problem with the above approach is that the code using the SomeClass’s object, suddenly now becomes dependent on the concrete implementation of SomeClass. There’s nothing wrong with using new to create objects but it comes with the baggage of tightly coupling our code to the concrete implementation class, which can occasionally be problematic.

3. Strategy

The strategy pattern allows grouping related algorithms under an abstraction, which allows switching out one algorithm or policy for another without modifying the client. Instead of directly implementing a single algorithm, the code receives runtime instructions specifying which of the group of algorithms to run.

4. Observer

This pattern is a one-to-many dependency between objects so that when one object changes state, all its dependents are notified. This is typically done by calling one of their methods.

For the sake of simplicity, think about what happens when you follow someone on Twitter. You are essentially asking Twitter to send you (the observer) tweet updates of the person (the subject) you followed. The pattern consists of two actors, the observer who is interested in the updates and the subject who generates the updates.

A subject can have many observers and is a one-to-many relationship. However, an observer is free to subscribe to updates from other subjects too. You can subscribe to a news feed from a Facebook page, which would be the subject and whenever the page has a new post, the subscriber would see the new post.

Key consideration: In the case of many subjects and few observers, if each subject stores its observers separately, it’ll increase the storage costs as some subjects will be storing the same observer multiple times.

5. Builder

As the name implies, a builder pattern is used to build objects. Sometimes, the objects we create can be complex, made up of several sub-objects, or require an elaborate construction process. The exercise of creating complex types can be simplified by using the builder pattern. A composite of an aggregate object is what a builder generally builds.

Key consideration: The builder pattern might seem similar to the ‘abstract factory’ pattern but one difference is that the builder pattern creates an object step by step whereas the abstract factory pattern returns the object in one go.

6. Adapter

This allows incompatible classes to work together by converting the interface of one class into another. Think of it as a sort of translator: when two heads of state who don’t speak a common language meet, usually an interpreter sits between the two and translates the conversation, thus enabling communication.

If you have two applications, with one spitting out output as XML with the other requiring JSON input, then you’ll need an adapter between the two to make them work seamlessly.

7. State

The state pattern encapsulates the various states a machine can be in, and allows an object to alter its behavior when its internal state changes. The machine or the context, as it is called in pattern-speak, can have actions taken on it that propels it into different states. Without the use of the pattern, the code becomes inflexible and littered with if-else conditionals.


Thank you!! Keep Learning.

Friday, April 8, 2022

C# Coding Standards

 C# is a general-purpose, modern and object-oriented programming language pronounced as “C Sharp”. It was developed by Microsoft led by Anders Hejlsberg and his team within the .NET initiative and was approved by the European Computer Manufacturers Association (ECMA) and International Standards Organization (ISO).

Below are some of the best practices which all the .Net Developers should follow: 

1. Class and Method names should always be in Pascal Case

public class Employee
{
    public Employee GetDetails()
    {
        //...
    }
    public double GetSalary()
    {
        //...
    }
}
2. Method argument and Local variables should always be in Camel Case .
public class Employee
{
    public void PrintDetails(int employeeId, String firstName)
    {
        int totalSalary = 2000;
        // ...
    }
}
Method argument( employeeId,firstName and totalSalary).
3. Avoid the use of underscore while naming identifiers.
// Correct
public DateTime fromDate;
public String firstName;
 

// Avoid
public DateTime from_Date;
public String first_Name;
4. Avoid the use of System data types and prefer using the Predefined data types.
// Correct
int employeeId;
string employeeName;
bool isActive;
 

// Avoid
Int32 employeeId;
String employeeName;
Boolean isActive;
Always prefix an interface with letter I.  
// Correct
public interface IEmployee
{
}
public interface IShape
{
}
public interface IAnimal
{
}

// Avoid
public interface Employee
{
}
public interface Shape
{
}
public interface Animal
{
}
6. For better code indentation and readability always align the curly braces vertically.  
// Correct
class Employee
{
    static void PrintDetails()
    {
    }
}
 

// Avoid
class Employee
    {
    static void PrintDetails()
    {
      }
}
7. Always use the using keyword when working with disposable types. It automatically disposes the object when program flow leaves the scope.  
using(var conn = new SqlConnection(connectionString))
{
    // use the connection and the stream
    using (var dr = cmd.ExecuteReader())
    {
     //
    }
}
8. Always declare the variables as close as possible to their use. 
// Correct
String firstName = "Shubham";
Console.WriteLine(firstName);
//--------------------------
 

// Avoid
String firstName = "Shubham";
//--------------------------
//--------------------------
//--------------------------
Console.WriteLine(firstName);

9. Always declare the properties as private so as to achieve Encapsulation and ensure data hiding.  

// Correct
private int employeeId { get; set; }

// Avoid
public int employeeId { get; set; }

10. Always separate the methods, different sections of program by one space.  

// Correct
class Employee
{
private int employeeId { get; set; }

public void PrintDetails()
{
//------------
}
}

// Avoid
class Employee
{

private int employeeId { get; set; }



public void PrintDetails()
{
//------------
}

}

11. Constants should always be declared in UPPER_CASE.  

// Correct
public const int MIN_AGE = 18;
public const int MAX_AGE = 60;

// Avoid
public const int Min_Age = 18;
public const int Max_Age = 60;

Happy Coding !!!!!!!!!!