What care need to take inheriting from library class? - java

We have application in Java, and we are using one library class. After long time after project start we got situation where, in every function we have used that class we want to add one more element in object of the class (just adding value, not adding any new member).
This change is huge. Not difficult to do, but we have used this class in 100s of functions.
Now one solution is we can inherit this class and add required change in derived class. We keep name of class same (and use fully qualified name for base class to inherit), just will change package name so we can use derived class in our code.
Is there any problem in this approach? Because my manager's suggestion is 'Its not easy as it seems to be'.
Kindly suggest if I am doing anything wrong.

Whether inheritance is the best solution depends upon the element you are trying to add. If possible consider composition over inheritance. The advantages can be found here. There you can find a example of one of the pitfall when one tries to override one of the methods. This is more possible in your case since you do not have the source code of library.

you can make small changes in the original class as long as it does not interfere with the original functioning of the class. this is better idea instead of making a derived class with the same name as base class.

If all you're adding is a single variable, this is probably safe. Anything more complicated is dangerous. I don't have any code to go on, but inheritance is probably not the right choice. What happens if you make another subclass that adds a different field, and a few months later you realize now you need both fields? Inheritance is not composable - you can't mix and match the specializations you make in subclasses. Use aggregation. If you need a Foo that also has a Bar, then make a simple container class that has both a foo and a bar:
class FooWithBar {
public final Foo foo;
public final Bar bar;
public FooWithBar(Foo foo, Bar bar) {
this.foo = foo;
this.bar = bar;
}
}

Related

Java class hierarchy, how to implement optional variable throughout

