Say I have have a class Event
as follows:
class Event {
private var attendees: [Person] = []
// Case 1
//*******
// Should I use a func…
func countOfAttendees() -> Int {
return attendees.count
}
// …or a var
var countOfAttendees: Int {
return attendees.count
}
// Case 2
//*******
// Should I use a func…
func countOfPaidAttendees() -> Int {
return attendees.filter({$0.hasPaid}).count
}
// …or a var
var countOfPaidAttendees: Int {
return attendees.filter({$0.hasPaid}).count
}
}
Is it best practice to use functions or computed properties in the 2 cases indicated above?
Best Answer
Follow the Uniform Access Principle,
To me, this means that I don't write funcs that take no arguments and return a value. I always use computed properties. That way, if I later decide to change the computed property into a stored property, I can do so without having the urge to remove the parens everywhere in my app and without having a separate "getter" method that just returns the value of a stored property, which seems pretty wasteful IMHO.
And if I change a stored property into a computed one, I don't have to add parens to the end of it, and everywhere that it is used in the app.