I have a class, that takes a lot of esoteric parameters to construct an object. I didn't write the code and frankly speaking, I don't understand completely, all of it's nuances. There is a valueOf(String) method of this class, that is primarily used to construct objects of this class and it also does fairly complex computation to construct the object.

I pass an array of objects of this class into a report generation package that calls the toString() method of each of these objects and constructs a header.

I need to override the toString() method to get rid of some extra stuff that it returns, so that my headers look clean.

What would be the best way to do this. I thought of subclassing this class, but even that is proving to be a bit painful, since I have to replicate valueOf() method for the subclass.


I need to override the toString() method to get rid of some extra stuff

This approach seems to be the main issue. When I read this sentence, it gave me an immediate warning sign, since you are trying to change the behaviour of a class in an incompatible fashion by using inheritance. This can easily become a violation of the LSP and can cause a lot of unforeseen issues.

Instead of (ab)using inheritance, a better way might be to create something like a proxy or wrapper object for each of the objects in the returned array, which can be done after the construction of the original objects, there is no need to tweak the construction code itself. The wrapper class implements toString in the desired fashion, using calls to toString of the wrapped object, if necessary. It can also implement any other method required by your report generator in a similar fashion. Then pass the resulting array of wrapped objects into the report generation package.

Note this solution is independent from the construction process, so it does not actually matter if there are mainly static methods involved or not.


You can't. The usage of static methods makes your code, well, static.

I would encourage you to create a builder for this class which calls protected but non-static methods. From there, you can easily extend that class and override the methods as you need to.

You don't have to eliminate the static methods outright if you think there are those who use them. Instead consider deprecating them and in your following release, you can remove them then.

Good luck to you!

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service, privacy policy and cookie policy

Not the answer you're looking for? Browse other questions tagged or ask your own question.