Win a copy of Clojure in Action this week in the Clojure forum!
  • Post Reply
  • Bookmark Topic Watch Topic
  • New Topic

Bad Form to name indentifier and method the same?

 
Adam Price
Ranch Hand
Posts: 95
  • 0
  • Mark post as helpful
  • send pies
  • Quote
  • Report post to moderator
Is it considered poor form to do something like this:


shoeSize is the method, shoeSize is the variable that is returned within the method.

I know there are other ways to do this particular example - and I am using one of them in the code that made me think of this, but in general, does one avoid having a method named similarly to one of it's internal variables?
 
Bear Bibeault
Author and ninkuma
Marshal
Pie
Posts: 64190
83
IntelliJ IDE Java jQuery Mac Mac OS X
  • 0
  • Mark post as helpful
  • send pies
  • Quote
  • Report post to moderator
A more conventional approach is to name methods that return a property such as "shoeSize" as getShoeSize().
 
Jim Yingst
Wanderer
Sheriff
Posts: 18671
  • 0
  • Mark post as helpful
  • send pies
  • Quote
  • Report post to moderator
However, this convention isn't an absolute requirement, and there are many classes in the standard libraries that don't follow it - size() being one very common example. I think it's only a problem if you're using some reflection-based framework that assumes getters and setters will always follow the standard naming convention. In many classes this will not be an issue. In my experience there's no real problem if a method name matches a field name - it's always possible to tell which one you're talking about, based on whether or not there's a () after. (And in many cases they would have the same effect anyway.)

What I think would be a bad idea, would be if a method and field had the same name but were actually unrelated. If I see a field named size, and a method named size(), I'm probably going to expect that the definition of size() is

If on the other hand, it's

then I think that's a potential source of confusion; I wouldn't recommend that.
 
Stan James
(instanceof Sidekick)
Ranch Hand
Posts: 8791
  • 0
  • Mark post as helpful
  • send pies
  • Quote
  • Report post to moderator
I actually named a getter the same as a member variable the other day. I was aware it was counter to convention but it felt good.

C# (and I think Delphi Pascal) allow clients to reference variables as "object.var" and the object developer can add or remove getters and setters without affecting the clients. Slick.
 
I agree. Here's the link: http://aspose.com/file-tools
  • Post Reply
  • Bookmark Topic Watch Topic
  • New Topic