Following the Fitnesse TestBlankAndNullCells documentation, I am trying to pass null fields into the verify tables. My data types are Strings.
When I leave the field blank, there is a solid red square with no information. When I try adding "null," the actual is empty. The same problem occurred using "blank". Am I missing something?
Here is more documentation on it, which states the keywords "blank" or "null" are required. I was able to manually return the string "null" as the actual, which works when the expected is also the literal "null," but I am hoping to find a cleaner solution in which I can pass in null fields.
According to this question on the Fitnesse forums, it looks like Strings are treated differently with null values.
In the Java world, there are some differences in the way nulls are handled between the 'classic' fixtures like ColumnFixture and the FitLibrary fixtures developed by Rick. My guess is the classic fixtures support the 'null' keyword but FitLibrary doesn't.
In the .NET world, the 'null' keyword is supported by all fixtures.
I found a solution after browsing the Fitnesse forums, straight from one of the developers for Fit, Rick Mugridge:
public String findString(String s) {
if ("".equals(s))
return null;
return s;
}
}
I included this in the ArrayFixture and it worked! Here are some interesting points from Rick's message:
When the myList() method is called for the second table, FitLibrary
automatically wraps it with a SetFixture (because the returned value is
a Set). When it checks each of the name elements, which are of type
String, it determines that there is a findString() method of the right
types, so it calls it to parse the value from the cells in the name
column. That method turns an empty string into a null so that it will
match correctly with the actual value of null.
For any type T, FitLibrary checks for a method public Object
findT(String s). It calls it to parse the String value from a table
cell. This can be used in several ways.
SetFixture, ArrayFixture,
etc will access private instance variables if necessary (eg, no
getter)
Arrays, Lists, Maps, Sets and other Objects are all
auto-wrapped with an appropriate fixture in flow
Flow occurs when
the first fixture in a DoFixture (In the next release, a DoFixture
doesn't need to be the first fixture for flow to occur; it just
starts later.)
Related
I get this suggestion from IntelliJ IDEA when using #Data annotation from lombok.
The class in question is an #Entity.
Can someone explain:
what does it do exactly (especially the part with Hibernate)
Is this method preferred over comparing every field one-by-one? If yes, why?
#Override
public boolean equals(Object o) {
if (this == o)
return true;
if (o == null || Hibernate.getClass(this) != Hibernate.getClass(o))
return false;
MyObject that = (MyObject ) o;
return id != null && Objects.equals(id, that.id);
}
The project contains/uses Spring boot, Hibernate, Lombok.
Thank you
There's a fundamental problem at work, one inherent to JPA/Hibernate. For this example, let's say we have a db table named User, and we have a class also named User that models it.
The problem boils down to simply this:
What does the java class User represent? Does it represent 'a row in the database table "User"', or does it represent a User?
Depending on your answer, you get a wildly different requirement for the equals method. Depending on which equals method you chose, answering this question incorrectly leads to code bugs. As far as I know, there is no actual 'standard', people just sort of do something and most aren't aware that this is a fundamental problem.
It represents a row in the DB
Such an interpretation would then suggest the following implementation of your equals method:
If all fields that model the primary key columns in the DB definition are equal between the two instances, then they are equal, even if the other (non-primary-key) fields are different. After all, that's how the DB determines equality, so java code should match it.
The java code should be like SQL when dealing with NULLs. That is to say, quite unlike just about every equality definition, equals method code generator (including lombok, intellij, and eclipse), and even the Objects.equals method, in this mode, null == null should be FALSE, as it is in SQL! Specifically, if any of the primary key fields have a null value, that object cannot be equal to any other, even a carbon copy of itself; to stick to java rules, it can (must, really) be equal to its own reference.
In other words:
Any 2 objects are equal if either [A] they are literally the same object (this == other), or [B] BOTH object's unid field is initialized and equal. Whether you use null or 0 to track 'not written to DB yet', that value instantly disqualifies that row from being equal to any other, even another one with 100% identical values.
After all, if you make 2 separate new objects and save() them both, they would turn into 2 separate rows.
It represents a user object
Then what happens is that the equals rules do a 180. The primary key, assuming its an unid style primary key and not a natural primary key, are inherently an implementation detail. Imagine that somehow in your DB you end up with 2 rows for the exact same user (presumably somebody messed up and failed to add a UNIQUE constraint on username, perhaps). In the semantic model of users on the system, users are uniquely identified by their username, therefore, equality is defined by username alone. 2 objects with identical username but different unid values are nevertheless equal.
So which one do I take?
I have no idea. Fortunately, your question asked for explanation and not an answer!
What IntelliJ is telling you is to go with the first interpretation (row in the DB), and even applies the wonky null stuff correctly, so whomever wrote the suggestion tool in intellij at least seems to understand what's going on.
For what its worth, I think 'represents a row in the DB' is the more 'useful' interpretation (because not doing this involves invoking getters which make equality checks incredibly pricey, as it may result in hundreds of SELECT calls and a gigantic bunch of heap mem as you pull half the DB in!), however, the 'an instance of class User represents a user in the system' is the more java-like interpretation and the one that most java programmers would (erroneously then, if you use intellij's suggestion here) silently presume.
I've solved this problem in my own programming endeavours by never using hibernate/JPA in the first place, and using tools like JOOQ or JDBI instead. But, the downside is that generally you end up with more code – you really do sometimes have an object, e.g. called UserRow, representing a user row, and an object e.g. called User that represents a user on-system.
Another trick could be to decide to name all your Hibernate model classes as XRow. Names are important and the best documentation around: This makes no bones about it and clues in all users of this code about how they are to interpret its semantic meaning: Row in DB. Thus, the intellij suggestion would then be your equals implementation.
NB: Lombok is java and not Hibernate specific, so it makes the 'represents a user in the system' choice. You can try to push lombok towards the 'row in DB' interpretation by telling lombok to only use the id field (stick an #EqualsAndHashCode.Include on that field), but lombok would still consider 2 null values / 2 0 values identical even though it shouldn't. This is on hibernate, as it is breaking all sorts of rules and specs.
(NB: Added due to a comment on another answer)
Why is .getClass() being invoked?
Java has sensible rules about what equals is supposed to mean. This is in the javadoc of the equals method and these rules can be relied upon (and are, by e.g. HashSet and co). The rules are:
If aequals(b) is true , a.hashCode() == b.hashCode() must also be true.
a.equals(a) must be true.
If a.equals(b) then b.equals(a) must also be true.
If a.equals(b) and b.equals(c) then a.equals(c) must also be true.
Sensible and simple, right?
Nope. That's actually really complex.
Imagine you make a subclass of ArrayList: You decide to give lists a colour. You can have a blue list of strings and a red list of strings.
Right now the equality method of ArrayList checks if the that is a list and if so, compares elements. Seems sensible, right? We can see it in action:
List<String> a = new ArrayList<String>();
a.add("Hello");
List<String> b = new LinkedList<String>();
b.add("Hello");
System.out.println(a.equals(b));
This prints true.
Let's now make our coloured arraylist implementation: class ColoredList<T> extends ArrayList<T> { .. }. Surely, a red empty list is no longer equal to a blue empty list right?
Nope, you'd be breaking rules if you do that!
List<String> a = new ArrayList<String>();
List<String> b = new ColoredList<String>(Color.RED);
List<String> c = new ColoredList<String>(Color.BLUE);
System.out.println(a.equals(b));
System.out.println(a.equals(c));
System.out.println(b.equals(c));
That prints true/true/false which is invalid. The conclusion is that it is in fact impossible to make any list subclass that adds some semantically relevant information. The only subclasses that can exist are those which either actively break spec (bad idea), or whose additions have no impact on equality.
There is a different view of things which says that you ought to be able to make such classes. Again we're struggling, just like with the JPA/Hibernate case, about what equals is even supposed to mean.
A more common and far better default behaviour for your equals implementations is to simply state that any 2 objects can only be equal if they are of the exact same type: An instance of Dog cannot be equal to an instance of Animal.
The only way to accomplish this, given that the rule a.equals(b)? Then b.equals(a) exists, is that animal checks the class of that and returns false if it isn't exactly Animal. In other words:
Animal a = new Animal("Betsy");
Cow c = new Cow("Betsy");
a.equals(c); // must return false!!
The .getClass() check accomplishes this.
Lombok gives you the best of both worlds. It can't perform miracles, so it won't take away the rule that at the type level you need to choose extensibility, but lombok has the canEqual system to deal with this: The equals code of Animal will ask the that code if the two things can be equal. In this mode, if you have some non-semantically-different subclass of animal (such as ArrayList, which is a subclass of AbstractList and doesn't change the semantics at all, it just adds implementation details that have no bearing on equality), it can say that it can be equal, whereas if you have one that is semantically different, such as your coloured list, it can say that none are.
In other words, going back to the coloured lists, IF ArrayList and co were written with lombok's canEqual system, this could have worked out, you could have had the results (where a is an arraylist, b is a red list, and c is a blur list):
a.equals(b); // false, even though same items
a.equals(c); // false, same reason.
b.equals(c); // false and now it's not a conflict.
Lombok's default behaviour is that all subtypes add semantic load and therefore any X cannot be equal to any Y where Y is a subclass of X, but you can override this by writing out the canEqual method in Y. You would do that if you write a subclass that doesn't add semantic load.
This isn't going to help you in the slightest with the problems above about hibernate.
Who knew something as seemingly simple as equality is hiding 2 intractably difficult philosophical treatises, huh?
For more info on canEqual, see lombok's #EqualsAndHashCode documentation.
I'm not trying to undermine ~rzwitserloot 's excellent answer, just trying to help you figure out why it uses Hibernate.getClass(this) for you instead of this.getClass().
It doesn't do it for me, but I don't have Hibernate in my project anyway.
The code is generated using velocity macros as seen here:
The IntelliJ default uses a file 'equalsHelper.vm'. I found a possible source of that file version at https://github.com/JetBrains/intellij-community/blob/master/java/java-impl/src/com/intellij/codeInsight/generation/equalsHelper.vm
It contains this:
#macro(addInstanceOfToText)
#if ($checkParameterWithInstanceof)
if(!($paramName instanceof $classname)) return false;
#else
if($paramName == null || getClass() != ${paramName}.getClass()) return false;
#end
#end
So apparently you have a different version of that file? Or you use a different template? Maybe some plugin changed it?
Two objects are not equal if they are of different class.
For 'preferred', it depends on what an 'id' is. The last line seems a little redundant; it could have been
return Objects.equals(id, that.id);
since the null case is handled by Objects.equals. But to my taste, it's clearer to write
return id != null && id.equals(that.id);
The extra layer adds nothing that I can see in the example.
So I have a constructor with 5 different variables, where three of which might be null. It accepts user input and the user does not have to enter anything for three of the five attributes.
Therefore, if the user did not enter anything, the object is created using null for all missing values.
obj = new Object(String, null, null, null, String);
Now I am wondering what would be best practice to cope with this.
I can think of three different scenarios:
Deal with it only in the class using the constructor, i.e. always query whether the value is null (e.g. if(getSomeAttribute == null) { //do something }
Deal with it within the object class, i.e. always return some default value for each missing attribute instead of null
Deal with it within the object lcass, i.e. have helper-methods like isAttributeSet(), returning a boolean value indicating whether the attributes are set, that is: not null.
Although I have problems with the last two, as I think I might run into problems with default values, as sometimes it might hard to know if it is a default value; if I'd always check I could just as well check for null instead of inserting a default value first;
Same with the last one, if I have to check the helper-method, I could just as well check for null directly.
What my problem is with this situation, is that sometimes I might not be the one using the getter and setter methods; how should the one using it know there might be null attributes and which that are.
I know, I should document that within my object class, but still I am wondering if there is a "best practice" way to cope with this.
I believe it should be unusual to always check the documentary (or if there is none, the whole class) for something as simple as this.
Maybe I should not even start with null values within my constructor in the first place? But I think I would run into the same kinds of problems, anyway, so that would not really solve my problem
Read Bloch, Effective Java, 2nd ed. Item 2: "Consider a builder when faced with many constructor parameters."
Excellent advice in an excellent book.
Using a builder pattern would help with the constructor, however the main problem is to do with the design of the class - you want to be sure when you call a get/set method that it isn't one of the null/optional members.
You could use polymorphism to have two objects each with an interface that only exposes the getters and setters supported by the concrete implementation. This makes it impossible to call the wrong getters/setters and it is obvious what the intention is.
This question already has answers here:
Avoiding NullPointerException in Java
(66 answers)
Closed 9 years ago.
I am writing codes that query the database to get the data. There are some classes that consist of Lists, but sometime the list or other attribute can not be initiated and their value is null, so I need to write list!=null || list.isEmpty or attribute != null, before I can use the attribute.
Unfortunately, it easy to forget it, and I really think it is ugly to do it every time when I operate an attribute. I am going to write some code to explain it.
public class SpotVo {
private Double avg;
private String brief;
private ArrayList<HotelVo> hotels;
private int id;
private ArrayList<byte[]> images;
private AddressVo location;
private String name;
private ArrayList<RestaurantVo> restaurants;
}
As you can see, there are some lists and other attributes in this class, there can all be null or empty, can I do something to avoid it?
The answer depends on whether null has a special meaning. For example for a String field does your application need to distinguish between null and ""? For a Collection-valued field does it need to distinguish between null and an empty collection object?
If the answer is "no", then you could write your "data object" classes to normalize the nulls to the respective "in band" values. You could do this in the getters or the setters or the constructors, depending on exactly how the objects are materialized from the database.
A couple of other things you could do are:
Change the database schema to make the respective columns "not null".
If you are using an ORM or a data binding mechanism, try to configure that (via annotations or whatever) to use the "in band" values instead of null.
The point of turning null into "" or an empty array or collection is that you don't need to treat the "in band" value as a special case ... unless the business logic of your application specifically requires this.
In short, if you stamp out the null values systematically, you don't need to test for them in the business logic.
Note that this approach doesn't always work. The case that annoys me is fetching parameters from an HTTPRequest object in a servlet:
The application potentially has to deal with 4 distinct cases:
parameter not present
parameter present with no value / an empty value
parameter present with a non-empty value
parameter present multiple times.
The parameters are being fetched from a standard API rather than a custom class that could be made to normalize the values according to the webapp's requirements.
The easiest way to solve this is with CollectionUtils.isEmpty.
Returns: true if empty or null
This way you can do it in one line.
When it comes to "attributes", there are design patterns that can help with this. Or, you can use Guava's Optional class. You can read more about it here: What's the point of Guava's Optional class
You can write a function that checks if an object is null and/or if it's a String, is it "". Then simply call that function each time you would need to check all of the conditions. Make it return a boolean so that you can just insert it in the if statements.
boolean check(Object o)
{
if (o != null)
{
if (o instanceof String)
{
if (((String) o).equals(""))
return false;
}
return true;
}
return false;
}
Refer to rcook's suggestion in the comments for a better implementation of this.
I think there's two problems here:
One is that you have to check for null values which I absolutely agree is stupid. The problem is that null is a native to the Java language, so the only way to make it slightly nicer is to use methods like the ones mentioned by Steve P and tieTYT. There is however another way of dealing with null by never using it. Of course you cannot completely avoid it, but at least in your own code you should eliminate all null-references. There are a few great arguments for that which I won't cover here, but you can read Avoiding != null statements for more details.
If you're interested a Java-based language, Scala, have developed this nicely by implementing an Option class that can tell whether a value exists or does not (equal to the null value). Nice blog post about it here: http://jim-mcbeath.blogspot.fr/2008/10/avoiding-nulls.html
Having (mostly) stowed the null-issue away, the next problem will be to check for isEmpty or similar when using collections. This is, as you say, a pain in the arse. But I've actually found that these checks can be largely avoided. It all depends on what you need to do with your collection of course, but in most cases collections are used for traversing or manipulation in some way. Using the foreach-loop in Java will make sure nothing is performed if nothing is in the collection. Neat.
There are some cases where a collection must not be empty. Some of these can be avoided though, by having a good design (for instance one that allows empty lists, ensures that no list are empty etc.), but, for the rest of them there are simply no way around. Ever. But, having eliminated the null-checks, calling a few isEmpty now and then isn't that bad :-)
Hope that helped.
C# is the language I am most comfortable with but do Java when at work. I guess you can say I am very comfortable with using the Visual Studio IDE. One of the things I enjoyed about its debugger is that I can put watch variables ("Expressions" in Eclipse) for any expression. So I could take a peek at values of specific fields public or non-public, call methods, etc. with no problem as I am debugging.
It doesn't seem like I can do the same in Eclipse. I have to resort to calling the associated getter method for the field (assuming it has one). If it doesn't have one, I either have to temporarily add one so I can view it and remember to remove it when I'm done or I'm just SOL.
How can I put a watch expression for an object on one of its private fields? Or am I just doing it wrong and I have to craft special expressions to view them?
(Or is there a better way for me to get the information that I want?)
e.g.,
I have an HttpServletRequest and want to keep an eye on the requestURI. If I just watch the request variable, it lists a lot of its fields and it's just too much information. I'm only interested in one thing in the object so to minimize this, I want to add a watch expression for that one thing.
The field name is apparently requestURI so I added the expression: request.requestURI. Eclipse throws an error saying it's not a field (it is, it's just not public). Instead of going directly to the field, I had to go to the getter: request.getRequestURI() and that works fine. But I can't always count on the getter being available.
The Variables view
The Expressions view
The Eclipse evaluates expression considering the private/protected fields of Declared Type, not of Actual Type.
Example:
Number n1 = new Integer(1000);
Integer n2 = new Integer(1000);
Expressions:
n1.value can't be evaluate
n2.value returns 1000, perfectly
An alternative is use DetailFormatter (right-click in variable > New Detail Formatter).
The Eclipse will use this expression instead of toString() method when the textual representation of a object of type is displayed (in Variables View, for example).
Your DetailFormatter (for ApplicationHttpRequest) can be:
requestURI
or
"URI: " + requestURI + "\n" +
"Path: " + servletPath
Doesn’t matter if the field is private or protected, eclipse expressions will evaluate correctly. But the scope of variable matters.
Correct me if i am wrong.
requestURI is a protected field in org.apache.catalina.core.ApplicationHttpRequest which implements HttpServletRequest. In your case variable request is of type HttpServletRequest and you are trying to access HttpServletRequest.requestURI and this field Doesn’t exist and eclipse fails. I think it's normal. May be if you do proper casting, expression will evaluate correctly.
Writing an expression in the Expressions view evaluates just as if you had written a line of code, and just executed it prior to the currently highlighted line. There is one difference that I know about (probably others to, but this is the important one) which is that you can bypass the class accessor visibility restrictions, and see private, protected and default members that the current stack frame perhaps couldn't.
That said the expression does require you to have the correct kind of reference. If you inserted this line in to code, the java compiler would complain that requestURI is not a field of HttpServletRequest. And therefore, you need to cast to the class (or subclass of) that actually declares the field: ApplicationHttpRequest.
Now, why they didn't bother exposing the same magic in Expressions as they do in Variables where as you point out they list ALL members of the concrete class even if the declared type wouldn't show them, I couldn't say.
In Eclipse while debugging, you can right-click on a variable and click on the Watch menu item. In the Debug perspective it will add an Expressions tab that will have a list of variables you are watching. I'm not sure how to do it in the other IDE's.
Is it a bad practice to pass NULL argument to methods or in other words should we have method definitions which allow NULL argument as valid argument.
Suppose i want two method
1. to retrieve list of all of companies
2. to retrieve list of companies based upon filter.
We can either have two methods like as below
List<Company> getAllCompaniesList();
List<Company> getCompaniesList(Company companyFilter);
or we can have one single method
List<Company> getCompaniesList(Company companyFilter);
here in second case, if argument is NULL then method return list of all of companies.
Beside question of good practice practically i see one more issue with later approach which is explained below.
I am implementing Spring AOP, in which i want to have some checks on arguments like
1. Is argument NULL ?
2. is size of collection 0?
There are some scenarios where we can not have null argument at all like for method
void addBranches(int companyId, List<Branch>);
This check can be performed very well by using Spring AOP by defining method like following
#Before(argNames="args", value="execution(* *)")
void beforeCall(JoinPoint joinPoint ,Object[] args )
{
foreach(Object obj in args)
{
if(obj == NULL)
{
throw new Exception("Argument NULL");
}
}
}
But problem i am facing is since i have defined some of methods which should accept NULL argument for multiple functionality of one single method as mentioned above for method List getCompaniesList(Company companyFilter);
So i can not apply AOP uniformly for all of methods and neither some expression for methods name match will be useful here.
Please let me know if more information is required or problem is not descriptive enough.
Thanks for reading my problem and giving thought upon it.
It's fine, in cases when there are too many overloaded methods. So instead of having all combinations of parameters, you allow some of them to be null. But if you do so, document this explicitly with
#param foo foo description. Can be null
In your case I'd have the two methods, where the first one invokes the second with a null argument. It makes the API more usable.
There is no strict line where to stop overloading and where to start relying on nullable parameters. It's a matter of preference. But note that thus your method with the most params will allow some of them to be nullable, so document this as well.
Also note that a preferred way to cope with multiple constructor parameters is via a Builder. So instead of:
public Foo(String bar, String baz, int fooo, double barr, String asd);
where each of the arguments is optional, you can have:
Foo foo = new FooBuilder().setBar(bar).setFooo(fooo).build();
I use a very simple rule:
Never allow null as an argument or return value on a public method.
I make use of Optional and Preconditions or AOP to enforce that rule.
This decision already saved me tons of hours bugfixing after NPE's or strange behaviour.
It's common practice, but there are ways of making your code clearer - avoiding null checks in sometimes, or moving them elsewhere. Look up the null object pattern - it may well be exactly what you need: http://en.m.wikipedia.org/wiki/Null_Object_pattern?wasRedirected=true
The rule is: simple interface, complicated implementation.
Design decisions about your API should be made by considering how the client code is likely to use it. If you expect to see either
getAllCompaniesList(null);
or
if (companyFilter == null) {
getAllCompaniesList();
} else {
getAllCompaniesList(companyFilter);
}
then you're doing it wrong. If the likely use-case is that the client code will, at the time it is written, either have or not have a filter, you should supply two entry points; if that decision is likely not made until run-time, allow a null argument.
Another approach that may be workable may be to have a CompanyFilter interface with an companyIsIncluded(Company) method that accepts a Company and returns true or false to say whether any company should be included. Company could implement the interface so that companyIsIncluded method's behavior mirrored equals(), but one could easily have a singleton CompanyFilter.AllCompanies whose companyIsIncluded() method would always return true. Using that approach, there's no need to pass a null value--just pass a reference to the AllComapnies singleton.