Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

shortening method/variable names? [closed]

Is it considered bad style to use long, but descriptive method names such as "adjacentLocationsByState()" and if so, would it be better to shorten it to something like "adjLocByState" which is definitely shorter, but also less readable in my opinion

like image 483
manis Avatar asked Jan 17 '14 11:01

manis


4 Answers

Don't make me think.

When I read your code, if I have to stop and think about what the method name might mean, it usually means that the method name is wrong. Longer method names are preferable when it adds useful context to the method.

like image 131
Tom Cammann Avatar answered Sep 28 '22 16:09

Tom Cammann


There are two rules I basically follow when writing code:

  • Must be readable as a normal text to which a human eye got used from books and mass media (so adjLocByState is not the case)
  • Maximize brevity, utilize programming techniques - code conventions and default states. These could be applied when some of the terms start appear to repeat too often.

So, adjacentLocationsByState() reads perfectly fine, but it could be shortened to just:

adjacentLocations()

which by default would return locations by their state and adjacentLocations(STATE) or chaining with fluent interface technique which allows more options for having the criteria: adjacentLocations().by(STATE). STATE here is a member of an enum LocationCriteria.

So in the end of the day it could look like:

  • adjacentLocations()
  • adjacentLocations().by(STATE)
  • adjacentLocations(STATE)

Of course, there is a time sacrifice which is spent on coding the 2nd and the 3rd forms.

like image 38
Andrey Chaschev Avatar answered Sep 28 '22 16:09

Andrey Chaschev


Longer version is more readable and the the code is self documenting. So a good method name = method responsibility. Adj can be understand as adjust or adjacent, etc.

like image 36
woytech Avatar answered Sep 28 '22 16:09

woytech


Keep in mind: Code is read 10 times more than it is written.!

You really write code that will often be read again and again. The more meaningful your names are, the more understandable is the code.

You are declaring classes, fields, methods, variables, and many more. You are thinking about them, you are developping a well-defined structure. All the time, you make hard decisions. The names that you give to your entities (classes, fields, ...) reflect all your thoughts on that. They reflect the intention of your code.

Conclusion: Names are the most important properties of your code. So, you always should think deeply about the names you give to your variables, methods, and so on. And you always should not abbreviate them in what way ever.

like image 42
Seelenvirtuose Avatar answered Sep 28 '22 15:09

Seelenvirtuose