GithubHelp home page GithubHelp logo

精读《API设计原则》 about weekly HOT 2 CLOSED

ascoders avatar ascoders commented on April 28, 2024 2
精读《API设计原则》

from weekly.

Comments (2)

zhaoyangsoft avatar zhaoyangsoft commented on April 28, 2024

统一关键字库

所有api定义之前,先抽离业务和功能语义的关键字,统一关键字库; 可以更好的让多人协作看起来如出一辙, 而且关键字库 更能够让调用者感觉到 符合直觉、语义清晰; 关键字库也是项目组新同学 PREDO 的内容之一, 很有带入感;

单一职责

接口设计尽量要做到 单一职责,最细粒度化; 可以使用组合的方式把多个解耦的单个接口组合在一起作为一个大的功能项接口; 接口设计的单一职责,也更方便多人协作时候的扩展和组合;

面向未来的多态

对于接口参数的扩展,我们要做到面向扩展开放,面向修改关闭; 升级做到要兼容, 否则会导致大批量的下游不可用;

from weekly.

ascoders avatar ascoders commented on April 28, 2024

Const 入参

eslint 有一条规则,不要直接改变入参的值。这个规则的初衷是解决函数副作用问题,禁止可能产生副作用代码的产生。但却可以通过如下方式避免:

function (num) {
  let scopeNum = num
  scopeNum = 5
}

这是从包含指针类型编程语言学习过来的,因为当 *num 表示指针时,代表代码可能产生副作用(修改入参的风险)。而 js 并不总是这样的,不但没有指针申明,基本类型也总是通过拷贝进入传参,非基本类型通过引用传递,也就是会发生通过如上代码绕过检测,却依然产生副作用(改变函数入参)的情况。

为了避免副作用,建议引入 flowtypescript,通过 const 关键字与约定约束入参行为:

function (const num) {
  ...
}

将没有副作用函数的所有入参定义为 const 类型,静态检查阶段就禁止了对值的直接修改,同时因为有这个关键字的约束,在函数体内也约定不要通过引用浅拷贝修改它的值。

但这也无法彻底避免,仍然可以通过如下写法绕过检测,修改入参:

function (const num) {
  const scopeNum = { ...num }
  scopeNum.a.b = 'c'
}

在 js 中没有完美的方式避免对入参的修改,但通过对入参修饰 const 关键字,可以对使用者明确这是纯函数,对开发者提示不要写有副作用的代码。

c++ 的 const 定义从编译开始就完全杜绝了修改的可能性,虽然有 const_cast “去” const 行为,但仍然不会改变入参的值(虽然可以后续对值修改,指针指向保持不变,但用 const 修饰的入参值永远不会改变)。

from weekly.

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.