1

What is wrong in using HashMap instead of DTO ? Instead of calling bean's setters and getters, i can put and get value from a hashmap and pass it between services (hashmap implements Serializable interface). I know it is a bad practice.But why and under which scenario we would face the issue? Thanks for your help in advance.

1
  • This basically turns Java's very strict type system off. You lose every single benefit the Java compiler provides. If you want to do something like this, use a language that was designed specifically for that purpose; for example Python or Ruby. Apr 6, 2015 at 12:08

1 Answer 1

9
  • No compile time checking. When you pull something out of the returned HashMap, you can never get compile-time validation that what you're casting it to is valid.

  • Difficult refactoring. In many IDEs (such as IntelliJ) there are great facilities to refactor a class' method names, variables, etc. This becomes much more difficult when using the dictionary pattern.

  • Greater ambiguity for return values. Say in phase 1 of a project, you get back a user object and only use the "getUsername()" method. Then in phase 2 all of a sudden you need to have access to the password attribute. If you have a user object, you know exactly if that value is accessible and how to get it by simply looking at the class. With the HashMap that's not necessarily the case. If you don't have access to the source of the class that generates the HashMap (in this case the EJB), you'll never know what other data attributes are available.

Hoping it will be Helpful...

2
  • 2
    And it is less efficient due to the overheads of creating the HashMap data structure, inserting entries and looking them up. And the HashMap occupies considerably more memory.
    – Stephen C
    Apr 6, 2015 at 12:17
  • Why would there be a need to have the User object in the HashMap? Wouldn't a HashMap<DataType,String> suffice? Apr 6, 2015 at 16:46

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge that you have read and understand our privacy policy and code of conduct.

Not the answer you're looking for? Browse other questions tagged or ask your own question.