2

I need few related variables (for example I have the lengths of 3 lines given. I have to say whether they form a triangle). Which variable naming convention is preferable in Java?

  1. len0, len1, len2 or
  2. lenZero, lenOne, lenTwo or
  3. lens is declared as an array. Then lens[0], lens[1], lens[2].

Maybe if there are many variables (0, 1, 2, 3, 4, ......), then option 3 is preferable. But if there are few variables, then which one is preferable? Or should I follow any other convention?

closed as primarily opinion-based by gnat, 8bittree, BobDalgleish, amon, MetaFight Dec 15 '17 at 15:32

Many good questions generate some degree of opinion based on expert experience, but answers to this question will tend to be almost entirely based on opinions, rather than facts, references, or specific expertise. If this question can be reworded to fit the rules in the help center, please edit the question.

  • 1
    A record / struct / class of some sort is another option. – RemcoGerlich Nov 14 '17 at 12:44
  • 5
    All of these are very bad conventions. When you deal with e.g. a diameter, an area and a price, then for God's sake don't call them var0, var1 and var2. Call them diameter, areaand price already. – Kilian Foth Nov 14 '17 at 12:45
  • 2
    @Md.AbuNafeeIbnaZahid: yes, but then you give them meaningful names as Kilian says, and the fact that they're grouped in a record shows they belong together. But this question is anyway not concrete enough to answer. – RemcoGerlich Nov 14 '17 at 12:48
  • 1
    @Md.AbuNafeeIbnaZahid: but that's not obvious from your question, hence it is too vague. Another important thing: what's the reason that the number is 3? Answer differs depending. – RemcoGerlich Nov 14 '17 at 12:53
  • 1
    It's not really related to the specific question you are asking but given the problem you want to solve, you should really have a Line class. The reason I point this out is that you will likely need other sets of three variables. Having lenA, startA, angleA (for example) is a bad idea because it means you will have to duplicate a lot of code. This is much more important than how you name three variables holding the same kind of thing. – JimmyJames Dec 13 '17 at 17:51
4

This is based on your updated question. Note also that this not based on any scientific measurement of readability. Rather I am presenting the various factors that (I think) are likely to influence readability for the Average Joe Programmer.

Option 1 - len1, len2, len3

The only potential criticism of this is that maybe you should not abbreviate length as len. But the counter to that is that it is probably obvious from the context what len means.

Option 2 - lenOne, lenTwo, lenThree

No advantages over previous option. The disadvantages are:

  • these are marginally harder to read (for most people) as words
  • these are marginally more effort to type
  • the fact they have different lengths means that code using them will align differently.

Option 3 - lens[0], lens[1], lens[2].

The choice of lens is a bad one, because lens is also a English word in its own right.

Other problems:

  • Marginally harder to read than a simple variable.
  • You are "counting from zero". Most programmers know how to do this, but it conflicts with what most people do "naturally"1. That is likely to make len[I] or lens[I] marginally harder to read than lenI
  • This has (small) performance and memory usage costs.
  • This introduces potential runtime hazards:

    • A possible NullPointerException if you forget to initialize lens.
    • ArrayIndexOutOfBoundException if you get an index wrong.

Note that the compiler may flag the above hazards as errors or warnings, but not in all cases.

But the flip side is that this potentially allows you to index the lens array, which could simplify your algorithm.


Which is best?

  1. It is a matter of opinion!
  2. My opinion is that either option 1 or 3 is best ... depending on the context.

1 - I state this without evidence, and I note that there are competing definitions on what "natural numbers" are. However, if you ask someone to count to ten, most people will start at one, not at zero. Counting from one is ingrained into most peoples' thought process. Whether this is a good thing is beside the point. Readability is about real people's actual thinking patterns ... not about how the code author thinks that his code's readers should think.

7

Name your variables so that their names denote exactly what their purpose is. Do not name them var0, var1, var2. I assume that this var was just an example, but the principle stands. Be accurate when naming variables. If you scroll two screens down, and look at the code, would you be able to tell what the purpose of the variable is just from its name? That should be your primary criteria.

If you need to group variables, then create an encapsulating class or a struct, but even then, be careful how you name attributes of the class/struct and the class/struct itself (see first paragraph).

Edit based on the edited question

Len or length is OK. If you need to write an algorithm for a triangle, then option 1 or option 3 are both OK, although I would name the variables: 1. triangleSideLengthX (X is 1, 2, 3 or even A, B, C) in the first case 2. triangleSideLengths (array) in the second case.

Alternatively, I would create a class like this:

class TriangleSidesLengths {
    public float sideALength;
    public float sideBLength;
    public float sideCLength;
 }

Everybody would know exactly what the class and its members denote, since triangle sides are usually denoted with letters in geometry.

You could use the same approach for N-tangle.

Edit

