Populating large set of parameters with Setter methods - java

I am using POJO to create and fetch data. These POJOs represent our APIs and we use them for testing through REST Assured.
I have a RequestDTO class with 30 variables. Since this is a DTO, I am using 30 setter methods in my class for updating there values.
I am calling these setter methods as below with method chaining. I am using varList variable to read data from csv and supply to this DTO.
However this looks clumsy, less readable & incorrect. I want to know what is a good approach/design pattern here. As I have fairly less knowledge around best practices & design pattern.
Sample code:
public static void setRequestDTO(List<Object> varList) {
MyRequestDTO myrequest = new MyRequestDTO()
.setkey1(varList.get(0).toString())
.setkey2(varList.get(1).toString())
// ........
.setkey30(varList.get(30).toString());
}

Firstly, I believe your DTO is too bloated - is there really no other way that you can perhaps break this down into smaller classes?
Secondly, you're using a List<Object> but all of the examples show that you're using String values - is there a chance that you could change the type parameter of the List to eliminate the need for all of the .toString calls?
Thirdly, you are depending heavily on your List containing all of the necessary elements that you're looking to set on your DTO and that they are all in the correct order. This will lead to exceptions being thrown if you have too few elements.
Lastly, while I would consider refactoring this, I'll leave you with one idea that you could proceed with. If you are determined to keep your current DTO structure, then consider putting your List<Object> into a constructor for MyRequestDTO and then performing all of your setters in there. That way you don't have 30 lines of setters whenever you're instantiating a new instance of this DTO and you're only setting these values on instantiation.

Related

Sorting rest get request results by field passed as a parameter

I am currently working on a Rest API, in a get method which suppose to return an Array of objects in json format I now have the requirement to sort the result by a field passed as a parameter to the method. Consider for example the object to be
public class ExampleType {
int firstField ;
String secondField ;
}
Now according to the requirements the Rest API user should be able to pass as a parameter among other things either "firstField" or "secondField" and I should be sorting the array containing the result objects using this field.
Apparently my model is not so simplistic as the example, I do have more than 15 fields which could potentially be the one that I need to sort by, so an else if statement is not a choice at this point. My question is does anybody had a similar requirement for a rest api and if so how did you tackle it ? Or any recommendation on what could potentially by an elegant solution to my problem would be greatly appreciated.
You should create a Comparator and then use this to sort your data.
The comparators could be stored in a static map to avoid a switch/case if/else:
map.put("fieldName", Comparator.comparing(ExampleType::getFirstField));
You can combine two or more comparators using the thenComparing method.
The only other option is to create the appropriate comparators using reflection.
Note: requirements of API consumers often are not requirements that should be implemented in the API itself. You may also consider that sorting output is in fact a display problem and not something that an API needs to be concerned with.
It depends on the situation though, if data needs to be paginated then you may have no option other than to sort at the API level.

What is the best practice to return dynamic type from a REST API in SpringMVC

