For example, suppose I have a shopping app, which has a user info page to show user info:

class UserInfoController{
    toPurchaseRecord(){
    }
}

and a purchase record page to show purchase record, which can be reached from user info:

class PurchaseRecordController{
}

but the problem is, I need to get data from internet, and then show the data by using PurchaseRecordController. My question is, should I :

1.start connection at UserInfoController:

class UserInfoController{
    toPurchaseRecord(){
          new HttpConnection("(url)",function(result){
              new PurchaseRecordController();
          });
      }
    }
}

class PurchaseRecordController{
    constructor(result){
        //show data according to result
    }
}

2.start connection in PurchaseRecordController

class UserInfoController{
    toPurchaseRecord(){
          new PurchaseRecordController();
      }
    }
}

class PurchaseRecordController{
    constructor(result){
        new HttpConnection("(url)",function(result){
            //show data according to result
        }.bind(this));
    }
}

which one should I use?

有帮助吗?

解决方案

I'd suggest the first approach because:

  • Constructor is not a good place for accessing slow Internet network. Programmers generally expect a constructor be returned virtually instantly. What happen if the Internet connection is down, how are you going to report the errors to users in a constructor? In your first approach, you could easily show a popup box if the Internet connection is down.
  • Continued from the previous point. UserInfoController has a view, right? So you could show a download progress bar, make your app darker while downloading etc etc. You can't do that in a constructor!!
  • In your second approach, it'd be harder to mock and unit-test your PurchaseRecordController. However, if your controller takes the fetched objects (e.g. JSON), you can easily apply unit testing on them.
  • Don't allocate PurchaseRecordController too much responsibility. Make it simple. It should just transform your raw Internet data to a format that your user is happy to view.
许可以下: CC-BY-SA归因
scroll top