I need some advice on my code structure. I have read that setters and getters break one of the OOP principals, encapsulation, and that we should avoid them if possible but I cannot think of any other way to expose info other than getters.
I have a class which calculates price, savings and taxes based three inputs from the user through the initializer (initialPrice, discount and taxRate).
I'm using three computer properties to exposed the results, is this considered a bad thing? If yes, why and how can I improve my code?
Besides what I described above the class also has the ability to add all of the items in an array, assuming the instances of the CalculatorBrain were placed in an array.
Again, I'm more concern about the structure of my code. Any advice will be appreciated.
class CalculatorBrain {
private var taxRate:Double = 0
private var discount:Double = 0
private var initialPrice:Double = 0
func setInitialValues(initialPrice:Double, discount:Double, taxRate:Double){
self.taxRate = taxRate
self.discount = discount
self.initialPrice = initialPrice
}
private func salePrice()->Double{
return initialPrice - savings
}
var price:Double{
get{
return salePrice() + taxes
}
}
var savings:Double{
get{
return initialPrice * discount / 100
}
}
var taxes:Double{
get{
return salePrice() * taxRate / 100
}
}
internal func grandTotals(list:Array<Item>)->(grandPrice:Double, grandSavings:Double, grandTaxes:Double){
var grandPrice:Double = 0
var grandSavings:Double = 0
var grandTaxes:Double = 0
for i in 0..<list.count {
grandPrice = grandPrice + Double(list[i].totalPrice)
grandSavings = grandSavings + Double(list[i].savings)
grandTaxes = grandTaxes + Double(list[i].taxes)
}
return (grandPrice, grandSavings, grandTaxes)
}
}