I'm wondering if there's any "clean" way to implement an optional variable throughout a class hierarchy without simply leaving it null and nullchecking all the time. Let's say I have the following abstract parent class:
public abstract class Item {
public String name;
public Item(String name){
this.name = name;
}
public String getName(){
return name;
}
Pretty straightforward. Now I have another abstract class that extends this and a couple more that extend that one, each with a few additional variables/methods of their own. Item also has a stub class extending it (nothing but a constructor that calls super()) that may not be necessary if Item can be made concrete, but that depends on the solution.
Now, let's say that any of these concrete classes could potentially contain an instance of MyObject. A large number of Items will be created. Some of the instances of any of the classes in the Item hierarchy will have it and some won't. There's no way for the program to tell at compile time. I can't really split the hierarchy into two separate but nearly-identical trees, one with MyObject and one without. That's going to lead to a lot of code duplication. Subclassing the concrete implementations with another concrete class containing MyObject would mean excessive typechecking, which would get ugly, especially if the hierarchy grows. Putting an interface/abstract class further up isn't an option either as that would put MyObject in everything. Regardless of the solution, all of these must have a common interface/abstract class.
I may be nitpicking and should just implement MyObject at the top of the hierarchy and nullcheck it or use a simple boolean method to tell me if it's present or not, but it still feels a bit sloppy to me and I'd like to find a better solution if possible.
Your description of problem reminds me the very motivation for the Decorator pattern - an overgrown class hierarchy with some kind of wanted "multiple inheritance" and "combination of super-classes". Have a look at the description of Decorator on internet, and for good example have a look at how the Reader / Writer standard Java classes are implemented.

AbstractClass.getInstance() method is this an anti-pattern

In some places where a class hierarchy is present and the top most base class is an abstract class there is a static getInstance() method in the abstract class. This will be responsible for creating the correct sub-class and returning it to the caller. For example consider the below code.
public class abstract Product {
public static Product getInstance(String aCode) {
if ("a".equals(aCode) {
return new ProductA();
}
return ProductDefault();
}
// product behaviour methods
}
public class ProductA extends Product {}
public class ProductDefault extends Product {}
In Java, java.util.Calendar.getInstance() is one place this pattern has been followed. However this means each time a new subclass is introduced one has to modify the base class. i.e: Product class has to be modified in the above example. This seems to violate the ocp principle. Also the base class is aware about the sub class details which is again questionable.
My question is...
is the above pattern an anti-pattern ?
what are the draw-backs of using the above pattern ?
what alternatives can be followed instead ?
The interface is not an anti-pattern. But the way you've implemented it is rather poor ... for the reason you identified. A better idea would be to have some mechanism for registering factory objects for each code:
The Java class libraries do this kind of thing using SPIs and code that looks reflectively for "provider" classes to be dynamically loaded.
A simpler approach is to have a "registry" object, and populate it using dependency injection, or static initializers in the factory object classes, or a startup method that reads class names from a properties file, etcetera.
No it's not. It's more like factory method pattern http://en.wikipedia.org/wiki/Factory_method_pattern. E.g. Calendar.getInstance();. JDK is full of such examples. Also reminds of Effective Java Item 1: Consider static factory methods instead of constructors
There are a number of separate issues here.
getInstance is probably going to be a bad name. You explicitly want a new object you can play around with. "Create", "make", "new" or just leave that word out. "Instance" is also a pretty vacuous word in this context. If there is sufficient context from the class name leave it out, otherwise say what it is even if that is just a type name. If the method returns an immutable object, of is the convention (valueOf in olden times).
Putting it in an abstract base class (or in an interface if that were possible) is, as identified, not the best idea. In some cases an enumeration of all possible subtypes is appropriate - an enum obviously and really not that bad if you are going to use visitors anyway. Better to put it in a new file.
Anything to do with mutable statics is wrong. Whether it is reusing the same mutable instance, registration or doing something disgusting with the current thread. Don't do it or depend (direct or indirectly) on anything that does.
Based on the feedback i introduced a new ProductFactory class that took care of creating the correct Product. In my case the creation of the correct product instance depends on an external context (i've put the product code for the purpose of simplicity.. in the actual case it might be based on several parameters.. these could change over time). So having a Product.getInstance() method is not that suited because of the reasons outlined in the question. Also having a different ProductFactory means in the future.. Product class can become an interface if required. It just gives more extensibility.
I think when the creation of the object doesn't depend on an external context.. like in the case of Calendar.getInstance() it's perfectly ok to have such a method. In these situations the logic of finding the correct instance is internal to that particular module/class and doesn't depend on any externally provided information..

Name clash in java imports

Unless we change the compiler, Java misses the import X as Y syntax, which would be useful in cases like mine: In this very moment I'm working on a project having multiple classes with the same name, but belonging to different packages.
I would like to have something like
import com.very.long.prefix.bar.Foo as BarFoo
import org.other.very.long.prefix.baz.Foo as BazFoo
class X {
BarFoo a;
BazFoo b;
...
}
Instead I finish in having something like
class X {
com.very.long.prefix.bar.Foo a;
org.other.very.long.prefix.baz.Foo b;
...
}
Here it seems pretty harmful, but on my specific case I need to use horizontal scrolling in order to browse my source code, and that concours in making worse a program which is already a mess.
In your experience, what is the best practices in this case?
I feel your pain, whichever solution you use, the very fact that there are two classes with the same name is confusing enough.
There are several solutions workarounds:
If this is your code, just rename one of them (or both)
If this is library (which is more likely) import more commonly used class, fully qualify the other one, as Jeff Olson suggested.
Try to avoid having them in the same class in the first place if that is possible.
You could write your own BarFoo and BazFoo which do nothing other than extend their respective Foo classes thus providing them with their own names. You can even define these as inner classes. Example:
private BarFoo extends com.very.long.prefix.bar.Foo{
//nothing, except possibly constructor wrappers
}
private BazFoo extends com.very.long.prefix.bar.Foo{
//nothing, except possibly constructor wrappers
}
class X {
BarFoo a;
BazFoo b;
//...
}
There are some drawbacks, though:
You'd have to redefine the constructors
It wouldn't be the exact same class, if you need to pass it to a function which is explicitly checking its getClass.
You could solve these drawbacks by wrapping the Foo classes rather than extending them, e.g.:
private BarFoo {
public com.very.long.prefix.bar.Foo realFoo;
}
private BazFoo extends com.very.long.prefix.bar.Foo{
public com.very.long.prefix.baz.Foo realFoo;
}
class X {
BarFoo a;
BazFoo b;
//now if you need to pass them
someMethodThatTakesBazFoo(b.realFoo);
}
Choose the simplest solution and good luck with it!
The best practice is to refactor the code.
Either the classes should not have the same name, because it's normal to use them both in the same classes, and thus choosing the same name for both is not a wise choice. So one of them at least should be renamed.
Or it's not normal to use them both in the same classes because they belong to completely different abstraction levels (like database access code and UI code, for example), and code should be refactored to use each class where it must be used and not elsewhere.
What I've typically done in these situations is to import the most commonly used Foo in my class, and then fully-qualify the other one:
import com.very.long.prefix.bar.Foo
class X {
Foo a;
org.other.very.long.prefix.baz.Foo b;
...
}
OP here.
With time I actulally developed a strategy to workaround this limitation of the Java language. I don't know if this has some drawback (so far I've never found any), but if so please comment in this question.
The idea is to replace the last part of the fully-qualified name with a class instead of a package, and have actual classes defined as static inner-classes.
class Bar {
static class Foo { ... }
}
In this way we have something like
import f.q.n.Bar
import other.f.q.n.Baz
...
Bar.Foo a;
Bar.Foo b;
This is actually an extremely clean way of doing it. Of course it applies only to classes you control, and not on libraries.
Known drawbacks
Your boss might not like the idea and smash your finger with a hammer;
Eclipse will not like the idea, and you have to get used to it.
You may want to have a look at Kotlin, which is compatible with Java.
If there is a name clash in Kotlin, you can disambiguate by using as keyword to locally rename the clashing entity:
import foo.Bar // Bar is accessible
import bar.Bar as bBar // bBar stands for 'bar.Bar'
You can find more info at https://kotlinlang.org/docs/reference/packages.html

Public static methods - a bad sign?

I've just read this article here: http://hamletdarcy.blogspot.com/2008/04/10-best-idea-inspections-youre-not.html, and the last bit in particular got me thinking about my code, specifically the advice:
What in the world is a public method doing on your object that has no dependency on any fields within the object? This is certainly a code smell. The problem is that the "auto-fix" for the inspection is to apply the static keyword. Nooooo. That's not what you want to do. A public method without any dependency on object state can't possibly be part of an object that has one clearly stated charter. It's just not cohesive and should be placed somewhere else. So: if the method is private, accept the auto-fix, but if the method is public then don't.
The code in question is essentially an object transformer. It takes an object of type A and converts it to a different type.
My hierarchy is like this:
Interface ObjectTransformer -> GenericObjectTransformer
and then below this, GenericObjectTransformer is extended by ObjectTransformerA and ObjectTransformerB
Now, some functionality is required by both ObjectTransformerA and ObjectTransformerB, but doesnt actually depend on any instance variables of GenericObjectTransformer, so its a protected static method in GenericObjectTransformer.
Is this a violation of the rule above? Obviously this is protected rather than public, but its still a method accessible from outside of the class that has nothing to do with the class itself?
Any thoughts?
I disagree with the excerpt you pulled.
A public method without any dependency on object state can't possibly be part of an object that has one clearly stated charter. It's just not cohesive and should be placed somewhere else. So: if the method is private, accept the auto-fix, but if the method is public then don't.
Just because a method is static and has no relation to state, doesn't mean it falls under the "low cohesion" category. Cohesion/Functionality isn't based on state.
When you are trying to determine Cohesiveness think about the role of the class as a whole, not just the instance variables. If the logic you are looking at is related to the generic concept (GenericObjectTransformer) then leave it there.
If it is a routine to calculate the orbit of the moon, or the depth of the ocean move it to a utility class (another smelly area of our field).
It feels slightly unclean, but is seem preferable to the alternatives I can think of.
I think that the original
A public method without any dependency
on object state can't possibly be part
of an object that has one clearly
stated charter.
You reference is too black and white, and your situation is even greyer.
By having your protected method you are nicely documenting that its intended for use by derived classes. If you don't put it in the base class, then presumbly it's got to go in some ObjectTransformUtility class. Is that win? More artefacts, more places to look.
One thought: if your ObjectTransormer class undergoes significant change then how likely are you to need to change these utility methods. After all if their business is to work agains the object's interface then in fact their cohesion is quite high.

Java abstract static Workaround

I understand that neither a abstract class nor an interface can contain a method that is both abstract and static because of ambiguity problems, but is there a workaround?
I want to have either an abstract class or an interface that mandates the inclusion of a static method in all of the classes that extend/implement this class/interface. Is there a way to do this in Java? If not, this may be my final straw with Java...
EDIT 1: The context of this problem is that I have a bunch of classes, call them Stick, Ball, and Toy for now, that have a bunch of entries in a database. I want to create a superclass/interface called Fetchable that requires a static method getFetchables() in each of the classes below it. The reason the methods in Stick, Ball, and Toy have to be static is because they will be talking to a database to retrieve all of the entries in the database for each class.
EDIT 2: To those who say you cannot do this in any language, that is not true. You can certainly do this in Ruby where class methods are inherited. This is not a case of someone not getting OO, this is a case of missing functionality in the Java language. You can try to argue that you should never need to inherit static (class) methods, but that is utterly wrong and I will ignore any answers that make such points.
You have a couple of options:
Use reflection to see if the method exists and then call it.
Create an annotation for the static method named something like #GetAllWidgetsMethod.
As others have said, try to not use a static method.
There are lots of answers about 'this does'nt make sense..' but indeed I met a similar problem just yesterday.
I wanted to use inheritance with my unit tests. I have an API and several its implementations. So I need only 1 set of unit tests for all implementations but with different setUp methods which are static.
Workaround: all tests are abstract classes, with some static fields with protected access modifier. In all implementations I added static methods which set these static fields. It works rather nice, and I avoided copy and paste.
I too am dealing with this problem. For those that insist that it "doesn't make sense", I would invite you to think outside of that semantic box for a moment. The program I am working with is inherently about reflection.
Reflection, as you know, can take three orders of magnitude longer than straight-up binary function calling. That is an inevitable problem, and the software needs to port to as many machines as possible, some of which will be 32 bit and slower than my development machine to begin with. Thus, the applicability of a class to the requested operation needs to be checked via a static method, and all of the reflective methods are run at once during module booting.
Everything works, first and foremost. I've built the entire thing. The only catch is that a module can be compiled in a .class without compile time checking to see if the identifying static function exists at all, resulting in an innately useless class. Without the identifier, and its included information, for security's sake the module is not loaded.
I clearly understand the issue with the complete definition of "abstract" and "static", and understand that they don't make sense together. However, the ability to have a class method that is compiler-enforced for inclusion is lacking in Java, and as much as I like the language, I miss it. Thus, this is a human constraint on every programmer that ever works on the software, which I'm sure we can all agree is a pain.
There's a lot of 'this makes no sense' or 'this can't be because' and 'why do you want it?' (or worse: 'you don't have to want it!') in all those answers. However, these answers also indirectly give reasons why it should be possible.
It must be differentiated between the concept and the implementation.
Sure, overriding a static method makes no sense. And it also isn't what the question was about.
It was asked for a way to force implementation of a certain static method (or constant or whatever) in every derived class of an abstract class. Why this is required it the matter of the one who wants to write an appllication with Jave, and no business of anyone else.
This has nothing to do with how the compiler compiles the method and how it is done at runtime.
Why shoudl it be possible? because there are things that are class specific (and not instance specific) and therefore should be static, while they NEED to be impleented in every single subclass (or class that implements an interface).
Let's say there is an abstract class 'Being'. Now there are subclasses like 'animals' and 'plants'.
Now there are only mammals and fishes allowed for animals. This information is specific to the animals class, not to any instance nor doe sit belong to any superclass or subclass. However, this information must be provided by teh class, not an instance, because it is required to properly construct an animal instance. So it MUST be there and it CANNOT be in the instance.
In fact, Java has such a thing- Every object has a class specific field 'class'. It is class-specific, not inherited, no override and it must be there. Well the compiler creates it implicitly, but obviously the compiler CAN do it. So why not allowing this for own fields too.
After all, it is just a matter of definition how the combination 'abstract static' is interpreted when the compiler checks the intheritance chain for abstract functions.
Nobody was ever demanding that there should be an inheritance of the superclass class functions (which could still make some sense, depending on what this function actually does - after all classes inherit static functions of their superclasses, even though you might get a warning that you should access it directly when you call it by the subclass))
But to summarize: the Java language offers no way to do it at compile time while there is no reason (othe rthan plain dogmatic) to not doing so.
The only way is to write a static final function to the abstract class that tries to find the static function/field of the subclass when it is loaded (or loads all existing subclasses and checks them). If properly made, it gives a runtime error on first use. Complex and dirty but better than nothing. At least it prevents bugs where you get the information from the wrong superclass.
It won't work for interfaces, though.
A type system allows you to express some constraints among types, but it's limited. That's why javadocs are littered with constraints in human language, asking people to follow rules that the compiler cannot check.
if you want to extend it beyond what language provides natively, you can write your own static analysis tool. that is not uncommon. for example: findbug. also IDEs do that too, they checking thing beyond what language dictates. you can write a plug in to enforce that a subclass must have a static method of such signature.
in your case, it's not worth it. have javadoc in the superclass urge implementors to include a static method, that's good enough.
I'll provide a convoluted way of expressing your constraint anyway, but DO NO DO IT. people get really carried away of make everything checkable at compile time, at the price of making code unreadable.
interface WidgetEnumerator
{
List getAllWidgets();
}
public class Abs<T extends WidgetEnumerator>
{
static List getAllWidgets(Class<? extends Abs> clazz){ ... }
}
public class Sub extends Abs<SubWidgetEnumerator>
{
}
public class SubWidgetEnumerator implements WidgetEnumerator
{
public List getAllWidgets() { ... }
}
How it works: for any subclass of Abs, it is forced to provide an implementation of WidgetEnumerator. subclass author cannot forget that. Now invocation Abs.getAllWidgets(Sub.class) contains sufficient information to resolve that implementation, i.e. SubWidgetEnumerator. It is done through reflection, but it is type safe, there are no string literals involved.
I think I can give you a better answer after seeing your edits--your best bet is probably a factory pattern. (Not lovely, but better than singleton).
abstract class Widget
public static Widget[] getAllWidgetsOfType(Class widgetType) {
if(widgetType instanceof ...)
}
class Ball extends Widget
class Stick extends Widget
class Toy extends Widget
This is not a very good way to do it, but it's typical. Hibernate is the tool you would normally use to solve this problem, this is exactly what it's designed for.
The big problem is that it requires editing the base class whenever you add a new class of a given type. This can't be gotten around without reflection. If you want to use reflection, then you can implement it this way (Psuedocode, I'm not going to look up the exact syntax for the reflection, but it's not much more complex than this):
public static Widget[] getAllWidgetsOfType(Class widgetType) {
Method staticMethod=widgetType.getStaticMethod("getAllInstances");
return staticMethod.invoke();
}
This would give the solution you were asking for (to be bothered by the need to modify the base class each time you add a child class is a good instinct).
You could also make it an instance method instead of a static. It's not necessary, but you could then prototype the method (abstract) in Widget.
Again, all this is unnecessary and sloppy compared to Hibernate...
Edit: If you passed in a live "Empty" instance of a ball, stick or toy instead of it's "Class" object, you could then just call an inherited method and not use reflection at all. This would also work but you have to expand the definition of a Widget to include an "Empty" instance used as a key.
Static methods are relevant to an entire class of object, not the individual instances. Allowing a static method to be overridden breaks this dictum.
The first thing I would consider is to access your database from a non-static context. This is actually the norm for Java apps.
If you absolutely must use a static method, then have it parameterised with instance specific arguments (of a generic type) to allow the different subclasses to interact with it. Then call that single static method from you polymorphic methods.
No. You can't do that. If you're willing to compromise and make the method non-static or provide an implementation of the static method in your abstract class, you'll be able to code this in Java.
Is there a way to do this in Java?
I don't think there is a way to do this in any language. There's no point to it, since static methods belong to a class and can't be called polymorphically. And enabling polymorphic calls is the only reason for interfaces and abstract classes to exist.
Create a context interface containing your method with a name that matches your problem domain. (Name it "World" if you absolutely have to, but most of the time there's a better name)
Pass around implementation instances of the context object.
Ok, maybe my question was poorly asked, it seems like most of you didn't get what I was trying to do. Nonetheless, I have a solution that is somewhat satisfactory.
In the abstract super class, I am going to have a static method getAllWidgets(Class type). In it I'll check the class you passed it and do the correct fetching based on that. Generally I like to avoid passing around classes and using switches on stuff like this, but I'll make an exception here.
static methods can't be abstract because they aren't virtual. Therefore anywhere that calls them has to have the concrete type with the implementation. If you want to enforce that all implementations of an interface have a certain static method, then that suggests a unit test is required.
abstract class A
{
public static void foo()
{
java.lang.System.out.println("A::foo");
}
public void bar()
{
java.lang.System.out.println("A::bar");
}
}
class B extends A
{
public static void foo()
{
java.lang.System.out.println("B::foo");
}
public void bar()
{
java.lang.System.out.println("B::bar");
}
}
public class Main
{
public static void main(String[] args)
{
B b = new B();
b.foo();
b.bar();
A a = b;
a.foo();
a.bar();
}
}
For what it is worth I know exactly what you are trying to do.
I found this article while searching for the reasons I can't do it either.
In my case I have HUNDREDS of classes that inherit from a central base base and I want simply to get a reference like this:
ValueImSearchingFor visf = StaticClass.someArbitraryValue()
I do NOT want to write/maintain someArbitraryValue() for each and every one of hundreds of the inherited classes -- I just want to write logic once and have it calc a Unique Class-Sepcific value for each and every future written class WITHOUT touching the base class.
Yes I completely get OO - I've been writing Java for about as long as it's been available.
These specific classes are more like "Definitions" as opposed to actual Objects and I don't want to instantiate one every time I just need to see what someArbitraryValue() actually is.
Think of it as a PUBLIC STATIC FINAL that allows you to run a Method ONCE to set it initially. (Kinda like you can do when you define an Enum actually...)
I'd make a WidgetCollection class with an abstract Widget inner class.
You can extend the WidgetCollection.Widget class for each of your types of Widget.
No static methods necessary.
Example (not compiled or tested):
class WidgetCollection<W extends Widget> {
Set<W> widgets = new HashSet<W>();
Set<W> getAll() {
return widgets;
}
abstract class Widget {
Widget() {
widgets.add(this);
}
abstract String getName();
}
public static void main(String[] args) {
WidgetCollection<AWidget> aWidgets = new WidgetCollection<AWidget>();
a.new AWidget();
Set<AWidget> widgets = aWidgets.getAll();
}
}
class AWidget extends Widget {
String getName() {
return "AWidget";
}
}
It doesn't make sense to do what you're asking:
Why can't static methods be abstract in Java

Categories

Resources