开发者

What design pattern to use for one big method calling many private methods

开发者 https://www.devze.com 2023-01-03 18:37 出处:网络
I have a class that has a big method that calls on a lot of private methods. I think I want to extract those private methods into their own classes for one because they contain business logic and I th

I have a class that has a big method that calls on a lot of private methods. I think I want to extract those private methods into their own classes for one because they contain business logic and I think they should be public so they can be unit tested.

Here's a sample of the code:

public void handleRow(Object arg0) {
    if (continueRunning){
        hashData=(HashMap<String, Object>)arg0;
        Long stdReportId = null;
        Date effDate=null;
        if (stdReportIds!=null){
            stdReportId = stdReportIds[index];
        }   
        if (effDates!=null){
            effDate = effDates[index];
        }
        initAndPutPriceBrackets(hashData, stdReportId, effDate);
        putBrand(hashData,stdReportI开发者_如何学Pythond,formHandlerFor==0?true:useLiveForFirst);
        putMultiLangDescriptions(hashData,stdReportId);
        index++;
        if (stdReportIds!=null && stdReportIds[0].equals(stdReportIds[1])){
            continueRunning=false;
        }       
        if (formHandlerFor==REPORTS){
            putBeginDate(hashData,effDate,custId);
        }
        //handle logic that is related to pricemaps.
        lstOfData.add(hashData);
    }
}   

What design pattern should I apply to this problem?


The State Pattern covers this scenario quite nicely.

The details are here

Here is a C# example

Enjoy!


I'd just bundle related methods and state (fields) into classes with public methods and inject them as services into the host class.

State pattern like Doug posted, describes such a division.

Also be sure to avoid cyclic dependencies when you split the behavior. This can easily happen, when done hastily.

Generally split class behavior into multiple classes for reuse and customization. If the only purpose is improved testability, then exposing methods as protected or public is an easier option.


The dramatic refactoring you're describing solely to fit your unit-test tools is a really, really a bad idea.

Don't allow flaws in the tools to drive your design.


Your concern about unit testing could be addressed by making the methods 'protected' and putting the test classes in the same package as the original source code.

0

精彩评论

暂无评论...
验证码 换一张
取 消