1

Working on a customised JSON Converter to comply with company standard (basically adding many tags and handling for enum). The converter only works for objects with a public nullary constructor, so it had some problem with those objects enhanced by Spring and it has to workaround by something like this: ((Advised) advised).getTargetSource().getTargetClass();

The final product works pretty well, but having Spring library imported makes it a bit too large and we decided to have 2 different classes, one for projects which are using Spring and the other for those aren't.

Ideally, the 2 Converters should look something like this:

JsonConverter.java

public class JsonConverter {
    // public static toObject(){...}
    // public static toJSON(){...}
    // other methods
    protected static resolveTargetClass(Object obj){return obj.getClass();}
}

SpringJsonConverter.java

public class SpringJsonConverter extends JsonConverter {
    protected static resolveTargetClass(Object obj){
        if(obj instanceof Advised)
            ((Advised) obj).getTargetSource().getTargetClass();
        return obj.getClass();
    }
}

And just as everyone knows, this won't work as resolveTargetClass is static and not overridable. Is there any elegant way to do this? I would like to keep everything static as this converter had already been used by many projects and fixing it would cost so much time.

2

1 Answer 1

3

Seriously: don't use static here.

static leads to tight coupling between classes, and as you figured yourself: it "kills" polymorphism. In that sense: it is the opposite of good practices. Not always, but as soon as it hampers your ability to create a good design, static is obviously the wrong approach.

Thus: simply drop the static keyword from your current code. Yes, that will cost you now. But it enables you to do the right thing in the future.

Sign up to request clarification or add additional context in comments.

2 Comments

my company is advocating "WRITE EVERY TWICE" practice instead of working as DRY as possible, as copy-and-paste is really cheap at the beginning, even the maintenance afterwards would definitely be an ordeal :(
if only possible instead this static stuff also: for example declaring JsonConverter as an interface and implementing JsonConverterFactory that returns correct impl by checking this Object obj might be wiser considering the future

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.