typedefs are good
The designers of Java omitted typedefs on the ground that it introduces “too much context”. This is true to some extent. I mostly depend on typedefs for declaring generic containers. This saves a lot of keystrokes and screen space, especially when declaring functions that consume or return such containers:
typedef map<string, int> NameAgeMap; static void InitSample(NameAgeMap& sample) { sample["joe"] = 20; sample["mark"] = 22; } // .... NameAgeMap sample; InitSample(sample); NameAgeMap::const_iterator iter = sample.begin(); while (iter != sample.end()) { std::cout << iter->first << ':' << iter->second << '\n'; ++iter; }
If the new type is properly named, we need not look at the typedef to infer what it really is. An IDE might even show the real type when the mouse is hovered over the variable. Contrast this with Java. I have to type the lengthy container declaration where ever I need it:
public void InitSample(HashMap<String, Integer> sample) { sample.put("joe", 20); sample.put("mark", 22); } // ... HashMap<String, Integer>sample = new HashMap<String, Integer>(); InitSample(sample); Set<String>keys = sample.keySet(); for (String name : keys) { System.out.println(name + ':' + sample.get(name)); }
I suppose that the argument against typedef was made before Java had generics. As the view on enum was later compromised, Java may eventually introduce typedef.