Object Conversion Pattern - java

I have several different classes coming from external sources (unmodifiable) that represent the same concept. For example Address. I have com.namespace1.Address (with fields houseNum, street, city), com.namespace2.Address (with fields h, s, c), namespace3.com.CoolAddress (with fields house_num, street, city).
The problem is that certain web services I use require certain Address object types so I am required to create a com.namespace1.Address given a namespace3.com.CoolAddress. The fields are easy enough to map but I'm looking for a pattern on how to do it.
From my point of view, an instance object AddressConverter doesn't make sense as there is no state (only behaviour) and when classes only have behaviour it boils down to static methods in a utility class. In the long term, anytime I need to map new objects to one another, I have one place to add/modify/remove methods. How it's done might change, but I know where the code sits (in once place) and can change the mapping when I need to.
Thoughts?

I think what you're looking for is a factory class. The factory pattern is used when you need to be able to instantiate one of several related classes, to be determined by the factory, not the developer.
See http://en.wikipedia.org/wiki/Factory_method_pattern
You're right to try to keep all this business logic in one place instead of doing ClassOne.toClassTwo(), ClassOne.toClassThree(),...
The most flexible way I can think of implementing this (but not the easiest by far) would be to have the factory start with a simple class with only basic common methods in it, and add handlers to a Hashtable or other container. That way you don't need concrete implementations of every possible combinations of features.
Of course it would be quicker to have a concrete implementation for each possible address variant, but there would be a fair amount of duplicated code, and it would be a little harder to add new address class types.

Since you can't modify the classes themselves, I'd suggest an implementation of the Adapter pattern for each direction. As you said, the adapter methods themselves can be static, but you can group both directions inside a single class so that the logic is all in one place.
At the end of the day you're going to be performing the same task no matter what you call it, or where you put the code. I'd suggest that both directions live in the same file, as they'll often both need updating when either direction changes.

If you are always converting to the same Class I would keep it simple and put all you conversion code in that Class and not worry about factories and the like, especially if you are only dealing with a couple of different classes. Why does there always have to be a complicated pattern for these things?!
public class A {
...
public static A convertB(B b) {
...
}
}

Are the classes you need to output final? If not, you could subclass them to create proper Adapters. Otherwise I'd go with dj_segfault's suggestion of a Factory with a table of handlers.
Or, wait -- is it just a web service you need to talk to? If so, there should be no reason your implementations of its datatypes can't be Adapters wrapping the input datatypes, or some intermediate object of your own.

Related

Tuple vs Class in Java

Are there any advantages of using Tuples instead of creating a new class in Java?
I've seen something like this a few times
return Pair.of (username, password);. And I've always wondered what kind of advantages it has in relation to something like this return new Credentials (username, password).
Java doesn't have a (first class) notion of tuples. Some projects and libraries introduce types like Pair or Tuple2/Tuple3/Tuple4/... to make up for it, but this is often considered poor style in Java.
By contrast returning a clearly-defined type like Credentials that provides not just structure but also type safety and meaningful getters for your data you make your code clearer, safer, and easier to work with. The Auto/Value project in particular makes it quick and painless to create value-types, making tuple-esque types all but unnecessary.
A Pair (Apache) is immutable, for one. You cannot change it’s values after creation. Many people do in fact choose to create their own class and add methods as necessary.
In general it’s considered better practise to make your own class. You can validate parameters and so on and have the ability to add additional functionality if the need arises.
As dimo414 says, the Pair class is often encountered in 3rd party libs; it has two advantages:
it makes defining a separate class for each key/value pairing unnecessary; so you don't need to define a Credential class. Of course, this should only be used to temporarily store data, not to be used within your implementation model.
Even if you do have a Credential class already, usually Pair is immutable, while the Credential class may not be. That means that it may provide setUsername() and setPassword() methods which you don't always want; using a Pair class makes sure both key and value remain unchanged.

Choice of design pattern - serial execution

