Is it bad practice to use an object's attribute as the key for a map entry? Every time I do it, it feels wrong.
For example:
class Foo {
String name;
String bar;
}
And then use a Map like this:
Foo foo = new Foo();
foo.name = "foo bar";
foo.bar = "blaaaa";
Map<String, Foo> foos = new HashMap<>();
foos.add(foo.name, foo);
It feels kind of wrong.
At first glance it feels wrong.
But using a field as key is reasonable, perhaps a bit redundant but legitimate.
It doesn't matter where the key's value comes from! Because the purpose of a Map is to retrieve elements. And doing it like that fairly does the job.
If you feel that guilty, you may remove the field from the class if there aren't any side-effects.
What may be wrong about that is - you're not using methods for the fields. Consider following scenerio: You'd like to combine two strings as new key. If you have referenced a field a thousand times, you are out of luck! You just have to replace all occurences of the field. This may lead to bugs and inconveniences if you accidentally replaced something else.
But if you do have a method, you just change the part in the method and you're done.
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With