0

In a generic OO language (say C++, C#, java) I have a map of objects with a string ID and the same ID is also key of the relative object

class Foo(){
    Foo(string id){this.id = id;}
    string id;
    string otherProperty;
}
map<string,Foo> foos;

now if i want to add an object i'd

map.add("myFirstID", new Foo("myFirstID"));
map.add("mySecondID", new Foo("mySecondID"));

I don't like to repeat strings, it will just get worst ( think to when retrieving by key it just explode ).

I can't use an enum (since in some languages like c++ it can't be easily converted to string, and i need it)

only option seems to be a cascade of

const string MY_FIRST_ID = "myFirstID";
const string MY_SECOND_ID = "mySecondID";

to then

foos.add(MY_FIRST_ID, new Foo(MY_FIRST_ID));

This solutions is better, still it's very verbose, there's still some coupling in same class and there's no enforcing on the values ( like there's for an enum );

Can you think any better pattern?

PS: another solution is to only use enum as keys and put the string as a simple field. But this require to add high coupling between Foo and FooManager ( class instantiating foo instances )

jalone
  • 1,953
  • 4
  • 27
  • 46

2 Answers2

0

You could always do your

var f = new Foo("myFirstID")

and then do a

map.add(f.id, f);

Another thing to explore is, if need to have that key just to provide uniqueness of the object foo, explore the hashset collection, available in both c# and java world. If you provide a IEqualityComparer you can just add and delete you foo objects. This can be a solution if you don't need to access your hashset with the string acessor.

saamorim
  • 3,855
  • 17
  • 22
0

In C# you can do something like:

string foo;
map.add(foo = "myFirstID", new Foo(foo));

I'm not sure if you can do the same in Java or in C++ but it is a good staring point.

Davide Aversa
  • 5,628
  • 6
  • 28
  • 40
  • thank you but the problem is just delayed to the first required map.get("myFirstID"); moreover no uiniqueness is provided nor enforce on the provided values . – jalone Jun 26 '13 at 14:23