何时在API中使用CharSequence [英] When to use CharSequence in an API

查看:149
本文介绍了何时在API中使用CharSequence的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我正在为包设计公共接口(API)。我想知道,我应该使用 CharSequence ,而不是 String 。 (我主要是谈论公共接口)。

I'm designing a public interface (API) for a package. I wonder, should I use CharSequence generally instead of String. (I'm mainly talking about the public interfaces).

这样做有什么缺点吗?它被认为是一种好的做法吗?

Are there any drawbacks of doing so? Is it considered a good practice?

如何将它用于类似标识符的目的(当值与基于散列的容器中的集合匹配时)?

What about using it for identifier-like purposes (when the value is matched against a set in a hash-based container)?

推荐答案

CharSequence 很少用于通用库。当你的主要用例是字符串处理(操作,解析,......)时,通常应该使用它。

CharSequence is rarely used in general purpose libraries. It should usually be used when your main use case is string handling (manipulation, parsing, ...).

一般来说你可以做任何带有 CharSequence 的东西,你可以使用 String (通常,因为你可以转换每个 CharSequence 字符串 )。但是有一个重要区别: A CharSequence 不保证是不可变的!每当你处理 String 并在两个不同的时间点检查它,你可以确定它每次都具有相同的值。

Generally speaking you can do anything with a CharSequence that you could do with a String (trivially, since you can convert every CharSequence into a String). But there's one important difference: A CharSequence is not guaranteed to be immutable! Whenever you handle a String and inspect it at two different points in time, you can be sure that it will have the same value every time.

但是对于 CharSequence 这不一定是真的。例如,有人可以通过 StringBuilder 进入您的方法并在使用做某事时修改它,这会打破很多合理的代码。

But for a CharSequence that's not necessarily true. For example someone could pass a StringBuilder into your method and modify it while you do something with it, which can break a lot of sane code.

考虑这个伪代码:

public Object frobnicate(CharSequence something) {
  Object o = getFromCache(something);
  if (o == null) {
    o = computeValue(something);
    putIntoCache(o, something);
  }
  return o;
}

如果您使用过字符串这里它主要起作用(除非可能计算两次值)。但是如果某事 CharSequence 那么其内容可能会在 getFromCache 调用和 computeValue 调用。或者更糟:在 computeValue 调用和 putIntoCache 调用之间!

This looks harmless enough and if you'd had used String here it would mostly work (except maybe that the value might be calculated twice). But if something is a CharSequence then its content could change between the getFromCache call and the computeValue call. Or worse: between the computeValue call and the putIntoCache call!

因此:接受 CharSequence 如果有大优势且您知道缺点

Therefore: only accept CharSequence if there are big advantages and you know the drawbacks.

如果您接受 CharSequence ,您应该记录您的API如何处理可变性 CharSequence 对象。例如:在方法执行时修改参数会导致未定义的行为。

If you accept CharSequence you should document how your API handles mutable CharSequence objects. For example: "Modifying an argument while the method executes results in undefined behaviour."

这篇关于何时在API中使用CharSequence的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

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