What would you use if you wanted to pass a list of options into a function?
For example, if you have an interface to a server:
public interface Server {
public void authUser(String username, String password, <xyz> options);
}
What structure would use use for to pass a set of options? Something like a HashMap?
The reason I'm saying that it comes from tunnel vision is because I feel that this goes against Java standards. Java has method overloading. So if I get flames for raising the question I understand. But overall, maybe in different cases, would you ever pass bulk data in some collection and, if yes, which one?
Option1 : If you are choosing any collections like List or Set these are specific to an object . I mean,
Lets Assume, Set sets = new HashSet();
If I want 5 Object of different different class having no relationship to be send, then It would be very difficult to recognize that which Object is belong to which class while Iteration. So, I wont recommend Collections.
Option2 : If you are choosing Map, the same above problem may occurs while getting the Object Dynamically. So, This Options is also not recommended.
Option3 :
Why cann't you create your own DTO and in that DTO place your reqyired datastructure and pass it over.
If you want 5 different Object to be pass then, you can pass. If all are of same type then you may use Collection or array or Variable Arguement based on your scenerio.
I think anything Serializable is exactly the thing. If you can serialize the object, then you can pass (store, transmit...) it, passing it's properties in bulk. What format of serialized data to choose, is another question.
It depends on the data you want to pass.
You can use a map(hashmap) if you are passing key-value pairs.
If it is just a list of diffrent object, you can use List(ArrayList)
Other option is to create DTO(data transfer object) with getter and setter methods.
You may want to take a look at VARARGS feature that was introduced in JAVA5.
I'd suggest a Map [HashMap] as you can then access the argument values via their Keys.
Related
I am building a DAQ in a Java based Platform called KMax. This platform, has a design interface to use objects like histograms. Each histogram has a name, which is declared on the design interface.
To call the histogram in the code you have to use
hist = tlsh.getKmaxHist("DATA");
The string DATA is the name that the user gives in the design interface and hist is the variable that refers to the object. Every histogram object has certain classes it can use. For instance hist.getSum() gives the total sum of the histogram.
In my DAQ I have many histograms. My plan is to create a slider box that will pick the histogram, that the user wants to apply some functions(such as getSum()). The slider box has a class(string getProperty("VALUE")) that returns the value that the user has selected.
The plan is to use something like sliderBox.getProperty("VALUE").getSum(). Of course something like that is not valid, therefore I was wondering if there is a way to "convert" the string that the getProperty() returns, into a variable already defined in the code.
Sounds like a Map will do what you need. You can put the histograms in a Map keyed by whatever the property value is.
Map<String,Histogram> histograms = new HashMap<String,Histogram>();
histograms.put("PropertyValue1", histogram1);
histograms.put("PropertyValue2", histogram2);
String desiredHistogram = silderBox.getProperty("VALUE");
Histogram histogramToUse = histograms.get(desiredHistogram);
histogramToUse.getSum(); // do whatever you need to with this
You'll want to check for nulls and all that stuff too.
It looks to me like you need a Map<String, Histogram>. Variable names are lost when java code gets compiled.
You can use the *BeanInfo class mechanism. For instance. Having a class Hist, one can write a HistBeanInfo with a "sum" property. Though these classes were intended for GUI builders with components on palettes listing heterogene properties, one can use them indepedantly.
The BeanInfo classes might be generated.
This still is a far way to actually instrument that information, maybe using reflection.
An alternative to BeanInfo would be using home-brew annotations, but with BeanInfo you have an API supported by some IDEs.
Store it in a map:
yourHistogramsMap.get(sliderBox.getProperty("VALUE")).getSum();
Of course, you have to store your histograms there first.
I have some javascript code that looks like this
attachmentFiles.push(fileObj);
where fileObj is the file user has selected to upload.
Now if I want to represent in the java/json format, what should be the type of the list?
i.e
public class AttachmentHodler{
List<?> attachmentFiles;
public List<?> getAttachmentFiles() {
return attachmentFiles;
}
public void setAttachmentFiles(List<?> attachmentFiles) {
this.attachmentFiles = attachmentFiles;
}
}
It depends on the purpose of fileObj. Depending on what you want to do with it and what it's responsibilities are you could use:
some specialized Attachement class that you would create. Most versatile approach from the OO perspective. Example: http://ideone.com/H23Za7
An actual File that supports operation like .delete().
just a String to represent the path without any useful functionality.
It depends on what you want to store in your List. You can even choose to use List<?>, which will allow you to store almost anything in it. But if your attachment objects are of type Attachment, I'do go with List<Attachment>. That would allow you to store only Attachment objects in the list.
Since in Javascript there are no classes, it might be worth to mention that in Java, every object is an instance of a "class". Sometimes you define classes yourself, sometimes you re-use classes inside a framework or library.
So there is no general answer to the question, what type your elements will have.
I am designing an application that has two widgets:
-A list that contains arbitrary objects
-A table that displays specific properties of the currently selected object
The goal is to be able to pick an object from the list, look at the properties, and modify them as necessary. The list can hold objects of various types.
So say the list contains Vehicle objects and Person objects
public class Person
{
public String name;
public Integer age;
}
public class Vehicle
{
public String make;
public String model;
}
If I click on a Person object, the table will display the name and age, and I can assign new values to them. Similarly, if I click on a Vehicle object, it will display the make and model in the table and allow me to modify them.
I have considered writing a method like
public String[] getFields()
{
return new String[] {"name", "age"};
}
Which returns a list of strings that represent the instance variables I want to look at, and use some reflection methods to get/set them. I can define this getFields method in all of the classes so that I can use the table to handle arbitrary objects that might be thrown into the list.
But is there a way to design this so that I don't resort to reflection? The current approach seems like bad design.
On the other hand, I could create multiple TableModel objects, one for every possible class. The table would know what rows to display and how to access the object's instance variables. But then everytime a new class is added I would have to define a new table model, which also sounds like a weak design.
You have a class (Vehicle) and you know the names of some properties (make, model) that you want to be able to manipulate dynamically for an instance of this class through a JTable UI.
You have various different approaches to chose from.
A. Use the reflection API
This is what the reflection API is made for. If you want something so dynamic, there is nothing wrong with using reflection. The performance overhead will not be significant for this use case.
B. Use a library like beanutils that is based on the reflection API
This should be easier than directly using the reflection API, but it has the drawback that you need to include another dependency in your project.
C. Create dynamically at runtime the different TableModel classes.
You can do this using either the java compiler API or javassist. Based on information available at runtime, you are able to compile a new class for each different type of table model. If you follow this approach you must be aware that the creation of the class is a heavy task, so the first time you create a TableModel the application will take some time to respond.
What to chose?
Of course this is your decision. For the specific use case, the overhead added by reflection or beanutils is insignificant, so probably it is better to chose between A or B. In another use case where performance is more critical, then you could examine the C approach, without forgetting the class creation response time problem.
EDIT:
I just realized that in this specific use case there is another important functionality required. Convert from String to the appropriate data type of each property and vice cersa. Beanutils has perfect support for that, so it gets a plus here.
This is again, I guess, a 'best practices' question because i can think of some inelegant ways of getting my use case implemented.
My use case is as follows
Im writing a MethodManager(sort of) module which helps in the end user dealing with actual method(function) calls through a UI.
For this specific purpose i have a methodDefinition class which is an object form of what a method(function) looks like to my system.
A brief overview of what my methodDefinition's members look like is as follows
methodName -- String
methodInputs -- ArrayList<String>
methodResultType -- enum(STRING,MAP,LIST)
methodResult -- <<variable, on the basis of methodResultType>>
Now methodResult is variable and can be any of String, Map or List based on what methodResultType is set as.
I have created a MethodResultType class to account for methodResultType and it looks as follows
public enum MethodResultType {
LIST,
MAP,
STRING;
}
Now i know i have to write a class to account for methodResult and its variable nature based on methodResultType but cant think of a non botched up way to.
Any suggestions/ pointers in this regard would be greatly appreciated.
Thanks
p1ng
List, Map and String have a common ancestor class: java.lang.Object. methodResult can thus be an Object.
You could also wrap the result and its type into a MethodResult object, that would provide methods such as getType(), getValueAsString(), getValueAsList() and getValueAsMap(). These last three methods would throw an IllegalStateException if the type of the value is not the type returned by the method.
I am sorry if I am asking something that has been answered already but I could not find a reference. My question is where is the best place to put a comparator which layer does it belong to.For example I need a list of User Objects sorted by users date of birth then surname and then first name.
If the comparator is intrinsic to the object (e.g. it's the only way of ordering it that makes sense), then I would just implement Comparable on the object.
If the comparator is one of many (e.g. a Comparator instance), and only makes sense in a particular context, then I'd place the comparator class in that layer.
In your case if would put it on the domain class and sort it in the dao during fetch meaning have two methods(or more based on Comaprision types) on dao one to just get a list of unsorted object e.g. getUsers() and one method for sorted list e.g getSortedUers(); ofcourse you can only have a sorted method but always calling a sort is an over head if no sort is required.
If you are using database, then best way is to sort it in query itself, using order by
The general answer would be: put it where it is most required :-)
This depends a lot on your actual design and architecture. In general, either you can put it next to your user object, or into the layer which uses it most (or exclusively).
Yeah, if you use database or some external service and it's possible to sort there it's best way. But if you need to sort objects in your application it depends on your architecture. There are 2 variants. If you need sort only once - create anonymous class then you won't store reference on this object. If you need to make sort several times you can store it as static field of class or a non-static field.