Jackon JSON: Polymorphic deseralization when subclasses are unknown - jackson

I'm trying to do some polymorphic deseralization of JSON using Jackson, however the list of subclasses is unknown at compile time, so I can't use a #JsonSubtype annotation on the base class.
Instead I want to use a TypeIdResolver class to perform the conversion to and from a property value.
The list of possible subclasses I might encounter will be dynamic, but they are all registered at run time with a registry. So I would appear to need my TypeIdResolver object to have a reference to that registry class. It has to operate in what is essentially a dependency injection environment (i.e I can't have a singleton class that the TypeIdResolver consults), so I think I need to inject the registry class into the TypeIdResolver. The kind of code I think I want write is:
ObjectMapper mapper = new ObjectMapper();
mapper.something(new MyTypeIdResolver(subclassRegistry));
mapper.readValue(...)
However, I can't find a way of doing the bit in the middle. The only methods I can find use java annotations to specify what the TypeIdResolver is going to be.
This question Is there a way to specify #JsonTypeIdResolver on mapper config instead of annotation? is the same, though the motivation is different, and the answer is to use an annotation mixin, which won't work here.

SimpleModule has method registerSubtypes(), with which you can register subtypes. If only passing Classes, simple class name is used as type id, but you can also pass NamedType to define type id to use for sub-class.
So, if you do know full set, just build SimpleModule, register that to mapper.
Otherwise if this does not work you may need to resort to just sharing data via static singleton instance (if applicable), or even ThreadLocal.

Note that in the end what I did was abandon Jackson and write my own much simpler framework based on javax.json that just did the kinds of serialisation I wanted in a much more straightforward fashion. I was only dealing with simple DTO (data transfer object) classes, so it was just much simpler to write my own simple framework.

Related

Registering all classes that inherit from a particular abstract class in Kotlin

I have a singleton object called registry.
I also have an abstract base class, say Operation with an abstract field called name. I expect other people to subclass this abstract class and create classes denoting specific operations. I want to be able to store name -> Subclass mapping in my registry object.
Ideally, people who subclass this will not even know about this registration. But if that is unavoidable, I prefer them to write as little code as possible just next to their class declaration.
What is the best way of doing this?
The issue here is name being abstract.
If name were a constructor parameter, then you could simply put the code in the your abstract class's constructor. Every subclass, sub-subclass,… instance will call that constructor (directly or indirectly), so it would always get called. (That doesn't apply to a few special cases such as deserialisation and cloning, so you might have to handle those explicitly.)
However, your abstract class's constructor will get called before the sub(sub…)class constructor(s), and so the instance won't be fully initialised and its name property might not be available yet.
The options I see are:
Refactor your class so that the name is a constructor parameter (and can't be changed thereafter), and add your code to the constructor. (If that restriction is feasible, then this is the simplest solution, both for you and for implementers of subclasses, who won't need to do anything extra.)
Provide a method that subclasses can call once the name has been set up. (You'll have to make it clear in the documentation that subclasses must call that method; unfortunately, I don't know of any way to enforce it.)
It may be possible to use annotations and compiler plug-ins and/or runtime libraries, similar to frameworks such as Spring. But I don't know the details, and that's likely to take much more work; it may also need your implementers to add plug-ins and/or libraries to their project, so probably isn't worth it unless you're doing a lot of other frameworky stuff too.
In each case, you can get the name value and the concrete subclass (using this::class or this::class.java), and store them in your registry. (It doesn't look like you're asking about the internals of the registry; I assume you have that side of things covered.)

Why would I create an interface for each mapper class?

