I am attempting to do a project which models a grocery store that sells various desserts. Currently, I am trying to create a class for a tiered cake which is derived from a cake class which itself is derived from an abstract dessert class. Essentially, the cake class's constructor has two parameters, name and price. For the tiered cake, the price is the price of the base + the price of the top + an additional 10% of the total. I've found a way to do this, but it's a really long, ugly line of code. I've experimented with a few ways to try and simplify it using variables, but I can't seem to figure out a way that works with the fact that it is being done within a super()
. Is there a way I could make it simpler and more efficient? Thanks in advance!
Here is the code:
public class TieredCake extends Cake {
private Cake base;
private Cake top;
public TieredCake (Cake base, Cake top) {
super(base.getName() + " with an upper tier of " + top.getName(), (base.getPrice() + top.getPrice()) * 0.10 + base.getPrice()+top.getPrice());
this.base = base;
this.top = top;
}
public Cake getBase() {
return base;
}
public Cake getTop() {
return top;
}
}
Splitting the call to super
onto multiple lines helps a little:
public TieredCake(Cake base, Cake top) {
super(
base.getName() + " with an upper tier of " + top.getName(),
(base.getPrice() + top.getPrice()) * 0.10 + base.getPrice() + top.getPrice()
);
this.base = base;
this.top = top;
}
But more importantly, let’s take a look at that formula. There’s a bit of simplification we can do at a mathematical level:
B := base.getPrice()
T := top.getPrice()
(B + T) * 0.1 + B + T
= (B * 0.1) + (T * 0.1) + B + T
= (B * 1.1) + (T * 1.1)
= (B + T) * 1.1
That gives us:
public TieredCake(Cake base, Cake top) {
super(
base.getName() + " with an upper tier of " + top.getName(),
(base.getPrice() + top.getPrice()) * 1.1
);
this.base = base;
this.top = top;
}