Skip to main content

Posts

Showing posts with the label C# interview

Fixing Multiple If-Else problem with Chain of Responsibility Pattern

  Situation will become unmanageable if we have lot of if else condition in our code, Lets understand problem and then we will see it’s Solution. Problem with Multiple If Conditions Using multiple if-else conditions to handle different cases can lead to code that is hard to read, maintain, and extend. Here’s a simple example using multiple if conditions in a leave management system. We will implement below Business Logic for Leave management system a. IF Leave < = 3, then Team Lead will approve b. IF Leave < =5, then Project Manager will approve c. IF Leave > 5, then HR Manager will approve Request first go to team lead to check if Request can be handled by  Team lead  else it will go to  Project Manager  else request will go to  HR manager Example with Multiple If Conditions public class LeaveRequest { public string EmployeeName { get ; set ; } public int NumberOfDays { get ; set ; } public string Reason { get ; set ; } } publi...

Builder Pattern in C#: Practical Implementation and Examples

  This pattern can be ideal approach to create complex objects The Builder pattern is a creational design pattern that is used to construct complex objects step by step. It allows you to create different representations of an object using the same construction process. Let’s first understand the problems that exist without using this pattern. Complex Constructor with Many Parameters When creating objects that require many parameters, constructors can become lengthy and hard to read. public class House { public House ( int walls, int doors, int windows, bool hasGarage, bool hasSwimmingPool, bool hasStatues, bool hasGarden) { // Initialization } } There are many problems if constructor have too many parameters i) Each time we need to pass n numbers of parameters at time of object creations ii) we need to update constructor if we need to pass one more parameter so such constructor difficult to manage 2.  Constructor Overload Explosion Sometimes we ne...