Is Composition pattern good choice in this scenario? - java

Here is one design dilemma I have...
In my program, I have different kind of entries - numeric, textual, date, image, etc.
My first idea was to have model structured with inheritance like this:
Entry
-- NumericEntry (extends Entry)
-- TextualEntry (extends Entry)
-- DateEntry (extends Entry)
-- ImageEntry (extends Entry)
Then I can have a list of Entry objects, and each object will know how to handle & expose its data through common members (i.e. showData(), makeSummary() etc.) If I want to add new Entry object, I will just add another class with that specific type.
But, java limitations, and also android orm libraries limitations makes this pretty complicated.
So, I have turned to composite pattern, but I am not sure if I am approaching it right.
So, now I have this (pseudocode):
class Entry
{
Type type;
(nullable)NumericEntry numericEntry;
(nullable)TextualEntry textualEntry;
(nullable)DateEntry dateEntry;
(nullable)ImageEntry imageEntry;
public showData()
{
swicth (type)
{
case numeric: ..
case textual: ..
case date: ..
case image: ..
}
}
}
But this seems to me too wired, doesn't it?
What would be right approach in the described scenario?

I think what you're trying to do is legit, but I think the composite pattern is a bit off here. The composite pattern is rather used for hierarchical structures, as far as I know (like directory structures).
Your model seems quite good, using an (abstract) base class, and let the other types extend from it, however I fail to understand why you want to have all the different types of entries in your base Entry class.
If I understand correctly what you want then this would be more logical.
Interface example:
public interface Entry{
// Define all your methods as abstract and define them here
void showData();
}
public class TextualEntry implements Entry{
void showData(){
// Your implementation for textual entries here
}
}
// Repeat this for the other types of entries
You could also consider an abstract class implementation, which can define properties/fields used in all the extended classes. Moreover, you can implement methods in the abstract class which have the same implementation for all extended classes.
Abstract class example:
abstract class Entry{
// Define your properties here that are used in all the other classes
// Define all your methods as abstract and define them here
public abstract void showData();
}
class TextualEntry extends Entry{
// Define new properties here
public override void showData(){
// Your implementation for textual entries here
}
}
// Repeat this for the other types of entries
On http://docs.oracle.com/javase/tutorial/java/IandI/abstract.html they discuss a similar problem.

If I understand your request correctly you can use Composite, but I did not get how you came to pseudo code.
Composite pattern compose objects into tree structures to represent part-whole hierarchies. Group of objects is to be treated in the same way as a single instance of an object.
Component interface defines common method/methods for leafs and composites.
Leaf implements Component interface, but catch is that you can have multiple leaf objects(numeric, text, ...).
Composite implements Component interface, but it is container for leaf objects as well.
So usage can be:
Component leaf1 = new Leaf(); //numeric entry
Component leaf2 = new Leaf(); // text entry
Composite composite = new Composite();
composite.add(leaf1);
composite.add(leaf2);
composite.operation(); // showData()

Related

Invoke Method of Subclass with Matching Regex

