当我们使用 "iOS" 作为 class 名称中的单词时,我们应该将 "i" 大写吗?

Should we capitalize "i" when we use "iOS" as a word in a class name?

有些品牌名称实际上并不喜欢将其首字母大写,更改可以使其看起来完全不同,尤其是 "iOS"。还有更多像 "mCore"、"macOS" 等等。当涉及 class 个名字时,我应该将第一个字母大写还是保留原样?

例如“iOSCompatProxy”与“IOSCompatProxy

就我个人而言,我认为它是 iOSCompatProxy。我认为对于这个世界上的每条规则,都有例外。 :)

这种类型的 class 名称没有普遍遵循的约定。即使像 "XML" 这样的常规大写缩写也会导致不一致;查看 the official JDK class list,我看到名为 XMLSomething 的 class 与 XmlSomething.

一样多

Google 在 Google Java Style Guide 中处理这个主题,他们给出了将文本转换为 class 名称的方案:

Sometimes there is more than one reasonable way to convert an English phrase into camel case, such as when acronyms or unusual constructs like "IPv6" or "iOS" are present. To improve predictability, Google Style specifies the following (nearly) deterministic scheme.

Beginning with the prose form of the name:

  1. Convert the phrase to plain ASCII and remove any apostrophes. For example, "Müller's algorithm" might become "Muellers algorithm".

  2. Divide this result into words, splitting on spaces and any remaining punctuation (typically hyphens).

    • Recommended: if any word already has a conventional camel-case appearance in common usage, split this into its constituent parts (e.g., "AdWords" becomes "ad words"). Note that a word such as "iOS" is not really in camel case per se; it defies any convention, so this recommendation does not apply.
  3. Now lowercase everything (including acronyms), then uppercase only the first character of:

    • ... each word, to yield upper camel case, or
    • ... each word except the first, to yield lower camel case
  4. Finally, join all the words into a single identifier.

他们的方案产生 IosCompatProxy 作为 class 名称,iosCompatProxy 作为变量名称。他们故意无视原来的大写字母,转而采用更基于规则的驼峰式大小写形式。

也许这不是最好看的形式,但如果您四处寻找可以遵循的规则,并且您工作的地方没有这样的规则, Google 的风格指南是一个很好的规则,因为它特别提到了 "iOS"。我倾向于高度评价他们的约定,因为他们一直在使用大量 Java(截至 2018 年有 3 亿行 [1])。

一般来说,在 Java class 中,名称总是第一个字母和所有后续的新单词开头字母都大写,例如 ThisIsAClass。这是为了将它们与变量和方法名称区分开来。因此,根据我对 Oracle 风格指南的解释,我相信 IOSCompatProxy 将是正确的 class 名称,这是一般的 Java 风格指南,在这里看到(我不相信任何自上次更新以来进行了主要样式更改):

Class names should be nouns, in mixed case with the first letter of each internal word capitalized. Try to keep your class names simple and descriptive. Use whole words-avoid acronyms and abbreviations (unless the abbreviation is much more widely used than the long form, such as URL or HTML).

此外,因为 iOS 是一个比 'Internet and Operating System' 更广泛使用的首字母缩写词,所以我会说将整个首字母缩写词都大写。如果您有不同的解释,例如与@Boann 写的相匹配的解释,请使用它。

但是,我不鼓励您遵循 Google 的风格指南,除非您为 Google 工作(假设 Google 的风格指南基于 Oracle一)只是因为他们的风格可能与你将来工作的公司不同。相反,我建议遵循此处的 Oracle 风格指南:https://www.oracle.com/technetwork/java/codeconvtoc-136057.html