Is refactor method to field in this case?

public class WebContext(){

    private HttpServletRequest request;

    private WebContext(){};
    public static WebContext newPrototype(HttpServletRequest request){
        WebContext wc = new WebContext();
        wc.request = request;
    }

    public boolean isLogin(){
        return request.getSession().getAttribute(CONSTANT.SESSION_TOKEN)==null;
    }

    private RemoteUser getRemoteUser(){
        RemoteUser ru = new RemoteUser();
        if(isLogin()){
            ru = ...;    //...get remote user info from remote server
        }
        return ru;
    }

    public User getUser(){
        User user = new User();
        if(isLogin()){
            RemoteUser ru = getRemoteUser();
            long userid = ru.getUserid();
            user = ...;  //... get user info from db by userid;
        }
        return user;
    }

    public Trader getTrader(){
        Trader trader = new Trader();
        if(isLogin()){
            RemoteUser ru = getRemoteUser();
            long traderid = ru.getTraderid();
            trader = ...;  //... get trader info from db by traderid;
        }
        return trader;
    }
}

this make me uncomfortable, getUser() and getTrader() all must invoke getRemoteUser() firstly. so i refactor this class to

public class WebContext(){

    private HttpServletRequest request;
    private boolean isLogin;
    private RemoteUser ru;

    private WebContext(){};
    public static WebContext newPrototype(HttpServletRequest request){
        WebContext wc = new WebContext();
        wc.request = request;
        wc.islogin = request.getSession().getAttribute(CONSTANT.SESSION_TOKEN)==null;
        wc.ru = getRemoteUser();
    }

    public boolean isLogin(){
        return isLogin;
    }

    private RemoteUser getRemoteUser(){
        RemoteUser ru = new RemoteUser();
        if(isLogin){
            ru = ...;    //...get remote user info from remote server
        }
        return ru;
    }

    public User getUser(){
        User user = new User();
        if(isLogin){
            long userid = ru.getUserid();
            user = ...;  //... get user info from db by userid;
        }
        return user;
    }

    public Trader getTrader(){
        Trader trader = new Trader();
        if(isLogin){
            long traderid = ru.getTraderid();
            trader = ...;  //... get trader info from db by traderid;
        }
        return trader;
    }
}

refactored construct method init RemoteUser once. but i am confident about refactored construct method is not good for reused.i am confused how should i do for good code design;

参考资料

stack overflow跳点

阅读更多
个人分类: 问题与问题处理
想对作者说点什么? 我来说一句

没有更多推荐了,返回首页

加入CSDN,享受更精准的内容推荐,与500万程序员共同成长!
关闭
关闭