azizkhani.net

I know that I know nothing

What is Refactoring?

clock May 17, 2013 20:57 by author Administrator

Refactoring is a disciplined technique for restructuring an existing body of code, altering its internal structure without changing its external behavior. Its heart is a series of small behavior preserving transformations. Each transformation (called a 'refactoring') does little, but a sequence of transformations can produce a significant restructuring. Since each refactoring is small, it's less likely to go wrong. The system is also kept fully working after each small refactoring, reducing the chances that a system can get seriously broken during the restructuring.

This is a simple list of refactorings both from the original book and some later sources. Refactorings marked with with have some extra material to what's in the Refactoring book. Refactorings marked with are in addition to those in the refactoring book. Refactorings with Link Only are references to refactorings described elsewhere.

 

 



The generic repository is just a lazy anti-pattern

clock April 18, 2013 19:48 by author Administrator

A generic repository is often used with the entity framework to speed up the process of creating a data layer. In most cases this is a generalization too far and it can be a trap for lazy developers.

A generic repository often looks something like the code below. It defines generic methods for the most common types of data operation, such as updating, fetching and deleting. It’s appealing to developers because it’s simple, flexible and allows you to crank out a large domain model without having to write a lot of code.

public interface IRepository
{
    IEnumerable GetAll();
    IEnumerable Find(Expression> query);
    T GetByID(int id);
    void Add(T item);
    void Update(T item);
    void Delete(T item);
}

The problem is that this is not a neat and convenient abstraction, but rather a time-saving short-cut that can undermine the coherence of a solution in a number of respects.

It’s a leaky abstraction

Martin Fowler defines a repository as an “object that mediates between the domain and data mapping layers”. The objective is to isolate domain objects from details of the data access code.

However, the generic repository can allow developers to wrap the underlying data access technology such as Entity Framework classes. This allows a direct dependency from the data access technology to leak out into the application logic.

A repository should abstract the entire data access layer and enforce the concealment of details such as the database engine or data access technology. This generic implementation does not necessarily isolate anything – it’s just adding a pointless and leaking abstraction with no guaranteed benefits.

It’s too much of a generalization

Most repositories need “Save” and “Delete” methods… well, actually, do they? One objection to the generic repository is that it’s just plain lazy as the developer has not taken the time to consider how any consuming classes will use it. For example, are there any specialized fetch methods you need that may support, say, pagination? Will the repository specialize in reading or updating the model?

Very few real-world domain models can be addressed by the same set of methods. You should consider how you want data to be used. Once you start trying to serve more specialized business requirements then the generic repository quickly starts to look inadequate.

It doesn’t define a meaningful contract

The repository should represent a contract between the domain objects and a data store. It defines the kinds of operations that a data store is expected to service. A weakness of the generic repository is that it defines this contract so widely that it becomes almost meaningless.

The first line of code below illustrates the kind of search method that is often found in generic repositories. It provides a lot of flexibility over how you might query data, but it’s impossible to tell what form of contract this represents. It could be asking the data store to return pretty much anything.

    
IQueryable Find(object query);
    IQueryable FindCustomerByName(string name);

The second line represents something far more concrete. It clearly defines the relationship between domain objects and data store. Apart from the certainty of the contract, it provides a far more readable implementation.

A generic repository does have a place… just not on the frontline

Nobody likes to repeat themselves, but a generic repository interface is an over generalization. That said, there’s nothing to stop you from using a generic repository class as part of a more specific repository implementation. This will help you to derive the re-use benefits of a generic repository whilst still providing a strongly-defined contract.

The code below shows a simple example where a generic Repository<T> class marked for internal access is used within a public-facing repository implementation. This composition approach cuts down on the amount of code you have to write whilst still providing a meaningful public-facing contract.

public class CustomerRepository
{
    private Repository internalRepository;

    public IEnumerable FindCustomerByName(string input)
    {
        return internalRepository.FindBy(c => c.Name == input);
    }
}

A generic repository does have a place, but as a helper rather than a contract. The trick is not to expose a generic interface but achieve re-use through composition.

thanks mohsen salehi for share this post

ref:http://www.ben-morris.com/why-the-generic-repository-is-just-a-lazy-anti-pattern



50 Tricks for Faster Web Applications

clock November 25, 2012 13:05 by author Administrator

Jatinder Mann, an Internet Explorer PM at Microsoft, held the session 50 performance tricks to make your HTML5 apps and sites faster at BUILD 2012, providing many tips for creating faster web applications.

The advice provided by Mann was organized around six principles outlined below.

