Code Monkey home page Code Monkey logo

Comments (2)

piglei avatar piglei commented on May 17, 2024

你好,不确定是否完全理解了你的问题。以下是我的一些个人看法:

抛出异常的建议和空对象模式并不冲突,因为抛出异常是在针对“返回错误”的情景模式下提出的。

用户调用 Account.from_string 确实是应该期待拿到一个 “Account” 但是这个 Account 不一定就是真实的 Account 类实例,它可以是满足了 Account 协议的任何类型对象。比如 NullAccount。

返回空的 (username, balance) 与 NullAccount 的意义是不一样的。空对象模式的重点在于函数的返回值都是同属一种类型,比如 NullAccount 和 Account 虽然没有继承自同一基类,但是因为二者实现了一致的接口(和属性),所以我们可以把它们当做都是一种类型(比如叫做 AbstractAccount)。

因为函数返回的都是 AbstractAccount 类型,所以调用方可以不用做任何 if 判断或者异常检测。而如果返回空 username 和 balance 的话,那么调用方就仍然得判断结果到底是 Account 对象还是 (username, balance)了。

抱歉让你产生困扰,我能想到的文章改进点:

  • 增加 AbstractAccount 抽象类定义
  • 让 Account 和 NullAccount 显式继承自 AbstractAccount
  • 工厂函数从 Account.from_string 中剥离出来
  • 当工厂函数返回 NullAccount 时,实例中应该增加保存“非法原因”之类的字段,比如 invalid_reason

from one-python-craftsman.

catbaron0 avatar catbaron0 commented on May 17, 2024

@piglei 多谢解答。理解了。

from one-python-craftsman.

Related Issues (20)

Recommend Projects

  • React photo React

    A declarative, efficient, and flexible JavaScript library for building user interfaces.

  • Vue.js photo Vue.js

    🖖 Vue.js is a progressive, incrementally-adoptable JavaScript framework for building UI on the web.

  • Typescript photo Typescript

    TypeScript is a superset of JavaScript that compiles to clean JavaScript output.

  • TensorFlow photo TensorFlow

    An Open Source Machine Learning Framework for Everyone

  • Django photo Django

    The Web framework for perfectionists with deadlines.

  • D3 photo D3

    Bring data to life with SVG, Canvas and HTML. 📊📈🎉

Recommend Topics

  • javascript

    JavaScript (JS) is a lightweight interpreted programming language with first-class functions.

  • web

    Some thing interesting about web. New door for the world.

  • server

    A server is a program made to process requests and deliver data to clients.

  • Machine learning

    Machine learning is a way of modeling and interpreting data that allows a piece of software to respond intelligently.

  • Game

    Some thing interesting about game, make everyone happy.

Recommend Org

  • Facebook photo Facebook

    We are working to build community through open source technology. NB: members must have two-factor auth.

  • Microsoft photo Microsoft

    Open source projects and samples from Microsoft.

  • Google photo Google

    Google ❤️ Open Source for everyone.

  • D3 photo D3

    Data-Driven Documents codes.