I added the word 'lenght' to the class name and the names of its attributes, so that the names would be more clear. However, it might be an overkill, because even though the names of the attributes by themselves could be a bit ambiguous, when coupled with their type, they clearly denote one thing - side length.

  • I like the idea of the class, but I would recommend keeping the word length in the member names. When I see a TriangleSides class, and see 3 variables, my first thought isn't that it contains the lengths of the sides, but the coordinates of the endpoints. If I came across this in code, I'd be thinking, "how the heck does a float represent a side?" But a side's length I would instantly understand. – user1118321 Nov 15 '17 at 6:13
  • I have no objections to adding the word 'length' to the name. The point of the name is that it clearly denotes the purpose of the entity. Personally, if I saw a float type member named sideA in a class called TriangleSides, the first thing I would think would be that it is a side lenght, exactly because you cannot represent coordinates of two points with just one float. – Vladimir Stokic Nov 15 '17 at 7:40
  • This. If you are doing things to triangles, you probably need a class Triangle, with properties like side lengths and angles etc – Caleth Nov 15 '17 at 10:00
  • @Caleth If you are working with triangles, then all you need are sides. You do not actually need angles, because angles can easily be calculated if you have all three sides. See mathsisfun.com/algebra/trig-solving-sss-triangles.html – Vladimir Stokic Nov 15 '17 at 11:00
  • 1
    @Md.AbuNafeeIbnaZahid It all depends on what you want to do. If you really need a triangle, then call the class Triangle, and create a private method ValidateTriangleSides(float a, float b, float c) that will be called from constructor and would throw ArgumentException if a triangle cannot be constructed from those sides. If you really need just a validation, then call your class TriangleSidesValidator and implement static method ValidateTriangleSides (float a, float b, float c). – Vladimir Stokic Nov 15 '17 at 15:43
2

All your options are bad. Variable names should reflect the content of the variable - I already know it's a variable, so calling it var0 adds absolutely nothing to what I know already. If they are things which are logically a sequence, then put them in an array, but name the array appropriately - events or whatever. If they are not logically in a sequence, just call them what they are - startEvent, endEvent and whatever else you need.

1

In code, naming of variables should express what you are trying to do. In the context of using three lines to test if they create a triangle you would want to convey that in the naming of your variables.

Options 1 and 2 are exactly the same, the convey the same thing. I would call them lineLengthA, lineLengthB, lineLengthC, because:

  • len is ambiguous
  • we aren't just talking about arbitrary lengths
  • we are conveying we are talking about geometric constructs, in this case line segments
  • replacing 1,2,3 with A, B, C conveys we don't care about the ordering of parameters.
  • self documenting names, people will immediately know what these parameters represent.

Alternatively you could call these lineSegmentLengthX, segmentLengthX, or edgeLengthX for similar reasons.

This ends up looking like this:

...
public boolean canCreateValidTriangle(float lineLengthA, float lineLengthB, float lineLengthC){
     ...
}
...

As for the 3rd array option, this option is preferable if you have a language where you can define fixed size array types (like C++ with std::array<type, size>) however I am unaware of such a facility being possible in java, as primitive type generics do not exist in the language AFAIK. With out this functionality, the user of your program doesn't know how to properly pass an array to the function with out educated guessing, looking at implementation or you actually commenting that this is how the function needs to be used (which could change).

So for java, I would not pass a 3 element array, unless you had wrapped it in another class (say, "ThreeElementArray<T>"), which brings up some other problems.

Other people have suggested putting the three parameters into their own class. In my opinion this is not a good way to go about things in this instance. If you make a POD class just for this instance, you likely won't be able to find enough methods to create for it to justify its existence beyond being a data class. When you make a data class you end up writing procedural code, and it gives you no benefits of abstraction.

With a ThreeElementArray<T> you might be fooled into thinking you don't have a Data class since you will likely be providing methods for indexing and normal length and array operations, but what you are really doing is just delegating the same functionality that already exists in the encapsulated array object it contains to do the same thing but just directly on the class as a function call. It is no different than doing Myclass.mymember.mymemberfunction();. This isn't to say you shouldn't do this when creating a class, but that you should have other functions that justify the existence of the class in the first place.

Others have suggested using a "Triangle class", obviously a triangle class will have functions that exist outside the scope of a three element array, so that makes it good right? The issue with this method is that your passing in line lengths not a triangle. You are testing if those line lengths could be a triangle, passing in a triangle already doesn't make sense. Those line lengths might not make a valid triangle and thus your triangle object shouldn't exist. If you are just using the triangle class to hold those line lengths that is extremely misleading, your telling the programmer "this is a triangle" when it very clearly is not, and may not even form a valid one. Passing it in as a triangle also stops you from being able to pass in arbitrary line lengths, and remember, we don't care the order of the line lengths or where they came from.

Not the answer you're looking for? Browse other questions tagged or ask your own question.