I have implemented some REST API with springMVC+Jackson+hibernate.
All I needed to do is retrieve objects from database, return it as a list, the conversion to JSON is implicit.
But there is one problem. If I want to add some more information to those object before return/response. For example I am returning a list of "store" object, but I want to add a name of the person who is attending right now.
JAVA does not have dynamic type (how I solve this problem in C#). So, how do we solve this problem in JAVA?
I thought about this, and have come up with a few not so elegant solution.
1. use factory pattern, define another class which contain the name of that person.
2. covert store object to JSON objects (ObjectNode from jackson), put a new attribute into json objects, return json objects.
3. use reflection to inject a new property to store object, return objects, maybe SpringMVC conversion will generate JSON correctly?
option 1 looks bad, will end up with a lot of boiler plate class which doesn't really useful. option 2 looks ok, but is this the best we could do with springMVC?
option 1
Actually your JSON domain is different from your core domain. I would decouple them and create a seperate domain for your JSON objects, as this is a seperate concern and you don't want to mix it. This however might require a lot of 1-to-1 mapping. This is your option 1, with boilerplate. There are frameworks that help you with the boilerplate (such as dozer, MapStruct), but you will always have a performance penalty with frameworks that use generic reflection.
option 2, 3
If you really insist on hacking it in because it's only a few exceptions and not a common pattern, I would certainly not alter the JSON nodes or use reflection (your option 2 and 3). This is certainly not the way to do it in Java.
option 4 [hack]
What you could do is extend your core domain with new types that contain the extra information and in a post-processing step replace the old objects with the new domain objects:
UnaryOperator<String> toJsonStores = domainStore -> toJsonStore(domainStore);
list.replaceAll(toJsonStores);
where the JSONStore extends the domain Store and toJsonStore maps the domain Store to the JSONStore object by adding the person name.
That way you preserve type safety and keep the codebase comprehensive. But if you have to do it more then in a few exceptional cases, you should change strategy.
Are you looking for a rest service that return list of objects that contain not just one type, but many type of objects? If so, Have you tried making the return type of that service method to List<Object>?
I recommend to create a abstract class BaseRestResponse that will be extended by all the items in the list which you want return by your rest service method.
Then make return type as List<BaseRestResponse>.
BaseRestResponse should have all the common properties and the customized object can have the property name as you said

Which is better adding new fields to existing DTO class or new DTO class?

This may be a general java question
DTO1
attribute1
attribute2
attribute3
DTO2
attribute1
attribute2
attribute3
attribute4
attribute5
attribute6
attribute7
attribute8
attribute9
attribute10
attribute11
attribute12
I'll be showing some list of values in a gxt grid on my screen. Those values are nothing else but a list of DTO1 class in which I have 3 strings which I'll be getting from a service call. Now I need to show 12 different fields in a similar fashion but based on a condition (I won't be showing DTO1 this time around).
Is it better (performance wise) to create a new DTO2 class with those 12 fields or add these 12 fields to the existing DTO1 class so that I don't have to create a new DTO2 class anymore.
Case 1. Added extra fields to the existing DTO class
Wouldn't there be extra space each time I'm using the DTO class for only 3 attributes instead of the newly added 12 attributes?
Case 2. New DTO2 class created
Can the extra space created be compensated by adding those 12 fields to the DTO1 as in case 1?
Throw some light on which approach improves the performance?
If your DTO2 has 3 of its 12 attributes the same type as DTO1, you should definitely use inheritance:
class DTO1{
private String attribute1;
private String attribute2;
private String attribute3;
//getters and setters
}
class DTO2 extends DTO1{
private String attribute4;
//other attributes
}
and use DTO2 wherever you neeed exactly all the 12 attributes, and DTO1 when you need only 3 attributes.
If your DTO2 doesn't have at least 3 attributes the same type as DTO1, you should create a new separate DTO2 class. There's no purpose in adding all the 12 attributes to DTO1 and use only 3 of them, because the JVM will allocate memory for all 12 of them them when you create an instance of your DTO1, even though you do not initialize those other 9( each reference would occupy 4/8 bytes - depending on the machine JVM is running).
Of course, a few bytes more are insignificant, unless you deal with millions of DTOs. But if we consider the design, and the posibillity that in the future you will need multiple kinds of DTOs, you should not rely only on one type of DTO to do your job.
As for the extra space added by DTO2 fields, there is no way around. If you need 12 attributes, you have to allocate memory for them, so there's nothing wrong here.
While both approaches may be technically correct, i am more inclined towards creating new DTOs rather than adding more fields for the following reasons:
It makes the code easier to read: coupled with good naming an extra DTO will give your successor less headache at first glance.
Classes are supposed to have only one reason to change: muddling a DTO up with unrelated fields will give that class several reasons to change in the future, making it a source of failure for unrelated dependents.
The extra class won't hurt your application.
I really wouldn't worry about performance since I do not believe there is reasonable difference between mentioned approaches. I would rather consider best design practice that will allow you to maintain your application should you need to add/edit fields in the future. I think having a separate dto with only what you need is best here. You may also use inheritance if every dto uses the same basic fields that you can put in a parent class, and add the rest to child classes. For your example the attributes 1,2,3 would go on a parent class, and the rest on a child class.

4 Key Value HashMap? Array? Best Approach?

I've got loads of the following to implement.
validateParameter(field_name, field_type, field_validationMessage, visibleBoolean);
Instead of having 50-60 of these in a row, is there some form of nested hashmap/4d array I can use to build it up and loop through them?
Whats the best approach for doing something like that?
Thanks!
EDIT: Was 4 items.
What you could do is create a new Class that holds three values. (The type, the boolean, and name, or the fourth value (you didn't list it)). Then, when creating the HashMap, all you have to do is call the method to get your three values. It may seem like more work, but all you would have to do is create a simple loop to go through all of the values you need. Since I don't know exactly what it is that you're trying to do, all I can do is provide an example of what I'm trying to do. Hope it applies to your problem.
Anyways, creating the Class to hold the three(or four) values you need.
For example,
Class Fields{
String field_name;
Integer field_type;
Boolean validationMessageVisible;
Fields(String name, Integer type, Boolean mv) {
// this.field_name = name;
this.field_type = type;
this.validationMessageVisible = mv;
}
Then put them in a HashMap somewhat like this:
HashMap map = new HashMap<String, Triple>();
map.put(LOCAL STRING FOR NAME OF FIELD, new Field(new Integer(YOUR INTEGER),new Boolean(YOUR BOOLEAN)));
NOTE: This is only going to work as long as these three or four values can all be stored together. For example if you need all of the values to be stored separately for whatever reason it may be, then this won't work. Only if they can be grouped together without it affecting the function of the program, that this will work.
This was a quick brainstorm. Not sure if it will work, but think along these lines and I believe it should work out for you.
You may have to make a few edits, but this should get you in the right direction
P.S. Sorry for it being so wordy, just tried to get as many details out as possible.
The other answer is close but you don't need a key in this case.
Just define a class to contain your three fields. Create a List or array of that class. Loop over the list or array calling the method for each combination.
The approach I'd use is to create a POJO (or some POJOs) to store the values as attributes and validate attribute by attribute.
Since many times you're going to have the same validation per attribute type (e.g. dates and numbers can be validated by range, strings can be validated to ensure they´re not null or empty, etc), you could just iterate on these attributes using reflection (or even better, using annotations).
If you need to validate on the POJO level, you can still reuse these attribute-level validators via composition, while you add more specific validations are you´re going up in the abstraction level (going up means basic attributes -> pojos -> pojos that contain other pojos -> etc).
Passing several basic types as parameters of the same method is not good because the parameters themselves don't tell much and you can easily exchange two parameters of the same type by accident in the method call.

What's the best pattern to handle a table row datastructure?

The Facts
I have the following datastructure consisting of a table and a list of attributes (simplified):
class Table {
List<Attribute> m_attributes;
}
abstract class Attribute {}
class LongAttribute extends Attribute {}
class StringAttribute extends Attribute {}
class DateAttribute extends Attribute {}
...
Now I want to do different actions with this datastructure:
print it in XML notation
print it in textual form
create an SQL insert statement
create an SQL update statement
initialize it from a SQL result set
First Try
My first attempt was to put all these functionality inside the Attribute, but then the Attribute was overloaded with very different responsibilities.
Alternative
It feels like a visitor pattern could do the job very well instead, but on the other side it looks like overkill for this simple structure.
Question
What's the most elegant way to solve this?
I would look at using a combination of JAXB and Hibernate.
JAXB will let you marshall and unmarshall from XML. By default, properties are converted to elements with the same name as the property, but that can be controlled via #XmlElement and #XmlAttribute annotations.
Hibernate (or JPA) are the standard ways of moving data objects to and from a database.
The Command pattern comes to mind, or a small variation of it.
You have a bunch of classes, each of which is specialized to do a certain thing with your data class. You can keep these classes in a hashmap or some other structure where an external choice can pick one for execution. To do your thing, you call the selected Command's execute() method with your data as an argument.
Edit: Elaboration.
At the bottom level, you need to do something with each attribute of a data row.
This indeed sounds like a case for the Visitor pattern: Visitor simulates a double
dispatch operation, insofar as you are able to combine a variable "victim" object
with a variable "operation" encapsulated in a method.
Your attributes all want to be xml-ed, text-ed, insert-ed updat-ed and initializ-ed.
So you end up with a matrix of 5 x 3 classes to do each of these 5 operations
to each of 3 attribute types. The rest of the machinery of the visitor pattern
will traverse your list of attributes for you and apply the correct visitor for
the operation you chose in the right way for each attribute.
Writing 15 classes plus interface(s) does sound a little heavy. You can do this
and have a very general and flexible solution. On the other hand, in the time
you've spent thinking about a solution, you could have hacked together the code
to it for the currently known structure and crossed your fingers that the shape
of your classes won't change too much too often.
Where I thought of the command pattern was for choosing among a variety of similar
operations. If the operation to be performed came in as a String, perhaps in a
script or configuration file or such, you could then have a mapping from
"xml" -> XmlifierCommand
"text" -> TextPrinterCommand
"serial" -> SerializerCommand
...where each of those Commands would then fire up the appropriate Visitor to do
the job. But as the operation is more likely to be determined in code, you probably
don't need this.
I dunno why you'd store stuff in a database yourself these days instead of just using hibernate, but here's my call:
LongAttribute, DateAttribute, StringAttribute,… all have different internals (i.e. fields specific to them not present in Attribute class), so you cannot create one generic method to serialize them all. Now XML, SQL and plain text all have different properties when serializing to them. There's really no way you can avoid writing O(#subclasses of Attribute #output formats)* different methods of serializing.
Visitor is not a bad pattern for serializing. True, it's a bit overkill if used on non-recursive structures, but a random programmer reading your code will immediately grasp what it is doing.
Now for deserialization (from XML to object, from SQL to object) you need a Factory.
One more hint, for SQL update you probably want to have something that takes old version of the object, new version of the object and creates update query only on the difference between them.
In the end, I used the visitor pattern. Now looking back, it was a good choice.

Categories

Resources