1. Quickly Respond to Network Requests.

  • Avoid Redirections. 63% of the top 1,000 websites use redirections. They could increase the speed of their pages by 10% by not performing a redirect.
  • Avoid Meta-refresh. 14% of the world’s URLs use meta-refreshes.
  • Minimize server response time by using CDNs located as close as possible to the user
  • Maximize the usage of concurrent connections by downloading resources from different domains
  • Reuse connections. Don’t close the connection when responding to a request.
  • Make sure data served by partner sites is not delaying page load
  • Understand the network timing components –Redirect, Cache, DNS, Request, Response, etc. –. Use the Navigation Timing API on IE 9&10 to measure the time spent by the browser on each operation.

2. Minimize Bytes Downloaded. Minimize the amount of data downloaded when a web page is loaded. The average website downloads 777KB of data out of which 474KB being images, 128KB scripts, and 84KB Flash.

  • Request gzipped content
  • Keep resources locally in packages, such as the Package Resource Index generated for the Windows Store apps. That way they are readily available when necessary.
  • Cache dynamic resources in HTML5 App Cache. This cache downloads the resources only once avoiding multiple network trips. The cache automatically re-downloads resources when the version of the application changes.
  • Provide cacheable content whenever possible by using the “Expires” field in the response.
  • Use conditional requests by setting the If-Modified-Since field of the request. 
  • Cache data requests –HTTP, XML, JSON, etc. – because about 95-96% of the requests don’t change over the day. Although a reasonable idea, less than 1% of the websites cache the requests received.
  • Standardize file naming capitalization. While a server may recognize Icon.jpg as icon.jpg, they are different resources for the web platform, generating different network requests.

3. Efficiently Structure Markup. For IE use the latest markup standardization since it is the fastest. Earlier IE6-IE9 markup styles are recognized by IE 10 but they are not as fast as the latest one.

  • Use the HTTP header field “X-UA-Compatible: IE=EmulateIE7” instead of the HTML tag <meta http-equiv="X-UA-Compatible" content="IE=EmulateIE7"> to force IE run in a legacy mode that might be needed for certain business web applications. It’s faster that way.
  • Stylesheets should be linked at the top of the page inside the <head>, after the <title> in order to provide a smooth rendering.
  • Stylesheets should never be linked at the bottom of the page. The page may be flashing while loading.
  • Avoid “@import” for hierarchical styles because it synchronously blocks the creation of CSS data structures and screen painting.
  • Avoid embedded and inline styles because it forces the browser to make a context switch between the HTML and CSS parsers.
  • Only include the necessary styles. Avoid downloading and parsing style that won’t be used.
  • Link JavaScript only at the bottom of the page. This makes sure that the images, CSS, etc. are already loaded so the scripts can do they job without waiting on the resources, and avoiding context switching.
  • Do not link JavaScript in the head of the page. Use the “defer” attribute if some scripts must be loaded at the beginning.
  • Avoid inline JavaScript to avoid context switching.
  • Use the “async” attribute to load JavaScript to make the entire script loading and executing asynchronous.
  • Avoid duplicate code. 52% of the world’s web pages contain 100 lines or more of duplicate code such as linking a JavaScript file twice.
  • Standardize on one JS framework, be it jQuery, Dojo, Prototype.js, etc.. The browser won’t have to load multiple frameworks that provide basically the same functionality.
  • Don’t load scripts –FB, Twitter, etc. - just to be cool. They compete for resources.

4. Optimize Media Usage. Images are the most utilized resource, on average a website downloading 58 images.

  • Avoid downloading too many images, keeping their number to maximum 20-30 due to page load time.
  • Use image sprites to combine multiple images into one. This technique reduces the number of network connections, and the number of bytes downloaded and GPU cycles.
  • Create image sprites by hand because tools may leave large empty spaces leading to larger downloads and more GPU cycles.
  • Use PNG: best compromise between download size, decoding time, compatibility, and compression rate. JPEG may be used for photographs.
  • Use the native image resolution to avoid unnecessary bytes download and CPU processing for scaling.
  • Replace images with CSS3 gradients when possible.
  • Replace images with CSS3 border radius when possible.
  • Use CSS3 transforms to create move, rotate or skew effects.
  • Use Data URI for small single images. It saves an image download.
  • Avoid complex SVGs which require longer downloads and processing.
  • Specify an image preview when including an HTML5. The browser won’t have to download the entire video to figure out what the preview image should be.
  • Use HTML5 instead of Flash, Silverlight, or QuickTime. HTML5 is faster and the plug-in runtime takes system resources.
  • Proactively download rich media asynchronously and keep it in the app cache.

