What is the use of empty classes in #jsonview? - java

I am new to ajax and json. Recently when I tried to use ajax and json implementation in Spring mvc. I came across tutorials using annotation like
#JsonView(Views.Public.class)
And below is the view definition
public class Views {
public static class Public {}
public static class Internal extends Public {}
}
Q1. What is the importance using Views.Public.class in #JsonView as Public class has no definition?
Q2. Why #jsonview is designed in this way?
Q3. The view class does not have normal definition and also inner classes (Public and Internal) as well. What do you called such type of classes and when do you use usually? I have heard of marker interface in serialization but I have not heard like marker class.
I am asking these question because I have never learnt such coding methology in java. Is it a kind of design pattern?

#Angom The reason is a combination of things. To start, Java annotation values can have only a very limited set of types; simple primitives (int, boolean, long), Strings, Enum values, Annotation types or Classes.
So the choice of value type for logical Views is bit limited, when used with annotations. Many developers would choose Strings, but Classes actually have one nice benefit: composability. Since you can extend Classes and interfaces, you can have derived "child-views"; and checking for inclusion criteria (by Jackson) is very fast.
Now: if you only need view ids, then an empty interface or Class works just fine: you really just need the id, and possible inheritance hierarchy. There is no need to add methods or values.
It is, however, possible to use regular full classes as well, or add methods in these classes. View functionality makes no use of these; it does not care. So you could use existing classes/interfaces as View ids if you wanted to.
But since there isn't much cost to having empty classes, it is often cleaner to separate actual code and view classes.

Related

A design confusion about inheritance and interfaces

I'm stuck with a rather peculiar design problem. I'm using a Java ORM, and have defined one of my model classes as follows:
class User extends Model {
// . . .
}
Now, there are more models, and I'd like them all to support data validations. The idea is simple: As each setter method is called, an internal ArrayList of errors keeps getting populated.
Now, the mechanism of error handling is exactly the same for all the model classes. I can envision the following interface:
public interface ErrorReportable {
ArrayList<String> errors = new ArrayList<String>();
boolean hasErrors();
ArrayList<String> getErrors();
void resetErrors();
}
Now I have a problem: All the methods are abstract, which means I'll have to provide an implementation for all of them in my classes. This is sad, because all these methods are going to be implemented in exactly the same way. Ideally, this would've been another class I would've neatly inherited from, but sadly, there's no multiple inheritance in Java.
My next option is use default methods in interfaces, but here the problem is the errors field, which will become static whereas I need a regular field for each instance.
It looks like the only solution is composition, but then I'll have to have a hasErrors() method on User, which will go return this.error_obj.hasErrors(). This is fine, but not really neat in my opinion as I'm having to write things twice.
How can I do better?
I think it would be better for the model classes to only expose List<Error> validate() method, and to have a stand-alone validator that validates all the fields and collects the errors.
That way, the collected messages are not part of the model's state, you have explicit control over when will the validation happen, you're preferring composition (which is almost always a good thing), and the only method you need to implement in model class is the entity-specific validation.
If you ever need to add any cross-field validations, it will also be probably quite easy to extend this design to also perform those alongside with field validations.
If I get your need right, I would implement an own Model-class, that implements all neceaasary Interfaces and extends the Model-ancestor, but still is Abstract.
Then all your normal model-classes inherit from your abstract model-class to get the implementation for the interface and also the inheritance from the model-class (2nd Generation would that be). Any framework checking with 'instance of' will still check true for the later model-class.
The abstract class does not even have to have any abstract methods/members, but it should stay abstract to prevent direct instanciating from that class.
public abstract class myModel extends Model implements ErrorReportable{ ... }
public class User extends myModel { ... }

Subclasses in clojure

I'm learning Clojure and I was wondering how to deal with OO-like subclasses in Clojure. For example: a master abstract class, two abstract subclasses (each one redefines some functions) and in the 3rd level, final subclasses that creates "objects" that will be used in the functions. No clue how to do this. However, I managed to do it with one abstract class to a child class, with defprotocol and defrecord. But I can't implement a protocol inside another. Thanks
You don't need classes or subclasses. Represent your data as maps with attributes. The "subclasses" might have more attributes.
If you have a function that varies on attribute, then either use conditional logic based on attribute (if, cond, etc) or use polymorphism based on multimethods or protocols if you really need to.
In the words of the Matrix, there is no spoon.
You can do inheritance with protocols like this:
(extend <subtype>
<protocol>
(merge (get-in <protocol> [:impls <basetype>])
<map-of-redefined-methods>))
Multimethods provide direct support for inheritance with derive.
Actual Java subclass relationships can be specified with the :extends keyword to gen-class. This is meant exclusively for Java interop, though.
Generally, it is worth checking whether you really need inheritance. It is usually not the preferred method of modeling in Clojure.

