面向对象设计原则

Programming is fun until you have to incorporate a new requirement that changes the whole design of your code. Everyone writes code but it’s too difficult to write a code that your colleagues can understand. It’s difficult to write a code that sucks less and doesn’t succumb to changes. However, there are a few design principles that can be learned, practiced, and absorbed so that it will make us suck less.

编程很有趣,除非您必须合并一个新要求以更改代码的整个设计。 每个人都编写代码,但是编写同事可以理解的代码太困难了。 编写难以吸收且不屈服于更改的代码是很困难的。 但是,有一些设计原则可以学习,实践和吸收,因此可以减少我们的负担。

Design principles are basic guidelines that help us to avoid bad object-oriented design. Nobody is going to point a gun towards you and make you adhere to it strictly. It’s not a rule of thumb but it will definitely help you. We are now going to see three principles.

设计原则是帮助我们避免不良的面向对象设计的基本准则。 没有人会朝您开枪并使您严格遵守。 这不是经验法则,但肯定会为您提供帮助。 现在,我们将看到三个原则。

  1. Encapsulate what varies.封装各种内容。
  2. Favor composition over inheritance.优先考虑组成而不是继承。
  3. Program to interface.程序接口。

封装各种内容。 (Encapsulate what varies.)

The principle is so simple. Identify the aspects of the code that varies and isolate it with what stays the same. You gotta ask yourself

原理是如此简单。 确定代码方面的变化,并将其保持不变。 你要问自己

“每次获得新要求时,此代码都会更改吗?” (“Does this code change every time I get the new requirement?”)

If the answer is yes then you now know what to do. Encapsulate. Let’s see an example.

如果答案是肯定的,那么您现在知道该怎么办。 封装。 让我们来看一个例子。

public void connectToDatabase(String connectionType) {    DBConnection connection = null;    if ("mysql".equals(connectionType)) {        connection = new MySqlConnection();    } else if("mongodb".equals(connectionType)){        connection = new MongoConnection();    }else if("postgres".equals(connectionType)){        connection = new PostgresConnection();    }    connection.createConnection();}

I bet every one of us has seen code like this and who knows we may still have such code running in production. So, let’s say we need to add an Oracle database in our code. How are we going to add it? Another else if condition, isn’t it? But let’s say there are a bunch of other important codes in the same file and while adding a new Oracle database you mistakenly touched other production codes in the same file which introduced many newer bugs. Had it been encapsulated, then there would have been a single place to change. By encapsulating it, our design will be much more flexible.

我敢打赌,我们每个人都已经看到过这样的代码,并且谁知道我们可能仍在生产环境中运行这样的代码。 因此,假设我们需要在代码中添加一个Oracle数据库。 我们如何添加它? 还有其他条件吗? 但是,假设同一文件中还有许多其他重要代码,并且在添加新的Oracle数据库时,您错误地触摸了同一文件中的其他生产代码,从而引入了许多新的错误。 如果将其封装起来,那么将只有一个地方可以更改。 通过封装,我们的设计将更加灵活。

The part that will change with every new requirement is if-else conditions. So, we can create a factory class that will be solely responsible for creating database connections. I will not show how to create a factory class but I will show how the code looks once we encapsulated all the logics inside the factory class.

如果有其他新要求,将会改变的部分是if-else条件。 因此,我们可以创建一个工厂类,该类将全权负责创建数据库连接。 我不会显示如何创建工厂类,但是一旦将所有逻辑封装在工厂类中,我将显示代码的外观。

public void connectToDatabase(String connectionType) {    DBConnectionFactory dbConnectionFactory = new DBConnectionFactory();    DBConnection connection = dbConnectionFactory.getConnection(connectionType);    connection.createConnection();}

With this approach, let’s say if you want to add an H2 database connection then you have to change only in DBConnectionFactory class.

假设使用这种方法,如果要添加H2数据库连接,则只需在DBConnectionFactory类中进行更改。

