Friday, October 25, 2013

Coupling and Cohesion

What is Coupling ?
- Coupling indicates the degree of dependence among components. Higher coupling tends to indicate poor design of classes, since it makes modifying parts of the system difficult, as modifying a component affects all the components to which the component is connected.
- Class A has behaviourA and propertiesA, and Class B has behaviourB and propertiesB. Class A uses the properties and behaviours in Class B, and Class B also uses the properties and behaviours in Class A.
- We call High Coupling (Tighly Coupling)

What is the solution ?
- Lower Coupling is better .

Problem: Sample code High Coupling
package com.scjp6.oop.coupling;
public class CalculateTaxes {
    float rate;
    float doIndia() {
    TaxRatesInIndia str = new TaxRatesInIndia();
    return rate = str.salesRate; // ouch again
    }
}

package com.scjp6.oop.coupling;

public class TaxRatesInIndia {
    public float salesRate; // should be private

    public float adjustedSalesRate; // should be private
    public float getSalesTaxRates() {
        adjustedSalesRate = new CalculateTaxes().doIndia();
        return adjustedSalesRate;
    }
}
package com.scjp6.oop.coupling;


public class LowCoupling {


    public static void main(String[] args) {
    // TODO Auto-generated method stub

    Calculate calculate = new CalculateTaxeRateIndiaImpl();
    System.out.println(calculate.doIndia());
    System.out.println(calculate.getSalesTaxRates());
    }
}
Solution: Sample code Low/ Tigh Coupling

package com.scjp6.oop.coupling;

public interface Calculate {
    float doIndia();
    float getSalesTaxRates();   
}


package com.scjp6.oop.coupling;
public class CalculateTaxeRateIndiaImpl implements Calculate {
    @Override
    public float doIndia() {
       return 0;
    }


    @Override
    public float getSalesTaxRates() {
      return 0;
    }
}


package com.scjp6.oop.coupling;

public class LowCoupling {

    public static void main(String[] args) {
     Calculate calculate = new CalculateTaxeRateIndiaImpl();
     System.out.println(calculate.doIndia());
     System.out.println(calculate.getSalesTaxRates());
    }
}


What is Cohesion
- Cohesion is the extent to which methods in a class are related. It means, a class has many methods are related.
- We can call Low Cohesion

What is the solution ?
- High Cohesion is better .

Problem: Sample code Low Cohesion
package com.scjp6.oop.cohesion;

public class ReportGrade {
    Student getStudent() {
      return new Student();
    }

    Subject getSubject() {
      return new Subject();
    } 

    Grade getGrade(){
      return new Grade();
    }
}

package com.scjp6.oop.cohesion;

public class RunLowerCohesion {

    public static void main(String[] args) {
      ReportGrade reportGrade = new ReportGrade();
      reportGrade.getGrade();
      reportGrade.getStudent();
      reportGrade.getSubject();
    }
}

Solution: Sample code High Cohesion

public class Grade {
    String studentID;
    String subjectID;
    float grade01;
    float grade02;
}

package com.scjp6.oop.cohesion;
public class Student {
    String studentID;
    String name;
    int age;
}


package com.scjp6.oop.cohesion;
public class Subject {
    String subjectID;
    String subjectName;
}


package com.scjp6.oop.cohesion;
public class ReportGradeHighCohesion {   
     Grade getGrade(){
       return new Grade();
    }
}


package com.scjp6.oop.cohesion;
public class ReportStudentHighCohesion {
    Student getStudent() {
      return new Student();
    }   
}


package com.scjp6.oop.cohesion;
public class ReportSubjectHighCohesion {
    Subject getSubject() {
      return new Subject();
    }
}


package com.scjp6.oop.cohesion;
public class RunHighCohesion {


    public static void main(String[] args) {
    ReportGradeHighCohesion reportGradeHighCohesion = new ReportGradeHighCohesion();
    reportGradeHighCohesion.getGrade();

    ReportStudentHighCohesion reportStudentHighCohesion = new ReportStudentHighCohesion();
    reportStudentHighCohesion.getStudent();

    ReportSubjectHighCohesion reportSubjectHighCohesion = new ReportSubjectHighCohesion();
    reportSubjectHighCohesion.getSubject();
    }
}




Wednesday, October 23, 2013

MDC Logger

What is MDC?
- MDC stands for Mapped Diagnostic Context.
- It is a map which stores the context data of the particular thread where the context is running
Where do we use it ?
- For Jersey: ContainerRequestFilter, ContainerResponseFilter
- For Spring MVC : HttpServletRequest, HttpServletResponse
Why do we use it ?
- It helps you to distinguish inter-leaving logs from multiple sources.
- When we have multiple user-requests coming in for a given servlet, each request of an user is serviced using a thread. This leaves multiple users logging to the same log file and the log statements get inter-mixed.
- Now, to filter out logs of a particular user, we need to append the user-id to the log statements so that we can search them in the log file easily.
- An obvious way of logging, is to append the user-id in the log statements i.e. log.info(userId+” logged something “);
- A non-invasive way of logging is to use MDC.
- With MDC, you put the user-id in a context-map which is attached to the thread (of each user request) by the logger.

public class SimpleMDC {
    static public void main(String[] args) throws Exception {
    // You can put values in the MDC at any time. Before anything else

    // we put the USER-ID

    MDC.put("USER-ID""DirecTV");
    Logger logger = LoggerFactory.getLogger(SimpleMDC.class);
    // We now put the IP-ADDRESS
    MDC.put("IP-ADDRESS""10.88.68.11");
  
    logger.info("Start Logging");
    logger.debug("Mapped Diagnostic Context");
    logger.error("One of the design goals of logback is to audit and debug complex distributed applications");
    logger.error("Most real-world distributed systems need to deal with multiple clients simultaneously. ");
    logger.error("In a typical multithreaded implementation of such a system");
    MDC.put("USER-ID""FPT");
    MDC.put("IP-ADDRESS""100.888.688.111");
  
    logger.info("Start Logging");
    logger.debug("Mapped Diagnostic Context");
    logger.error("One of the design goals of logback is to audit and debug complex distributed applications");
    logger.error("Most real-world distributed systems need to deal with multiple clients simultaneously. ");
    logger.error("In a typical multithreaded implementation of such a system");
    }
}

Source Code