I have a simple design problem - I am looking for the best pattern to implement a simple functionality. Let's say, I am going to create an xml message in java. This message consists of many fields in different logic groups.
So, the first idea - create a class to set all fields. I can do it one method (which will be really long...) or split the method into multiple smaller (for each of the logical groups). However, I don't think it is a good approach, because the class will be really long and difficult to mantain.
The second idea is to create a functional interface and some implementations for different groups, for instance GroupXxxSetter, GroupYyySetter, etc. I can create and keep all instances in a list or a set and call the method defined inside the interface for each object stored inside the collection. It seems to be very similar to the 'Chain of responsibility' pattern. However, the idea of this pattern is different, so I am not sure if it is a good idea to use this pattern in my case.
Should I use the 'chain of responsibility' pattern here? Or, maybe there is something better?
Thanks in advance.
Should I use the 'chain of responsibility' pattern here?
Clearly, no. You don't have the notion of candidate responsible to respond to a request. All elements will do a processing.
Or, maybe there is something better?
You have multiple possibilities.
Your context is not totally set. So it is hard to propose one rather than another.
I may propose you a implementation with the Builder pattern (Java Effective reference and not GOF).
For each logic group, you could have a specific class.
You would also have a composite class that is composed of logic group instances.
Instead of providing a public constructor or setters that prevent immutability and that can make rules validation cumbersome, you could use the Builder pattern for each one logic group class and in the composite class, you could use the same kind of Builder pattern where you will build the final message from the previously created logic group instances.
You could so create the instances in this way :
OneLogicGroup oneLogicGroup = OneLogicGroup.builder().fieldXXX(...).fieldYYY(...).build();
AnotherLogicGroup anotherLogicGroup = AnotherLogicGroup .builder().fieldXXX(...).fieldYYY(...).build();
MyMessage myMessage = MyMessage.builder().oneLogicGroup(oneLogicGroup).anotherLogicGroup(anotherLogicGroup).build().
I can create and keep all instances in a list or a set and call the
method defined inside the interface for each object stored inside the
collection.
It seems referring to a structural concern.
It is not directly related to the creation of the object. It is much related to how to share the created objects.
The flyweight pattern addresses this need and may be used conjointly with the presented builder Pattern.

Is it possible to have a POJO as ESuperType in EMF?

