What is correct Java naming convention for id?

拥有回忆 提交于 2019-12-03 19:48:10

问题


If I have user id variable, what is correct java naming convention for it?

userId or userID


回答1:


I think I read somewhere that the best guideline is to always capitalize only the first letter of an acronym (i.e., if you have a user TTL where TTL is some random acronym in your project, then it's best to write userTtl).

This makes sense, since it solves some problems. For example, say you want a user id counter. Readability of userIDCounter is worse than userIdCounter. For a longer acronym, it gets even worse.




回答2:


This is a tough decision, even Sun isn't so sure what to do. Look at classes in JRE,

java.net.URL
java.security.acl.Acl
java.net.HttpURLConnection
java.awt.dnd.DnDConstants
java.awt.color.ICC_Profile

Personally, I prefer to use camel-case always to be consistent.




回答3:


I consider the item described in: Effective Java by Joshua Bloch authoritative in this matter:

Adhere to generally accepted naming conventions

Class and interface names should consist of one or more words, with the first letter of each word capitalized [..] Abbreviations are to be avoided, except for acronyms and certain common abbreviations like max and min. [...] a strong argument can be made in favor of capitalizing only the first letter. [...] you can still tell where one word starts and the next word ends. Which class name would you rather see, HTTPURL or HttpUrl?

So, It should be userId




回答4:


It's like this:

  1. For acronyms, uppercase only the first letter. Definitely. Ignore the fact that some JDK methods don't.
  2. But "id" is one of the strangest words in the language -- an abbreviation for which no one even really knows exactly what it's short for. Some have suggested "identifying document", but this is likely just made up after the fact. 'identifiying... something' is about the best we have. Anyway, if you were to use userID, it suggests that a plain id would be iD, and you sure as heck don't want to do that, so the winner is:

userId

(as others have said).

So it ends up being treated like an acronym anyway.




回答5:


The first one is preferred according to Java naming convention (1) (2).




回答6:


It mainly depends on your naming convention together with your application (if there are any). For instance, userId is a preferred one with Java convention




回答7:


This is quite a handy resource for Java naming conventions http://geosoft.no/development/javastyle.html




回答8:


As far as the Java convention is concerned its there in lot of books that the first letter of each word is capatailsed and the all other letters are in small letters, So you have classes like AcademicStudent, and so is the UserId.



来源:https://stackoverflow.com/questions/1699944/what-is-correct-java-naming-convention-for-id

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!