Clean Code – Chapter 6 Objects and Data Structures

本文详细解读了代码重构中至关重要的笛米特法则,通过实例展示了如何遵循这一原则来优化代码结构,减少耦合度,提高代码的可维护性和可扩展性。介绍了数据抽象、隐藏实现、面向对象的特性以及Procedural和OO编程风格的差异,特别强调了在添加新功能或数据结构时应遵循的原则。
  • Data Abstraction

    Hiding implementation

  • Data/Object Anti-Symmetry

    Objects hide their data behind abstractions and expose function that operate on that data. Data structure expose their data and hava no meaningful functions.

    Procedural code(code using data structure) makes it easy to add new functions without changing the existing data structures. OO code, on the other hand, makes it easy to add new classes without changing existing functions.

    Procedural code makes it hard to add new data structures because all functions must change. OO code makes it hard to add new functions because all the classes must change.

  • The Law of Demeter

    A module should not know about the innards of the objects it manipulates.

    A method f of a class C should only call the methods of these:

    • C
    • An object created by f
    • An object passed as an argument to f
    • An object held in an instance variable of C

    推荐一篇博文:笛米特法则详解,通过一个简单的代码示例解释了上述概念。

    • Train Wrecks

      Bad code:

      final String outputDir = ctxt.getOptions().getScratchDir().getAbsolutePath();

      Or

      Options opts = ctxt.getOptions();
      File scratchDir = opts.getScratchDir();
      final String outputDir = scratchDir.getAbsolutePath();

      Only used for data structures

      final String outputDir = ctxt.options.scratchDir.absolutePath;
    • Hybrids

      Avoid hybrid structures that are half object and half data structure.

    • Hiding Structure

      Tell an object to do something, not ask it about its internals.

  • Data Transfer Objects (DTO)

    The quintessential form of a data structure is a class with public variables and no functions.

    • Active Record

      Special form of DTO. Hava navigational methods like save and find.

      Typically direct translations from database tables, or other data sources.

转载于:https://www.cnblogs.com/gumuyueying/p/cleancode-ch6.html

评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值