After many years of programming, I realized that there are only 3 basic concepts that you need to master to write good code: loose coupling, high cohesion and complexity reduction. Almost all design patterns or coding principles boil down to these 3 basic concepts.
经过多年的编程,我意识到编写好的代码只需要掌握3个基本概念: 松耦合 , 高内聚性和降低复杂性 。 几乎所有设计模式或编码原理都可以归结为这三个基本概念。
Detailed information about them can be found for example on Wikipedia. For now, let’s just start with a short intuitive definition of all 3 concepts:
有关它们的详细信息,例如可以在Wikipedia上找到。 现在,让我们从对这三个概念的简短直观定义开始:
1.松耦合 (1. Loose coupling)
- is about interaction between components (classes, interfaces, methods, packages, services, …) 关于组件之间的交互(类,接口,方法,包,服务等)
- components should have as few knowledge about other components as possible 组件应尽可能少地了解其他组件
- components should hide their own internal structure (encapsulation) 组件应隐藏自己的内部结构(封装)
- allows you to work on individual components without touching other components, for easier refactoring, bug fixing and adding of new features 允许您在不接触其他组件的情况下处理单个组件,以便于重构,错误修复和添加新功能
- 100% decoupling is usually not possible, because the components still need to interact with each other (and some interactions need more coupling than others, for example to achieve transactional integrity) 通常不可能实现100%的解耦,因为组件仍然需要彼此交互(并且某些交互需要比其他交互更多的耦合,例如,以实现事务完整性)
more details: https://en.wikipedia.org/wiki/Loose_coupling
更多详细信息: https : //en.wikipedia.org/wiki/Loose_coupling
2.高凝聚力 (2. High cohesion)
- is about structuring components 关于构造组件
- a component should ideally contain only code that is needed to fulfill one single functionality (functional cohesion) 理想情况下,组件应仅包含实现一个功能(功能结合)所需的代码
- exceptions can be made for code parts that are very specific and can’t be reused anywhere else; or have to be evaluated sequentially, for example when the output of one part is needed as input for the next part (sequential/procedural cohesion); or operate on the same data (informational cohesion) 可以对非常特殊的代码部分进行例外处理,并且不能在其他任何地方重用; 或必须顺序评估,例如当需要将一个部分的输出作为下一个部分的输入时(顺序/过程内聚); 或对相同数据进行操作(信息内聚)
- avoid to put code parts into one component that are not related to each other at all, or that are only related by their category (when they do similar things but operate on different data) 避免将代码部分放到一个完全不相关或仅按类别关联的组件中(当它们执行相似的操作但对不同的数据进行操作时)
- good cohesion improves readability, maintainability, robustness and reusability 良好的内聚性提高了可读性,可维护性,鲁棒性和可重用性
details: https://en.wikipedia.org/wiki/Cohesion_(computer_science)
详细信息: https : //en.wikipedia.org/wiki/Cohesion_(computer_science)
3.降低复杂度 (3. Complexity reduction)
- any computable problem can be solved by an infinite number of different programs, some of which are more complex than others 任何可计算的问题都可以通过无数个不同的程序来解决,其中一些程序比其他程序更复杂
- there is an ideal solution for every problem that is as little complex as possible, but finding this solution is usually not trivial 对于每个问题,都有一个尽可能不复杂的理想解决方案,但是找到这种解决方案通常并不容易
- unnecessary complexity should be avoided, because simpler programs are more robust, adaptable, readable, understandable and maintainable 应避免不必要的复杂性,因为更简单的程序更健壮,更具适应性,可读性,可理解性和可维护性
- there are different metrics that can be used to measure code complexity, but they are often not easy to calculate 可以使用不同的度量标准来衡量代码的复杂性,但是它们通常不容易计算
- as a rule of thumb I usually try to find the smallest possible program (measured by number of classes, methods, lines of code, …) that solves the problem without violating the first two concepts (and meets additional requirements like performance or security) 根据经验,我通常尝试找到最小的程序(以类,方法,代码行的数量来衡量……),以解决该问题而不违反前两个概念(并满足其他要求,如性能或安全性)
More details: https://en.wikipedia.org/wiki/KISS_principle
更多详细信息: https : //en.wikipedia.org/wiki/KISS_principle
The first two concepts usually correlate very well, but they tend to work against the third.
前两个概念通常具有很好的相关性,但它们往往与第三个概念相反。
For example to achieve loose coupling, one often has to work with interfaces and add abstraction layers between different components, which increases complexity. Sometimes this is absolutely necessary, sometimes it’s reasonable, sometimes it’s just unnecessary complexity. It always depends on your specific use case.
例如,要实现松散耦合,通常必须使用接口并在不同组件之间添加抽象层,这增加了复杂性。 有时这是绝对必要的,有时是合理的,有时只是不必要的复杂性。 它始终取决于您的特定用例。
To find a good balance between all 3 concepts is not easy and requires a lot of experience.
要在这三个概念之间找到一个良好的平衡并不容易,而且需要大量经验。
Many developers tend to make programs more complicated than necessary. Either because they don’t invest the time to find a simpler solution and simply opt for the first solution that comes to mind, or because they do exactly the opposite and think too much about the solution, which can lead to overengineering and things being more complicated than needed.
许多开发人员倾向于使程序变得不必要的复杂。 要么是因为他们没有花时间去寻找一个更简单的解决方案,而只是选择了想到的第一个解决方案,要么是因为他们做的恰恰相反,并且对解决方案的考虑太多了,这可能导致过度设计和情况变得更多比需要的复杂。
On the other side, once you get a taste for reducing complexity, it can happen that you develop a tendency towards oversimplification (talking from my own experience here). It’s important to keep in mind that some issues are inherently complex and require a correspondingly complex solution. Some edge cases need to be handled, even when it means that you have to add “ugly” error management or special case treatments to your code.
另一方面,一旦您有降低复杂性的爱好,就可能会出现过度简化的趋势(从我自己的经验谈起)。 重要的是要记住,某些问题本质上是复杂的,因此需要相应的解决方案。 需要处理一些边缘情况,即使这意味着您必须在代码中添加“难看的”错误管理或特殊情况处理。
If you always keep the 3 concepts in mind, you will develop a feeling for the right balance after some time. I collected some tips and good habits that can help you to gain experience and train your intuition:
如果您始终牢记这三个概念,则一段时间后您会逐渐感觉到适当的平衡。 我收集了一些技巧和好的习惯,可以帮助您获得经验和训练自己的直觉:
- look at code from really good developers (typically found in popular tools or libraries) 查看真正优秀的开发人员提供的代码(通常在流行的工具或库中找到)
- look at common design patterns. Take them as examples of how to increase loose coupling and high cohesion, but be careful when using them as code templates without thinking about possible simpler solutions to your specific problem (remember complexity reduction) 看一下常见的设计模式。 以它们为例,如何增加松散的耦合和较高的内聚力,但是在将它们用作代码模板时要小心,不要考虑针对特定问题的可能更简单的解决方案(记住降低复杂性)
- learn about other coding principles such as SOLID, which explain some more specific ways to increase loose coupling and high cohesion 了解SOLID等其他编码原理,这些原理解释了一些更具体的方法来增加松散耦合和高内聚力
- do code reviews and discussions in your team 在团队中进行代码审查和讨论
- before you start writing code, think about multiple solutions. Try to compare them based on the 3 concepts. Gather feedback from your colleagues. But don’t put too much effort into premature optimization (overengineering) 在开始编写代码之前,请考虑多种解决方案。 尝试根据3个概念进行比较。 收集同事的反馈。 但是,不要在过早的优化(过度设计)上投入过多的精力
- before adding new complexity, always ask yourself “do i really need this? and why?” 在增加新的复杂性之前,请始终问自己“我真的需要这个吗? 为什么?”
- always keep the big picture of your application in mind and see how the feature you are currently developing fits in 始终牢记应用程序的全局,并了解当前正在开发的功能如何适合
- don’t stop thinking about alternative solutions while writing the code. You often will get a deeper insight into the topic and find obstacles that were not considered before. Don’t hesitate to refactor your code. This may take some extra time to complete the task, but it’s good training. And it will pay off in the long run, because your code will be simpler, easier to extend and easier to fix 在编写代码时不要停止思考替代解决方案。 您通常会对该主题有更深入的了解,并发现以前未考虑的障碍。 不要犹豫,重构您的代码。 这可能需要一些额外的时间才能完成任务,但这是很好的培训。 从长远来看,它会有所回报,因为您的代码将更简单,更易于扩展和更易于修复。
That’s it for today, thank you for reading and keep it loose, cohesive and simple!
今天就这样,感谢您的阅读,并使其保持宽松,紧密和简单!
:-)
:-)
翻译自: https://medium.com/@deaqun/3-basic-coding-concepts-3cc54787c2f9