• Post Reply Bookmark Topic Watch Topic
  • New Topic

Accessing HashTable within an object  RSS feed

 
Randy Johnson
Greenhorn
Posts: 22
  • Mark post as helpful
  • send pies
  • Quote
  • Report post to moderator
If an object instance contains a HashTable with many entries, and a client class or object wants to access the HashTable entries, which approach is more appropriate:
String keyInformation = "KEY";
HashTable hashTable = targetClass.getHashTable();
if hashTable.containsKey(keyInformation) {}
OR
String keyInformation = "KEY";
if targetClass.hashtable.containsKey(keyInformation) {}
The second approach seems as thought it would be more efficient use of memory, but I suspect it violates the objective of information-hiding.
Any thoughts?
 
Ernest Friedman-Hill
author and iconoclast
Sheriff
Posts: 24217
38
Chrome Eclipse IDE Mac OS X
  • Mark post as helpful
  • send pies
  • Quote
  • Report post to moderator
Both violate the principle of information hiding. A better approach would be

i.e., hide the fact that there's a hash table at all; the relevant concept is that the targetClass "knows about" the keys, somehow. The details don't matter.
An even better approach (not always practical) is

i.e., the logic that needs to know about targetClass's internal data belongs in targetClass.
 
Joel McNary
Bartender
Posts: 1840
Eclipse IDE Java Ruby
  • Mark post as helpful
  • send pies
  • Quote
  • Report post to moderator
In fact, both methods violate the OO concept of encapsulation. (Although the first method is a very common one; the second method is strongly discouraged in general, since not all classes make their member variables public)
Idealy, the "right" OO approach would be:

and in the SomeObject class:

..although this pattern is not always used, as it is cumbersome to write. However, if you wanted to change the underlying implementation (to another type of Map or to somethign else entirely) it would be quite easy to work with.
 
  • Post Reply Bookmark Topic Watch Topic
  • New Topic
Boost this thread!