Is decorator pattern suitable here - java

So I have a couple of classes, A, B, C, ... N. And a couple of possible properties, setP(), setQ(), setR(), ... setZ(). Now, each class can have a different combination of properties:
A B C N
- setX - setR - setP - setY
- setY - setZ - setQ - setZ
- setZ - setR
- setS
- setZ
all of the setters return an instance of the object itself so that chaining is possible.
im trying to find an elegant way to solve this problem. i dont want to redefine the tens of properties in each class (code duplication) and i dont wanna use inheritance since the there will be ugly, pointless intermediate classes (BaseABCD -> setZ) and cuz the base class setter will return an instance of type BaseABCD which will not allow full chaining of all properties.
here are some possible things im trying to look into:
somehow define each property as a decorator in an elegant fashion, and compose A something like Base.decorators().addX().addY().addZ().finalize().
define all possible properties in Base and hide non-required properties in derived classes. I dont think this is possible.
Is any of these things possible? or is there a better idea to solve a problem like this one?
More details
The classes are basically different message types used by the application to communicate with an external system. Different messages contain different fields of different types. For instance:
ECHO message:
- Timestamp (DateTime)
- SourceAddress (String)
CHECK RESOURCE message:
- Timestamp (DateTime)
- Resource Identifier (Integer)
MANIPULATE RESOURCE
- Resource Identifier (Integer)
- Operation Type (Enum)
The messages are serialized as a string when transmitted and type information is not retained. So I chose to go with a HashMap<String, String>. Each property corresponds to a key within that class's hashmap. When serializing, I just iterate over all key/value entries in that class's hashmap and produce a string message representation to be sent.
However, I want to enforce types towards the caller code. So I dont want to expose a method like A.set('RESOURCEIDENTIFIER', '123456'). Instead I want to expose methods like A.setResourceIdentifier(123456) and C.setOperation(OperationType.DELETE).
Internally, these setter functions are simply putting a relevant key in the hashmap and assigning a string value to it.
public A setOperation(OperationType operation) {
this.hashmap.put('OPERATION', operation.name());
return this;
}
There are about 40 unique field types and all messages employ a unique subset of these fields. Like A and B contain setTimestamp(). B and C contain setResourceIdentifier(). Only C contains setOperationType(). And so on.
I don't want to redefine these tens of properties in each class over and over again. That's why I want to explore the following two options:
Option 1
Define a Base class with ALL possible properties and in derived A class, override only the required properties to be public. This is do-able. But I want to see if it is possible to implement something like described in option #2.
Option 2
Somehow define decorators and a factory class such that
public ? getA() {
return Base.startDecorating()
.addTimestamp()
.addResourceIdentifier()
.finalize();
}
? objA = Factory.getA()
.setTimestamp(DateTime.now())
.setResourceIdentifier(123456);
Can this be possible? While writing out this question, I realized that Option 1 should be the way to go. It's simple and less error prone. But just out of curiosity I want to know if decorator pattern can be used here. After all, what I have here is a complete set of independent modules (properties) and different ways of assembling them together (the classes).

A decorator is made for something that you can keep adding to. Like a xmas tree. But once the xmas tree is decorated, then you use common methods like turnOn(). Its not made for adding new methods to an existing API. I think you can use regular old inheritance for this. I would also use examples like List. Your Base class can provide the common methods that all will share, and then each other sub-class will add new methods.
To help keep things clean you can add a Factory or a Builder to make things easier.
Here are some examples. Assuming base class is called Base, and sub-classes are one letter named classes, A, B, etc.
Factory example 1.
Base x = factory.getInstance(A.class);
Factory example 2.
Map props = ...;
Base x = factory.getInstance(A.class, props);
Builder example 1.
Base x = new ABuilder().setX(x).setY(y).setZ(z).create();
This involves creating a builder class for each individual sub-class. The sub-class builder classes may or may not inherit from an abstract BaseBuilder class that defines a method with signature public Base create();.

If the setters of the properties have some logic in them which is shared across multiple main classes, a decorator pattern can fit and be a good design approach. If not, e.g. you are sure that all they will ever do is this.x=x or that each class sets a property of some type diffrently then no.
You can define a class for each of the properties, and have your main classes have variables of types of the properties classes. this way when a property is being set on the main class it delegates the job to the setter of the appropriate property class, This way you define the setters of your properties once and use them everywhere. Again, in case you have more logic then this.x=x; in your setters this may be the best idea.
Oh and you can still return this for chainning after delegating the set job to the property class.
Also, if you are lazy and care less for real time performance, you can use reflections to ease the coding of your main classes.

From the names of the properties i would guess you are trying to define different coordinate representations? Why not use one base class with all properties?
Those are actually not that much properties and you can't combine them in random permutations. So why make every thing more complex then necessary?
I don't think Decorator would be a good fit here: the sense of a decorator is to stay transparent. If you define your properties like that, you would have to check (on type or existance of the property) for each and every access.

Related

