Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Use a HashMap to store instance variables?

Tags:

java

hashmap

I would like to create a base class that all classes in my program will extend. One thing I wanted to do was find a uniform way to store all instance variables inside the object.

What I have come up with is to use a HashMap to store the key/value pairs for the object and then expose those values through a get and set method.

The code that I have for this so far 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);
    }

}

While functionally this works, I am curious if there are any real issues with this implementation or if there is a better way to do this?

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

like image 641
Josh Pennington Avatar asked Oct 21 '11 23:10

Josh Pennington


1 Answers

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

You need to keep things clean and strongly typed, using the real paradigm of clean object oriented programming.

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

  1. First problem you have with this is performance and memory footprint: this will consume a lot of memory and will perform very badly.

  2. Second problem is concurrency, HashMap is not thread safe.

  3. Third problem is type safety: you don't have type safety anymore, you can write to a field whatever you want and no one is checking it, a real anti-pattern.

  4. Fourth problem is debugging... it will be hard to debug your code.

  5. Fifth problem is: everyone can write and read any field knowing his name.

  6. Sixth problem: when you change the name of a field in the hash set you don't get any kind of compile time error, you only get strange run-time behavior. Refactoring will become impossible.

Typed fields are much more useful and clean.

like image 179
Salvatore Previti Avatar answered Oct 04 '22 01:10

Salvatore Previti