Imagine this example: there are a Set<Loan> loans in one of my classes, the purpose of this Set is to save the Loan history of a user in this system (bank system for example), if this Set is empty, it indicates that this user doesn’t have any Loan, here is my question :
is it a good practice to have a separate Boolean field, like Boolean hasLoan; for each user that shows the loan status of the user? I mean instead of checking for the emptiness of Set<Loan> loans i check the Boolean field for being true (has loan) and false (doesn’t have).
same story about the number of loans: instead of calling loan.length , I provide a field, like int loanCount and read its value?
by the way, I update these fields (hasLoan and loanCount ) every time that a loan added or removed. I call these fields “query fields” because I use them to answer the queries about the main Collection.
You don’t necessarily need to have a private member
Boolean hasLoan; You can just make a getter: