Checking String parameters corresponding to field names - java

I'm heavily using Java.lang.Class.getField() method which requires a String variable as an argument. The problem I'm facing is when I change field names, that getField() refers to, Eclipse doesn't warn me that argument points nowhere (since it's String) and I end up having methods working improperly unnoticed.
So far I can see two ways out. It's either using try-catch blocks around every getField() call and running application to see what will be the next line to throw an exception. Fix it and watch out for the next exception. Or it's using Find/Replace feature every time I change a field name to manually look for the String value and replace it. Is there a more friendly (i.e. automatic) way to update String parameters in such cases?
Maybe there's a method (which I fail to find) that accepts a full field path as a non-String argument and returns a Field object? Something like turnToFieldObject(car.speed) returning Field object corresponding to speed field so that Eclipse would automatically check if there's such a field car.speed.
PS
First of all, thank you for your replies.
I can see that a lot of you, guys, suggest that I'm using reflection too much. That's why I feel I need to add extra explanation and would be glad to hear suggestions as well.
I'm doing a research about modeling social evolution and I need the entities to evolve new features that they don't have at the start. And it seemed to me that adding new fields to represent some evolutional changes is better understanding wise than adding new elements to arrays or collections. And the task suggests I shouldn't be able to know what feature will be evolved. That's why I rely so heavily on reflection.

AFAIK, there is no such method. You pass a reference (if it's an object) or value (if it's primitive); all data about the variables that they were originally assigned to is not available at runtime.
This is the huge downside of using reflection, and if you're "heavily" using this feature in such way, you're probably doing something wrong. Why not access the field directly, using getters and setters?
Don't get me wrong, reflection has its uses (for example, when you want to scan for fields with certain annotations and inject their values), but if you're referencing fields or methods by their name using a simple string, you could just as well access fields or methods directly. It implies that you know the field beforehand. If it's private, there is probably a reason why it's encapsulated. You're losing the content assist and refactoring possibilities by overusing reflection.
If you're modeling social evolution, I'd go with a more flexible solution. Adding new fields at runtime is (near?) impossible, so you are basically forced to implement a new class for each entity and create a new object each time the entity "evolves". That's why I suggest you to go with one of these solutions:
Use Map<String, Object> to store entities' properties. This is a very flexible solution which will allow you easily add and remove "fields" at the cost of losing their type data. Checking if the entity has a certain property will be a cheap contains call.
If you really want to stick to a million custom classes, use interfaces with getters and setters in addition to fields. For example, convert private String name to interface Named { String getName(); void setName(String name); }. This is much easier to refactor and does not rely on reflection. A class can implement as many interfaces as you want, so this is pretty much like the field solution, except it allows you to create custom getters/setters with extra logic if desperately needed. And determining if entity has a certain property is a entity instanceof MyInterface call, which is still cheaper than reflection.

I would suggest writing a method that use to get your fields supply it a string and then if the exception is thrown notify whatever needs to be notified that it was not valid and if the exception isn't caught return the field.
Although I do agree with the above that reflection should not be used heavily.

Related

Setter returning this vs builder

I was wondering, when constructing an object, is there any difference between a setter returning this:
public User withId(String name) {
this.name = name;
return this;
}
and a builder (for example one which is generated by Builder Generator plugin for IDEA)?
My first impression is that a setter returning this is much better:
it uses less code - no extra class for builder, no build() call at the end of object construction.
it reads better:
new User().withName("Some Name").withAge(30);
vs
User.UserBuilder.anUserBuilder().withName("Some Name").withAge(30).build();
Then why to use builder at all? Is there anything I am missing?
The crucial thing to understand is the concept of an immutable type.
Let's say I have this code:
public class UnitedStates {
private static final List<String> STATE_NAMES =
Arrays.asList("Washington", "Ohio", "Oregon", "... etc");
public static List<String> getStateNames() {
return STATE_NAMES:
}
}
Looks good, right?
Nope! This code is broken! See, I could do this, whilst twirling my moustache and wielding a monocle:
UnitedStates.getStateNames().set(0, "Turtlia"); // Haha, suck it washington!!
and that will work. Now for ALL callers, apparently there's some state called Turtlia. Washington? Wha? Nowhere to be found.
The problem is that Arrays.asList returns a mutable object: There are methods you can invoke on this object that change it.
Such objects cannot be shared with code you don't trust, and given that you don't remember every line you ever wrote, you can't trust yourself in a month or two, so, you basically can't trust anybody. If you want to write this code properly, all you had to do is use List.of instead of Arrays.asList, because List.of produces an immutable object. It has zero methods that change it. It seems like it has methods (it has a set method!), but try invoking it. It won't work, you'll get an exception, and crucially, the list does not change. It is in fact impossible to do so. Fortunately, String is also immutable.
Immutables are much easier to reason about, and can be shared freely with whatever you like without copying.
So, want your own immutable? Great - but apparently the only way to make one, is to have a constructor where all values are set and that's it - immutable types cannot have set methods, because that would mutate them.
If you have a lot of fields, especially if those fields have the same or similar types, this gets annoying fast. Quick!
new Bridge("Golden Gate", 1280, 1937, 2737);
when was it built? How long is it? What's the length of the largest span?
Uhhhhhhh..... how about this instead:
newBridge()
.name("Golden Gate")
.longestSpan(1280)
.built(1937)
.length(2737)
.build();
sweet. Names! builders also let you build over time (by passing the builder around to different bits of code, each responsible for setting up their bits). But a bridgebuilder isn't a bridge, and each invoke of build() will make a new one, so you keep the general rules about immutability (a BridgeBuilder is not immutable, but any Bridge objects made by the build() method are.
If we try to do this with setters, it doesn't work. Bridges can't have setters. you can have 'withers', where you have set-like methods that create entirely new objects, but, calling these 'set' is misleading, and you create both a ton of garbage (rarely relevant, the GC is very good at collecting short lived objects), and intermediate senseless bridges:
Bridge goldenGate = Bridge.create().withName("Golden Gate").withLength(2737);
somewhere in the middle of that operation you have a bridge named 'Golden Gate', with no length at all.
In fact, the builder can decide to not let you build() bridge with no length, by checking for that and throwing if you try. This process of invoking one method at a time can't do that. At best it can mark a bridge instance as 'invalid', and any attempt to interact with it, short of calling .withX() methods on it, results in an exception, but that's more effort, and leads to a less discoverable API (the with methods are mixed up with the rest, and all the other methods appear to throw some state exception that is normally never relevant.. that feels icky).
THAT is why you need builders.
NB: Project Lombok's #Builder annotation gives you builders for no effort at all. All you'd have to write is:
import lombok.Value;
import lombok.Builder;
#Value #Builder
public class Bridge {
String name;
int built;
int length;
int span;
}
and lombok automatically takes care of the rest. You can just Bridge.builder().name("Golden Gate").span(1280).built(1937).length(2737).build();.
Builders are design patterns and are used to bring a clear structure to the code. They are also often used to create immutable class variables. You can also define preconditions when calling the build() method.
I think your question is better formulated like:
Shall we create a separate Builder class when implementing the Builder Pattern or shall we just keep returning the same instance?
According to the Head First Design Patterns:
Use the Builder Pattern to encapsulate the construction of a product
and allow it to be constructed in steps.
Hence, the Encapsulation is important point.
Let's now see the difference in the approaches you have provided in your original question. The main difference is the Design, of how you implement the Builder Pattern, i.e. how you keep building the object:
In the ObjecBuilder separate class approach, you keep returning the Builder object, and you only(!) return the finalized/built Object, after you have finalized building, and that's what better encapsulates creation process, as it's more consistent and structurally well designed approach, because you have a clearly separated two distinct phases:
1.1) Building the object;
1.2) Finalizing the building, and returning the built instance (this may give you the facility to have immutable built objects, if you eliminate setters).
In the example of just returning this from the same type, you still can modify it, which probably will lead to inconsistent and insecure design of the class.
It depends on the nature of your class. If your fields are not final (i.e. if the class can be mutable), then doing this:
new User().setEmail("alalal#gmail.com").setPassword("abcde");
or doing this:
User.newBuilder().withEmail("alalal#gmail.com").withPassowrd("abcde").build();
... changes nothing.
However, if your fields are supposed to be final (which generally speaking is to be preferred, in order to avoid unwanted modifications of the fields, when of course it is not necessary for them to be mutable), then the builder pattern guarantees you that your object will not be constructed until when all fields are set.
Of course, you may reach the same result exposing a single constructor with all the parameters:
public User(String email, String password);
... but when you have a large number of parameters it becomes more convenient and more readable to be able to see each of the sets you do before building the object.
One advantage of a Builder is you can use it to create an object without knowing its precise class - similar to how you could use a Factory. Imagine a case where you want to create a database connection, but the connection class differs between MySQL, PostgreSQL, DB2 or whatever - the builder could then choose and instantiate the correct implementation class, and you do not need to actually worry about it.
A setter function, of course, can not do this, because it requires an object to already be instantiated.
The key point is whether the intermediate object is a valid instance.
If new User() is a valid User, and new User().withName("Some Name") is a valid User, and new User().withName("Some Name").withAge(30) is a valid user, then by all means use your pattern.
However, is a User really valid if you've not provided a name and an age? Perhaps, perhaps not: it could be if there is a sensible default value for these, but names and ages can't really have default values.
The thing about a User.Builder is the intermediate result isn't a User: you set multiple fields, and only then build a User.

Why creating a method better than declaring variable as a field?

int timeDuration = duration * MONTHS_IN_A_YEAR;
My online instructor said I should declare a method of name getTimeDuration() rather than creating a field of the same name. My question is a why creating a method is more preferable. Thanks.
This could fall into a style war. Folks from some camps will always use getters, while others rarely do so. You will find no single 100% agreed upon answer.
Practically, there will be little difference between a using a getter on a private final variable vs direct access. Good runtime environments will inline getters, making for only a slight additional overhead.
There are several reasons to prefer using a getter: If the value which is being retrieved is to be considered a part of an API; if the value obtained by the getter will be different in subclasses; if you want to place a break point or log or otherwise track calls to access the value; if you want a place to attach documentation of the value obtained by the getter, which would be the getter name and explicit documentation.
On the other hand, adding getters does add (a little) code bloat.
One reason, in future if you set variable as private or it will become private data, you are not allowed to access this variable outside the class boundary. So, the value of value of variable fetch by such getters and in object oriented getters are used for this purpose and came into action. Here getters is method like getTimeDuration().
Some code snippets are called "best practice"s, these are told by experienced people and accepted by developers and programmers because of the reasons like:
more readable code
easy to change for future extending or debugging
better performance
help developers to do better configurations
...
the matter we are talking about (using setter and getter for accessing or modifying fields), has one or some of matters that I have mentioned so it is better for developers to use it.
to talk more specific, by setting a field in a method (which that method is called setter) you can check the user input, put some rules for your code and many more features that some frameworks will give to you as a developer.
accessing the value of a field by a method (which is called getter), might add some abilities in some cases, imagine a situation that you want the user to read the field but not be able to change it. this could be done easily this way.

Best Practice - HashMap instead of list of parameters, good idea ?

Hi Stackoverflow community,
I am working on some code where a list of optional criterias criterias is submitted to my dao.
Method signature contains the list of +/- 10 parameters, which I really don't like and want to reformat.
Plus I would like to avoid having to refactor all method signatures from different layers just because I add/remove a criteria
List searchParams(String name, Long countryCode, ...){
...
}
would become
List searchParams(HashMap<String,Object> map) {
BeanUtils.populate(this,map);
...
}
I am a bit worried that this happen to because kind of a bad practice, because I give up control of what is passed in the map to give me that flexibility ? So my question is if I am on the right path proceeding that way?
When I encounter situations like this, I tend to create a Params class, and pass that around. The benefits are that:
unlike when using a Map, you can have meaningful getters/settings, proper validation etc;
it's type-safe and self-describing (meaning it's easy to find out the available parameters and their types).
you can add new parameters without having to refactor any intermediate layers.
You could define a new class to hold/handle your set of parameters, so you get a bit more control than a HashMap would give you. Annoying to write, or at least tedious, but seems like a better balance between flexibility & control.
You could look at your parameters and see if you can wrap them as a logical group into an object. For example a name an a country code could be a person object
public Person {
private String name;
private String countryCode;
}
Then you will just be passing this object down and can use getters to get the data out which should be easier to read and maintain than needing to know all the keys for the HashMap on multiple layers.
The only case where using a map is appropriate is when you are designing a factory, and you need to pass different kinds of parameters to different classes being created. In all other cases, a solution with a specialized parameter info class would be preferred.
For an example of where passing a map is appropriate, look at the DriverManager.getConnection method: this method needs to pass parameters to constructors of driver-specific implementations of the Connection being created, so it wraps a map into Properties, and lets the user pass it through to the driver-specific connection. Note that DriverManager does not have another solution that would be future-proof.
I would strongly discourage using a map in all other cases: the added flexibility shifts error detection from compile-time to run-time, which has a strong potential of multiplying your headache beyond belief.

getDeclaredField(String) vs. getMethod(String) for private fields in a bean

I have a bean whose properties I want to access via reflection. I receive the property names in String form. The beans have getter methods for their private fields.
I am currently getting the field using getDeclaredField(fieldName), making it accessible by using setAccessible(true) and then retrieving its value using get.
Another way to go about it would be to capitalize the field name and add get to the front of it, and then get the method by that name from the class and finally invoke the method to get the value of the private field.
Which way is better?
EDIT
Perhaps I should explain what I mean by "better"... By "better", I mean in the sense of best-practices. Or, if there are any subtle caveats or differences.
You may want to take a look at the Introspector class, its a nice wrapper if you want to only deal with properties which have been exposed, you can get a BeanInfo object and then call getPropertyDescriptors(), for example:
final BeanInfo info = Introspector.getBeanInfo(clazz);
for (PropertyDescriptor prop : info.getPropertyDescriptors()) {
final Method read = prop.getReadMethod();
if (read != null) {
// do something
}
}
It depends of your use, but in general I would prefer to use the getter as this is the "normal" way and will in more cases do the thing the developer of the class expects gets done.
In principle, if the developer of the class has made the field private he is free to do as he pleases, like for instance removing it later if it can be calculated in another way. Then the fieldaccess will break, hopefully immediately, if you are unlucky 3 months later when nobody remembers anymore.
Note that there a libraries like apache commons BeanUtils (I believe there is one in Spring too) which does that for you and offer a more sane interface, like a hash map for example.
Possibly using the getter method, as it may have additional behaviour besides just returning the property's value. However this depends on the class.
Better in what way?
You could write a 20 line unit test to see which is faster. You could write both and look at them to see which is easier to read. If one way is both easier to read and faster, go for it. If not, you will have to pick your poison...

Setting values of an object

Let's say I've got a class called House with the two fields
name
address
Each of these fields has got a getter and a setter.
Now I want another method in the House class called setValues. This method should set the fields with properties from a passed object of a different type.
There would be two ways on how to create this method. First way:
private void setHouse(HouseTransfer transer){
name = transfer.getName();
address = transfer.getAddress();
}
Or the second option:
private void setHouse(HouseTransfer transer){
setName(transfer.getName());
setAddress(transfer.getAddress());
}
Which one is more "best practice"?
At a certain level of granularity, software design is more subjective matter than one of black-and-white absolutes. I do not believe there is an absolute "best practice" here.
That being said, I personally would use the second form. The basic idea of having a setter method is that at some point you might need some some special logic around setting that value (e.g. formatting input, sanitation, validation, etc). So it makes the most sense to always rely on any such logic being in one central place, rather than scattered throughout you code anywhere this variable is set.
If you have a truly trivial example, where the setter is simply setting the value and know absolutely that no other logic will ever be added, then you could certainly use the first form for simplicity. Put there's not real performance hit to the second form, so I personally would just use that.
I would use the individual getters/setters inside of the setHouse method (which is your second option).
The fact that you have setters indicates that there is some kind of encapsulation involved around that operation. Rather than re-write the code to enforce that encapsulation, re-use what you already have.
Jon's answer to that question (Taken from another question about using getters/setters which is not a duplicate to this one)
You don't always need getters/setters, but if you have some, there's usually a good reason why you've implemented them and in that case: use them.
Perhaps if you are getting and setting in two different places you might consider factoring out your getter and setter to a common interface. This can make later customisations easier, right?

Categories