Hamcrest - Elegant way to test complex object with samepropertyvaluesas

I have quite complex object structure (with bunch of primitive fields and object references) and want to test all fields except -a few- of them. As an example;
ComplexObject actual = generateMagically("someInput");
ComplexObject expected = ActualFunction.instance.workMagically(actual);
// we want to be sure that workMagically() would create a new ComplexObject
// with some fields are different than "actual" object.
// assertThat(actual, samePropertyValuesAs(expected)); would check all fields.
// what I want is actually; - notice that "fieldName1" and "fieldName2" are
// primitives belong to ComplexObject
assertThat(actual, samePropertyValuesExceptAs(expected, "fieldName1", "fieldName2"))
Since I don't want to check all fields manually, I believe there must be a way to write that test elegantly. Any ideas?
Cheers.
You should have a look at shazamcrest, a great Hamcrest extension that offers what you need.
assertThat(expected, sameBeanAs(expectedPerson).ignoring("fieldName1").ignoring("fieldName2"));
See https://github.com/shazam/shazamcrest#ignoring-fields
Just pass the list of properties to ignore as 2nd parameter to samePropertyValuesAs.
Hamcrest matcher API
public static <B> Matcher<B> samePropertyValuesAs(B expectedBean, String... ignoredProperties)
e.g.
samePropertyValuesAs(salesRecord,"id")
In general I see two solutions if ComplexObject can be modified by yourself.
You could introduce an interface that represents the properties of ComplexObject that are being changed by ActualFunction. Then you can test that all properties of that new interface have changed. This would require that ComplexObject implements that new interface.
Another approach would be to replace the properties of ComplextObject that are changed by ActualFunction with a new property of a new type that contains all those properties. A better design would then be to let ActualFunction return an instance of the new type.
Last time I had a similar requirements I came to the conclusion that manually writing both code and tests to assert that some values are updated is inherently fagile and error-prone.
I externalized the fields in a bag object and generated the Java source files for both the bag class itself and the copier at compile time. This way you can test actual code (the generator) and have the actual definition of the domain in exactly one place, so the copy code can't be out-of-date.
The language to describe the property can be anything you are comfortable with, from JSON-schema to XML to Java itself (Java example follows - custom annotations are to be consumed from the generator)
public class MyBag {
#Prop public int oh;
#Prop public String yeah;
}

Java - Using Annotations/Tags to find which object to make

So let's say you have a class called Human, and a bunch of other classes that all extend Human (John, Sally, Mark). Human has an annotation "#Tags({"human"})", John has annotation "#Tags({"john"})", etc.. All classes have their corresponding tags.
My question is: how can I use these tags to figure out which object to make?
So like, a user will input either "john" "sally" or "mark" and I want to make that corresponding object...
Look at the Strategy Pattern:
a software design pattern, whereby an algorithm's behaviour can be selected at runtime
You could use this pattern to match input to a factory or as part of an enum that maps the name to a given class type (though there are several "hard-coding" issues with this approach).
As for construction of object instances, I recommend you also look at the Factory Pattern and combine the two to create these objects in an abstract manner.
I also recommend you don't tag your objects lik this, as you're hard-coding user input expectations against your codebase. At least externalise such expectations to a configuration file (.properties or .xml) so the mappings of input can change independently of the code.
I had faced similar requirements in a Project.
This is what I did,
Design a strategy to read the Class(s) : This is required because the classes are not referenced in any of your code directly. Hence these classes wont be processed by any ClassLoader automatically. Load class dynamically using Class.forName()
Generate a Factory : Make the scope of your annotation as Runtime. This will allow you to process the class files that you have read and extract your custom annotation value out of it. Then you can register the name of this class against the annotation in the factory class.
Use the factory to generate the Objects : Now you have a factory which can return the objects of your class when you pass a tag name. Use reflection to create a Object.
To know more about factory pattern please refer the link : Factory Pattern

Should I split up my XStream converter per class?

I am working on a program that uses XStream to write out to XML. As it stands I have only one class that implements Converter. This single converter takes in my ENTIRE configuration which is a HashMap at its root and the value of each key is an new instance of VMwareServer class which in turn has a HashMap where the value of key is a new instance of VMwareVirtualMachine class. Each of the respective classes have methods for setting and getting things like IP address and port number.
What I am wondering is if this is proper way to implement the XStream converter, or should I create a separate converter to convert each class to XML on it own?
I can show some code if there is still questions about what I mean.
This is somewhat debatable, but I would argue for having a separate converter for each class. This has several benefits: if you later need to return a subset of your complete view, you will be able to easily decompose the structure along class-based lines (perhaps, for example, to limit information by permissions). If you need to return slightly different representations in different contexts, you can do so on a class-by-class basis rather than duplicating all of the presentational logic in your monolithic class.

How should one use abstracted instances