Question/Problem
Given a plain Java class coming from a non-EMF-aware API such as
public class BankAccount {
String ownerName;
int accountNumber;
// ...
}
and also let's assume that I am not allowed to change or recompile this class (because it is from an API).
Is there any simple way to use this class as an ESuperType for an EClass in EMF? (And, of course, the single class is just an example. I'd need to wrap an API consisting of 30-50 classes ...).
Own thoughts
Personally, I think it is not possible out of the box.
I could only think of two ways, both with quite some effort and not easy to realize.
Create an Ecore model which reflects the original class (EBankAccount, having ownerName and accountNumber as EAttributes) and a utility method/mechanism that wraps the original object by copying its fields into the corresponding EStructuralFeatures and adds EAdapters which are responsible to synchonize both objects.
Hook into EMF.CodeGen and do some magic there which makes it possible to have the original class as super class in the generated code which at the same time still fulfilling the EMF contract (= implement the EObject interface etc.).
But maybe there's some hidden feature of EMF (or an existing extension) which does something along these lines, and I am not aware of it?
It's not clear to me what you real want, but I will try to describe the several options.
If you want just to extend the POJO (which is what the question text suggests), the answer is YES, you can simply add a new EClass to your model and refer to the POJO qualified name in the "Instance Type Name" attribute. Then you can create other classes that extend from this one, but its state won't be managed by EMF.
But if you want EMF to track that POJO state as if it was a real EMF object (so those properties are also EStructuralFeature), then I don't see another solution, you really need to model it completely in EMF.
In this second case, both options you described seem possible.
The first option you described (and I assume you mean you want to synchronize the 2 objects, and not the 2 classes) seems the easiest one, and I don't think it would take so much effort if you use some generic method via reflection.
This might be a good solution if you get the objects in very concrete locations, so you only need to wrap and unwrap in specific places. Otherwise you will need to convert be converting (wraping/unwrapping) the object all the time.
It may be also possible but it requires more effort for sure, since it's not easy to extend the Java JET templates
I'm not aware of any extension for this.

Passing many variables to a class (swing components) [duplicate]

I have just started to learn Java and is curious is it any good practice in Java for good object decomposition? Let me describe a problem. In big software project it's always a big classes like 'core' or 'ui' that tends to have a lot of methods and are intended as a mediators between smaller classes. For example, if user clicks a button on some window, this window's class sends a message to 'ui' class. This 'ui' class catches this message and acts accordingly by doing something with application user interface ( via calling method of one of it's member objects ) or by posting message to application 'core' if it's something like 'exit application' or 'start network connection'.
Such objects is very hard to break apart since they are a mere mediators between a lots of small application objects. But having a classes in application with hundreds and thousands of methods is not very handy, event if such methods are trivial task delegation from one object to another. C# solves such problem by allowing to break class implementation into multiple source files: you can divide god object any way you choose, and it will work.
Any practices by dividing such objects in Java?
One way to begin breaking such a large object apart is to first find a good subset of fields or properties managed by the large object that are related to each other and that don't interact with other fields or properties of the object. Then, create a new, smaller object using only those fields. That is, move all logic from the large class to the new smaller class. In the original large class, create a delegation method that simply passes the request along. This is a good first step that only involves changing the big object. It doesn't reduce the number of methods, but it can greatly reduce the amount of logic needed in the large class.
After a few rounds of doing this, you can begin to remove some of the delegation by pointing other objects directly at the newer, smaller objects, rather than going through the previously-huge object that was in the middle of everything.
See Wikipedia's Delegation pattern discussion for example.
As a simple example, if you have a personnel object to represent staff at a company, then you could create a payroll object to keep track of payroll-related values, a ratings object to keep track of employee ratings, an awards object to keep track of awards that the person has won, and so on.
To wit, if you started out with one big class containing the following methods, each containing business logic, among many other methods:
...
public boolean isManagement() { ... }
public boolean isExecutive() { ... }
public int getYearsOfService() { ... }
public Date getHireDate() { ... }
public int getDepartment() { ... }
public BigDecimal getBasePay() { ... }
public BigDecimal getStockShares() { ... }
public boolean hasStockSharePlan() { ... }
...
then this big object could, in its constructor, create a newly created object StaffType and a newly created object PayInformation and a newly created object StaffInformation, and initially these methods in the big object would look like:
// Newly added variables, initialized in the constructor (or as appropriate)
private final StaffType staffType;
private final StaffInformation staffInformation;
private final PayInformation payInformation;
...
public boolean isManagement() { return staffType.isManagement(); }
public boolean isExecutive() { return staffType.isExecutive(); }
public int getYearsOfService() { return staffInformation.getYearsOfService(); }
public Date getHireDate() { return staffInformation.getHireDate(); }
public int getDepartment() { return staffInformation.getDepartment(); }
public BigDecimal getBasePay() { return payInformation.getBasePay(); }
public BigDecimal getStockShares() { return payInformation.getStockShares(); }
public boolean hasStockSharePlan() { return payInformation.hasStockSharePlan(); }
...
where the full logic that used to be in the big object has been moved to these three new smaller objects. With this change, you can break the big object into smaller parts without having to touch anything that makes use of the big object. However, as you do this over time, you'll find that some clients of the big object may only need access to one of the divisible components. For these clients, instead of them using the big object and delegating to the specific object, they can make direct use of the small object. But even if this refactoring never occurs, you've improved things by separating the business logic of unrelated items into different classes.
The next logical step may be to change the BigClass into a java package. Next create new objects for each group of related functionality (noting in each class that the object is part of the new package).
The benefits of doing this are dependency reduction and performance.
No need to import the entire
package/BigClass just to get a few
methods.
Code changes to related
functionality don't require a
recompile/redeploy of the entire
package/BigClass.
Less memory used
for allocating/deallocating objects,
since you are using smaller classes.
I've seen some cases where this is solved by inheritance: let's say class Big takes care of 5 different things, and (for various reasons) they all have to be in the same class. So you pick an arbitrary inheritance order, and define:
BigPart1 // all methods dealing with topic #1
BigPart2 extends BigPart1 // all methods dealing with topic #2
...
Big extends BigPart4 // all methods dealing with the last topic.
If you can really layer things up, so that the breakage makes sense (Part2 actually uses stuff from Part1, but not vice versa, etc.) then maybe it makes some sense.
The place where I've seen this is in WebWorks, where a single class had tons of getter/setter methods -- the setters used for dependency injection (e.g., URL args passed to the object upon execution) and the getters for making values accessible to various page templates (I think it was JSPs).
So, the breakdown grouped stuff logically, e.g., assuming the class was called MyAction, there was MyActionBasicArgs (fields and setters for basic CGI arguments), extended by MyActionAdvancedArgs (advanced-option args), extended by MyActionExposedValues (getters), extended by MyActionDependencies (setters used by Spring dependency injection, non-CGI args), extended by MyAction (which contained the actual execute() method).
Because of the way dependency injection in WebWorks works (or at least, used to work, back then), it had to be one huge class, so breaking it down this way made things more maintainable. But first, please, please, see if you can simply avoid having a single huge class; think carefully about your design.
Yes, C# provides partial classes. I assume this is what you are referring to when you say:
C# solves such problem by allowing to break class implementation into multiple source
files: you can divide god object any way you choose, and it will work.
This does help make huge classes more manageable. However, I find partial classes best used when one needs to extend code created by a code generator. When a class is as large as you're talking about, it can almost always be divided into smaller classes by proper object oriented design. Using a partial class sidesteps the more correct object oriented design, which is sometimes OK as the end goal is stable, reliable, maintainable code, and not a textbook example of OO code. However, many times, putting the code of a large object into a large number of smaller partial class instances of the same class is not the ideal solution.
If you can possibly find subsets of the properties of the "god" object that do not interact with one another, then each one of those sets would logically make a good candidate for a new object type. However, if all properties of this "god" object depend on one another, then there is not much you can do to decompose the object.
I don't know why you would ever have such a large class.
I suppose if you were using a gui builder code generation and being lazy about it, you might end up in such a situation, but codegen usually ends up nasty unless you take control yourself.
Splitting a single class arbitrarily is a terrible solution to a terrible manufactured problem. (Code reuse, for one thing will become virtually impossible)
If you have to use a GUI builder, have it build smaller components, then use the small components to build up a bigger GUI. Each component should do exactly one job and do it well.
Try not to EVER edit generated code if you can avoid it. Putting business logic into a genned "frame" is just a horrid design pattern. Most code generators aren't very helpful with this, so try to just make a single, minimal edit to get at what you need from external classes (think MVC where the genned code is your View and the code you edit should be in your Model and Controller).
Sometimes you can just expose the getComponents method from the Frame object, get all the components out by iterating through the containers and then dynamically bind them to data and code (often binding to the name property works well), I've been able to safely use form editors this way, and all the binding code tends to be very easily abstracted and reused.
If you're not talking about generated code--Well in your "God" class, does it do exactly one small job and do it well? If not, pull out a "Job", put it in it's own class, and delegate to it.
Is your GOD class fully factored? When I've seen huge classes like this, I've usually seen a lot of copy/paste/edit lines. If there is enough of a similarity to copy and past and edit some section, then there is enough to factor these lines into a single chunk of code.
If your big class is a GUI class, consider decorators--reusable and moves stuff out of your main class. A double win.
I guess the answer to your question is that in Java we just use good OO to ensure that the problem doesn't arise in the first place (or we don't--Java's certainly not immune to the problems you are talking about any more than any other language)

In a Java interface, how can I *not* use one particular method inherited from a parent interface?

I have a hierarchy of three interfaces, grandparent, parent and child. Parent and child have a method "add", which requires different input parameters in the child. While it's no problem to add the required signature in the child, the inherited method will be pointless, so is there a way to not have it in there at all? The other methods work fine.
Maybe, to achieve what I want, I can improve the design altogether, so I'll shortly outline what the interfaces are about:
I collect meter readings that consist of a time and a value. The grandparent interface is for a single reading. I also have classes that represent a number of consecutive readings (a series), and one that contains multiple series running over the same period of time (let's just call that a table).
The table can be viewed as a series (which aggregates the values orthogonally to the time axis), and both table and series can be viewed as a single reading (the implementations providing different means of aggregation), hence the inheritance. This seems to work out fine, but for the add method. (I can add a single point to the series, but for the table I need an additional parameter to tell me to which series it belongs.)
No, you cannot avoid inheriting a method, since doing so would violate the Liskov substitution principle.
In practice, you could have implementations throw an UnsupportedOperationException, but that would be pretty nasty.
Can't you implement the inherited method with some sort of default value for the series?
Maybe it would make sense to break the interface inheritance all together. Just have specific interfaces for specific types of behaviors. Whatever classes you have that implement these interfaces can just pick the ones that make sense, and won't have to worry about implementing methods that don't make sense.
The problem with inheritance is that the focus on the language mechanism makes people think about implementation rather than semantics.
When B inherits from A, it means that every instance of B is also an instance of A. In OOP, being an instance of something means typically that you should have a sensible response to its methods and at least support their messages.
If you feel that B should not support one of the messages of A, then as far as I am concerned you have two options:
BAD - Throw an "Unimplemented" exception as you would get with the collections framework. However, this is in my opinion poor form.
Good - Accept that B is not a type of A and avoid the inheritance, or restructure it (e.g., using composition and/or interfaces) so that you don't have to rewrite the code but you do not use a subtyping relation. If your application will live over time, you don't want to have semantic issues in your hierarchies.
Thanks for putting me on the right track, I upvoted the posts I found most helpful. Since my solution was inspired by the posts, but is not posted, I'll share what I decided to do:
As the hierarchy was inspired by how the data should be viewed, while the problems arise on the semantics of how you add data, I'm going to split up the interfaces for series and table into a read and a write interface each. The write interfaces have nothing to do with each other, and the read interfaces can inherit without conflicts.
I'll make this wiki, in case someone wants to expand on this.
You might want to look at the Refused Bequest code smell.
An interface is a contract. It means that anything that implements that interface will necessarily implement the methods defined. You could technically just implement it as a dummy method (no body, simply return, whatever) but to my knowledge, it must be implemented.
You can always implement the method as empty, for example:
class A implements B{ void add(A) { /*Goes Nowhere Does Nothing*/ return;} }
but really, it's not a good idea. A better solution would be for all of your grandparents, parents, and children all be the same class with two extra methods- hasParent():boolean and hasChild():boolean. This has the benefit of being a liskov substition compatible change as well as a cleaner design.

Categories