Use HashMap to store instance variables?

I would like to create a base class that extends all classes in my program. The only thing I wanted to do was find a single way to store all instance variables inside the object.

What I came up with is to use a HashMap to store key / value pairs for an object, and then set these values ​​using the get and set method.

The code I have for this is as follows:

package ocaff; import java.util.HashMap; public class OcaffObject { private HashMap<String, Object> data; public OcaffObject() { this.data = new HashMap<String, Object>(); } public Object get(String value) { return this.data.get(value); } public void set(String key, Object value) { this.data.put(key, value); } } 

Although this works functionally, I'm curious if there are any real problems with this implementation, or if there is a better way to do this?

In my daily work, I am a PHP programmer, and my goal was to mimic the functionality that I used in PHP in Java.

+7
source share
2 answers

I don't think this is a good way to deal with what you mean. Programming in java is completely different from programming in php, from my point of view.

You need to be clean and strongly typed using the true paradigm of pure object-oriented programming.

Some problems with this technique come to my mind, here are some, not in order of importance.

  • The first problem you are facing is the performance and the amount of memory: it will consume a lot of memory and will work very poorly.

  • The second problem is concurrency, the HashMap is not thread safe.

  • The third problem is type safety: you no longer have type safety, you can write whatever you want in the field, and no one checks it, a real anti-pattern.

  • The fourth problem is debugging ... it will be difficult to debug your code.

  • The fifth problem: everyone can write and read any field, knowing his name.

  • Sixth question: when you change the field name in the hash set, you do not get any compile-time error, you only get strange behavior at runtime. Refactoring will become impossible.

Typed fields are much more useful and clean.

+13
source

If you take the time to create a class for this, I will simply add what you need as members of the class. This will give you the opportunity to check the compilation time of your class members, greatly reducing your subtle errors.

+1
source

All Articles