Is -1 a magic number? An anti-pattern? A code smell? Quotes and guidelines from authorities

Posted by polygenelubricants on Stack Overflow See other posts from Stack Overflow or by polygenelubricants
Published on 2010-06-13T11:03:50Z Indexed on 2010/06/13 11:12 UTC
Read the original article Hit count: 322

I've seen -1 used in various APIs, most commonly when searching into a "collection" with zero-based indices, usually to indicate the "not found" index. This "works" because -1 is never a legal index to begin with. It seems that any negative number should work, but I think -1 is almost always used, as some sort of (unwritten?) convention.

I would like to limit the scope to Java at least for now. My questions are:

  • What are the official words from Sun regarding using -1 as a "special" return value like this?
  • What quotes are there regarding this issue, from e.g. James Gosling, Josh Bloch, or even other authoritative figures outside of Java?
  • What were some of the notable discussions regarding this issue in the past?

© Stack Overflow or respective owner

Related posts about java

Related posts about best-practices