Eclipse: Create getters with java.util.Optional for String members - java

In eclipse you can easily create getters and setters for your classes' fields.
Before:
package main;
public class TestClass {
private String someString;
private boolean someBoolean;
}
After creating the getters (as we don't care for setters in this question):
package main;
public class TestClass {
private String someString;
private boolean someBoolean;
/**
* #return the someString
*/
public String getSomeString() {
return someString;
}
/**
* #return the someBoolean
*/
public boolean isSomeBoolean() {
return someBoolean;
}
}
But if you do not initialize the String value getSomeString() will return null, meaning that if I want to work with the String in the calling object, I have to always check if for null first.
To avoid this I found some solutions:
Initialize the Strings immediately at their declaration: private String someString = "";
Reflections
return someString == null ? someString : "";
Using java.util.Optional
there are probably many more ways...
While writing this question I figured out that probably for the simple String case the first method should work best: I can easily initialize the Strings to whatever I like and am done.
The reflection approach linked above seemed okay, but a bit messy to handle
exceptions where a String should not be initialized with the empty string.
The null check is okay but now with Java 8 the last method, employing java.util.Optional feels like the right way to do that. I would do it like this:
public String getSomeString() {
return Optional.ofNullable(someString).orElse("");
}
Is it possible to get eclipse's code templates into creating getters like this one for Strings (or all non-primitive types) only?
The standard template used (see Project -> Properties -> Java Code Style -> Code Templates -> Code -> Getter body) is:
return ${field};
I can replace it with
return java.util.Optional.ofNullable(${field}).orElse("");
which helps for Strings - but for all other types it obviously fails.
So I tried
${:import(java.util.Optional)}
return Optional.ofNullable(${field}).orElse(new ${return_type}());
which is not allowed, because Variable 'return_type' is not known. and additionally the ${:import(java.util.Optional)} is not solved as the help makes you believe (I assume it is because Code Templates are just a stricter subset of Templates, more or less). The first makes sense - if ${return_type} is a primitive, this is likely to fail.
Is there a way to make it happen that eclipse generates such custom getters for me? This answer allows to create such getter for one field, but that would mean I had to do it for each field individually. Is it possible to also just have it done by Source -> Generate getters/setters (or any other similar method)?
Or do you think it's best to initialize such objects at their declaration anyway?

Related

Java String predefine

I'm sure this question has allready been answered somewhere, but I' ve searched for half an hour now and I'm running out of keywords, because I have absolutly no idea how to do this.
I have a constructor for a class like this
public MyClass (String name)
{}
what I want is to define Strings so that only those Strings can be entered.
I assume it has something to do with static final strings, but there is quite a lot to be found to those and I dont know how to narrow down the search. Please tell me how that thing I want to do is called, so that I can search for it.
Edit:
Example to what I want:
I want to somehow define a number of Strings. (Or do somethig else that has the same effect, as I said I dont know how to do it)
String one = "ExampleOne";
String two = "ExampleTwo";
so that when I call the constuctor
MyClass myClass = new MyClass("somethingElse");
the constructor wont take it. Or even better eclipse allready showing my what options I have like it does whit "Color. "
Yes you have right you can not override String class because it is final so simply you can create your own StringWrapper class that wraps string.
public class StringWrapper{
private String content;
public StringWrapper(String c){
content = c;
}
//all your methods and fields there, for example delegated methods
public String toString(){
return content.toString();
}
}
But Enum could be also used in your case then you define your Enum values
public enum Color {
WHITE, BLACK, RED, YELLOW, BLUE; //; is required here.
#Override public String toString() {
//only capitalize the first letter
String s = super.toString();
return s.substring(0, 1) + s.substring(1).toLowerCase();
}
}
public myClass (Color color)
{}
There are two ways you can acheive this, either use a enum as constructor parameter. The enum itself contains only the allowed values, which is what I would do, keep everythign nice an oop and you can add logic to enums at a later date.
Or alternatively you can just check if the constuctor paramters value is valid, by performing a comparison and throwing an exception if not in allowed values. Have a predfined list and then, myList.contains(myString) - throw exception if false.
What I want is to define String so that only those Strings can be entered
I think that what you are after are Enums.
Enums will allow you to define a range of values which you can then use. In the example I have linked, the developer can restrict the type of input that he/she will receive to the days of the week.
You can check it in constructor's body at runtime, or if you want to compile-time checks, then you can use enum type argument (enum is a predefined set of constants).
From what I understand it seems like you want to limit what the String can be.
You would do this by putting conditional statements inside the constructor to weed out any Strings you don't want to be entered that would either notify the user that it is an invalid string or throw an exception, and the remainder of the constructor would only be executed in an else statement once it has passed all the tests making sure it is a valid String

