Reputation: 313
I am developing a mobile app, where there is a requests class responsible for sending requests to the server. What is a good practice, to initialize this requests class in the constructor of the classes which access it and then call the functions, or declare the api functions as static so functions can be called with no prior initialization ?
Upvotes: 1
Views: 112
Reputation: 9264
If you want the requests to share instance variables such as an http.Client
you should prefer the constructor variation. It also makes testing easier as ryanwebjackson said. If they are simply a collection of functions that don't share information then static methods are fine.
If you're worried about instantiating several resource intensive objects, then you could create getters that lazy initialize expensive tasks, e.g.
abstract class Request {
final Client client;
var _loadsOfData;
Request(this.client);
Future get loadsOfData async => _loadsOfData ??= _fetchLoadsOfData();
}
Upvotes: 0