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);
Related
I am developing an app that compares files. I decided to use the Strategy design pattern, to handle different formats, so I have something like this:
public class Report {
CompareStrategy strategy;
...
}
public interface CompareStrategy {
int compare(InputStream A, InputStreamB);
}
Then, naturally I implement the compare method for different file formats.
Now suppose I wanted to add another method, that deals with certain restrictions for the comparison (e.g. omit a row in case of an Excel or csv file, or omit a node in XML).
Would it be better to:
Add another method to the interface and every implementation (there are few for the moment)
Write a new interface which inherits from CompareStrategy and then implement it?
The second question is: since the differences can be of various types - would it be OK to make a marker interface Difference to enable something like:
int compareWithDifferences(..., Iterable<Difference> differences);
and then go on defining what a difference means for the specific file format?
Now suppose I wanted to add another method, that deals with certain restrictions for the comparison (e.g. omit a row in case of an Excel or csv file, or omit a node in XML).
Looks like you need the Template Pattern
You can create some abstract class like
public abstract class XMLCompareStrategy implements CompareStrategy {
public int compare(InputStream A, InputStreamB) {
// several steps
customMethod(...);
// more steps
}
protected abstract ... customMethod(...);
}
This way you can create several classes that have the main or core functionality and provide custom details for every situation
The answer really depends on your needs:
If the method will always be implemented - add it to the existing interface. If it's only optional - create a new interface that will extend the current one, and then the implemented class could implement either the base interface or the child interface if it needs both methods.
For your second question - looks a bit like over-designing to me, but again depends on your needs.
I think you should maybe write another interface that inherit from the CompareStrategy. Like that if you need to compareWithDifferences() you can, but you don't have to use this interface you still can use the simpler one with no differences.
As Jonathan said, if you can foresee difficulties prepare for it. In that case I think you should prepare. Indeed that won't cost you much time to create another interface and you won't have to refactor later.
I have a common jar that uses some unmarshaling of a String object. The method should act differently depending on which application it is called from, how can I do that besides from the fact that I can identify the application by trying to load some unique class it has (don't like that). Is there some design pattern that solves this issue?
As I alluded to in my comment, the best thing to do is to break that uber-method up into different methods that encapsulate the specific behaviors, and likely also another method (used by all of the app-specific ones) that deals with the common behaviors.
The most important thing to remember is that behavior matters. If something is behaving differently in different scenarios, a calling application effectively cannot use that method because it doesn't have any control over what happens.
If you still really want to have a single method that all of your applications call that behaves differently in each one, you can do it, using a certain design pattern, in a way that makes sense and is maintainable. The pattern is called "Template Method".
The general idea of it is that the calling application passes in a chunk of logic that the called method wraps around and calls when it needs to. This is very similar to functional programming or programming using closures, where you are passing around chunks of logic as if it were data. While Java proper doesn't support closures, other JVM-based languages like Groovy, Scala, Clojure, JRuby, etc. do support closures.
This same general idea is very powerful in certain circumstances, and may apply in your case, but such a question requires very intimate knowledge of the application domain and architecture and there really isn't enough information in your posted question do dig too much deeper.
Actually, I think a good OO oriented solution is, in the common jar, to have one base class, and several derived classes. The base class would contain the common logic for the method being called, and each derived class would contain specific behavior.
So, in your jar, you might have the following:
public abstact class JarClass {
public method jarMethod() {
//common code here
}
}
public class JarClassVersion1 extends JarClass {
public method jarMethod() {
// initiailzation code specific to JarClassVerion1
super.jarMethod();
// wrapup code specific to JarClassVerion1
}
}
public class JarClassVersion2 extends JarClass {
public method jarMethod() {
// initiailzation code specific to JarClassVerion2
super.jarMethod();
// wrapup code specific to JarClassVerion2
}
}
As to how the caller works, if you are willing to design your code so that the knowledge of which derived class to use resides with the caller, then you obviously just have the caller create the appropriate derived class and call jarMethod.
However, I take it from your question, you want the knowledge of which class to use to reside in the jar. In that case, there are several solutions. But a fairly easy one is to define a factory method inside the jar which creates the appropriate derived class. So, inside the abstract JarClass, you might define the following method:
public static JarClass createJarClass(Class callerClass) {
if (callerClass.equals(CallerClassType1.class)) {
return new JarClassVersion1();
} else if (callerClass.equals(CallerClassType2.class)) {
return new JarClassVersion1();
// etc. for all derived classess
}
And then the caller would simply do the following:
JarClass.createJarClass(this.getClass()).jarMethod();
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.
I am implementing a sort of ORM in Java. I am trying to do a static find method that is only in the parent class. Let me get to the point:
public class DB {
public static Object find (int id) {
// i want to return anew instance of the calling subclass
}
}
public class Item extends DB {
// nothing here
}
public class Test {
public static void main () {
Item i = (Item) Item.find(2);
...
}
}
I don't know how to have the find method know which of its inherited class is calling it, so that i can return the right instance (and maybe call the right constructor, etc.) And the inherited class could be anything, no limit.
I've tried stacktrace, but it's only traced from Test to DB.
Any ideas?
Thank you everyone!
Static methods are not inherited, so you can't do this. A common approach to this problem (not including using one of tons of available ORM solutions) is to split your class hierarchy into two:
"Entity" (e.g. classes representing your actual data)
and "DAO" (Data Access Object) - classes that contain methods to manipulate data persistence.
A word to the wise: It's probably a bad idea to try and implement your own ORM. Projects like hibernate have covered this task in great detail, so if you roll your own you are likely to reinvent the wheel and possibly attempt to solve problems that have already been solved.
More on topic, ChssPly76 is correct in that you cannot accomplish this because of how static methods are handled in Java. When the VM loads the bytecode for the static method invocation, it will perform a lookup to find where the method actually is located. It won't find it on the Item class, so it will instead bind the call to DB.find.
However! It may be possible to achieve what you are trying to do with some bytecode wrangling. Viewing the bytecode (using javap -c) for the static method call in your example, we get the following:
invokestatic Method Item.find:(I)Ljava/lang/Object
Thus, once your call reaches DB.find, you could follow the stacktrace back to the callsite, and then inspect the bytecode at the callsite to retrive the actual target of the call. In theory, anyway, as I haven't seen this myself in practice. Also, beware of hacking bytecode like this, for here be dragons.
Kudos for identifying the active record pattern, and wanting to use it in Java. I do agree it's a design pattern that makes more sense than most DB access patterns found in Java, and it's one of the strengths of Ruby and PHP.
I think you may find the "Generic DAO" article at IBM developerworks useful.
Short: use Generics wisely.