Framework to populate common field in unrelated classes

I'm attempting to write a framework to handle an interface with an external library and its API. As part of that, I need to populate a header field that exists with the same name and type in each of many (70ish) possible message classes. Unfortunately, instead of having each message class derive from a common base class that would contain the header field, each one is entirely separate.
As as toy example:
public class A
{
public Header header;
public Integer aData;
}
public class B
{
public Header header;
public Long bData;
}
If they had designed them sanely where A and B derived from some base class containing the header, I could just do:
public boolean sendMessage(BaseType b)
{
b.header = populateHeader();
stuffNecessaryToSendMessage();
}
But as it stands, Object is the only common class. The various options I've thought of would be:
A separate method for each type. This would work, and be fast, but the code duplication would be depressingly wasteful.
I could subclass each of the types and have them implement a common Interface. While this would work, creating 70+ subclasses and then modifying the code to use them instead of the original messaging classes is a bridge too far.
Reflection. Workable, but I'd expect it to be too slow (performance is a concern here)
Given these, the separate method for each seems like my best bet, but I'd love to have a better option.
I'd suggest you the following. Create a set of interfaces you'd like to have. For example
public interface HeaderHolder {
public void setHeader(Header header);
public Header getHeader();
}
I'd like your classes to implement them, i.e you's like that your class B is defined as
class B implements HeaderHolder {...}
Unfortunately it is not. Now problem!
Create facade:
public class InterfaceWrapper {
public <T> T wrap(Object obj, Class<T> api) {...}
}
You can implement it at this phase using dynamic proxy. Yes, dynamic proxy uses reflection, but forget about this right now.
Once you are done you can use your InterfaceWrapper as following:
B b = new B();
new IntefaceWrapper().wrap(b, HeaderHolder.class).setHeader("my header");
As you can see now you can set headers to any class you want (if it has appropriate property). Once you are done you can check your performance. If and only if usage of reflection in dynamic proxy is a bottleneck change the implementation to code generation (e.g. based on custom annotation, package name etc). There are a lot of tools that can help you to do this or alternatively you can implement such logic yourself. The point is that you can always change implementation of IntefaceWrapper without changing other code.
But avoid premature optimization. Reflection works very efficiently these days. Sun/Oracle worked hard to achieve this. They for example create classes on the fly and cache them to make reflection faster. So probably taking in consideration the full flow the reflective call does not take too much time.
How about dynamically generating those 70+ subclasses in the build time of your project ? That way you won't need to maintain 70+ source files while keeping the benefits of the approach from your second bullet.
The only library I know of that can do this Dozer. It does use reflection, but the good news is that it'll be easier to test if it's slow than to write your own reflection code to discover that it's slow.
By default, dozer will call the same getter/setters on two objects even if they are completely different. You can configure it in much more complex ways though. For example, you can also tell it to access the fields directly. You can give it a custom converter to convert a Map to a List, things like that.
You can just take one populated instance, or perhaps even your own BaseType and say, dozer.map(baseType, SubType.class);

Create different Objects with same base type. Factory pattern?

