Is there anything wrong with replacing class attributes with a HashMap?

丶灬走出姿态 提交于 2019-12-13 01:51:38

问题


Just a theoretical question that could lead to some considerations in terms of design. What if you were to replace POJOs with this reusable class ? It might avoid some boilerplate code but what issues could it bring about ?

// Does not include failsafes, guards, defensive copying, whatever...

class MySingleGetterAndSetterClass{

    private HashMap<String,Object> myProperties;

    public SingleGetterAndSetter( String name ){
        myProperties = new HashMap<String,Object>();
        myProperties.put( "name", name );
    }

    public Object get( string propertyName ){
        return myProperties.get( propertyName );
    }

    public Object set( string propertyName, Object value ){
        myProperties.put( propertyName, value );
    }

}

回答1:


The main disadvantages

  • much slower
  • uses more memory
  • less type safety
  • more error prone
  • more difficult to maintain
  • more code to write/read
  • more thread safety problems (more ways to break) and more difficult to make thread safe.
  • harder to debug, note the order of fields can be arranged pseudo randomly, different for different objects of the same "type" making them harder to read.
  • more difficult to refactor
  • little or not support in code analysis.
  • no support in code completion.

BTW Some dynamic languages do exactly what you suggest and they have all these issues.




回答2:


That would lead to very unstable code. None of your getting/setting would be compile-time checked. Generally you want your code to fail-fast, and compile-time is the absolute fastest that can be done.

To make it even relatively safe you'd have to have null-checks/exception handling all over the place, and then how do you consistently handle the case where the value isn't found, all over your code? It would get very bloated very fast.




回答3:


  • Not compile checking.
  • You have to downcasting, this is not good.
  • Difficult to mantain.
  • Against OOP,

Your pojos are classes represents an abstraction of something in real world. If i understood well you want to put their properties inside a map, this is not a good design. Your are against using OOP. If you think in this way you can take all classes in a single big String and search them by position and this would be better than having only a dictionary with property as key.



来源:https://stackoverflow.com/questions/17159502/is-there-anything-wrong-with-replacing-class-attributes-with-a-hashmap

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!