gpt4 book ai didi

How to understand 'Code at Wrong Level of Abstraction' from Clean code book?(如何从干净的代码手册中理解“错误抽象级别的代码”?)

转载 作者:bug小助手 更新时间:2023-10-25 21:31:18 31 4
gpt4 key购买 nike



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.

我正在阅读干净的代码第17章-嗅觉和启发式G6部分:错误抽象级别的代码,但我可以理解如何定义正确的抽象级别。



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 {}
}

更多回答
优秀答案推荐

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:

例如,如果您有一个基类Person,以及两个派生类Baby和Adult,这两个类都必须吃东西,并且它们都每天吃3次,但Baby一餐吃40克(例如),成人一餐吃150克,因此您将有2个常量,如下所示:


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)

您的代码中的错误在于Percent Full函数...并非所有堆栈都限制为最大数量的元素(如果没有最大数量的元素,Stack.FullException也没有意义)



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 {}

更多回答

31 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com