简体   繁体   中英

Naming Convention Java for different class but same variable name

Just needed some clarity on the below. Might be stupid but please throw some light on pros and cons.Assuming in IDE we search variables names while debugging and also during mapping or sending some data to others apps during that time.

Class State{
 private String stateName;
 private String stateCode;
}

Class City{
 private String cityName;
 private String cityCode;
}

is the above variable name fine or we should have names like

Class State{
 private String name;
 private String code;
}

Class City{
 private String name;
 private String code;
}

Assume that this would go as part of some CountryDTO to some api's.

I have tried to find this convention online but could not get anything more than the word mnemonic

Not sure if to accept answer or not since this is mostly preference based question and so the answers.

Personally I think the naming convention depends on what the object is being used for. I would use the first example if I was querying a complex database that way the variable names most likely follows Column names inside the database. To me that helps any programmer read where in the database the object belongs etc.

If this is just a quick script the second example will work fine, I would just recommend that you at least document the variables!

As the class name already defines the object type, it does not require each element within it to repeat itself.

   Class City {
     private String name;
     private String code;
   }

As you would name the instance of the object ex. City city = new City(); you again have the class type being part of the name.

Just compare city.name to city.cityName , the first one is much simpler and cleaner.

Depending on the object complexity (amount of attributes each information consists of), it can happen that you need to define two attributes with the same name within the same object.

Simple example: something.getCityName() and something.getCountryName() , but this applies only if both city and country are not available as separate objects, as in that case it would be something.getCity().getName() .

Hope this helps

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM