I described my previous problem here:
Java - how can I loop methods with same name but different parameters
And I have question related to that.
Is given there example - a good example of using wrapper class?
class Wrapper{
Part param1;
File param2;
File param3;
}
class Validator{
void validate (Wrapper wrapper);
}
class ValidatorA extends Validate{
void validate (Wrapper wrapper){
//use wrapper.part...
}
}
class ValidatorC extends Validate{
void validate (Wrapper wrapper){
//use wrapper.file...
}
}
But it makes me wonder. Is wrapper correct name for it? Is is valid wrapper class? From what I read wrapper classes are used for primitives to use them as objects, shouldn't then it be named different? Or am I wrong?
I need it to be called same way, so I can loop over it so overloading is not the answer. Given class works fine - I just think if is it correct way to use wrapper name?
Wrapper is not good choice in this case. Usually wrapper is used to wrap some different things so they look alike even they are totally different. For example you may have some stream of data which comes from different sources - file, http connection, resources. All what you care is to read data from this source. So, you write wrapper which reads from any source and just deliver data.
Wrapper should not be mixed with common functionality. In example above all 3 sources could be treated as stream so natural solution would be use them all as streams. But even eventually inside wrapper they are used as streams they still require different treatment and actions to work with them. And wrapper takes care about it. You do not care what is wrapped wraps - you just use this wrapped thing in common way which wrapper provides.
In your example we have regular object which encapsulates some data and functionality. This is regular OOP approach. Calling it Wrapper only misguide users who may use this code later.
Related
I'm attempting to write a framework to handle an interface with an external library and its API. As part of that, I need to populate a header field that exists with the same name and type in each of many (70ish) possible message classes. Unfortunately, instead of having each message class derive from a common base class that would contain the header field, each one is entirely separate.
As as toy example:
public class A
{
public Header header;
public Integer aData;
}
public class B
{
public Header header;
public Long bData;
}
If they had designed them sanely where A and B derived from some base class containing the header, I could just do:
public boolean sendMessage(BaseType b)
{
b.header = populateHeader();
stuffNecessaryToSendMessage();
}
But as it stands, Object is the only common class. The various options I've thought of would be:
A separate method for each type. This would work, and be fast, but the code duplication would be depressingly wasteful.
I could subclass each of the types and have them implement a common Interface. While this would work, creating 70+ subclasses and then modifying the code to use them instead of the original messaging classes is a bridge too far.
Reflection. Workable, but I'd expect it to be too slow (performance is a concern here)
Given these, the separate method for each seems like my best bet, but I'd love to have a better option.
I'd suggest you the following. Create a set of interfaces you'd like to have. For example
public interface HeaderHolder {
public void setHeader(Header header);
public Header getHeader();
}
I'd like your classes to implement them, i.e you's like that your class B is defined as
class B implements HeaderHolder {...}
Unfortunately it is not. Now problem!
Create facade:
public class InterfaceWrapper {
public <T> T wrap(Object obj, Class<T> api) {...}
}
You can implement it at this phase using dynamic proxy. Yes, dynamic proxy uses reflection, but forget about this right now.
Once you are done you can use your InterfaceWrapper as following:
B b = new B();
new IntefaceWrapper().wrap(b, HeaderHolder.class).setHeader("my header");
As you can see now you can set headers to any class you want (if it has appropriate property). Once you are done you can check your performance. If and only if usage of reflection in dynamic proxy is a bottleneck change the implementation to code generation (e.g. based on custom annotation, package name etc). There are a lot of tools that can help you to do this or alternatively you can implement such logic yourself. The point is that you can always change implementation of IntefaceWrapper without changing other code.
But avoid premature optimization. Reflection works very efficiently these days. Sun/Oracle worked hard to achieve this. They for example create classes on the fly and cache them to make reflection faster. So probably taking in consideration the full flow the reflective call does not take too much time.
How about dynamically generating those 70+ subclasses in the build time of your project ? That way you won't need to maintain 70+ source files while keeping the benefits of the approach from your second bullet.
The only library I know of that can do this Dozer. It does use reflection, but the good news is that it'll be easier to test if it's slow than to write your own reflection code to discover that it's slow.
By default, dozer will call the same getter/setters on two objects even if they are completely different. You can configure it in much more complex ways though. For example, you can also tell it to access the fields directly. You can give it a custom converter to convert a Map to a List, things like that.
You can just take one populated instance, or perhaps even your own BaseType and say, dozer.map(baseType, SubType.class);
I have an Object Conversion Class that converts from my domain level objects to DTOs.
I effectively have the following structure
class RuleGroupDTO {
List<RuleDTO> ruleDTOs;
// other members
EvaluationRuleDTO and AssignmentRuleDTO both extend from RuleDTO
My API for conversion is as follows:
public RuleGroupDTO convert(RuleGroup ruleGroup);
So when I pass in my domain RuleGroup to the convert class, it looks at a code associated with the RuleGroup and then constructs either EvaluationRuleDTO or AssignmentRuleDTOs encapsulated within the RuleGroupDTO.
When I retrieve back my RuleGroupDTO, I know that it will contain a List<RuleDTO> that is either List<EvaluationRuleDTO> or List<AssignmentRuleDTO>.
However, to get the correct class version I need to loop through the List<RuleDTO> and cast to either List<EvaluationRuleDTO> or List<AssignmentRuleDTO>
This seems messy, and I am thinking that I can leverage some generic concepts to avoid performing this loop + cast.
What would be a possible approach to changing my API or object structure to take advantage of generics here?
If you have a set amount of types and you want them separate, then return a pojo with the various types separated into different collections, e.g.:
public class DTOResult {
public List<EvaluationRuleDTO> evalDTOs;
public List<AssignmentRuleDTO> assignDTOs;
}
Use List<RuleDTO> to avoid casting, and for god's sake don't write a loop. Make RuleDTO implement a visitor pattern that allows any consumer to handle either kind of subclass in a type-safe manner.
Java sucks at variant types.
How are templated methods implemented in C++?
I'm thinking about implementing templates in the JVM and have got a possible implementation thought out for templated classes, but am unsure on methods.
If, for example, you did:
class Test
{
public static boolean isIterable<T>(T variable)
{
return T instanceof Iterable;
}
}
System.out.println(Test.isIterable(new int[] { 0 }));
Would I create a version of Test that replied to int[]? (In my implementation, the class would be named as such: $g$Test$A_Java_lang_int)
Please ignore any problems with generics (such as only requiring boxed objects), as I intend to remove them.
I plan on creating these resolved templates dynamically, and keeping track of the number of references so I can remove them if they are not used. I believe this is how .Net manages it, although I'd be happy to be wrong here!
Would I create a version of Test that replied to int[]?
Essentially, yes. Templates in C++ are purely a compile-time mechanism that uses a (glorified) macro mechanism to generate code based on a template for each type with which it’s instantiated.
(C++ actually does a lot more due to the possibility of specialisation but this is the gist of it.)
I would suggest trying to do this staticly by generating the classes. You might find http://trove.starlight-systems.com/ interesting as it has a templating approach to generating its primitive collections. e.g. TintLongHashMap This doesn't rely on any language features.
I would suggest you work out how to do this staticly before trying to do it dynamicly which is much harder.
I have two classes in my Java project that are not 'related' to each other (one inherits from Thread, and one is a custom object. However, they both need to use the same function, which takes two String arguments and does soem file writing stuff. Where do I best put this function? Code duplication is ugly, but I also wouldn't want to create a whole new class just for this one function.
I have the feeling I am missing a very obvious way to do this here, but I can't think of an easy way.
[a function], which takes two String arguments and does soem file writing stuff
As others have suggested, you can place that function in a separate class, which both your existing classes could then access. Others have suggested calling the class Utility or something similar. I recommend not naming the class in that manner. My objections are twofold.
One would expect that all the code in your program was useful. That is, it had utility, so such a name conveys no information about the class.
It might be argued that Utility is a suitable name because the class is utilized by others. But in that case the name describes how the class is used, not what it does. Classes should be named by what they do, rather than how they are used, because how they are used can change without what they do changing. Consider that Java has a string class, which can be used to hold a name, a description or a text fragment. The class does things with a "string of characters"; it might or might not be used for a name, so string was a good name for it, but name was not.
So I'd suggest a different name for that class. Something that describes the kind of manipulation it does to the file, or describes the format of the file.
Create a Utility class and put all common utility methods in it.
Sounds like an ideal candidate for a FileUtils class that only has static functions. Take a look at SwingUtilities to see what I'm talking about.
You could make the function static in just one of the classes and then reference the static method in the other, assuming there aren't variables being used that require the object to have been instantiated already.
Alternatively, create another class to store all your static methods like that.
To answer the first part of your question - To the best of my knowledge it is impossible to have a function standalone in java; ergo - the function must go into a class.
The second part is more fun - A utility class is a good idea. A better idea may be to expand on what KitsuneYMG wrote; Let your class take responsibility for it's own reading/writing. Then delegate the read/write operation to the utility class. This allows your read/write to be manipulated independently of the rest of the file operations.
Just my 2c (+:
I have a custom INIFile class that I've written that read/write INI files containing fields under a header. I have several classes that I want to serialize using this class, but I'm kind of confused as to the best way to go about doing it. I've considered two possible approaches.
Method 1: Define an Interface like ObjectPersistent enforcing two methods like so:
public interface ObjectPersistent
{
public void save(INIFile ini);
public void load(INIFile ini);
}
Each class would then be responsible for using the INIFile class to output all properties out to the file.
Method 2: Expose all properties of the classes needing serialization via getters/setters so that saving can be handling in one centralized place like so:
public void savePlayer(Player p)
{
INIFile i = new INIFile(p.getName() + ".ini");
i.put("general", "name", p.getName());
i.put("stats", "str", p.getSTR());
// and so on
}
The best part of method 1 is that not all properties need to be exposed, so encapsulation is held firm. What's bad about method 1 is that saving isn't technically something that the player would "do". It also ties me down to flat files via the ini object passed into the method, so switching to a relational database later on would be a huge pain.
The best part of method 2 is that all I/O is centralized into one location, and the actual saving process is completely hidden from you. It could be saving to a flat file or database. What's bad about method 2 is that I have to completely expose the classes internal members so that the centralized serializer can get all the data from the class.
I want to keep this as simple as possible. I prefer to do this manually without use of a framework. I'm also definitely not interested in using the built in serialization provided in Java. Is there something I'm missing here? Any suggestions on what pattern would be best suited for this, I would be grateful. Thanks.
Since you don't want (for some reason) to use Java serialization, you can use XML serialization. The simplest way is via XStream:
XStream is a simple library to serialize objects to XML and back again.
If you are really sure you don't want to use any serialization framework, you can of course use reflection. Important points there are:
getClass().getDeclaredFields() returns all fields of the class - both public and private
field.setAccessible(true) - makes a private (or protected) field accessible via reflection
Modifier.isTransient(field.getModifiers()) tells you whether the field has been marked with the transient keyword - i.e. not eligible for serialization.
nested object structures may be represented by a dot notation - team.coach.name, for example.
All serialization libraries are using reflection (or introspection) to achieve their goals.
I would choose Method 1.
It might not be the most object oriented way, but in my experience it is simpler, less error-prone and easier to maintain than Method 2.
If you are conserned about providing multiple implementations for your own serialization, you can use interfaces for save and load methods.
public interface ObjectSerializer
{
public void writeInt(String key, int value);
...
}
public interface ObjectPersistent
{
public void save(ObjectSerializer serializer);
public void load(ObjectDeserializer deserializer);
}
You can improve these ObjectSerializer/Deserializer interfaces to have enough methods and parameters to cover both flat file and database cases.
This is a job for the Visitor pattern.