Looking at the distant window from where I sit,
I know it’s another bleak day.
I can’t remember if I had seen sunlight two or three days ago. Perhaps four? Maybe there was one yesterday. Seriously, I can’t recall and I can’t be bothered at all.
I’m glued to my screen that I can’t hear the noise around me – because I’m busy keeping the barbarians at the gate.
class User {
private TimeInterval accessibleTime;
private Set<String> accessCodes;
public User(TimeInterval accessibleTime) {
this.accessibleTime = accessibleTime;
}
}
Add null pointer check to parameter and ensure the API validates against incorrect time interval:
public User(TimeInterval accessibleTime) {
if (accessibleTime== null) {
throw new IllegalArgumentException(
"accessibleTime parameter cannot be null");
if (accessibleTime.getFromTime() > accessibleTime.getToTime()) {
throw new IllegalArgumentException("accessibleTime time from [" + acc
essibleTime.getTimeFrom() + "] is later than time to [" + accessibleTime.getTime
To() + "]");
this.accessibleTime = accessibleTime;
}
Generate getter and setter methods:
@YetAnotherNotNullValidation(message = "access codes cannot be null")
public String getAccessCodes() {
return accessCodes;
}
public String setAccessCodes(Set<String> accessCodes) {
this.accessCodes = accessCodes;
}
Hang on, should I expose this setter method even though I have a validation annotation of NotNull hoisted up there? It should be alright I guess, as the validation framework should catch this during runtime. But then again, it requires extra effort to check null values.
// Someone accidentally wipes out accessCodes somewhere in the code
user.setAccessCodes(null);
// and I need to add null check to prevent NPE
if (user.getAccessCodes() == null) {
user.setAccessCodes(new HashSet<String>());
}
Do I want to see this sprinkled everywhere? Perhaps not. It is easy to misuse the setter method and leave accessCode variable in limbo. Better get rid of this, I would rather not have "Midas Touch" effect here.
doSomething(user.getAccessCodes());
// to clear out values
user.getAccessCodes().clear();
No comments:
Post a Comment