Set custom variables from method

I have some String variables:
private String cur, last, avg, vol, shop;
I have method which accept String and gives me some result:
public void SomeMethod(String somestring)
{
//Here some action with `string`
System.out.print(result)
}
So i want to put result into one of String variables, but this variable must be named as value of somestring in my method. Some method which compare somestring with existent variables names. Is such a thing even possible?
You're talking about variable variable name. They're a native feature in PHP, but not in Java, however you can achieve similar functionality using a HashMap, or using Reflection. I'm going to show you the HashMap option, because frankly Reflection is the work of Satan.
Example
Now the way to implement this is like this:
public void someMethod(String name, String value)
{
values.put(name, value);
}
And you can retrieve them with
public void getValue(String name)
{
return values.get(name);
}
I won't write the code for you, because it's a simple transformation to get this to work in your use case.
A hint because I'm feeling nice
You can replace all of your String variables with a Map implementation. Then simply add the values to the Map, as and when the need arises.

What is the Java convention for using get methods inside other methods of the same class?

After I have written a get method in a java class, is it better to use the get method in the same class or the variable itself?
For example:
if(a.getWidth()>this.getWidth())
or:
if(a.getWidth()>this.width)
Also I am confused if i should be using the this.anything so much. It seemed easier to read when comparing objects of the same type to each other.
is it better to use the get method in the same class or the variable
itself?
IMHO use the variable. Accessor methods are primarily for other objects to use.
Also I am confused if i should be using the this.anything so much. It
seemed easier to read when comparing objects of the same type to each
other.
It's not always required for you to explicitly use the this reference..it's mainly used for readability, like you said.
I think that using the getter methods are better for mantainability. Consider the Null Object pattern which a way to achieve is by making this:
public String getName(){
if (this.name == null){
this.name = "";
}
return this.name;
}
This should save you from checking up a lot of null before operating with the variable.
public boolean isCorrect(){
if(this.name != null && this.name.isEmpty()){
//The null check up is boilerplate code
return false;
}else{
return true;
}
}
I'd rather write this:
public boolean isCorrect(){
if(this.getName().isEmpty()){
//The null check up is boilerplate code
return false;
}else{
return true;
}
}
Of course, this depends if you adopt this pattern.
Also consider that you have
double width;
double height;
public double getWidth(){
return this.width;
}
but at some point you decide to change it for a class but still have the methods so your program doesn't break down.
Dimension dimension;
public double getWidth(){
return this.getDimension().getWidth();
}
// etc...
Finally (as commented by MadProgrammer), when you use inheritance, the methods can be overridden to represent better the intended object.
1) It may seem from inside a class that there is no difference between using field and getter but what if a getter is overridden by a subclass?
class A {
String name;
String address;
String getName() {
return name;
}
String getAddress() {
return address;
}
String getDescription() {
return name + " " + address;
}
}
class B extends A {
String country;
#Override
String getAddress() {
return super.getAddress() + ", " + country;
}
}
B.getDescription() is expected to return an extended address but it wouldnt. It would if A.getDescription() was implemented as
return getName() + " " + getAddress();
2) I personally dont use this for readability because IDE marks this with a different color
The use of this is not necessary unless you have a case (such as in a constructor) where a parameter has the same name as a field.
For accessing properties, it may be beneficial in the long run to use the public getters, because you may want to add some form of processing to the property, and if you use getters everywhere, you only have to make that change once.
If your get method returns the data with some formatting, you have to use the get method, otherwise, the variable itself will be fine to use.
this is only required if your method parameters are same as your member variables, otherwise, this is not compulsory.
For example:
private String str;
public void setString(String str){
this.str = str; // here this.str is necessary because this represents the memeber variable
}
public String getString(){
return this.str; // here this is optional and you can simply omit it
}
You can use either the accessor or the variable itself, its one of those personal preference things.
Some people like to use the variable itself because you don't have the overhead of calling a function. But, if you have any restrictions on the values your variables can be, sometimes it is just cleaner to only use your accessors and mutators; especially if you are going to be subclassing. But its one of those things that can go either way.
The way that I like to use the this keyword, is I always use it for instance variables. I find that it makes the code easier to read because you can visually determine where you are using instance variables, and where you are using local variables. Again this is a personal preference thing.
The main thing is to make sure your code is clean, and readable. Also, make sure that you are following whatever coding standard your organization is using, and be sure to be consistent.