I am trying to call a method, convert(), based upon the return value matching the class' regex() method, both of which are defined in the below base class:
public abstract class BaseClass {
public abstract BaseClass convert(String value);
public abstract String regex();
}
I also have several subclasses that have implementations of those methods. I want to be able to do something like the below method (which will reside in BaseClass):
public static BaseClass parseNew (String value) {
// I use a switch statement to convey the idea of what I want to
// do, not for functionallity. Any non-constant cases raise
// compiler errors.
switch (value) {
case new Subclass1().regex():
return new Subclass1().convert(value);
case new Subclass1().regex():
return new Subclass1().convert(value);
// Repeat for all known and possibly unknown subclasses
}
}
I was thinking about using reflection, but I am very afluent in it. How would I get this functionality using reflection or some other concept?
The problem with this design is that it breaks abstraction (base aware of sub classes), making it a terrible idea.
A little about abstraction:
Abstraction is a process of hiding the implementation details from the user. Оnly the functionality will be provided to the user.
Instead you could make a different class which will contain this logic, and will act as a sort of factory.
Basically, you provide a base which exposes operations. This base is at the top of your inheritance tree. From it you provide implementations. The base in not aware of those implementations, they are not connected, they are specific. So the base class should know that sub exists, this just causes the code to be coupled and makes it non-modular and hard to maintain.
This mostly relates to creating a clean code.
So a quick look into factories... We want an object which will receive a value and parse it into an instance of BaseClass.
public class Parser {
private final Collection<BaseClass> implementations;
public Parser(Collection<BaseClass> implementations) {
this.implementations = implementations;
}
public BaseClass parseNew(String value) {
for (BaseClass implementation : implementations) {
if (implementation.regex().equals(value)) {
return implementation.convert(value);
}
}
throw new IllegalArgumentException("unsupported value");
}
}
The Parser class above is a factory which contains a collection of known BaseClass implementations. Using those, it may determine which implementation is wanted.
This is a pretty dynamic implementation. You would want to create an instance of this factory once, with the known implementations, and use it wherever.
General Design Note
There is also something weird about the the fact that BaseClass.convert returns BaseClass. I would expect it to return something else. BaseClass seems like a converter, and convert should return a value.
But that's just a general note.
Some reading resources:
https://www.geeksforgeeks.org/design-patterns-set-2-factory-method/
https://www.tutorialspoint.com/design_pattern/factory_pattern.htm
https://javatutorial.net/java-abstraction-example
http://www.javawithus.com/tutorial/relation-between-a-super-class-and-a-class

What's this java pattern called?

I'm wondering what the following pattern is called, if it has a name at all.
Purpose
Store data that is associated with an object (MyObject), but that is private to an implementation of an interface that deals with that object. Clients of the object have no business looking at this data.
Alternatives
Some alternatives are
a WeakHashMap<MyObject, FooApiMyObjectAttachment> maintained in the implementation of the interface,
using subclassing and factories everywhere the value is created, so that the extra data can be stored in the subclass or
using subclassing and accepting both MyObject and subclasses in the API.
Code example
public interface MyApi {
void doSomething(MyObject x);
}
public class MyObject {
public interface Attachment {} // empty interface, type bound only
private Attachment attachment;
public void setAttachment(Attachment attachment) {
this.attachment = attachment;
}
public <T extends Attachment> T getAttachment(Class<T> type) {
return type.cast(attachment);
}
}
class FooApiMyObjectAttachment implements MyObject.Attachment {
Foo foo; // some data that one MyApi implementer `foo' wants to persist between calls, but that is neither needed nor desired on MyObject
}
class BarApiMyObjectAttachment implements MyObject.Attachment {
Bar bar; // some data that another MyApi implementer `bar' wants to persist between calls, but that is neither needed nor desired on MyObject
}
class FooApi implements MyApi {
// associates FooApiMyObjectAttachment with any MyObjects passed to it or created by it
}
class BarApi implements MyApi {
// associates BarApiMyObjectAttachment with any MyObjects passed to it or created by it
}
Compared to subclassing, the advantage is that no factories are needed for MyObject, just so that implementers of MyApi can associate extra data with the objects.
Compared to a WeakHashMap in the implementers, a disadvantage is two methods on MyObject that aren't useful to clients, but an advantage is the simplicity.
A nice property of this pattern is that you can generalize it to store any number of attachments of different types with each node by changing the field to Map<Class<?>, Attachment> attachments, which cannot be done with subclassing at all.
I've seen the generalized form used successfully to annotate tree nodes in a tree rewriting system with various data used by various modules that processed the nodes. (c.f. pointers to parent nodes, origin information)
Question
Does this pattern have a name? If so, what is it? Any references?
It looks like a structural pattern, very close derivation from Whole-part, or composite.
Looking for a reference online, an overview of Whole-Part:
Sometimes called Composite
Helps with the aggregation of components (parts) that together form a semantic unit (whole).
Direct access to the Parts is not possible
Compose objects into tree structures to represent part-whole hierarchies.
Whole-Part lets clients treat individual objects and compositions of object uniformly
Composite Pattern
Really the difference between what you are doing and the composite is that you are storing non-composites, so you don't get the tree structure that composites would allow, but a UML would look similar just without the pigs ear.
Found it!
The form where multiple attachments are possible (Map<Class<?>, Attachment> attachments) is described by Erich Gamma as the Extension Objects Pattern.
The Gang of Four calls this a Memento.
The Role Object Pattern is really really similar, maybe even up to the point where I conclude that the answer to my own question is: It's the Role Object Pattern.

