Reputation: 11
I'm reading the clean code Chapter 17 - Smells and Heuristics part G6: Code at Wrong Level of Abstraction but I can understand how can define a correct level of abstraction.
For example, constants, variables, or utility functions that pertain only to the detailed implementation should not be present in the base class. The base class should know nothing about them.
Could somebody please explain to me with a clearer example? There's an example but I don't understand why it's wrong.
public interface Stack {
Object pop() throws EmptyException;
void push(Object o) throws FullException;
double percentFull();
class EmptyException extends Exception {}
class FullException extends Exception {}
}
Upvotes: 0
Views: 321
Reputation: 1
I am trying to get my point across with this semicode
public interface Stack {
Object pop() throws Exception;
void push(Object o) throws Exception;
double percentFull();
class Exception {}
}
public class Exception {}
public class EmptyException extends Exception {}
public class FullException extends Exception {}
Upvotes: 0
Reputation: 12949
For example if you have a base class Person
, and two derived classes Baby
and Adult
, both of them have to eat, and both of them eats 3 times a day, but a Baby
eats 40g a meal (example) and an Adult
eats 150g a meal,
therefore you will have 2 constants like this:
class Person{
int howMuchEats();
}
class Baby extends Person{
int BABY_AVG_MEAL = 40;
int howMuchEats(){ return 3 * BABY_AVG_MEAL; }
}
class Adult extends Person{
int ADULT_AVG_MEAL = 150;
int howMuchEats(){ return 3 * ADULT_AVG_MEAL; }
}
If those constants were in the base class, than it would violate what your book is saying
This is for constants, but let's say that the average grams are calculated on the weight of the adult, that you would have a helper function that makes sense to exists only in the derived class
What's wrong in your code is the percentFull
function... not all stacks are bounded to a max number of elements (and without that, also Stack.FullException
makes no sense to be there)
Upvotes: 1