Can someone give a better example of fragile base class issues?

后端 未结 1 1771
别跟我提以往
别跟我提以往 2021-02-08 19:48

Fragile base class is one of the most common point that gets popped up in every discussion where reusability through implementation inheritance is discussed.

Has anyone

1条回答
  •  一向
    一向 (楼主)
    2021-02-08 20:42

    Yes - java.util.Properties is a pain to derive from.

    For the moment let's leave aside the fact that it derives from java.util.Hashtable to start with (which means it has get(Object) and put(Object, Object) despite the fact that properties are always strings...

    I once subclassed java.util.Properties to provide a sort of hierarchical structure - in a properties file I had:

    x.y.z = 10
    a.b.c = 10
    

    and you could ask the "master" properties for "x" (with a new method call) and it would give you another properties object which would effectively contain "y.z = 10" etc. It was handy to subclass java.util.Properties as many other pieces of code already knew used properties. If it had implemented an interface, I wouldn't have subclassed, and I wouldn't have had any problems :(

    Anyway, I needed to override getProperty() to refer back to the parent properties if necessary. But there are two overloads - which should I override? Does getProperty(String) call getProperty(String,String) or vice versa? Maybe I only need to override get()? It's not documented, and if I only overrode one of them, the implementation could change in a later version to switch things round - so I needed to override both of them.

    The same went for various other methods (saving and loading were a pain, IIRC - this was a long time ago). Basically I could have done the job more simply if I could have relied on bits of the implementation of Properties not changing - but that would obviously have made it harder for Sun to improve the implementation at a later date.

    Anyway, this was a definite example where composition and exposing an interface which clients would rely on would have been much better.

    0 讨论(0)
提交回复
热议问题