FAQ Design Patterns Flashcards

(78 cards)

1
Q

Abstraction Encapsulation

A

Abstraction

refers to modelling of complex entity through abstracts taking only relevant details and skipping irrelevant details.

It hides implementation details. It helps in reducing code complexity and standardization.

Achieved using Abstract classes and Interfaces

For example creating interface of product service and only declaring what it can do. How is later implemented by relegated classes

Encapsulation

Refers to wrapping data and behavior of entity and giving public access points to these.

Achieved using class access Modifiers getters setters

It helps in data integrity and modularity. Avoids accidental overwrites of data through validations in setters.

For example creating Patient class to protect PHI data

How well did you know this?
1
Not at all
2
3
4
5
Perfectly
2
Q

Inheritance

A

Extending existing types to create specialised types giving hierarchy.

It helps in reusability

For example creating admin from user. Admin is a type of user

How well did you know this?
1
Not at all
2
3
4
5
Perfectly
3
Q

Polymorphism

A

Refers to ability of entity to take different forms based on context.

Achieved using overloading and overriding

Helps in generic coding flexibility

For example a search function being able to function differently based on filter types

How well did you know this?
1
Not at all
2
3
4
5
Perfectly
4
Q

Over loading vs Over ridding

A
How well did you know this?
1
Not at all
2
3
4
5
Perfectly
5
Q

Shadowing
Method Hiding

A

Child methods will be hidden from parents during polymorphism

Child methods will not be invoked by parent class during polymorphism

Only happens when parent is pointing towards child instance

It is implementation using new keyword on same signature method of parent in child class

Useful in liskov problem when child doesn’t implement everything parent does.

How well did you know this?
1
Not at all
2
3
4
5
Perfectly
6
Q

Operator overloading

A
How well did you know this?
1
Not at all
2
3
4
5
Perfectly
7
Q

What is abstract classes

A

Partially defined parent class. Some implementations defined and some which is left for child to implement

It can be a base class but can’t have instances. Runtime safety.

Create child, implement abstract to create instances

Abstract class. Abstract method

How well did you know this?
1
Not at all
2
3
4
5
Perfectly
8
Q

Why do we need shadowing

A

Hiding is a hack to achieve safe polymorphism by following LSP when a child class doesn’t implement all methods of base class and needs to be hidden so that base pointing to child can’t invoke it and use the base method.

Shadowing is a reactive measure/hack when face a liskov problem due to child not implementing all methods of parent which gives unexpected behaviour runtime errors

Hack when child class doesn’t implement all methods of parent
Liskov problem and happens due to wrong abstraction . It causes unexpected or runtime errors

How well did you know this?
1
Not at all
2
3
4
5
Perfectly
9
Q

Shadowing Hiding vs Overriding

A

Overriding is type of polymorphism. Parent class can invoke child methods which are overriden when parent points to a child instance.

In shadowing, parent class can’t invoke child method because it is hidden from the parent. Only instance child class can invoke those methods

How well did you know this?
1
Not at all
2
3
4
5
Perfectly
10
Q

Nested class use cases

A

Class definition inside another class

Deeper logical group classes than Namespaces

When nested class is only useful to enclosing class.

For example prescription validation is only rental order

How well did you know this?
1
Not at all
2
3
4
5
Perfectly
11
Q

Can nested class access outer class variables

A

No. Only structural connection. No instance connection.

We need to pass an instance and then access

How well did you know this?
1
Not at all
2
3
4
5
Perfectly
12
Q

Can nested have any access Modifiers in nested class

A

Technically yes.

If the usage to is to only logical group : public

If only used for related and hidden : private

How well did you know this?
1
Not at all
2
3
4
5
Perfectly
13
Q

Partial classes

A

Can be written in two different physical files but compiler will compile into one class

We need to use partial class

Useful when we need to organise complex code into different files.

DO NOT TELL PARALLEL DEVELOPMENT BY MULTIPLE

How well did you know this?
1
Not at all
2
3
4
5
Perfectly
14
Q

Abstract method is virtual method ?

A

Yes. Child can override. It is implicitly virtual

How well did you know this?
1
Not at all
2
3
4
5
Perfectly
15
Q

Is it compulsory to implement abstract methods

A

Yes. If not, compile error

How well did you know this?
1
Not at all
2
3
4
5
Perfectly
16
Q

Why can’t simple base class replace abstract class