Unsure how approach design of application

I am trying to create an application in Java which allows for generation of large Provenance graphs from small seed graphs but I am having a little trouble figuring out the best way to design my classes.
To begin with, Provenance essentially has a graph structure, nodes and edges. I have created a Java library which acts as a mapping of the Provenance Data Model to Java Objects. This allows me to abstract my application specific information from Provenance model.
My class structure looks a little like this:
Graph (containing Sets of Node and Edge)
abstract Node (Just a String name for now)
Agent
Activity
Entity
Other subclasses of Node
abstract Edge
Generation
Association
Other subclasses of Edge
Now, what I would like to do is provide weighting on the nodes and edges which act as multipliers/saturation levels. There are a couple of ways I could use the library to achieve this aim but I'm not clear on what is the best from a development and maintainability perspective.
Firstly, I defined a Weighable interface with some simple methods such as get and set minimum and maximum weights.
Now, I could either extend each subclass Node e.g.
class WeighableAgent extends Agent implements Weighable
But then this requires an extended class for every type of node available, and required me to implement the Weighable interface at every level.
Alternatively, I could provide a mixin but it would still rely on me implementing the same functionality across each subclass.
Alternatively I could have a class that composes upon Agent, but that still requires me to implement Weighable across every composition class.
Alternatively, I could compose solely on the Node class e.g.
class WeighableNode implements Weighable {
private Node node;
public WeighableNode(Node node) {
this.node = node;
}
etc etc...
And this would allow me to only implement Weighable in one place. However, then I lose some important information about the concrete class type from anything using WeighableNode and the only way around this that I see is to provide a method:
Node getNode();
Which I'm concerned about due to the Law Of Demeter. Furthermore, this WeighableNode will be composed upon by a PresentationNode, to help with Swing which would mean I would end up chaining calls such as:
presentationNode.getWeighableNode().getNode() instanceof Agent
Which seems very unpleasant.
One final solution which I just thought of is to compose upon Node as above and then extend WeighableNode with WeighableAgent, etc etc. This means I do not need to reimplement Weighable each time and if I know I have
instanceof WeighableAgent
then the wrapped node is an Agent.
I appreciate this is quite long but I hope that an experienced developer will very quickly see the correct design practice.
Too bad Java has neither real mixins nor multiple inheritance…
Generic wrapper
I guess I'd use WeighableNode<NodeType extends Node> as a generic wrapper type. That way, all places which require nodes of a specific type could clearly state that fact. Its getNode method could return the correct class. And you wouldn't end up with too many classes all over the place.
Conversion idiom
Even if you don't use the above approach, the following idiom might be interesting:
class Node {
public T asNode(Class<T extends Node> clazz) {
return clazz.cast(this);
}
}
class NodeWrapper<N extends Node> {
private N realNode;
public T asNode(Class<T extends Node> clazz) {
try {
return super.asNode(clazz);
}
catch (ClassCastException e) {
return realNode.asNode(clazz);
}
}
}
You could change the above to return null instead of throwing an exception if you prefer. The idea is that the calling code doesn't have to worry about how to convert your node to various types. You'd e.g. simply write
presentationNode.getNode(Agent.class)
This separates implementation from interface, giving you much freedom to change things later on if the need arises. The basic Node implementation would know how to convert itself, taking care of derived classes. The NodeWrapper would add conversion using composition. You could use that as the base class for WeighableNode and your presentationNode.
Fat interface
You could implement the weighing stuff in Node itself, and use WeighedNode just as a tagging interface, or not at all. Not the nicest solution, but will help keep your number of classes down, and shouldn't do any real harm except for the bit of memory consumed by the extra data. The levels of indirection required by the other schemes will probably outweight that memory requirement by far.

Possible design pattern instead of instanceof?

I am writing an object conversion class, used to convert domain layer objects into UI objects and vice versa. The problem is that my UI objects are organized into a hierarchy and as a result my object conversion class contains "instanceof" statements. There is a definite code smell here but I'm not sure what the solution is.
So my UI hierarchy contains a RuleDTO as follows:
public class RuleDTO {
protected long ruleID;
protected long rowID;
protected AttributeDTO leftCondition;
protected AttributeDTO rightCondition;
protected OperationTypeDTO operationType;
protected boolean isActive;
// etc...
}
My RuleDTO can then be subclassed by AssignmentRuleDTO as follows:
public class AssignmentRuleDTO extends RuleDTO {
protected String assignedToTeam;
protected String assignmentOperator;
// etc...
}
RuleDTO can also be subclassed by EvaluationRuleDTO:
public class EvaluationRuleDTO extends RuleDTO {
protected String successAction;
protected String failureAction;
// etc...
}
The problem is reached then in my ObjectConversionHelper class which contains the following type of logic:
{
// Perform logic common to RuleDTO such as setting ruleID, isActive etc
if(ruleDTO instanceof AssignmentRuleDTO) {
// Set assignedToTeam and assignmentOperator etc
}
else if (ruleDTO instanceOf EvaluationRuleDTO) {
// Set successAction and failureAction etc
}
}
What would be a good solution here instead? I've read about the visitor pattern, but not sure how it applies here.
Thanks
Your RuleDTO class should have a method called setStuff() or something similar.
Then you override it in AssignmentRuleDTO and in EvaluationRuleDTO to set the relevant fields.
This way your ObjectConversionHelper can just call
ruleDTO.setStuff();
I think using a Visitor pattern would be a reasonable approach here. So you'd have the Visitor interface
interface RuleDTO {
void visit(RuleDTO theRule);
void visit(EvaluationRuleDTO theEval);
void visit(AssignmentRuleDTO theAssign);
... and so on ...
}
And you'd add a method to these concrete classes to handle the double dispatch
public void accept(RuleDTOVisitor theVisitor) {
theVisitor.visit(this);
}
Lastly, you'd create some class which implements the visitor, say SettingPropertiesVisitor, and for each method, you can do the implementation where the appropriate fields for each object are set accordingly to your application requirements.
So then to use it
aRuleDTO.accept(new SettingPropertiesVisitor());
This way the appropriate visitor method will get invoked for each type, and then within the methods for your SettingPropertiesVisitor, you can do the appropriate assignments. This will get around the instanceof checks, and decouples that setter logic from the objects.
Of course, that might be overkill if this is the only visitor you ever create, in that case, instanceof isn't like killing kittens. But the obvious drawback here is each time you extend the API, you need to modify the visitor interface, and then probably all the concrete visitors to support the new method.
Visitor looks like overkill here IMHO.
There is no iteration over a graph of objects.
There is no requirement for double dispatch.
Remember KISS and YAGNI.
Just add an abstract method or leave it as-is.
You can always refactor later - assuming you have tests in place ;)
In your case, the visitor pattern could be applied by writing a convertToOtherClass method in RuleDTO, which is then overridden by its subclasses. You would then have, in your object conversion class, a method along the lines of convertRuleDTO (called in RuleDTO's convertToOtherClass method), which executes the relevant code, secure in the knowledge that it is operating on an instance of RuleDTO which has not been subclasses, because otherwise the subclass would override the convertToOtherClass method.
Take out the "else"... what's the problem?
There are a couple of plausible approaches. The two I would consider are using either an interface which all of your classes implement or using an enum that corresponds to your different classes.
If you have an interface (let's call it public interface DTO, you can have a method signature in it called setFields() or something similar which each of the implementing classes must implement. Then, through the magic of polymorphism, you can now treat all of your objects as DTO using typecasting and call setFields() on them without worrying what the actual object is. The setFields() method in each of the individual classes will take care of it for you.
Alternatively, you can make an enum that is essentially an ID for each of your classes and make each class have a global variable of that type (complete with getters and setters) in order to identify it. This is a somewhat "hacky" workaround but still a doable one.
How about creating a single ObjectConversionHelper class for each DTO class? Each of them could implement a common conversion interface differently, call inherited members etc. You could then make use of some object creation factory that would create relevant Helper for DTO and vice-versa (i.e. using reflection mechanizms).

There must be a better way to code this :(

I was told "model an abstract container for database objects that constructs accepting a varargs of children and then exposes some children inspection functionality without code repetition".
This hints to things like "count # of children", "find by identifier", etc.
For simplicity's sake, the code below just has one field from the base abstract DatabaseObject type (i.e. name) but the real code has things like "identifier" and some complex metadata look-up gimmicks.
The idea of this is certainly useful but just looking at what I started to code makes me wanna puke: it's gonna be a Frankenstein of entanglement if I continue along this path. Any way to make this into decent Java? Any design pattern to reference? (Composite comes to mind...)
Premise: the actual functionality to be shared is useful and indeed applicable to any potential nestable types (Schemas have Tables, Tables have Columns, CompositeIndex(es) have sub-Indexes, etc.), especially the identifier look-ups...
... but "there must be a better way". I feel that voice inside me saying "whenever you write code like that, slap yourself in the face".
Help :)
public abstract class DatabaseContainerObject<ChildType extends DatabaseObject>
extends DatabaseObject {
protected List<ChildType> children;
public DatabaseContainerObject(String name, ChildType... children) {
super(name);
this.children = new ArrayList<ChildType>(children.length);
this.children.addAll(Arrays.asList(children));
}
protected List<ChildType> getChildren() {
return Collections.unmodifiableList(children);
}
... count ...
... find ...
... sort ...
... remove ...
...
}
Think about Strategy pattern(http://en.wikipedia.org/wiki/Strategy_pattern). Cause:
decouple data and data operation.
you can change algorithm("count # of children", "find by identifier") at run time.
I guess, it is something like this:
public abstract class DatabaseContainerObject<ChildType extends DatabaseObject>
extends DatabaseObject {
protected List<ChildType> children;
private DataOperator dataOperator;
public Object find(){
return dataOperator.find(children);
}
}
public interface DataOperator{
public <ChildType extends DatabaseObject> find(List<ChildType> childList);
}
public Class GeneralDataOperator extends DataOperator{
public <ChildType> find(List<ChildType> childList){
//implements find;
}
}
Then, you can use dependency injection.
Composite comes to mind very fast, but you should also investigate the Decorator Pattern.
Find clearly goes recursive, but Count e.g. is very limited on leaf objects and much the same on all kind of nodes.
Composite Pattern with suggestions (Skeletal Implementations) from Item 18: Prefer Interfaces to Abstract Classes from Effective Java 2nd Edition.
Define an iterface (EntityCollection) with methods count(), find(), sort(), remove() etc
Abstract Class DatabaseContainerObject implements EntityCollection interface
Schema, Table, CompositeIndex classes extending DatabaseContainerObject and implementing EntityCollection interface. Here Schema, Table, CompositeIndex are *Component*s in Composite Pattern
The advantage is future classes can either extend DatabaseContainerObject or implement EntityCollection

Categories