Properties vs constructor:
I’m currently creating a new project and have a class called Repository that gathers info about the system the code is running on and makes some api requests. If the class has several internal values like system status which is fetched from an api, should I run the code to fetch the status in the constructor or can I have a property getter so I can write repo.system_status to get the latest value without needing to call a function ?
5 Replies
Your constructor is for setting the initial state, but it should do so with the values it gets provided and it should remain a dumb component in your application. What you want is not only too complex, it is also asnchronous. You should check out the factory pattern for this if your class relies on a fetched/complex initial state
Can properties not be asynchronous?
no
Ahh okay thank you
You mentioned the factory pattern, so is it a bad idea to have a get_state() function in the constructor and instead have a factory with a build method that performs that logic ?
Idk what you mean with
get_state()
but I assume you mean using a property getter
You should use a factory pattern for initialization in general where the state has to be determined. So asynchronous, but also just big tasks that your class requires to set up