Any standard pattern or strategy for making Null Object Immutable

In java, we prefer null object pattern than cluttering the code with not null check in all referencing. Recently we faced a problem over using null object by keeping a singleton object.
Assume we have Person class as below
public class Person {
public String firstName;
public String lastName;
public boolean isNull() {
return false;
}
public static final Person NULL = new Person() {
public boolean isNull() { return true; }
}
}
In this case, though I have declared NULL object as final, I can still modify the member variable and its available globally.
Person nullRef = Person.NULL;
Person.NULL.firstName = "sample";
System.out.println(nullRef.firstName);
In this case, its just three fields and I could solve mutability problem by overriding those three getter methods. But pratically there will be many fields which will be tough to override all corresponding getter methods.
Is there any standard pattern or strategy to solve this mutability issue in NULL objects?
Use Optional From Google Guava library
Optional<Integer> possible = Optional.of(5);
possible.isPresent(); // returns true
possible.get(); // returns 5
Quoting the library documentation:
Besides the increase in readability that comes from giving null a
name, the biggest advantage of Optional is its idiot-proof-ness
This is more natural way of dealing with null objects
Optional Google Guava
You need to have two levels of interface: One for the immutable part (only getters and immutable methods) and one for mutable parts that extends the immutable interface. Then the code needs to be refactored to only use the most restrictive interface possible in all relevant places.
So
public interface ImmutablePerson {
final String getFirstName();
}
public interface MutablePerson extends ImmutablePerson {
final void setLastName(final String newName);
}
Yes, now MutablePerson "is a" ImmutablePerson, but only when used as one :)
Additionally, the isNull check indicates that you need to think more about inversion of control.
To be concrete:
When you find yourself writing code like
if (!person.isNull()) {
person.setLastName("Foo");
}
You should instead just use your Null Object and think of it as a neutral element insted. Like so:
First:
final Person NullPerson = new Person() {
void setLastName(final String newName) {
// Do nothing, this is a neutral (Null) object
}
}
...and then later:
// Never need to check for isNull ever again - null objects just decide to ignore your request
person.setLastName("Foo");
You need to make all the fields "private" so that these are not accessible outside except for the getter code.
You need to modify "setter" methods and not the getter ones for making it immutable.
For eg.
public String setFirstName(String name){
if(!isNull()){
firstName = name;
}
}

Assert that two java beans are equivalent

