Showing posts with label Design_Patterns. Show all posts
Showing posts with label Design_Patterns. Show all posts

Thursday, January 30, 2020

Anti Pattern / Code Smells


Anti-patterns/Design smell

"Design smells are certain structures in the design that indicate violation of fundamental design principles and negatively impact design quality”. 

Tips :
  • Functions should be as small as possible.
  • Avoid if else / Case statements instead used Class and inheritance (Open Closed principle).
  • The number arguments sent to function should be not more than 2 . If exceeds either create a class and send as an object or send as a map.
  • Never send boolean into a function ( as usually it contain if else to validate the same).


There are many design smells classified based on violating design principles:

Abstraction smells

  1. Missing Abstraction: When clumps of data or encoded strings are used instead of creating a class or an interface.
  2. Imperative Abstraction:  When an operation is turned into a class.
  3. Incomplete Abstraction:When an abstraction does not support complementary or interrelated methods completely.
  4. Multifaceted Abstraction: When an abstraction has more than one responsibility assigned to it.
  5. Unnecessary Abstraction: When an abstraction that is actually not needed .
  6. Unutilized Abstraction: When an abstraction is left unused (either not directly used or not reachable).
  7. Duplicate Abstraction: When two or more abstractions have identical names or identical implementation or both.

Encapsulation smells

  1. Deficient Encapsulation: When the declared accessibility of one or more members of an abstraction is more permissive than actually required.
  2. Leaky Encapsulation: When an abstraction “exposes” or “leaks” implementation details through its public interface.
  3. Missing Encapsulation: When implementation variations are not encapsulated within an abstraction or hierarchy.
  4. Unexploited Encapsulation: When client code uses explicit type checks (using chained if-else or switch statements that check for the type of the object) instead of exploiting the variation in types already encapsulated within a hierarchy.

Modularisation smells

  1. Broken Modularisation: When data and/or methods that ideally should have been localized into a single abstraction are separated and spread across multiple abstractions.
  2. Insufficient Modularisation: When an abstraction exists that has not been completely decomposed, and a further decomposition could reduce its size, implementation complexity, or both.
  3. Cyclically-Dependent Modularisation: When two or more abstractions depend on each other directly or indirectly (creating a tight coupling between the abstractions).
  4. Hub-Like Modularisation: When an abstraction has dependencies (both incoming and outgoing) with a large number of other abstractions.

Hierarchy smells

  1. Missing Hierarchy: When a code segment uses conditional logic (typically in conjunction with “tagged types”) to explicitly manage variation in behavior where a hierarchy could have been created and used to encapsulate those variations.
  2. Unnecessary Hierarchy: When the whole inheritance hierarchy is unnecessary, indicating that inheritance has been applied needlessly for the particular design context.
  3. Unfactored Hierarchy: This smell arises when there is unnecessary duplication among types in a hierarchy.
  4. Wide Hierarchy: When an inheritance hierarchy is “too” wide indicating that intermediate types may be missing.
  5. Speculative Hierarchy: When one or more types in a hierarchy are provided speculatively (i.e., based on imagined needs rather than real requirements).
  6. Deep Hierarchy: When an inheritance hierarchy is “excessively” deep.
  7. Rebellious Hierarchy: When a subtype rejects the methods provided by its supertype(s).
  8. Broken Hierarchy:When a supertype and its subtype conceptually do not share an “IS- A” relationship resulting in broken substitutability.
  9. Multipath Hierarchy: When a subtype inherits both directly as well as indirectly from a supertype leading to unnecessary inheritance paths in the hierarchy.
  10. Cyclic Hierarchy: When a supertype in a hierarchy depends on any of its subtypes.

