你如何定义好的或坏的 API? [英] How do you define a good or bad API?

查看:23
本文介绍了你如何定义好的或坏的 API?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我正在我的大学上一门名为软件约束"的课程.在第一堂课中,我们学习了如何构建优秀的 API.

I am taking a class at my university called "Software Constraints". In the first lectures we were learning how to build good APIs.

我们得到的一个非常糟糕的 API 函数的一个很好的例子是 C# 中的套接字 public static void Select(IList checkRead, IList checkWrite, IList checkError, int microseconds);.该函数接收 3 个套接字列表,并销毁它们,使用户必须在将它们输入 Select() 之前克隆所有套接字.它还有一个超时(以微秒为单位),它是一个 int,它设置服务器可以等待套接字的最长时间.这个限制是 +/-35 分钟(因为它是一个整数).

A good example we got of a really bad API function is the socket public static void Select(IList checkRead, IList checkWrite, IList checkError, int microseconds); in C#. The function receives 3 lists of sockets, and destroys them making the user have to clone all the sockets before feeding them into the Select(). It also has a timeout (in microseconds) which is an int, that sets the maximum time the server can wait for a socket. The limits of this is +/-35 minutes (because it is an int).

  1. 您如何将 API 定义为'坏'?
  2. 你如何定义一个API好"?


要考虑的要点:

  • 难以记住的函数名称.
  • 难以理解的函数参数.
  • 糟糕的文档.
  • 一切都如此相互关联,以至于如果您需要更改 1 行代码,您实际上需要更改其他地方的数百行代码.
  • 破坏其论点的函数.
  • 由于隐藏"而导致可扩展性差复杂性.
  • 用户/开发人员需要围绕 API 构建包装器,以便可以使用它.
  • 推荐答案

    在 API 设计中,我一直觉得这个主题演讲很有帮助:
    如何设计一个好的API 及其重要性 - 作者:Joshua Bloch

    In API design I've always found this keynote very helpful:
    How to Design a Good API and Why it Matters - by Joshua Bloch

    这是摘录,我建议您阅读整篇文章/观看视频.

    Here's an excerpt, I'd recommend reading the whole thing / watching the video.

    二.一般原则

    • API 应该做一件事并且做好
    • API 应该尽可能小,但不能更小
    • 实施不应影响 API
    • 尽量减少一切的可访问性
    • 名称很重要——API 是一种小语言
    • 文档事项
    • 宗教文献
    • 考虑 API 设计决策对性能的影响
    • API 设计决策对性能的影响是真实且永久的
    • API 必须与平台和平共处

    三.班级设计

    • 最小化可变性
    • 仅在有意义的地方子类
    • 用于继承或其他禁止的设计和文档

    四.方法设计

    • 不要让客户做模块能做的任何事情
    • 不要违反最小惊讶原则
    • 快速失败 - 在错误发生后尽快报告
    • 提供对字符串形式的所有可用数据的编程访问
    • 小心超载
    • 使用适当的参数和返回类型
    • 在方法间使用一致的参数顺序
    • 避免长参数列表
    • 避免需要异常处理的返回值

    这篇关于你如何定义好的或坏的 API?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

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