A

We can’t leave some without implementation. We have to write dummy implementation which is tech debt. Not clean code

How well did you know this?
1
Not at all
2
3
4
5
Perfectly
17
Q

What are interfaces

A

Interface is a contract
With the consumers of the interface.

Interface supports multiple inheritance which Helps in versioning by implementing multiple interfaces.

Helps in creating loosely coupled applications

Consumer MUST implement all properties and methods defined by interface. Else compile error

Contract between developer who is writing contract so he can use the concrete classes safely because another created the concrete strictly following contract rules. Else compile error and impact is shown

Contract creator will use interface reference = to concrete class and invoke the methods of interface

How well did you know this?
1
Not at all
2
3
4
5
Perfectly
18
Q

Private methods ?
Logic

A

Only pure signature

No access Modifiers. Private gives Compile error

Now default implementation can be given

How well did you know this?
1
Not at all
2
3
4
5
Perfectly
19
Q

Interface vs Abstract class

A

Interface only signatures but abstract can some definition some signature

Interface to plan abstraction. After defining Interface we can create abstract class if there are related classes implementing it and have same logic.
Abstract class to implement abstraction. Common logic of related classes go in abstract class where the class itself shouldn’t exist as an entity in code.

Interface supports multiple inheritance but abstract only supports single inheritance.

How well did you know this?
1
Not at all
2
3
4
5
Perfectly
20
Q

Constructor and order

A

Special methods which are automatically invoked when instance created. Used to initialize variables

Parent then child constructor order

How well did you know this?
1
Not at all
2
3
4
5
Perfectly
21
Q

What is the goal of SOLID principles

A

Minimize dependencies

Write reliable code

Code easy to understand maintain test and refactor

How well did you know this?
1
Not at all
2
3
4
5
Perfectly
22
Q

Initializer order

A

First child then parent

How well did you know this?
1
Not at all
2
3
4
5
Perfectly
23
Q

Static constructor order

A

Child then parent

Then
Instance constructor of child then instance constructor of parent

How well did you know this?
1
Not at all
2
3
4
5
Perfectly
24
Q

When static constructor fires

A

First time the class is accessed