I have to implement a multiple producers / multiple consumers example application for a university course and have a hard time to find a solution for the following problem, that doesn't make me feel, that I do something wrong ;)
I have to implement a Producer which produces a given kind of Component (CPUComponent, MainboardComponent. All subclasses of a common Component class). Each instance of a Producer will only produce a given amount of one type of component (e.g. only Mainboards) and then quits.
The Components are all more or less immutable objects (only final fields) and all logic is implemented in the common base class Component (simplified below)
public abstract class Component implements Serializable
{
private final long id;
public Component(int id) { ... }
public long getId()
{
return id;
}
}
The subclasses of Component are merely primitive, like
public class CPUComponent extends Component
{
public CPUComponent(long id) { ... }
}
With the language being Java, I cannot solve this object generation easily with Generics (as I would be able to in C#, because I cannot instantiate new objects of generic type parameters in Java). So I started to implement a Factory
public interface ComponentFactory {
Component createComponent(Producer producer, boolean defective);
}
And provide concrete factory implementations for each Component type.
The problem I have now is that, when I want to store the produced components in my Storage class (just manages all produced components for the consumers), I need to figure out the exact type of the objects (every CPUComponent, etc. in it's own shelf), but I only get a Component (base type) from the factory.
So the only thing that would help now, would be instanceof, but I think there has to be a better solution for my problem.
The other solution I can think of would be to implement a Producers for each type of Component, but I wanted to avoid that way.
Maybe I'm thinking way to complex and have already completely over-engineered the whole thing. Just point me in the right direction ;)
On the basis that OO is about telling objects to do things for you, I would call a method store() on each of your components (define this as abstract in your base class), passing in the Storage object. Your subclasses will implement this method in their own particular way, and mediate with the Storage object in order to store themselves. If you do this then your Storage class doesn't need to know about different components, and adding a new Component type only requires the definition of that class and no extra work elsewhere.
I note that in your question you give the impression that your subclasses have no further functionality beyond the base class (if I've read it correctly). It;'s precisely because of scenarios like this that the subclasses should have functionality specific to their type. You're absolutely right re. instanceof. If you have to use it then it's often a pointer that you're not using the full flexibility of OO and/or that your object analysis is not right.
1) Java does support generics. Are you saying that for some reason the generic support in Java is not sufficient in this case? From your description it looks like you could just parameterize the Producer class using a generic type.
2) From your description, it seems like Component could be an enum.
The factory design pattern is a way of leveraging polymorphism. Polymorphism means that your base class has a particular interface, i.e. it has a particular set of methods through which external objects will communicate. Derived classes may implement this interface in their own way.
The bottom line is that if your classes are designed properly, you should be able to do everything you need through the base class. The Storage class will store Components, and users of the Storage class will know nothing about the actual class of the Components; only that they can be used through the Component interface.
You can store your Component objects in separate lists like: motherboards = ArrayList<Component>
You are right in that you do need to implement a Factory pattern here.
public class ComponentFactory() {
public Component getComponent(Integer id, String componentType) {
if (componentType.equals("motherboard"))
return new MotherboardComponent(id);
else if(componentType.equals("cpu"))
return new CpuComponent(id);
else
return null;
}
}
You will need to implement concrete classes for all component sub-types, that all inherit from the Component base class, as you say.

Is Interface as labels a bad practice in java OO?

During the parsing of certain xml files, I come across a situation that I have to use interface as labels to identify that certain tags belong to certain category, for example, I created a Tag interface to identify that these classes are used to represent xml tags, and ContainableTag to point out that certain tags can be one of the children tags of some tags.
Then I stumble into this page: http://xahlee.org/java-a-day/interface.html (Please look for the "Interface as Labels" session.). It says:
The gist of the problem is that it is
a piece of mathematical irrelevance in
the language. As a labeling mechanism
in a language, for the possible
benefit from the software engineering
perspective, then it should not be
designed as part of the Class
Interface, since the concept of
labeling, and concept of programing
interface, are semantically disparate.
So is interface as labels necessarily a bad practice? As a java programmer, do we have some other alternatives?
Interfaces as markers have largely been replaces by the annotation mechanism in Java 5 or later. They allow you to add arbitrary meta-data. If your interfaces are empty and are only serving to act as class markers, then you should be using annotations instead.
While annotations may provide an alternative for what marker interfaces accomplish, they are only available in Java, and do not integrate well with IDEs: I also use marker interfaces to tag related concepts in my project, and I can then use the type hierarchy browser to find all members (I guess this will be eventually supported by major IDEs for annotations soon).
As for the article you mention, I do not see the point in arguing that if a class syntactically/structurally "fulfills" an interface, that interface may/should be applied automatically to the class ("Any class can declare it [RandomAccess] as a interface..."). That's backwards thinking, in my opinion.
I would argue that the places, where such a marker interface is used in an `instanceof' statement, use inverted logic, but as long as you are stuck within a language without multiple inheritance, aspects and annotations, I see no better way to accomplish this without stepping out of the base language.
Also note that this dead-beat argument about an empty interface always being applicable could also be applied to annotations.
Annotations are not necessarily what you want. Tagging interfaces are a way of working a property of a type into the type itself. For example, if you're about to start writing code looking like this:
#interface ContainableTag{}
#ContainableTag public class Foo {}
// ... elsewhere...
/**
* Adds obj as a child element.
* #throws IllegalArgumentException if obj is not tagged with
* the ContainableTag annotation.
*/
public void addElement(Object obj){
if (!obj.getClass().isAnnotationPresent(ContainableTag.class))
throw new IllegalArgumentException("obj is not a ContainableTag");
// add the containable tag as an element
}
Then consider if you really don't think this looks better:
interface ContainableTag {}
public class Foo implements ContainableTag {}
// ... elsewhere...
public void addElement(ContainableTag ct){
// add the containable tag as an element
}
Sure, the tagging interface does not provide any information about what behavior the type itself provides, but it does allow other types to enforce this non-behavioral property. I certainly would have been spared a lot of annoying bugs if ObjectOutputStream had a writeObject(Serializable) method rather than writeObject(Object).
Edit: I have not insignificant support here.

Categories

Resources