5. Write Fast JavaScript.

  • Use Integers when doing math operations in JavaScript, if possible. Floating point operations take much longer in JavaScript than their corresponding integer operations. Convert floating points into integers with Math.floor and Math.ceil, especially for computationally intensive operations.
  • Minify JavaScript code for smaller downloads and better runtime performance.
  • Initialize JS on demand. Load JS dynamically when needed.
  • Minimize DOM interactions by caching variable such as document, body, etc.
  • Use the built-in DOM code such as element.firstChild or node.nextSibling. They are highly optimized, better than what a third party library might provide.
  • Use querySelectorAll for accessing a large number of DOM elements.
  • Use .innerHTML to construct dynamic pages.
  • Batch markup changes.
  • Maintain a Small and Healthy DOM – maximum 1,000 elements.
  • JSON is faster than XML.
  • Use the browser’s JSON native methods.
  • Don’t abuse the usage of regular expressions.

6. Know What Your Application is Doing

  • Understand JavaScript timers: setTimeout and clearInterval. Don’t let timers run unless you use them for something. Also, combine timers.
  • Align timers to the display frame at 16.7 ms if the monitor refreshes at 60Hz.
  • Use requestAnimationFrame for animations to do graphics work in IE 10/Chrome/Firefox. It makes a call back when it is the time to paint, so there is no need for a timer.
  • Use the visibility API (document.hidden, Visibilityhange) to determine the visibility state of the application, and throttle down activity when the page is hidden. Saves CPU and battery life.

Mann recommended using Windows Performance Tools to measure the performance of web pages in IE and optimizing pages for less CPU time and increasing parallelism.

 



Decorator Design Pattern Case Study

clock October 24, 2012 22:36 by author Administrator



Decorator pattern is basically a way to extend functionality of an object by decorating with other objects which can wrap the target object and add their own behavior to it. If you never used or heard of decorators, I highly recommend reading chapter 3 of Head First Design Patterns.

Pretty much like other patterns mentioned in my posts before, JavaEE has an easy an elegant way to use the decorator pattern. Lets start with a simple stateless session bean.


package com.devchronicles.decorator;

import javax.ejb.Stateless;
import javax.ejb.TransactionAttribute;
import javax.ejb.TransactionAttributeType;

/**
 *
 * @author murat
 */
@Stateless
@TransactionAttribute(TransactionAttributeType.REQUIRED)
public class EventService {
    
    public void startService(){
        System.out.println("do something important here...");
    }
}

To start implementing the decorator pattern, we need an interface so we can bind the decorators and the object to be decorated together.


package com.devchronicles.decorator;

/**
 *
 * @author murat
 */
public interface ServiceInterface {
    public void startService();
}

The interface has the method which the decorators will add functionality on. Next we need some changes on our existing EventService bean to make it decoratable.


package com.devchronicles.decorator;

import javax.ejb.Stateless;
import javax.ejb.TransactionAttribute;
import javax.ejb.TransactionAttributeType;

/**
 *
 * @author murat
 */
@Stateless
@TransactionAttribute(TransactionAttributeType.REQUIRED)
public class EventService implements ServiceInterface{
    
    public void startService(){
        System.out.println("do something important here...");
    }
}


Now we are ready to add as much as decorator we need. All we need to do is to annotate our class, implement the ServiceInterface and to inject our service delegate.


package com.devchronicles.decorator;

import javax.decorator.Decorator;
import javax.decorator.Delegate;
import javax.inject.Inject;

/**
 *
 * @author murat
 */
@Decorator //declares this class as a decorator
public class DecoratorService implements ServiceInterface{ //must implement the service interface
    
    @Inject //inject the service
    @Delegate //and annotate as the delegate
    ServiceInterface service;

    @Override
    public void startService() { //implement the startService method to add functionality
        System.out.println("decorating the existing service!");
        service.startService(); //let the execution chain continue
    } 
}

Several decorators can be using the service interface.


package com.devchronicles.decorator;

import javax.decorator.Decorator;
import javax.decorator.Delegate;
import javax.inject.Inject;

/**
 *
 * @author murat
 */
@Decorator
public class Decorator2Service implements ServiceInterface{
     @Inject
    @Delegate
    ServiceInterface service;

    @Override
    public void startService() {
        System.out.println("decorating the service even further!!!");
        service.startService();
    }
}

Most of the configuration can be done via annotation in JavaEE6. However we still need to add some xml configuration to make decorators work. It might seem disappointing since we already annotated our decorators but still the configuration is pretty simple and needed in order to declare the order of execution. Add the following lines to the empty beans.xml.


<?xml version="1.0" encoding="UTF-8"?>
<beans xmlns="http://java.sun.com/xml/ns/javaee"
       xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance"
       xsi:schemaLocation="http://java.sun.com/xml/ns/javaee http://java.sun.com/xml/ns/javaee/beans_1_0.xsd">
           <decorators>
               <class>com.devchronicles.decorator.DecoratorService</class>
           <class>com.devchronicles.decorator.Decorator2Service</class>
           </decorators>
</beans>

When the startService method of our EventService is executed, the decorators will decorate the ejb and add their own behavior to the execution.

...