How well did you know this?
1
Not at all
2
3
4
5
Perfectly
25
Single Responsibility Principle
A class should have only one purpose and be focused on it. Modular code. Lean and focused class. Quality of class. Easy to understand and maintain For example a service class should only focus on business logic. Not notifications and data access
26
Open closed principle
Class is open for extension and closed for modification If impact of class change is high then stable consumers needs to be tested again. Keeps existing unaffected and only new features need to be tested. Instead of adding another else if, create new interface and implement its concrete. Pick using behavior pattern like strategy.
27
Liskov Substitution Principle
Child class should be substitute the parent class without changing existing behaviour. Without side effects and seamlessly Ensures safe polymorphism else we get runtime exceptions or unexpected behaviour For example a sampleorderprocessor which inherits orderprocessor that has billing method can't be substituted because sample orders are not to be billed Split interface and Compose. Then create concrete classes
28
How to solve liskov problem
Understand requirement Refactor. Interface and Compose. Then create concrete class. Hack Method hiding
29
Interface Segregation Principle
No class should be forced to implement methods that it does not need. Else we will have dummy implementations and that is technical debt Instead of creating huge interfaces. Split it and compose. For example. Instead of useractions. Have patientactions. Admin actions
30
Liskov vs Interfaces Segregation
Liskov happens when inheritance is done wrong and causes unsafe polymorphism Interface focuses on class implementing Interface
31
Dependency Inversion
Higher level modules should not directly depend on low level modules and instead via abstractions Helps us not be tied to specific implementation. Else refactoring will be a major rewrite because the related code is scattered. Here it centralise and only one place needs to be changed. For example endpoint shouldn't directly depend on service instead have an abstraction of service so that implementation of service change doesn't impact the controller. Because the new service will implement the contract
32
How to application decoupling
New keyword is scattered and tied to specific concrete implementation Dependency Inversion and dependency Injection gives decoupling We first make high level class depend only on abstractions of concrete implementation And then a provider creates the concrete object and injects for the class
33
Inversion of control
We invert the unnecessary additional work of a class to outside provider so that class can focus on it's single Responsibility Loosely couple object creation and usage.
34
Dependency Injection
Technique to Implementation of INVERSION OF CONTROL principle. Class delegates object creation to external provider. The provider creates the instance and injects it. Class only focuses on its single Responsibility
35
What is composition
Composition is whole object which is parent Is owner of the part object. That object isn't shared and parent controls the lifetime which is it's own lifetime ————— Part whole relationship Where lifetime of part object and whole object is same One can't exist without other Like patient is whole object. Disease is part object. Patient is only patient when they have disease. Tight connections
36
What is aggregation
There is relationship between part object and whole object but they are independent of each other. They can exist without the other. Like patient has a doctor object. Doctor object can patient object. They own their own lifetimes
37
What is association
Defines that two objects depend on each other Composition and aggregation are subset of association that have part whole relationship Like patient class can have part object to get appointment dates
38
What are design patterns
Well tested solutions for Recurring architectural problems Example. Repository Pattern. Factory Pattern CQRS
39
Prototype Pattern
Fully initialize instance to be copied or cloned
40
Adapter Pattern
Helps incompatible interfaces compatible
41
Repository Pattern
Abstract and centralise Data access logic layer Layer of separation between business logic and data access layer Makes code modular maintainable and testable
42
Categories of design patterns
Gang of four. Creational - problems related object creation Singleton for shared single instance Factory Pattern for complex object creation in centralised manner Behavioural to deal with problems of communication between objects Chain of responsibilities like middlewares Mediator pattern simplifies communication between classes. Structural to solve concerns of class Structure and object composition Adapter to match interfaces of different classes
43
Singleton Pattern
Pattern to create single shared instance of app lifetime and providing a global access point to it Useful for caching and logging
44
Structure of Singleton
There should be a root. Whole part relationship. Instance of the class as private field with static so that only one exists A static readonly lock for thread safely Concurrent Collections for state for thread safety Lazy loading
45
Why private constructor
So that outside code can't create instance because idea is to have only one instance
46
Static class with everything static and no constructor vs private constructor
Static is a keyword Singleton is a design pattern Static class can't have instances Singleton uses Static features with More features like thread safety, lazy loading, performance. Has a defined structure. Static doesn't have state thread safety. Can't have instances. Can't implement interface. Can't have inheritance. Can't be injected.
47
How to implement thread safety in Singleton pattern
Lock keyword helps implement thread safety. The code block will get executed by only on thread at a given time. Other threads wait and there is no conflicts If not there then unexpected behaviour Use lock. Make the lock static and readonly Only one thread can enter the block of code. Other threads will be waiting Multithreaded environment like c#. Multiple threads can execute code.
48
Why is there double null check in Singleton
Inner check is for lazy loading. Only if some state is null, only then initialize. Like get method. Only initialize when it is first called and check if it is null. Don't at constructor. Outer check is for performance. Make sure that lock is not obtained unnecessarily. Unless instance not created or state not initialized In single check all thread obtain lock even if instance already created
49
How to get rid of double check lock
Use lazy keyword Thread safety guaranteed Late initialization When accessing .Value ... the value gets initialized
50
Which design pattern have you used in your projects
Repository Pattern. Unit of work. Options Pattern. Factory Pattern
51
What is Repository Pattern
Abstract and centralise data access layer Helps us to have consistent interface for CRUD actions of model Loosely coupled architecture Reusable code by using abstract repository
52
Is data access layer and repository same
No Data access layer is more detailed steps on to access data from source Repository is abstraction over DAL. It is high level. It gives what CRUD actions an happen on model and just that, no implementation of getting data.
53
What is generic repository Pattern
It is extension to repository Pattern. It helps use to create a generic repository interface for all entities instead of creating a repository each for every entity
54
Is abstraction the only benefit of repository
Repository helps in loose coupling but also reusability of code across DALs Common logic in DALs can be put in a common abstract class and all repositories can inherit
55
How to implement transactions in repository
Unit of work design pattern
56
What is unit of work pattern
Helps abstract transactions in repository
57
What is a transaction
Group of tasks or operations Either whole group is committed if all tasks are completed successfully If there is an issue with even one task. The whole group is rolled back
58
Do we need repository when entity framework does the same job
Even though it is repository with unit of work, it is a good practice to implement an abstraction over it for long term adaptability. It can be an abstraction for any kind of data source. If we decide to replace, then we have a centralised place to do so It is easier to implement mock unit testing Always good to have abstraction whenever we use third party library in case we need to replace It can be overkill if different types of data source or replacement of entity framework is not expected Entity Framework is a technology to handle repository over only heterogeneous relational database only. Repository Pattern can handle repository over any heterogeneous data sources.
59
What is mock testing
Repository represented by generic repository interface helps in easy unit testing. It can be isolated for mock unit testing 1. Helps in bypassing the data access logic to test only the business logic 2. Helps in parallel development and testing. When another has not completed code. We can still test our part of code by mocking the code that is not complete. Helps save time.
60
How repository Pattern helps in unit testing
Repository pattern abstracts the data access layer, letting business logic depend on interfaces instead of EF or SQL. This makes unit testing easy because we can mock repositories and return fake data without hitting the database. It isolates business logic, supports mocking frameworks like Moq, speeds up test runs, and improves maintainability in large systems.
61
What is factory Pattern
Creational pattern Centralises object creation Making application loosely coupled
62
How does centralised object creation help in loose coupling
When new keyword is used to create object, we are using a reference which makes consumer tightly coupled to the specific implementation Every consumer would have to create the same and hence new keyword is scattered throughout the code Switching an implementation would be a major rewrite and many code file changes So better to have it created at one place. Change in one place.
63
What is IoC
Design principle states that class should delegate additional work than core work to external framework so that class can focus on it's single Responsibility
64
What is dependency Injection pattern
Is a technique To implement Inversion of control principle It will create the object and provide the consumer It centralised dependencies of application. Decoupling consumers and dependencies. Easy to test and refactor happens only on few files Loosely couple usage and creation
65
What is service locator
Centralised registry That retrieve and manage dependencies. Searches for it. It hides dependencies of a class and doesn't follow explicit dependency rules Class still depends on the service locator
66
Service locator vs dependency Injection
Service locator is tightly coupled application. Dependency loosely coupled. It doesn't follow explicit Dependency rules. Consumer doesn't explicitly state dependencies but has an indirect path to search for it making dependencies hidden. Class needs to know where the Dependency is coming from Dependency Injection resolves the dependencies on its own scope and injects. Class doesn't need to know where the Dependency is coming from
67
Can we have simple class in dependency Injection
Yes. But that tightly couples consumer to an implementation Abstraction gives loose coupling
68
Is dependency Injection a design pattern
No. It is a technique to implement Inversion of control principle It doesn't have its own pseudo code.
69
Is dependency Injection factory Pattern
No. Dependency Injection only focuses on Injection of Dependency We have to say how to construct the object. Factory Pattern is a way to do that for complex objects in a centralised way
70
Static DI vs Dynamic DI
Static DI needs a restart of application for any change Dynamic DI will create the object at runtime if it needs a change. Static is done using type implementation style Dynamic is done using factory implementation style Static use for service, repository, logger Dynamic use for creating order processors based on user selection
71
What is real factory pattern
It defines interface for object creation and class decide which concrete implementation for the object WITH factory method allows class to delegate the instance creation to subclass
72
When to use factory pattern
If the object creation pattern is complex If certain combinations of dependency gives new object behaviours Like different types of order processor is created based on product selected, whether the patient is at facility or homecare, whether they billing is to be free, insurance paid or customer paid.
73
Example of factory pattern
different types of order processor is created based on product selected, whether the patient is at facility or homecare, whether they billing is to be free, insurance paid or customer paid. We create a interface for orderprocessor with a factory method to create the object. And methods to vary the behaviour based on product, location and payor Default class implements it with virtual for all those variations Subclass of Default class will override the specialised variation. And its object is returned by the factory method
74
Factory method vs Factory Pattern
Pattern is the bigger picture Factory method is lower level. It wires up the object creation
75
How are new behaviours created in factory patternl
By inheritance. Inherit default class and override
76
Abstract factory Pattern
Provides interface to create family of related objects without specifying concrete classes Abstraction to create related objects without specifying concrete classes
77
Does abstract pattern use factory pattern inside
Yes. Abstract pattern aggregates similar families of factory Too many factories. Manage by grouping into abstract factory pattern
78
Simple factory vs Real Factory method vs Abstract factory
Simple for Simple object creation Factory for complex object creation Abstract for when grouping factories Simple factory generates object using selection if else or lookup collection . Done using class Rest both need interface Factory pattern delegates object creation to subclasses Abstract pattern logically groups related factories ————— Simple factory is actually not factory pattern. Centralised object creation using polymorphism