tk_
tk_

Reputation: 17418

Best practice for naming different contents(Ex:String and byte) which has similar reference(Ex:name)

This is a simple best practice issue that I faced recently in a legacy code that I'm working these days. I couldn't find a good reference for this specific issue cause there can be multiple ways that we can achieve this. However, I would like to know the best and most effective way to achieve this. Below I have created some of my findings and I hope to get others opinion on what would be the best way to name naming different contents which has similar reference.

Example 1

String name = "Thushara";
byte[] nameByte = toBytes(name);

Example 2

String nameStr = "Thushara";
byte[] nameByte = toBytes(nameStr);

Example 3

String strName = "Thushara";
byte[] byteName = toBytes(strName);

I know there will not be a standard to achieve this. Therefore, I would like to know the best way to do this in maintainability or other perspective which I don't know.


Update

String name = "Thushara"; 
byte[] nameBytes = toBytes(name);

Upvotes: 0

Views: 924

Answers (1)

Sasha Shpota
Sasha Shpota

Reputation: 10310

The best practice is to escape from such decisions.

You have to rethink your code in case if you need to name differently objects of different type that represent the same entity. Most likely there is a design problem. Why do you need them both in the same scope? Can't you extract the logic which requires byte[] into separate method/class? Can you solve it using polymorphism? May be you can simply inline the call?

General rule is to name variables closer to domain model you have. byteName does not carry any valuable information and it should signal that something is wrong.

The only exception is unit testing. Obviously if you write unit test for toBytes() method you'll face this issue. But even in this case you can name objects input and output, expected and actual etc.

Once you think on this questions you'll come with idea on how to get rid of this.

Upvotes: 1

Related Questions