Search code examples
javaconstructorfactory-pattern

Constructor Has many Elements. how to refactor (Factory pattern)


i am having a constructor with Factory pattern. i am passing to many parameters. how to refactor it.

ServerFactory serverFactory = new ServerFactory();
CalendarResults calResults= serverFactory.getResults(serverName,locale, Day, week,     
                            month,vdate,results,uri, EmailShare, inc, upperLimit, 
                            endLimit,exchWD, YearMonthDay,WeekMonthDate);
results=calResults.serverNameDay(serverName,locale, Day, week, month,vdate,
        results,uri, EmailShare, inc, upperLimit, endLimit, exchWD, YearMonthDay);

public class ServerFactory {
    public CalendarResults getResults(String serverName,String locale, String day,    
                     String week, String month, 
             boolean vdate, ArrayList<CalendarOutput> results, String uri, 
                     List<String> emailShare, int inc, int upperLimit, 
             int endLimit, NexWebDav exchWD, String yearMonth, boolean 
                     weekMonthDate){

        CalendarResults calresults=null;
        if(serverName.equals("www.google.com")){
            calresults=new Google();
        }else{
            calresults=new Exchange();
        }
        return calresults;
    }
 }

Solution

  • Hard to tell since you don't show all the code (I assume) where all these parameters get used.

    But here are some things to consider:

    • Replaces arguments of primitive type with value objects, this makes it much clearer what parameter is expected in what position.

    • combine multiple related arguments to value objects. One example that seems obvious is upperLimit, endLimit (and maybe inc) which might end up in an object called Intervall.

    • replace booleans with different methods. Often booleans are used to perform different algorithms. If that's the case drop the booleans an make seperate methods instead.

    • If you have still to many and to confusing arguments, you might want to go with a Builder Pattern. This and the following blog posts might be helpfull: http://blog.schauderhaft.de/2012/07/29/named-parameters-in-java/