Edit: I'm copying the question but changing the example code. Apparently, I used a bad example earlier that contained an imprue getter. I'm keeping the old example code at the bottom so the first answers stay relevant.
Is storing computed values in the app runtime state always bad in OOP? Assuming that:
- Computation cost is low or neglectable.
- The object representing the state is immutable but many instances will be created from various parts of the code.
For example, is this code bad, and should be written as the next code block?
// bad
class AppState {
AppState(int debt, int savings, int netWorht);
final int debt;
final int savings;
final int netWorth;
}
// good
class AppState {
AppState(int debt, int savings);
final int debt;
final int savings;
int get netWorth => savings - debt;
}
If you think that the answer is yes (the first code block is bad), please share any resources you may have. I do believe so too but couldn't find any resource to back up my argument.
The old example for reference
// bad
class AppState {
AppState(Date birthday, int age);
final Date birthday;
final int age;
}
// good
class AppState {
AppState(Date birthday);
final Date birthday;
int get age => DateTime.now - birthday;
}
DateTime.now
as that does not have referential transparency, thus making your object not immutable in many senses of the term.debt
andsavings
are immutable, the compiler can optimize and store the result automatically.