I am designing a game and I have good overview of what I am doing.
However I've been trying to improve my OOP skills but now and then I face the same problem, how should I use the abstracted objects?
Lets say I have a list of Entitys that represents anything that has x and y property on screen and probably width and height haven't figured all out yet!
Then I have special types of entitys, one that can move and one that cannot and probably something like collidable in future.
They're all in a collection of Entitys (List<Entity> in my case) and now I want to simulate entitys that moves and are instances of DynamicEntity on main loop but they're all on abstract list of Entitys and I don't know is the Entity in loop either dynamic entity or not.
I know I could just check it with instanceof but I am pretty sure that's not the best idea..
I've seen some people having something like boolean inside the Entity for checking its type but I don't really want to hardcode all kind of entitys there..
I just want to know what is the best practice in such case?
Usually it's better to avoid checking the type if possible. If you think you need to use instanceof in your code then there's probably an abstraction you could be using to make your design more extensible. (If you decide to add a third type of Entity in the future you don't want to have to go back and update all of your instanceof checks with a third case.)
There are two common ways to have different actions based on an instance's concrete type without checking the concrete type:
One common way is the visitor pattern. The idea here is to create a Visitor class with an action for each type of object. Next, each concrete class has an accept method which simply calls the correct visit method inside the visitor class. This single level of indirection allows the objects to choose the correct action themselves rather than you choosing it by checking the type.
The visitor pattern is usually used for one of two reasons. 1) You can add new actions to a class hierarchy that implements the visitor pattern without access to the classes' source code. You only have to implement a new visitor class and use it in tandem with the visitable classes' pre-existing accept methods. 2) When there are many possible actions one can perform on classes from some type hierarchy sometimes it's more clear to split each action off into it's own visitor class rather than polluting the target classes with a bunch of methods for a bunch of different actions, so you group them with the visitor rather than the target classes.
However, in most cases it's easier to do things the second way: to simply override the definition of a common method in each concrete class. The Entity class might have an abstract draw() method, then each type of Entity would implement that draw() method in a different way. You know that each type of Entity has a draw() method that you can call, but you don't have to know the details of which type of entity it is or what the method's implementation does. All you have to do is iterate over your List<Entity> and call draw() on each one, then they'll perform the correct actions themselves depending on their type since each type has its own specialized draw() implementation.
You're right that you don't want to check the instance type or have some sort of function to check capability. My first question would be - why do you have a list of entities of that base type in the first place ? It sounds to me like you need to maintain a list of dynamic entities.
You could implement a move() method that does nothing for non-dynamic entities, but again that doesn't seem right in this particular scenario.
Perhaps it would be better to implement an event that triggers the iteration of that list, and pass that event into each object in turn. The dynamic entities could decide to move upon that event. The static entities would obviously not.
e.g.
Event ev = ...
foreach(e : entities) {
e.actUpon(ev);
}
In this scenario you could have different event types, and the entities would decide upon their action upon the basis of the event type and the entity type. This is known as double-dispatch or the visitor pattern.
If your processing of entities relies on knowing details about the entity types, then your Entity abstraction doesn't buy you much (at least not in this use-case): your List<Entity> is almost as opaque for you as a mere List<Object>.
If you know that every entity you can imagine will be either static or dynamic, there's no "hard-coding" in having a boolean property to all entities: isDynamic() or something.
However, if the dynamic aspect only makes sense for a subset of your entities, this flag will indeed bring some mess to your abstraction. In this case, my first guess is that you didn't model the use-case properly since you need to work with a list of items that do not provide enough polymorphic information for you to handle them.

Structural design pattern

I'm working with three separate classes: Group, Segment and Field. Each group is a collection of one or more segments, and each segment is a collection of one or more fields. There are different types of fields that subclass the Field base class. There are also different types of segments that are all subclasses of the Segment base class. The subclasses define the types of fields expected in the segment. In any segment, some of the fields defined must have values inputted, while some can be left out. I'm not sure where to store this metadata (whether a given field in a segment is optional or mandatory.)
What is the most clean way to store this metadata?
I'm not sure you are giving enough information about the complete application to get the best answer. However here are some possible approaches:
Define an isValid() method in your base class, which by default returns true. In your subclasses, you can code specific logic for each Segment or FieldType to return false if any requirements are missing. If you want to report an error message to say which fields are missing, you could add a List argument to the isValid method to allow each type to report the list of missing values.
Use Annotations (as AlexR said above).
The benefit of the above 2 approaches is that meta data is within the code, tied directly to the objects that require it. The disadvantage is that if you want to change the required fields, you will need to update the code and deploy a new build.
If you need something which can be changed on the fly, then Gangus suggestion of Xml is a good start, because your application could reload the Xml definition at run-time and produce different validation results.
I think, the best placement for such data will be normal XML file. And for work with such data the best structure will be also XMLDOM with XPATH. Work with classes will be too complicated.
Since java 5 is released this kind of metadata can be stored using annotations. Define your own annotation #MandatoryField and mark all mandatory fields with it. Then you can discover object field-by-field using reflection and check whether not initiated fields are mandatory and throw exception in this case.

Categories