Which approach of checking beeing valid is better? The first one:
public class Order {
...
private boolean valid;
public boolean isValid() {
return valid;
}
public boolean setValid(boolean valid) {
this.valid = valid;
}
// getters, setters, etc.
}
where valid is kept as boolean in DB and set by Java code somewhere else, e.g. in DAO.
Or the second one:
public class Order {
...
public boolean isValid() {
// some business code, e.g.:
return !orderItems.isEmpty();
}
// getters, setters, etc.
}
where we don't have valid value keeped in DB, but everytime when it's needed it is been calculated on demand.
Which approach is better?
In the first example you are treating 'valid' as a POJO field, ie just like a getter() or setter() method, except because it is boolean it is an isser() method. This is OK, as I would not break this bean-like pattern. Getters and setters should have no logic behind them.
Insetad I would have another method validate() which does the heavy stuff.
validate() performs the validation and sets the valid variable. isValid() returns the last validation performed.
An antipattern I often see is a getXXXXX() method which takes about 30 seconds to complete because it is performing calculations and database hits, confusing the user of this class as the user assumes it is a normal getter in a normal POJO class.
There's no exact answer. It just depends. Depends on the design of your class and the business rules of your business.
For example, if the valid state of an order only checks for a simple rule like checking the current state of the object reference, then have it as a method with a body.
public class Order {
public boolean isValid() {
//validate current state of object reference
//re using your same example
return !orderDetail.isEmpty();
}
}
But in the case you have a business rule that demands the order should pass for a validation process before sending it to the client and this status (and a proper description) should be known at any moment of the application, then having a valid field in database is one way to solve it. In fact, if this was the case, it would be even better to store the valid field as a VARCHAR(X) and limit the values of this field by using an enum OrderStatus. But then again, this depends on the design for your class.
Fisrt structure with setValid method is ugly. I can not imagine the usage of setValid method.
If you want to use separate property, the better way is to use lazy initialization:
public class Order
{
...
private Boolean valid;
public boolean isValid()
{
if (valid == null)
{
valid = !orderItems.isEmpty();
}
// some business code, e.g.:
return valid;
}
}
If isValid method contains hard logic and your class is immutable (orderItems is a constant) then you can use this variant.
In other cases second variant is better.
Related
How to write junit test case to test the duplicate value in the userList below mentioned in the code
public List<User> getUsersNotInCurrentGroup()
{
List<User> userList = null;
userList = getEntityManager().createQuery("select * from User")
return userList;
}
I suppose, in this specific case, you should at least know what makes an User unique.
Then add a second SQL query with the distinct clause and compare if the sizes of both returned collections. It the collections have the same size there are no duplicates.
And would be much easier if you compare the size returned by SQL count(1) for each query.
But then this is not a Java Unit test anymore, becomes a kind of DB unit test :)
The proper way to write a test for duplicates depends on what your application defines as a duplicate.
In Java, every object inherits the method equals(Object obj) from the Object class. Unless your User object overrides that method, no two User objects saved in the list will considered equal, because the equals() method compares the hash code representing the object and not the values of the data stored in that object.
If you can conceive of ever needing to check whether two User objects are the same anywhere else in the application, your best bet would be to override equals(Object obj) so that it compares the values your application considers relevant for determining if the two User objects are the same.
For example:
public class User {
private int ID;
private String nickname;
private String email;
...
#Overrides
public boolean equals(Object obj) {
if (obj.getClass() != User.getClass()) {
return false;
} else {
if (obj.getId() == this.getId() &&
obj.getEmail().equals(this.getEmail()
) {
return true;
} else {
return false;
}
}
}
}
In this example, the way to determine if one User is a duplicate of another, we check whether the ID and email of the two objects are the same, but we don't care if the nickname field is different. That determination is purely based on the business need.
Once you have this method in place you can iterate through the list to see if a given object is the same as any of the other objects in the list using the equals() method to compare them.
As a side note, if you are just generally concerned about having a collection without any duplicates, you can use a Set instead of a List, which will call that equals() method that you overrode to compare objects for you.
What is the best approach to validate the arguments for null while calling a method?
1) before making the method call
private void myMethod(String param1, String param2){
String a = param2;
if(StringUtils.isNotBlank(a)){
validate(a);
}
}
private void validate(String a) {
int temp = Integer.parseInt(a);
if(a > 4){
addError()
}
}
2) inside the method once you receive the arguments
private void myMethod(String param1, String param2){
String a = param2;
validate(a);
}
private void validate(String a) {
if(StringUtils.isNotBlank(a)){
int temp = Integer.parseInt(a);
if(a > 4){
addError()
}
}
}
OR Both
IMO, StringUtils.isNotBlank(a) is some form of validation only, so it should be in validate() method. And if that has to be checked every time you call validate() method, then certainly it will make more sense to move it there.
From the two approaches you give, the second is better.
Reason: DRY principle (Don't Repeat Yourself aka avoid code duplication).
The code in the first snipped duplicates (or triplicates, etc) the "check for blank" part of the code for every place validate() is called.
Also the responsibility of the consistency, the "not blank" invariant (a domain/business rule), belongs (is inherent) to the validate() method, so it should have the responsibility for taking care of it.
In practical terms: Consider the possibility of a change to this domain rule, if one needed to add some new check to it, in what case you'd have to change less (thus less error-prone)? Where the developer that'll do the change would expect to find such rule? In the validate() or scattered through the whole code base?
If that error validation is useful everytime you call some method, it obviously should be done inside the method, or else you would have to do it everytime before calling that method. Just remember to comment the code, so you remember that later.
Conceptually the validate() method should capable to identify that the passing parameter is null or not. So in your given scenario the approach 2 should be preferable.
Would be inside the method throwing a java.lang.IllegalArgumentException.
Like:
private void validate(String a) {
if(StringUtils.isNotBlank(a)){
int temp = Integer.parseInt(a);
if(a > 4){
addError()
}
}
else{
throw new IllegalArgumentException("argument must not be null or blank");
}
}
What is the best approach to validate the arguments
IMO, your second approach is better one
because it is not a task for which you have to provide a separate method, it is just a parameter validation which is part of same logic which you are going to implement in your method. and another thing to be considered is second approach will form higher redability of your code.
OR Both
NEVER, Choose one as per your coding practice and stick to it.
Other considerations for validation :
Check parameters annotated with #Nonnull for null?
You can use assertion for Private arguments.
I'm new to Java and have the following question:
Is there an easier way of making methods for each variable?
The meaning behind the question is:
Do I have to define a method that does the exact same thing as other methods except that they use different variable names and types?
I think the most common methods with the same problem are the get- and set-accessors:
They share the same structure, the only difference are the variable types and names.
In my following example, you need to know:
Variables varA-varD just represent the existance of multiple variables with various types and names.
The variable "inheritor" is special. I do NOT implement inheritance, but I DO have to verify that somewhere, maybe in the inheritor of the inheritor of the inheritor the same variable
has a value ("!= null"; in case of Lists, HashMaps, Enumerations, etc.)
or
has a value other than -2 (because 0 means nothing and -1 indicates "infinite" in my system, so I thought using -2 for indicating that the variable hasn't been set yet is a good idea; in case of Integers, Floats, Doubles, etc.).
I have verification methods...
...to check whether the variables have already been set (or not)
and for this reason the code is located
...outside of the setter because I have to check the variables even when they have not been set yet.
public class ExampleClass {
private int varA;
private String varB;
private ExampleEnum varC;
private List<OtherClass> varD;
//there are more variables here...
private ExampleClass inheritor;
public int getVarA() {
return varA;
}
public void setVarA(int varA) {
this.varA = varA;
}
public boolean validateVarA() {
//-2 is "not set" for Integers
if (varA == -2 && inheritor != null) {
return inheritor.getVarA() != -2;
} else {
return varA != -2;
}
}
//Do I have to define three methods for each variable?
//What if I had like 20 variables?!?
//I would need 60 methods altough every third one
//shares the same structure.
}
I needed some sort of "building plan" for a method:
public T getVar() {
return var;
}
public void setVar(T var) {
this.var = var;
}
public boolean verifyVar() {
//How would I get the invalid value for each type?
T invalidValue = ?;
if (var == invalidValue && inheritor != null) {
return inheritor.getVar() != invalidValue;
} else {
return var != invalidValue;
}
}
In the example above:
"Var" or "var" would be the variable name
and
"T" would be the type of var
I have no idea how I would get the invalid value...
Sorry in case I think too complicated and there is a simple answer to my question. Furthermore, I apologize for any grammar mistakes that may occur.
For generic getters and setters, there's always Map<String, Object>, but I'm pretty sure that's not what you want, so you should stick to the JavaBean conventions (as mentioned in the comments, any IDE would generate those for you and it makes total sense to have them according to OOP recommendations).
Any attempt to implement generic accessors would sooner or later become some java.util.Map with tones of reflection around it. If that's what you want, perhaps you should reconsider your model and switch your type-safe beans to some free-form types like map.
For validation, there's the javax.validation package (JSR-303).
Using class methods, I want to make sure that the getAverage method is always called before the setAverage method
If setAverage is called first, it should return an error.
I'm confused as to how to check if the set is called before the get.
If getAverable returns a non primitive object, you can check if the value is null.
If you return primitive value, like integer, you can use a boolean to check if the setMethod was called.
class Name {
int value;
boolean isCalled;
public int getValue() {
if(isCalled == false) {
throw new Exception();
}
else {
return value;
}
}
public void setValue(int value) {
isCalled = true;
this.value = value;
}
}
There is no direct Java support for doing this. Of course, you could implement directly in the methods some algorithm which memorize which method was executed in which order. Better way to do this is with Aspect-oriented programming.
The simplest way to do what you want is to write an Aspect which writes in a Boolean that getter was executed and allows execution of setter only in case where Boolean flag is true.
Of course, this is only a first step and would be very error prone. (Concurrency, Repetiton etc.)
(I have written such a framework during my master thesis. Of course, it was a bit more complex than just checking single sequential method invocations.)
the answer to this question is probably "not possible", but let me ask regardless :)
Assuming we have a very simple JAVA class that has a primary key, for example:
class Person {
String ssid;
String name;
String address;
...
}
Now, I want to store people in a collection, meaning I will have to override the equals method. Not a completely trivial matter, but on a bare basis I will have something along the lines of:
#Override
public boolean equals (Object other) {
if(other==this) return true;
if(!other.getClass().equals(this.getClass()) return false;
Person otherPerson = (Person)other;
if(this.ssid.equals(otherPerson.getSsid()) return true;
}
Excuse any obvious blunders, just typing this out of my head. Now, let's say later on in the application I have a ssid I obtained through user input. If I want to compare my ssid to a Person, I would have to call something like:
String mySsid = getFromSomewhere();
Person myPerson = getFromSomewhere();
if(myPerson.equals(new Person(mySsid)) doSomething();
This means I have to create a convenience constructor to create a Person based on ssid (if I don't already have one), and it's also quite verbose. It would be much nicer to simply call
myPerson.equals(mySsid)
but if I added a string comparison to my Person equals class, that would break the symmetry property, since the String hasn't got a clue on how to compare itself to a Person.
So finally, the big question, is there any way to enable this sort of "shorthand" comparisons using the overriden equals method, and without breaking the symmetry rule?
Thanks for any thoughts on this!
EDIT: Just to clarify, this is more of an open question than a problem seeking an exact solution. The equals should cater for cases when I want to extract a Person from a collection. So it should be possible to do something like this:
List<Person> people = ...
people.get(ssid);
It would appear obvious and intuitive to be able to define equality on a class based on a primary key, but I haven't found a straightforward way of doing that.
A better bet is to store your People in a map, then you can retrieve them easily:
HashMap<String, Person> people = new HashMap<String, Person>();
Person p = constructPersonFromStuff();
people.put(p.ssid, p);
and then later, you can see if the person exists:
String ssid = getFromSomewhere();
if(people.contains(ssid)){
Person thatGuy = people.get(ssid);
}else{
//that person DOESN'T EXIST! HE'S A FIGMENT OF YOUR IMGAINATION!
}
You're not comparing two Persons, you're comparing two ssids. I would use:
myPerson.getSsid().equals(mySsid);
It makes no sense to say that a Person is equal to a string, do not go down that path.
I just don't understand your problem. You have this code:
String mySsid = getFromSomewhere();
Person myPerson = getFromSomewhere();
if (myPerson.getSsid().equals(mySsid) doSomething();
That just doesn't look bad to me. I guess you could define a function to do that for you:
if (myPerson.ssidEquals(mySsid)) doSomething();
But that's really not that big improvement.
What's the problem?
I'd argue that a Person isn't equal to an ssid. The fact that you use ssid comparison to determine whether two Persons are equal is a shortcut -- we accept as a convention that two Persons with the same ssid refer to the same real-world person -- but isn't actually what makes the equality true.
Perhaps what you really want here is to give your Person a boolean "hasSsid()" method. Or just call myPerson.getSsid().equals(mySsid).
the equals method must never return true when its argument is not an instance of the class on which the method was invoked.
if you like, you can create an interface, say Identifiable.
public interface Identifiable {
public Serializable getSsid();
}
public class Person implements Identifiable { ...
you can then write your code in a generic way in terms of Identifiable ... this might help.
(i'm assuming that the real problem is to handle your identifiable objects in a generic fashion for utility routines and such).
You could create a custom data structure that uses a map or set internally:
public interface EntityStore<T,K> {
T get(K id);
boolean contains(Object o);
void put(K id, T entity);
void remove(Object o);
// ...
}
public class MapEntityStore<T,K> {
private Map<K,T> entities = new HashMap<K,T>();
public T get(K id) { return entities.get(id); }
public boolean contains(Object o) {
if (entities.keySet().contains(o))
return true; // search by id
if(entities.values().contains(o))
return true; // search by value (this can be optimized if necessary)
return false;
}
...
}
You can use a factory method to create instances of EntityStore so that you can change to optimized / fancy implementations as necessary.