3

suppose I have code like this

someFunction:function(userId){
  var url=SomeClass.SomeNetworkConnector.SOME_URL;
  if(url !== undefined && userId !== undefined){
    this.openURL(url+"?userid="+userId);
  }
}

Initially I think the name of actual constant SomeClass.SomeNetworkConnector.SOME_URL is too long, so I use a variable with shorter name to hold it, and then use it later.

But I'm struggling if I should do this, my reason to oppose above is : SomeClass.SomeNetworkConnector.SOME_URL is already a well defined name of the constant, is it misleading to rename it as another variable? Should I always use SomeClass.SomeNetworkConnector.SOME_URL instead of creating a shorter variable name?

ocomfd
  • 5,652
  • 8
  • 29
  • 37
  • 1
    This is perfectly reasonable. The definition and usage are so close together, that it's easy to see what's going on. It's ceratinly easier to read than using `SomeClass.SomeNetworkConnector.SOME_URL` multiple times – Alexander Feb 07 '18 at 04:15
  • Though I would further improve readability by applying some reasonable spacing: `...url = SomeClass...`, `if (...) {` – Alexander Feb 07 '18 at 04:16
  • Possible duplicate of [Are short identifiers bad?](https://softwareengineering.stackexchange.com/questions/24077/are-short-identifiers-bad) – gnat Feb 07 '18 at 04:54
  • @Alexander, I agree. Providing a local alias for a value is perfectly acceptable. – Steve Feb 07 '18 at 09:36
  • 1
    @Steve So long as the equality operator doesn't hidden semantics. God C++ is such a mind fuck. – Alexander Feb 07 '18 at 20:01

1 Answers1

5

This is a perfectly fine practice.

The point of having a long and detailed name for a constant exported from a library is to distinguish it from all the other URLs that might occur in your program, or any program, or in fact from all other constants in the world. It's necessary to distinguish between them, so it makes sense give it a maximally informative name. It helps establish the identity of that constant.

Within your method, the focus is not on the identity of that URL. Instead, it is on the function of the URL you are using to achieve your present, limited-scope purpose. Therefore, it's perfectly fine to use a short name like url for to indicate "the endpoint that I'm currently talking to". If one day your code switches providers, the external constant would change to another long name, but the local variable should probably still be called url.

Kilian Foth
  • 107,706
  • 45
  • 295
  • 310
  • Something could be said for not removing a constant out from under the feet of those who use your library. If it is possible to mark it deprecated, the old constant should be marked as such with a comment indicating the new constant to use. If it cannot be marked for deprecation, mention of it in the changelog is almost as good. It guarantees that the change won't create problems while making your intentions to rename the constant known. – Neil Feb 07 '18 at 11:47