In cases of MVC applications where the model is split into separate domain and mapper layers, why would you give each of the mapper classes its own interface?
I have seen a few examples now, some from well respected developers such as the case with this blog, http://site.svn.dasprids.de/trunk/application/modules/blog/models/
I suspect that its because the developers are expecting the code to be re-used by others who may have their own back-ends. Is this the case? Or am I missing something?
Note that in the examples I have seen, developers are not necessarily creating interfaces for the domain objects.
Since interfaces are contracts between classes (I'm kinda assuming that you already know that). When a class expects you to pass an object with as specific interface, the goal is to inform you, that this class instance expect specific method to be executable on said object.
The only case that i can think of, when having a defined interface for data mappers make sense might be when using unit of work to manage the persistence. But even then it would make more sense to simply inject a factory, that can create data mappers.
TL;DR: someone's been overdoing.
P.S.: it is quite possible, that I am completely wrong about this one, since I'm a bit biased on the subject - my mappers contain only 3 (+constructor) public methods: fetch(), store() and remove() .. though names method names tend to change. I prefer to take the retrieval conditions from domain object, as described here.

How to extend/decorate third-party classes in VB.NET?

In Ruby all classes are forever open. New behavior can be added to any class at just about any time. Is there a way to do this in VB.NET?
For example, what if I want all DataRows in an existing app (a large one) to take on a new behavior. I realize I could create a custom row class that inherits from DataRow, but inheritance is not what I'm after. That would involved a lot of rework to make sure that at all places rows are instantiated, we are instantiating from our custom row class.
I had two rough ideas about how this might be done:
It occurred to me that aspects (AOP) could work here. Is there a way to layer behavior on top of existing methods?
Would it be possible to apply a given Interface to existing classes.
The primary goal here is to not have to do any large retrofit of existing code. The system should practically remain oblivious to these layered-on behaviors/aspects. It should involve a minimal change to the codebase.
Currently, we implement layered aspects using decorator classes. The problem is, the system knows the difference between a native row and a row decorator object. I want to be able to pass around something that the system thinks is a native row. Again, the system needn't be mindful of the decorations applied to the row. It should think it has a row, not some special decorator.
Specifically, I want to decorate the default set Item(colName) property of a row so that I can modify the incoming value.
Much of what you are asking for is possible with Extension Methods. See here for more info:
http://msdn.microsoft.com/en-us/library/bb384936.aspx
Here's an example from that link which adds a Print method to all String objects:
Module StringExtensions
<Extension()>
Public Sub Print(ByVal aString As String)
Console.WriteLine(aString)
End Sub
End Module
However, you can only use extension methods to add methods, not properties nor fields. Also, you can only add a new method or overload. You can't override an existing method with a new one.
Since what you are talking about, specifically, is the ability to override the indexer property on a class, extension methods won't help you in that case. The only other option that I'm aware of would be to trick your projects into using your wrapper class instead of the real one. You could create your own library that implements the same classes with the same names in the same namespace as whatever library you are trying to extend. Your wrapper library would reference the real one and would inherit all the classes from the original one. Then you could extend them all you want and your other projects could simply reference your library instead of the real one. To do this, you would of course need to use lots of namespace aliasing and quite possibly assembly reference aliasing (which is not available in VB.NET, so you might have to write the library in C#, which supports it with the extern keyword). But I suspect this may not be worth it for you.

OO principle: c#: design to interface and not concrete classes

I have some questions about the affects of using concrete classes and interfaces.
Say some chunk of code (call it chunkCode) uses concrete class A. Would I have to re-compile chunkCode if:
I add some new public methods to A? If so, isn't that a bit stange? After all I still provide the interface chunkCode relies on. (Or do I have to re-compile because chunkCode may never know otherwise that this is true and I haven't omitted some API)
I add some new private methods to A?
I add a new public field to A?
I add a new private field to A?
Factory Design Pattern:
The main code doesn't care what the concrete type of the object is. It relies only on the API. But what would you do if there are few methods which are relevant to only one concrete type? This type implements the interface but adds some more public methods? Would you use some if (A is type1) statements (or the like) the main code?
Thanks for any clarification
1) Compiling is not an activity in OO. It is a detail of specific OO implementations. If you want an answer for a specific implementation (e.g. Java), then you need to clarify.
In general, some would say that adding to an interface is not considered a breaking change, wheras others say you cannot change an interface once it is published, and you have to create a new interface.
Edit: You specified C#, so check out this question regarding breaking changes in .Net. I don't want to do that answer a disservice, so I won't try to replicate it here.
2) People often hack their designs to do this, but it is a sign that you have a poor design.
Good alternatives:
Create a method in your interface that allows you to invoke the custom behavior, but not be required to know what that behavior is.
Create an additional interface (and a new factory) that supports the new methods. The new interface does not have to inherit the old interface, but it can if it makes sense (if an is-a relationship can be expressed between the interfaces).
If your language supports it, use the Abstract Factory pattern, and take advantage of Covariant Return Types in the concrete factory. If you need a specific derived type, accept a concrete factory instead of an abstract one.
Bad alternatives (anti-patterns):
Adding a method to the interface that does nothing in other derived classed.
Throwing an exception in a method that doesn't make sense for your derived class.
Adding query methods to the interface that tell the user if they can call a certain method.
Unless the method name is generic enough that the user wouldn't expect it to do anything (e.g. DoExtraProcessing), then adding a method that is no-op in most derived classes breaks the contract defined by that interface.
E.g.: Someone invoking bird.Fly() would expect it to actually do something. We know that chickens can't fly. So either a Chicken isn't a Bird, or Birds don't Fly.
Adding query methods is a poor work-around for this. E.g. Adding a boolean CanFly() method or property in your interface. So is throwing an exception. Neither of them get around the fact that the type simply isn't substitutable. Check out the Liskov Substitution Principle (LSP).
For your first question the answer is NO for all your points. If it would be that way then backward compatibility would not make any sense. You have to recompile chunkCode only if you brake the API, that is remove some functionality that chunkCode is using, changing calling conventions, modifying number of parameters, these sort of things == breaking changes.
For the second I usually, but only if I really have to, use dynamic_cast in those situations.
Note my answer is valid in the context of C++;I just saw the question is language agnostic(kind of tired at this hour; I'll remove the answer if it offenses anybody).
Question 1: Depends on what language you are talking about. Its always safer to recompile both languages though. Mostly because chuckCode does not know what actually exists inside A. Recompiling refreshes its memory. But it should work in Java without recompiling.
Question 2: No. The entire point of writing a Factory is to get rid of if(A is type1). These if statements are terrible from maintenance perspective.
Factory is designed to build objects of similar type. If you are having a situation where you are using this statement then that object is either not a similar type to rest of the classes. If you are sure it is of similar type and have similar interfaces. I would write an extra function in all the concrete base classes and implement it only on this one.
Ideally All these concrete classes should have a common abstract base class or a Interface to define what the API is. Nothing other than what is designed in this Interface should be expected to be called anywhere in the code unless you are writing functions that takes this specific class.

How do you fight growing parameter list in class hierarchy?

I have a strong feeling that I do not know what pattern or particular language technique use in this situation.
So, the question itself is how to manage the growing parameter list in class hierarchy in language that has OOP support? I mean if for root class in the hierarchy you have, let's say 3 or 4 parameters, then in it's derived class you need to call base constructor and pass additional parameters for derived part of the object, and so forth... Parameter lists become enormous even if you have depth of inheritance more than two.
I`m pretty sure that many of SOwers faced this problem. And I am interested in ways how to solve it. Many thanks in advance.
Constructors with long parameter lists is an indication that your class is trying to do too much. One approach to resolving that problem is to break it apart, and use a "coordinator" class to manage the pieces. Subclasses that have constructor parameter lists that differ significantly from their superclass is another example of a class doing too much. If a subclass truly is-a superclass, then it shouldn't require significantly more data to do its job.
That said, there are occasional cases where a class needs to work on a large number of related objects. In this situation, I would create a new object to hold the related parameters.
Alternatives:
Use setter injection instead of constructor injection
Encapsulate the parameters in a separate container class, and pass that between constructors instead.
Don't use constructors to initialize the whole object at once. Only have it initialize those things which (1) are absolutely required for the existence of the object and (2) which must be done immediately at its creation. This will dramatically reduce the number of parameters you have to pass (likely to zero).
For a typical hierarchy like SalariedEmployee >> Employee >> Person you will have getters and setters to retrieve and change the various properties of the object.
Seeing the code would help me suggest a solution..
However long parameter lists are a code-smell, so I'd take a careful look at the design which requires this. The suggested refactorings to counter this are
Introduce Parameter Object
Preserve Whole Object
However if you find that you absolutely need this and a long inheritance chain, consider using a hash / property bag like object as the sole parameter
public MyClass(PropertyBag configSettings)
{
// each class extracts properties it needs and applies them
m_Setting1 = configSettings["Setting1"];
}
Possibilities:
Perhaps your class(es) are doing too much if they require so much state to be provided up-front? Aim to adhere to the Single Responsibility Principle.
Perhaps some of these parameters should logically exist in a value object of their own that is itself passed in as a parameter?
For classes whose construction really is complex, consider using the builder or factory pattern to instantiate these objects in a readable way - unlike method names, constructor parameters lack the ability to self document.
Another tip: Keep your class hierarchy shallow and prefer composition to inheritence. That way your constructor parameter list will remain short.