在这种情况下是重构方法吗?

时间:2016-12-22 02:26:11

标签: java refactoring

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;
    }
}

这让我感到不舒服,getUser()和getTrader()都必须首先调用getRemoteUser()。 所以我重构这个课程

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;
    }
}

重构的构造方法init RemoteUser一次。但我对重构的构造方法对重用没有好处。我很困惑我应该如何做好代码设计;

0 个答案:

没有答案