偏爱继承而不是继承 (Favor composition over inheritance)

In object-oriented programming (OOP), inheritance is IS-A relationship (A car is a vehicle) whereas composition is HAS-A relationship (A car has an engine).

在面向对象编程(OOP)中,继承是IS-A关系(汽车是汽车),而组成是HAS-A关系(汽车有引擎)。

Inheritance provides a great way to reuse the code but it becomes less effective once the hierarchy grows on. Classes and objects created through inheritance are tightly coupled because if something is changed in the base class then it will affect its subclasses. But it’s not true for composition. The classes and objects created through composition are loosely coupled. There is another great benefit of using Composition over Inheritance. Inheritance is not easily testable because to test derived class you also need superclass but the composition is as we can use mock objects.

继承提供了一种重用代码的好方法,但是一旦层次结构发展起来,它就会变得无效。 通过继承创建的类和对象紧密耦合,因为如果在基类中进行了某些更改,则会影响其子类。 但这对构图不是正确的。 通过合成创建的类和对象是松散耦合的 使用“合成”而不是“继承”还有另一个好处。 继承不容易测试,因为要测试派生类,您还需要超类,但是其组成与我们可以使用模拟对象一样。

程序接口 (Program to interface)

The term interface here doesn’t merely mean the keyword we have in Java programming language. It is a kind of contract that has a bunch of rules that needs to be followed by concrete classes that implement it. It is often called as program to the supertype. If we program to an interface rather than the concrete implementations then it provides the flexibility to exploit polymorphism.

这里的接口一词不仅意味着我们在Java编程语言中拥有的关键字。 它是一种合同,它具有一堆规则,需要遵循一些规则来实现它。 它通常被称为超类型的程序。 如果我们对接口进行编程而不是对具体的实现进行编程,那么它将为利用多态性提供灵活性。

The interface provides rules and doesn’t care whoever implements it and how the implementation looks like. Let’s take a real-world simple example.

该接口提供了规则,无论在何处实施规则,以及实施的外观如何,都不在乎。 让我们以一个真实的简单示例为例。

interface FileUpload {    void upload(Object o);}

We want to upload the file in our application. There may be many different ways to do so. We can use Cloudinary, AWS S3 bucket, upload care, etc. So the implementations of FileUpload would look like AmazonS3FileUpload, CloudinaryFileUpload, UploadCareFileUpload etcetera.

我们想将文件上传到我们的应用程序中。 可能有许多不同的方法。 我们可以使用Cloudinary,AWS S3存储桶,上传服务等。因此FileUpload的实现看起来像AmazonS3FileUpload,CloudinaryFileUpload,UploadCareFileUpload等。

Let’s program to interface.

让我们编程进行接口。

FileUpload fileUpload = new CloudinaryFileUpload();// code related to fileupload

Great, our file uploading feature is working correctly and after one year, we want to switch our file uploading from Cloudinary to AmazonS3. We just need to change the implementation like:

太好了,我们的文件上传功能正常运行,并且在一年之后,我们希望将文件上传从Cloudinary切换到AmazonS3。 我们只需要更改实现,例如:

FileUpload fileUpload = new AmazonS3FileUpload();

It will not break other codes because we are relying on the interface and the methods provided by it. We can only use methods defined within the FileUpload interface. Had it been concrete implementation with a bunch of extra methods, then it would have created a havoc.

它不会破坏其他代码,因为我们依赖于它提供的接口和方法。 我们只能使用FileUpload接口中定义的方法。 如果它是使用一堆额外方法的具体实现,那么它将造成严重破坏。

//program to concrete implementationCloudinaryFileUpload fileUpload = new CloudinaryFileUpload();//code related to fileUpload

So, it’s always a good idea to program to an interface. Besides, the flexibility it provides, it is also easy to test. We can easily mock FileUpload interface wherever necessary.