This question is close, but still not what I want. I'd like to assert in a generic way that two bean objects are equivalent. In case they are not, I'd like a detailed error message explaining the difference instead of a boolean "equal" or "not equal".
import static org.hamcrest.beans.SamePropertyValuesAs.samePropertyValuesAs;
import static org.junit.Assert.assertThat;
#Test
public void beansAreTheSame(){
MyDomianClass bean1 = new MyDomainClass();
MyDomianClass bean2 = new MyDomainClass();
//TODO - some more test logic
assertThat(bean1, samePropertyValuesAs(bean2));
}
I recommend you use unitils library:
http://www.unitils.org/tutorial-reflectionassert.html
public class User {
private long id;
private String first;
private String last;
public User(long id, String first, String last) {
this.id = id;
this.first = first;
this.last = last;
}
}
User user1 = new User(1, "John", "Doe");
User user2 = new User(1, "John", "Doe");
assertReflectionEquals(user1, user2);
See also:
Is there a Java reflection utility to do a deep comparison of two objects?
NUnit - Assert to check all properties are equal?
You can use Commons Lang's ToStringBuilder to convert both of them into readable strings and then use assertEquals() on both strings.
If you like XML, you can use java.lang.XMLEncoder to turn your bean into XML and then compare the two XML documents.
Personally, I prefer ToStringBuilder since it gives you more control over the formatting and allows you to do things like sorting the elements in a set to avoid false negatives.
I suggest to put each field of the bean in a different line to make it much more simple to compare them (see my blog for details).
You can set all fields like this:
import static org.hamcrest.MatcherAssert.assertThat;
import static org.hamcrest.Matchers.allOf;
import static org.hamcrest.beans.HasPropertyWithValue.hasProperty;
import static org.hamcrest.Matchers.is;
#Test
public void test_returnBean(){
arrange();
MyBean myBean = act();
assertThat(myBean, allOf(hasProperty("id", is(7L)),
hasProperty("name", is("testName1")),
hasProperty("description", is("testDesc1"))));
}
I think, the most generic approach is to reflect the bean members and test them for equality one-by-one. The common lang's EqualsBuilder is a good start and it should be not a big deal, to adapt it (on source level) to your requirements (reporting the differences instead of returning the equals result).
For unit testing this can be done with JUnit and Mockito using ReflectionEquals. When implementing in the following manner, it will dump the JSON representations of the objects when any fields are not equal which makes it easy to find the offending difference.
import static org.junit.Assert.assertThat;
import org.mockito.internal.matchers.apachecommons.ReflectionEquals;
assertThat("Validating field equivalence of objects", expectedObjectValues, new ReflectionEquals(actualObjectValues));
Since you didn't like the answers in the question you referenced, why not just have a toXml method in each bean, turn them into an xml file and then use xmlUnit to compare.
You can get more info on comparing xml files here:
Best way to compare 2 XML documents in Java
You're not really asserting equality, more doing a "diff". Clearly, the meaning of "same" depends upon particular logic for each type, and the representation of the difference also may vary. One major difference between this requirment and a conventional equals() is that usually equals() will stop as soon as the first difference is seen, you will want to carry on and compare every field.
I would look at reusing some of the equals() patterns, but I suspect you'll need to write your own code.
I am assuming here that both beans are of the same type, in which case only the member variable values will differ across bean instances.
Define an util class (public static final with private ctor) called, say, BeanAssertEquals. Use Java reflection to obtain the value of each member variable in each bean. Then do an equals() between values for the same member variable in different beans. If an equality fails, mention the field name.
Note: member variables are usually private, so you would need to use reflection to temporarily change the accessibility of private members.
Additionally, depending how fine-grained you want the assertion to work, you should consider the following:
Equality of member variables not in the bean class but all superclasses.
Equality of elements in arrays, in case a member variable is of type array.
For two values of a given member across beans, you might consider doing BeanAssertEquals.assertEquals(value1, value2) instead of value1.equals(value2).
(to build on my comment to Andreas_D above)
/** Asserts two objects are equals using a reflective equals.
*
* #param message The message to display.
* #param expected The expected result.
* #param actual The actual result
*/
public static void assertReflectiveEquals(final String message,
final Object expected, final Object actual) {
if (!EqualsBuilder.reflectionEquals(expected, actual)) {
assertEquals(message,
reflectionToString(expected, ToStringStyle.SHORT_PREFIX_STYLE),
reflectionToString(actual, ToStringStyle.SHORT_PREFIX_STYLE));
fail(message + "expected: <" + expected + "> actual: <" + actual + ">");
}
}
This is what I use, and I believe it meets all basic requirements. By doing the assert on the reflective ToString then Eclipse will highlight the difference.
While Hamcrest can offer a much nicer message, this does involve a good deal less code.
The first quesion I'd have to ask if is, do you want to do 'deep' equals on the Bean? does it have child beans that need to be tested? You can override the equals method, but this only returns a boolean, so you could create a 'comparator' and that could throw an exception with a message about what was not equal.
In the following examples, I've listed a few ways to implement the equals method.
if you want to check if they are the same object instance, then the normal equals method from Object will tell you.
objectA.equals(objectB);
if you want to write a customer equals method to check that all the member varibles of an object make them equal then you can override the equals method like this...
/**
* Method to check the following...
* <br>
* <ul>
* <li>getTitle</li>
* <li>getInitials</li>
* <li>getForename</li>
* <li>getSurname</li>
* <li>getSurnamePrefix</li>
* </ul>
*
* #see java.lang.Object#equals(java.lang.Object)
*/
#Override
public boolean equals(Object obj)
{
if ( (!compare(((ICustomer) obj).getTitle(), this.getTitle()))
|| (!compare(((ICustomer) obj).getInitials(), this.getInitials()))
|| (!compare(((ICustomer) obj).getForename(), this.getForename()))
|| (!compare(((ICustomer) obj).getSurname(), this.getSurname()))
|| (!compare(((ICustomer) obj).getSurnamePrefix(), this.getSurnamePrefix()))
|| (!compare(((ICustomer) obj).getSalutation(), this.getSalutation())) ){
return false;
}
return true;
}
The last option is to use java reflection to check all the member varibles in the equals method. This is great if you really want to check every member varible via its bean get/set method. It wont (I dont think) allow you to check private memeber varibles when testing of the two objects are the same. (not if your object model has a circular dependancy, dont do this, it will never return)
NOTE: this is not my code, it comes from...
Java Reflection equals
public static boolean equals(Object bean1, Object bean2)
{
// Handle the trivial cases
if (bean1 == bean2)
return true;
if (bean1 == null)
return false;
if (bean2 == null)
return false;
// Get the class of one of the parameters
Class clazz = bean1.getClass();
// Make sure bean1 and bean2 are the same class
if (!clazz.equals(bean2.getClass()))
{
return false;
}
// Iterate through each field looking for differences
Field[] fields = clazz.getDeclaredFields();
for (int i = 0; i < fields.length; i++)
{
// setAccessible is great (encapsulation
// purists will disagree), setting to true
// allows reflection to have access to
// private members.
fields[i].setAccessible(true);
try
{
Object value1 = fields[i].get(bean1);
Object value2 = fields[i].get(bean2);
if ((value1 == null && value2 != null) ||
(value1 != null && value2 == null))
{
return false;
}
if (value1 != null &&
value2 != null &&
!value1.equals(value2))
{
return false;
}
}
catch (IllegalArgumentException e)
{
e.printStackTrace();
}
catch (IllegalAccessException e)
{
e.printStackTrace();
}
}
return true;
The one thing that this does not do it to tell you the reason for the difference, but that could be done via message to Log4J when you find a section that is not equal.
The xtendbeans library could be of interest in this context:
AssertBeans.assertEqualBeans(expectedBean, actualBean);
This produces a JUnit ComparisonFailure à la:
expected:
new Person => [
firstName = 'Homer'
lastName = 'Simpson'
address = new Address => [
street = '742 Evergreen Terrace'
city = 'SpringField'
]
]
but was:
new Person => [
firstName = 'Marge'
lastName = 'Simpson'
address = new Address => [
street = '742 Evergreen Terrace Road'
city = 'SpringField'
]
]
You could also use it just to get the textual representation for other purposes:
String beanAsLiteralText = new XtendBeanGenerator().getExpression(yourBean)
With this library you can use the above syntactically valid object initialization code fragment to copy/paste it into a (Xtend) source class for the expectedBean, but you don't not have to, it can perfectly well be used without Xtend as well.

Categories

Resources