我什么时候应该将我的代码分成不同的类? [英] When should I separate my code into separate classes?

查看:40
本文介绍了我什么时候应该将我的代码分成不同的类?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

在将代码分成相关类时,我知道 OOP 的强大功能.但是,我什么时候应该将我的代码分成类?

I know the power of the OOP when it comes to separating the code into related classes. But, when should I separate my code into classes?

我认为更多的类需要更多的对象来从这些类中调用一些方法.这是过度使用内存吗?

I think more classes need more objects to call some methods from these classes. Is this overuse of memory?

推荐答案

通常按照单一职责原则将代码分离到更多类中.

Generally separate your code in more classes following the Single Responsibility Principle.

每个班级应该只做一件事.

如果你的班级做得太多,把它分成不同的班级.

If your class do too much, split it in different classes.

尝试在互联网上搜索关于单一职责原则的一些很好的例子.

Try to search on internet about Single Responsibility Principle to have some nice example.

通常问题与内存无关,而是与错误的编程有关.即使对代码一无所知的人,代码也应该易于阅读.仅当您是非常高级的程序员并且您的代码需要这些增强功能时才尝试提高性能.

Generally problems are not linked to the memory but to the bad programming. The code should be easy to read even for people who don't know anything about it. Try to enhance performances only when you are a very advanced programmer and your code needs these enhancements.

有 5 个设计原则.他们可以用缩写词 SOLID 记住:

There are 5 design principles. They can be remembered with the acronym SOLID that stay for:

  • 单一职责原则
  • 开闭原则
  • 里氏替换原则
  • 接口隔离原则
  • 依赖倒置原则

这里我只讲单一职责原则.

Here I talked only about the single responsibility principle.

设计模式更接近于代码.模式是对反复出现的问题的解决方案.相反,原则是驱动代码设计要遵循的想法.您会发现数十种模式可以拆分您的代码以解决特定问题.他们都遵循指导方针,保持每个班级的单一职责.

The design patterns are something closer to the code. A pattern is a solution to a recurrent problem. Instead a principle is an idea to follow to drive the design of the code. You will find dozens of patterns that can split your code to solve a specific problem. All of them follow the guideline to maintain a single responsibility for each class.

作为开始,我添加了一个链接到一个很好的站点,详细解释了每个原理和许多模式.链接

Just as point of start I add a link to a nice site explaining each principle and many patterns in detail. Link

这篇关于我什么时候应该将我的代码分成不同的类?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