Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Java Map: Using value object's attribute as key, bad practice?

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.

like image 471
Mark Buikema Avatar asked Jul 08 '26 23:07

Mark Buikema


1 Answers

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.

like image 160
sxleixer Avatar answered Jul 11 '26 12:07

sxleixer