INFO: WEB0671: Loading application [Decorator] at [/Decorator]
INFO: Decorator was successfully deployed in 2,534 milliseconds.
INFO: decorating the existing service!
INFO: decorating the service even further!!!
INFO: do something important here...
...

Reference: JavaEE Revisits Design Patterns: Decorator



Factory Design Pattern Case Study

clock October 18, 2012 21:52 by author Administrator

I had a job to check our project code quality. And have to report it back to my team leader for any obstacle that i found in the project. I found a lot of leaks and i think would be good to be discussed on the blog. Not to mock the author, but to learn and improve ourselves together.

Like this code, this is the part that i found in our code.

 

public ContactInfoBean(final Reseller resellerInfo) {

       switch(resellerInfo.getType()) {

           case PROGRAM_CONTACT:
                   readExecutiveInfo(resellerInfo);
               break;
           case FILE_CONTACT:
                  readOperationalInfo(resellerInfo);
               break;
           default:

               break;

       }

   }

The code works fine, and do its job pretty well. But some problem will appear by using this code-style. This class will grow tailing the biz changes, as usual, the bigger one class, the “merrier” to maintain it is. And most likely this class, will be having more than one purpose, can be called low-cohesion.

Better OOP Approach

Well the better approach for the case above would be using the Factory Design Pattern. We can let the factory of READER to generate every single instance according to their type. It would be easier to grow the instance type, since we just need to create a new class and do a little modification in the Factory class. The caller class, wont grow and will stand still at its current shape.

public interface InfoReader {

      public void readInfo();

}


public class ExecutiveReader implements InfoReader {

      public void readInfo() {
           // override
      }

}

 


public class OperationalReader implements InfoReader {

        public void readInfo() {
         // override
        }

}

And The Factory

public class InfoReaderFactory {

      private static final int PROGRAM_CONTACT = 1;

      private static final int FILE_CONTACT = 2;

      public static InfoReader getInstance(Reseller resellerInfo) {

              InfoReader instance = null;

             switch (resellerInfo.getType()) {

                 case PROGRAM_CONTACT:

                       instance = new ExecutiveReader();

                    break;

                 case FILE_CONTACT:

                     instance = new OperationalReader();

                   break;

                default:

                    throw new IllegalArgumentException('Unknown Reseller');

      }

     return instance;

   }

}

And now The Caller

InfoReader reader = InfoReaderFactory.getInstance(resellerInfo);

reader.readInfo();


The Benefits

With the Factory Design Pattern to handle this case, we can achieve some benefits,

  • Specifying a class for one task, means, easier to maintain since one class is for one purpose only (modularity/High Cohesion). i.e: Operational Reader is only to read data for Operational only, no other purpose. Just in case, one day in the future we need another Reader (say: NonOperationalReader). We just need create a new Class that extends (or implements) the InfoReader class and then we can override our own readInfo() function. This Caller class will have no impact. We just need to do some modification in the Factory code.


public class InfoReaderFactory {
    private static final int PROGRAM_CONTACT = 1;
    private static final int FILE_CONTACT = 2;
    private static final int NEW_READER = 3;

    public static InfoReader getInstance(ResellerInfo resellerInfo) {
        InfoReader instance = null;
        switch (resellerInfo.getType()) {
          case PROGRAM_CONTACT:
              instance = new ExecutiveReader();
              break;
          case FILE_CONTACT:
              instance = new OperationalReader();
              break;
          case NEW_READER:
              instance = new NonOperationalReader();
              break;
          default:
              throw new IllegalArgumentException('Unknown Reseller');
        }
        return instance;
    }
}

Higher Reusability of Parent’s Component (Inheritance): Since we have parent class (InfoReader), we can put common functions and thingies inside this InfoReader class, and later all of the derivative classes (ExecutiveReader and OperationalReader) can reuse the common components from InfoReader . Avoid code redundancy and can minimize coding time. Eventhough this one depends on how you do the code and cant be guaranteed.


But, It’s Run Perfectly, Should We Change It?

Obviously the answer is big NO. This is only the case study and for your further experience and knowledge. OOP is good, do it anywhere it’s applicable. But the most important thing is, if it’s running, dont change it. It would be ridiculous if you ruin the entire working code just to pursue some OOP approach. Dont be naive also, no one can achieve the perfect code. The most important is we know what is the better approach.

 

 

ref:http://namingexception.wordpress.com/2012/10/17/case-study-factory-design-pattern/



About the author

 Welcome to this web site . This page has two purposes: Sharing information about my professional life such as articles, presentations, etc.
This website is also a place where I would like to share content I enjoy with the rest of the world. Feel free to take a look around, read my blog


Java,J2EE,Spring Framework,JQuery,

Hibernate,NoSql,Cloud,SOA,Rest WebService and Web Stack tech...

RecentPosts

Month List

Sign In