因此,对接口进行编程始终是一个好主意。 此外,它提供的灵活性也很容易测试。 我们可以在必要时轻松地模拟FileUpload接口。

Thanks a lot for reading my article. If you have any suggestions, then they are welcomed.

非常感谢您阅读我的文章。 如果您有任何建议,欢迎您。

翻译自: https://medium.com/@surajgautam077/object-oriented-design-principles-ef4be2f51826

面向对象设计原则


http://www.taodudu.cc/news/show-2801389.html

相关文章:

  • 2020年计算机网络王道_2020年8种最大的网络安全威胁
  • plus钱包受黑客攻击_如何保护您的在线业务免受黑客攻击
  • 程序员为何喜欢debian_程序员为何拖延以及如何停止
  • xr企业级应用在哪里_如何在XR中保持私密
  • 深度学习去燥学习编码_您不应该学习编码的5个理由
  • 如何写出难以维护的代码--代码命名
  • How To JUST DO IT
  • 雅思阅读考点词-同义替换
  • 深度学习框架tensorflow学习与应用——代码笔记11(未完成)
  • 谈判如何在谈判中_工资谈判软件开发人员指南
  • 微观平台_不再受到微观管理
  • Spoken English Practice(I won't succumb to you, not ever again)
  • 数学建模-层次分析法
  • 层次分析法——确定指标权重、解决评价类问题
  • 【数学建模】—— 层次分析法(AHP)
  • Unity UI Text组件添加contentsizefitter后获取RectTransform宽度
  • unity中content size fitter组件不起作用
  • python3.8 安装fitter包失败,网上所有办法都试过不行之后!
  • 关于Unity ContentSizeFitter的坑
  • python pip install fitter 失败解决方案
  • Unity3D Content Size Fitter的坑
  • ContentSizeFitter刷新不及时
  • 压缩包安装fitter库,gbk编码错误解决方法
  • UGUI ContentSizeFitter 嵌套 适配
  • 【python】——数据分布拟合工具包fitter
  • 浅析 ContentSizeFitter 以及 Horizontal Layout Group 嵌套问题
  • UGUI源码解析——ContentSizeFitter
  • Unity3d Ugui 20 Grid Layout Group Aspect Ratio Fitter
  • Unity3d中UGUI组件精简复盘(十九)ContentSizeFitter组件
  • Unity 【Content Size Fitter】- 聊天气泡自动适配Text文本框大小

面向对象设计原则_面向对象的设计原则相关推荐

  1. HTML5期末大作业:甜品店网站设计——美食甜品店铺加盟企业(1页) HTML+CSS+JavaScript web期末作业设计网页_美食网页设计作业成品

    HTML5期末大作业:甜品店网站设计--美食甜品店铺加盟企业(1页) HTML+CSS+JavaScript web期末作业设计网页_美食网页设计作业成品 常见网页设计作业题材有 个人. 美食. 公司 ...

  2. 依赖倒置原则_面向对象的设计原则你不要了解一下么?

    昨天我看了单一职责原则和开闭原则,今天我们再来看里式替换原则和依赖倒置原则,千万别小看这些设计原则,他在设计模式中会有很多体现,所以理解好设计原则之后,那么设计模式,也会让你更加的好理解一点. 前言 ...

  3. java面向对象模拟电梯_面向对象的程序设计-电梯调度系统的设计、优化与测试...

    面向对象的程序设计(2019)第二单元总结 I  对问题的初体验 在开始OO之旅前,对OO电梯早有耳闻.这一次终于轮到我自己实现OO电梯了.首先从顶层需求出发对电梯系统进行分析,对象包括电梯.任务和乘 ...

  4. java solid设计原则_设计模式之SOLID原则

    什么是SOLID原则 SOLID = SRP(职责单一原则) + OCP(对扩展开发,修改关闭原则)+ LSP(里氏替换原则)+ ISP(接口隔离原则)+ DIP(依赖反转原则) SRP: Singl ...

  5. 依赖倒置原则_设计模式之SOLID原则

    在程序设计领域, SOLID(单一功能.开闭原则.里氏替换.接口隔离以及依赖反转)是由罗伯特·C·马丁在21世纪早期引入,指代了面向对象编程和面向对象设计的五个基本原则.当这些原则被一起应用时,它们使 ...

  6. 猫和老鼠面向对象java语言_面向对象葵花宝典- 完整版.pdf

    构架,均衡,负载,网站,应用,net,存储系统,java,设计模式,互联网 面向对象葵花宝典 /yunhua_lee 面向对象葵花宝典 目录 第一部分:面向对象基础6 1.面向对象概述6 1.1. 程 ...

  7. java面向对象的理解_面向对象及其核心的概念:抽象、继承与多态、封装

    面向对象的思想是上个世界60年代出现的,一些比较典型的面向对象的编程语言包括JAVA.C++等.很多脚本语言也支持面向对象的语法比如PHP.Python. 什么是面向对象呢?它是一种现实对象的建模方法 ...

  8. 代码规范七大原则_设计模式的七大原则详解||上篇

    Hello 丨World  当机会变得稀有,当竞争变得激烈 当方向不再清晰,当风口不再有风 关键词||设计模式 全文约7685字,细读大约需要20分钟 1 认识设计模式 1.1 什么是设计模式 所谓设 ...

  9. 背包系统 设计要点_建立新设计系统的要点和要点

    背包系统 设计要点 重点 (Top highlight) When I first sat down with my company's CEO and CRO to pitch them on a ...

  10. 工业设计中一般运用计算机,计算机辅助工业设计知识点_计算机辅助工业设计中的人机交互...

    摘要:随着科技的发展,工业设计行业也在不断发展,而与此同时,工业市场对工业设计中的产品的品种多样化.趣味化的要求也变得越发的严格.为了确保工业设计在质量和数量上能够更好的发展,计算机辅助工业设计中的建 ...

最新文章

  1. linux下bus、devices和platform的基础模型
  2. deepnode处理过的图片_这款实用的图片软件,其功能相当于十几款图片处理软件的功能之和...
  3. 10061 mysql,Navicat无法连接到MySQL server的10061错误
  4. linux搭建环境经验,经验总结54--搭建linux虚拟机环境
  5. php软件升级管理系统,POSCMS开源内容管理系统 v3.6.1 升级说明
  6. 减少C++代码编译时间的方法
  7. python 热力图_python高维数据型图表热力图、树形图
  8. 【综述】Google团队发布,一文概览Transformer模型的17大高效变种
  9. 计算机操作系统笔记——线程及其实现
  10. 有趣的USB接口和颜色分类
  11. 转:: 刺鸟:用python来开发webgame服务端(4)
  12. GitHub简单入门
  13. ArcGIS:矢量、栅格文件裁剪(批量处理)
  14. matlab gz,MATLAB之single函数
  15. 魔法才能打败魔法?银行现身说法
  16. 嵌入式软考备考_8 软件测试
  17. 美团支付宝互探腹地 相爱相杀再度升级
  18. JMeter测试多用户登录
  19. python发微信提醒天气_基于Python实现定时自动给微信好友发送天气预报
  20. 数值分析思考题(钟尔杰版)参考解答——第七章

热门文章

  1. 联想T260 G3服务器系统安装手册
  2. HBase NoSQL数据库详解
  3. rx6800和rtx3070ti选哪个
  4. 小程序改变swiper样式(带缩略图)
  5. 祝贺!80后“双一流”教授,当选院士!
  6. Java基础强化训练——开发工具及输出语句训练
  7. Android如何解决文字转语音播报的问题
  8. 多设备时设置default serial的方法
  9. pin limiting the speed
  10. 越努力,越幸运—2021年终总结