Other Code Smells:

  1. Duplicated Code and Logic Code Smell:refractor part into a separate method 
  2. Long Methods and Classes Code Smell:The perfect method should be between 4 to 20 lines.
  3. Duplicated Methods in the Same or Different Class Code Smell:when you have two methods that do the same functionality. 
  4. Class Divergent Change Code Smell: Not following single responsibility principle
  5. Shotgun Surgery Code Smell: For example, you need to create a new user rule such as ‘Supper-Admin’ then you found yourself must edit some methods in Profile, Products and Employees classes. In that case, consider grouping these methods in one single class so this new class will have a single reason to change.
  6. Feature Envy Code Smell:A method in your class that extensively makes use of another class , then refractor that method into a different class.
  7. Data Clumps Code Smell:A list of functions accepts same group of large parameters.In that case its better to create a class which accepts parameters and send an object instead of parameter group.
  8. Switch Statement Code Smell: Case statements should not have lot of statements instead delegate call other methods/functions or return factory method
  9. Temporary Fields Code Smell:When you have a class instance variables that have been used only sometimes. 
  10. Message Chains Code Smell:When you have a class that uses another class which uses another class and so on.
  11. (in scala : Make your code cleaner by shortening the chain to Employee->Config
  12. Middle Man Code Smell:Sometimes you find many methods in one class do nothing but delegating to another method in a different class.t would be better to get rid of it.
  13. Alternative Classes with Different Interfaces Code Smell:two different classes are created which do the same thing 
  14. Incomplete Library Class Code Smell:Sometimes when you need to retrieve all documents of a particular user? Remember that it is horrible if you tried to edit third-party classes on your own. In this case, you need to extend the functionality of the Document class without editing the original class. Well, the decorator design pattern can be helpful here
  15. Comments Code Smell : Comments is a code smell
  16. Speculative Generality Code Smell : 
    1. * Don’t over plan your code.
    2. * Don’t try to cover a case that likely has 1% chance to happen in the future.
    3. * Sacrifice some speed in order to make your algorithm simpler, especially if you don’t need a real-time result from your application.
    4. * Optimise for speed when your application is actually slow not when you only have 100 users.

Ref :Refactoring for Software Design Smells: Managing Technical Debt  by Girish Suryanarayana

Friday, December 27, 2019

Python : SOLID Principles


SOLID principles:


  • S Single Responsibility - Should have single reason to change and should be related to its primary objective.
  • O Open Closed - add features by extension, not by modification
  • L Liskov Substitution
  • I Interface Segregation
  • D Dependecny Inversion

AntiPattern:
    God Object : Reverse of Single Responsibility ie., 1 class doing everything

- - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - -
Single Responsibility : A class should have only one job
Example :
class User:
def __init__(self, name: str): self.name = name
def get_name(self) :pass
def save(self, user: User): pass

Problem: User class is taking responsibility of Saving as well .
Solution :
class User:
def __init__(self, name: str): self.name = name
def get_name(self): pass

class UserDB:
def save(self, user: User):pass
- - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - -
Open Closed : Classes should be open for extension, not for modification.
Example :
class bottle:
def __init__(self, season, price):
self.season = season
self.price = price

def give_discount(self):
if self.season == 'normal': return self.price
if self.season == 'festival': return self.price * 0.1

Problem : Let’s imagine you have a store, and you give a discount of 20% to your favorite customers using this class:
When you decide to offer double the 20% discount to VIP customers. You may modify the class

Solution:
class bottle:
def __init__(self, season, price):
self.season = season
self.price = price
def give_discount(self):return self.price

class Festival_bottle_price(bottle):
def give_discount(self): return self.price * 0.1
- - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - -
Liskov Substitution Principle:  A sub-class can assume the place of its super-class without errors.
Example :
class Bird():
def fly(self):pass

class Duck(Bird):
def fly(self):pass

class penguin(Bird):
def fly(self):pass

Problem : This breaks LSP.As penguin cannot fly hence this causes error
Solution :
class Bird():pass
class FlyingBirds(Bird) :
def fly(self):pass

class Duck ( FlyingBirds):pass
class Ostrich ( Bird): pass
- - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - -
Interface Segregation:Make interfaces that are client specific Clients should not be forced to depend upon interfaces that they do not use
Example :
class Machine:
def print(self):raise NotImplementedError()
def call(self):raise NotImplementedError()

class Printer(Machine):
def print(self, document): pass

Problem : Printer object throws exception when Printer().call() is performed as it should not have been exposed in the first place.
Solution:
class Machine:
def perform_operation(self):raise NotImplementedError()

class Printer(Machine):
def perform_operation(self, document): pass
class call_phone(Machine):
def perform_operation(self, document): pass
- - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - -
Dependency Inversion  :A: High-level modules should not depend on low-level level modules. It should depend upon its abstraction.
Example :
class Http:
def __init__(self, xml_http_service: XMLHttpService):self.xml_http_service = xml_http_service

def get(self, url: str, options: dict):self.xml_http_service.request(url, 'GET')

def post(self, url, options: dict):self.xml_http_service.request(url, 'POST')

class XMLHttpService(XMLHttpRequestService):pass

Problem:Http =high-level component , XMLHttpService= low-level component.
The Http class should care less the type of Http service you are using

Solution:
class Connection:
def request(self, url: str, options: dict):
raise NotImplementedError

class Http:
def __init__(self, http_connection: Connection):
self.http_connection = http_connection

def get(self, url: str, options: dict):self.http_connection.request(url, 'GET')

def post(self, url, options: dict):self.http_connection.request(url, 'POST')

class NodeHttpService(Connection):def request(self, url: str, options:dict):pass

class MockHttpService(Connection):def request(self, url: str, options:dict):pass






Python :open Closed principle



"""OCP - Open Closed PrincipleOpen for expansion but closed for modification 
Goal : Instead of modifing existing class , your are encouraged to create a new class to solve the problem
Summary : To select object from a list of objects based on the properties
Description :Assume you have a box containing objects .You job is to select an object based on the properties like size and color . Here number of objects , size and color can be of any number .You have to printTrue for object which satisfies all the properties mentioned using Open Closed Principle.
Solution:1. you can select an object by size or color .Eg: small2. You can select object by both size and color . Eg: small and red
Steps:1. Start by creating classes which selects an object based on 1 property2. If u have 2 property create 2 classes3. For combination create last class which takes above 2 class objects as input  
"""
from enum import Enum
class COLOR(Enum):
    black="BLACK"    white="WHITE"
class SIZE(Enum):
    big="BIG"    small="small"
class Product():
    def __init__(self,color,size):
        self.color=color
        self.size=size

class match():
    def test(self,obj1,obj2):
        pass
class color_match(match):
    def __init__(self,color):
        self.color=color

    def test(self,target):
        return self.color==target.color

class size_match(match):
    def __init__(self,size):
        self.size=size

    def test(self,target):
        return self.size==target.size

class And_operation():
    def __init__(self,match1,match2):
        self.match1=match1
        self.match2=match2

    def test(self,target):
        return self.match1.test(target) and self.match2.test(target)

pen=Product(COLOR.black.value, SIZE.small.value)
paper=Product(COLOR.white.value,SIZE.small.value)
book=Product(COLOR.white.value,SIZE.big.value)

Products=[pen,paper,book]
Color_match=color_match(COLOR.white.value)
Size_match=size_match(SIZE.small.value)

combination=And_operation(Color_match,Size_match)
for product in Products:
    print(combination.test(product))
Output :
False
True
False