I have a domain model A which I want to transform into another domain model B. So for each model element I need to convert it into one or a number of elements of B.
Domain A looks very simplified like:
public class Model
{
public List<ModelElement> elements;
}
public class ModelElement
{
public SubElement subElement;
}
public class SubElement
{
public String someData;
}
Domain B looks like
public class Layout
{
public List<Layer> layers;
}
public class Layer
{
public LayerData layerData;
}
public class LayerData
{
public int layerNumber;
public String name;
}
This is really simplified, my models are a bit more complex, but for explaining I think it is enough.
So my question is, what is a good approach for the converter.
I thought writing a single class, which traverses through the model and converts each element. By the end I have a huge converter class, which is not so nice.
My other approach was to build a factory, which gives for each element of Domain A a specific converter. Each converter can then call the factory to get the converter for sub elements. Unfortunately I need for some element conversions additional data. So to use it in some converters I must pass them through all the upper converters, which does not sound very nice as well.
What would be a good way to do it?
Thanks for help
Simon
If your data modle is hierarchical and finite I'd go with the first approach, but divide its responsibilities down to several classes. Have the main class publishing the data needed to convert. Then it calls a converter class for the root (Model/Layout) which converts and calls sub-converters (ModelElement/Layer level) and so on. The trick is to always pass a reference to the main class, which will work like an envelope or data store to the converters. By doing so, you'll get a nice, decoupled design with single responsiblites: providing data, converting a single class and so on.
This is only a sketch of the design I'd go. It's the best I can draw given the information. You may want to adapt it and maybe add some abstraction (e.g. interfaces with reduced data publishing for the envelope class).
You may want to look at DOZER. The lib will allow wildcard transformation of fields (if they share the same name) and also permit custom converter.
Related
We have 3 types of attributes in our project: CategoryAttribute, ProductAttribute and ProductTypeAttribute. These are outside of our control as they come from autogenerated classes and may contain attribute values of different types e.g. text, number or image. Now, each attribute has its own strategy to retrieve attributeValue. For simplicity, let's assume that all 3 of them have TextStrategy, NumberStrategy and ImageStrategy.
Example strategy:
#Component
public class CategoryImageAttributeStrategy implements CategoryAttributeStrategy {
#Override
public boolean isApplicable(CategoryAttribute attribute) {
return attribute.getImage() != null;
}
#Override
public Object getAttributeValue(CategoryAttribute attribute) {
//return attribute value here
//may be different or may be the same
//for ProductImageAttributeStrategy and ProductTypeImageAttributeStrategy
}
}
While getting image value may be different for all of them, getting text value is the same and we end up with 3 classes of almost the same code and I really really really don't like duplicating code.
I thought about creating an abstract class/default interface for each strategy type e.g. DefaultTextStrategy that all 3 text strategies would inherit from and either use default code provided higher or override it with own implementation, however I'm not really satisfied with this approach as it requires to create even more classes for such a simple task.
Maybe is it even possible to combine strategies of the same type (e.g. image) into one?
I would really like to hear what more experienced folks have to say in this matter as I would like to learn and improve.
Thanks in advance for your time.
There should be only 3 strategies. TextStrategy, NumberStrategy and ImageStrategy which extend the base strategy. Mixing attributes and strategy will make it confusing as both are actually independent and have many to many relationship with one another.
Let the 3 attributes extend a single Attribute class : CategoryAttribute, ProductAttribute and ProductTypeAttribute.
Let the strategies decide on what needs to be done based on the Attribute class object being passed to it. For Text strategy there would be single implementation. For Image strategy, you may require special handling for the one class.
Here's what I did:
First, I created an interface for all types of strategies named "AttributeValueStrategy". Then added 3 callbacks (type specific, e.g. NumberValueCallback etc.). Now, each strategy implements callback interface of its type and AttributeValueStrategy interface. Then there's DefaultStrategyMethods class that contains default "getAtrribute" for each type and the actual strategy call the defaultStrategyMethods (like below) or just implements its own code.
#Override
public Object getAttributeValue(Object attribute) {
return defaultStrategyMethods.getNumberValue(attribute, this);
}
Callbacks are created because only the actual strategy knows which class should it cast to (and has a method to do that), and DefaultStrategyMethods needs to use it so that's why I pass "this" as second argument (which is the callback itself).
No more duplicates, everything is clear and clean.
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);
I'm working on designing a validator for certain objects (fields of those objects). These objects are enclosed in one, bigger object - container.
Example: Car as a container . Consists of Wheels, Engine, Body.
Lets say i need to validate if wheels have correct diameter, engine has correct capacity, body has certain length etc.
Theoretically I think I should validate everything before construction of a container (car).
What is the best way to achieve this? Do I make an abstract validator class with validate() method and implement it in every enclosed class? What about the container, do I just not include it at all in the validation process? Thanks for help.
I'd suggest you not to put the validation logic inside the classes you're going to validate.
I find it better to keep those classes as mere value objects, and create a parallel hierarchy of validators, roughly one for each entity to be validated. Alternatively, you could also create a single validator that can validate all the entities: however, this solution is less scalable and could bring you to violate the open-closed principle when you have to add a new entity (e.g. you want to deal also with the rear-view mirrors of the car).
Assuming you choose the one entity : one validator approach, the validator of the container will first validate the components inside the container and then validate if they fit together.
Please consider also the possibility of using validator frameworks such as Apache Commons Validator, that can save you from writing boilerplate code. However, since I don't know what kind of complex validation you have to perform, I don't know if it fits your needs.
Furthermore, I don't think you should be worried of validating everything before it is constructed. Just construct it and validate afterwards: then, if it violates the validation rules, you can discard it (i.e. don't persist it anywhere).
piggy backing off of gd1 answer, I agree. One such way would be to have a ValidatorAdapter for each of your value objects. So it would look like this:
public class GreenCarValidator {
public GreenCarValidator(Car car) {
// save reference
}
#Override
public boolean isValid() {
return car.getColor().equals("green");
}
}
public class RedCarValidator {
public RedCarValidator(Car car) {
// save reference
}
#Override
public boolean isValid() {
// you could compose more validators here for each property in the car object as needed
return car.getColor().equals("red");
}
}
Now you can have many types of validators for a single type of object, dynamic and configurable at runtime. Should you put the "valid()" method inside the classes the classes as gd1 suggest you not do, you would lose this flexibility.
You could create a ValidatablePart interface with a validate method, have all parts implement this interface, and then have the container validate all inclosed parts as they are being added to the container or perhaps when calling the the container's build or whatever method that is supposed to construct it.
Your Container class could follow the Template Method Design 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.
I have a custom INIFile class that I've written that read/write INI files containing fields under a header. I have several classes that I want to serialize using this class, but I'm kind of confused as to the best way to go about doing it. I've considered two possible approaches.
Method 1: Define an Interface like ObjectPersistent enforcing two methods like so:
public interface ObjectPersistent
{
public void save(INIFile ini);
public void load(INIFile ini);
}
Each class would then be responsible for using the INIFile class to output all properties out to the file.
Method 2: Expose all properties of the classes needing serialization via getters/setters so that saving can be handling in one centralized place like so:
public void savePlayer(Player p)
{
INIFile i = new INIFile(p.getName() + ".ini");
i.put("general", "name", p.getName());
i.put("stats", "str", p.getSTR());
// and so on
}
The best part of method 1 is that not all properties need to be exposed, so encapsulation is held firm. What's bad about method 1 is that saving isn't technically something that the player would "do". It also ties me down to flat files via the ini object passed into the method, so switching to a relational database later on would be a huge pain.
The best part of method 2 is that all I/O is centralized into one location, and the actual saving process is completely hidden from you. It could be saving to a flat file or database. What's bad about method 2 is that I have to completely expose the classes internal members so that the centralized serializer can get all the data from the class.
I want to keep this as simple as possible. I prefer to do this manually without use of a framework. I'm also definitely not interested in using the built in serialization provided in Java. Is there something I'm missing here? Any suggestions on what pattern would be best suited for this, I would be grateful. Thanks.
Since you don't want (for some reason) to use Java serialization, you can use XML serialization. The simplest way is via XStream:
XStream is a simple library to serialize objects to XML and back again.
If you are really sure you don't want to use any serialization framework, you can of course use reflection. Important points there are:
getClass().getDeclaredFields() returns all fields of the class - both public and private
field.setAccessible(true) - makes a private (or protected) field accessible via reflection
Modifier.isTransient(field.getModifiers()) tells you whether the field has been marked with the transient keyword - i.e. not eligible for serialization.
nested object structures may be represented by a dot notation - team.coach.name, for example.
All serialization libraries are using reflection (or introspection) to achieve their goals.
I would choose Method 1.
It might not be the most object oriented way, but in my experience it is simpler, less error-prone and easier to maintain than Method 2.
If you are conserned about providing multiple implementations for your own serialization, you can use interfaces for save and load methods.
public interface ObjectSerializer
{
public void writeInt(String key, int value);
...
}
public interface ObjectPersistent
{
public void save(ObjectSerializer serializer);
public void load(ObjectDeserializer deserializer);
}
You can improve these ObjectSerializer/Deserializer interfaces to have enough methods and parameters to cover both flat file and database cases.
This is a job for the Visitor pattern.