tags:

views:

304

answers:

3

What is the fragile base class problem in java?

+9  A: 

It's a rare condition that renders the sufferer completely unable to Google things ;)

http://en.wikipedia.org/wiki/Fragile_base_class

There are links throughout that page that will give you very deep insight into the problem and some workarounds.

Oli
+1 I don't usually like the "google it" answers but I must admit when the question is merely a definition...
DrDro
I don't like "google it" answers even in this context; because "google it" only dismisses the question, and now this page is not adding anything to internet except more noise. If it's not a worthwhile question it should be closed instead.
Colin Pickard
Allen Holub has a good point on it in "Object Oriented Design Voodoo" (Google for it :)
mlvljr
@Colin I don't consider a link to some valid content to be "noise". Even if it's how I summed it up everyone noticed that Oli's answer was a bit more then "google it".
DrDro
Or even "google it, ***" :)
mlvljr
+6  A: 

A fragile base class is a common problem with inheritance, which applies to Java and any other language which supports inheritance.

In a nutshell, the base class is the class you are inheriting from, and it is often called fragile because changes to this class can have unexpected results in the classes that inherit from it.

There are few methods of mitigating this; but no straightforward method to entirely avoid it while still using inheritance. You can prevent other classes inheriting from a class by labelling the class declaration as final in Java.

A best practice to avoid the worst of these problems is to label all classes as final unless you are specifically intending to inherit from them. For those to intend to inherit from, design them as if you were designing an API: hide all the implementation details; be strict about what you emit and careful about what you accept, and document the expected behaviour of the class in detail.

Colin Pickard
+7  A: 

A base class is called fragile when changes made to it break a derived class.

class Base{
    protected int x;
    protected void m(){
       x++;
    }

    protected void n(){
      x++;      // <- defect 
      m();
     }
 }


class Sub extends Base{
        protected void m(){
            n();
        }
    }
stacker
It's fragile when simple changes to the parent class break the child class. If you're changing everything in the parent and that causes children to break, that doesn't necessarily mean the parent was fragile; if you change something seemingly benign and things fall apart, it was fragile.
Dean J
But which changes are simple then, i.e. what's the criteria?
mlvljr