Showing posts with label boolean. Show all posts
Showing posts with label boolean. Show all posts

Sunday, April 22, 2007

Fail-fast vs. complete validation

Almost all applications work with data that come from the interaction with humans or other applications. These data, however, may not necessarily meet the requirements of the accepting applications. Data must be validated.

What is validation?

Data entered must pass a set of validation rules in order to be recognized as valid and allowed for further processing.

As an example, lets take a class that has three members: name:String, created:Date and total:int. Our application requires that name is set (not null) and has at least three characters; created is also required and must be a date representing time before now; and total must be a non-negative integer.

There are two common approaches to data validation: fail-fast validation and complete validation.

Fail-fast validation

How it works

If any of the validation rules fails, validation is stopped and data is pronounced invalid and rejected for further processing.

Output

Boolean result that indicates the validity of input data: true for valid, false for invalid.

Pros

It is generally faster than complete validation as first failure terminates the execution of consecutive validation rules. Does not have the over of failure cause reporting.

Cons

Does not provide enough information about the cause of failure.

When to use it

If a simple result: true or false is enough; detailed information about the cause of failure is not required. May be suitable for cases when the source of data cannot correct the data (usually a system without human input).

Example

boolean isValid(String name, Date created, int total)

Data is passed in and boolean result is returned.

Complete validation

How it works

Failure of a validation rule does not stop the validation process. Data is marked as invalid and rejected for further processing after completing whole validation process.

Output

Boolean result that indicates the validity of input data: true for valid, false for invalid. Some form of error collection that contains the information about the causes of validation failure.

For examples see ActionMessages class from Struts framework, Errors class from Spring framework or ErrorCollection class in Atlassian JIRA.

Pros

Provides information about the cause or causes of validation failure. This information can provide the necessary feedback for correcting the input data.

Cons

Slower than fail-fast validation as extra information about causes of validation failure are reported and full set of validation rules is executed independently on the validation result.

When to use it

When a complete set of failure causes is required. The causes of failure may provide hints to the user entering the data about how to correct the data.

Example

void validate(String name, Date created, int total, ErrorCollection errorCollection)

Data is passed in along with the error collection. Method does not have to return anything (void) as invalid data is indicated by the presence of errors in the error collection.

Conclusion

If the complex validation rule set can be broken down into separate validations per input field, these can be used in order to enhance the user experience (via JavaScript or AJAX) – they can provide a real-time feedback for the data being entered.

Also consider that some cases can involve several other input values in order to make a decision about validity of input data. Such case can for example be a single date value consisting on the values from three input fields (don't do this, it's not a really good way of entering dates)

or conditionally required fields, such as the text area in the next picture is only required to be filled in if "other" is selected.

Both types of validation serve their purpose. Which one you decide to use depends mostly on how much information about data being validated you really need in order to make a decision or to correct it in case of failure.

Tuesday, February 27, 2007

toString() and primitive values

How can one convert a primitive value such as integer or boolean to String object?

Well, there are many ways. There is one way that I have seen so many times:

String strValue = new Integer(intValue).toString();

or

String strValue = new Boolean(booleanValue).toString();

Similarly new instance can be created and the toString() method invoked on classes such as Integer, Long, Float, Double, Byte, Short and Boolean.

The problem is that a boxed primitive is allocated just to call toString() method on it. Each time this is executed, a new instance, new object is created. However, object creation is not necessary and can be avoided. Creating object just for one method call is highly inefficient as the object can be garbage collected on the consecutive line.

The solution

It is more efficient to use the static form of toString() method, which takes the primitive value as a parameter.

String strValue = Integer.toString(intValue);

or

String strValue = Boolean.toString(booleanValue);

Side note

...and please don't do the following

Integer number = ...
String strValue = Integer.toString(number.intValue());

If you already have an instance of integer wrapper class, simply call

String strValue = number.toString();

Friday, March 17, 2006

To Boolean or not to Boolean

There is no reason to create new Boolean object. In 99.99% cases we are only interested in using a Boolean object that holds either true or false value. The only case where we might need to create a new instance is for instance comparison rather then value comparison (equals()), e.g.

new Boolean(true) == new Boolean(true)

Java Boolean class comes with two constants that will do the job: Boolean.TRUE and Boolean.FALSE.

private Boolean isNegative(int i) {
return new Boolean(i < 0);
}

Better way:

private Boolean isNegative(int i) {
return i < 0 ? Boolean.TRUE : Boolean.FALSE;
}

This might be trivial, but can significantly improve performance. Creating new objects is an expensive operation and it also consumes more memory that must be allocated to these objects and then potentially garbage collected.

Second issue that can potentially rise with using Boolean class is how to convert a String value to boolean. Boolean class offers two methods that accept String as a parameter:

  • static boolean getBoolean(String)

  • static Boolean valueOf(String)

Which one to use?

The JavaDoc for the later states: Returns a Boolean with a value represented by the specified String. The Boolean returned represents the value true if the string argument is not null and is equal, ignoring case, to the string "true".

The JavaDoc for getBoolean(String)states: Returns true if and only if the system property named by the argument exists and is equal to the string "true". (Beginning with version 1.0.2 of the JavaTM platform, the test of this string is case insensitive.) A system property is accessible through getProperty, a method defined by the System class. If there is no property with the specified name, or if the specified name is empty or null, then false is returned.

People tend to forget this from time to time and tend to use getBoolean(String), especially when require a boolean primitive as outcome. Fortunately, with good tests in place this is discovered and fixed in early development stages.

Therefore use getBoolean(String) only if you need to read system property value as a boolean. For String conversion always use valueOf(String)

String valid = getValidity(); // implemented elsewhere
boolean isValid = Boolean.valueOf(valid).booleanValue();

Any questions? Boolean.FALSE


Creative Commons License This work is licensed under a Creative Commons Attribution-NonCommercial-ShareAlike 2.5 License.