Reputation: 359
I am having a @NotNull set in the parent object. But the fields for that object are optional. For example:
class A {
@NotNull
private Facet fc;
}
class Facet {
String CR;
String brand;
String range;
}
The questions are:
Any suggestion on this will be helpful.
Upvotes: 0
Views: 771
Reputation: 338730
Regarding the first question:
Since Facet has only optional fields , is it mandatory to have @NotNull in class A?
Consider a place setting in a café. Every customer is expected to have a coffee cup as part of the setting, even though that coffee cup is empty. The coffee is optional, but the cup is required. When a customer sits down at that setting, there is a big difference between an empty coffee cup and no cup at all.
So the cup is required to be non-null. But the contents of the cup, the coffee, is optional and is allowed to be null.
class PlaceSetting {
@NotNull
private CoffeeCup coffeeCup; // A cup is required for every setting.
}
class CoffeeCup {
String coffee; // Optional, null allowed, for an empty coffee cup.
}
Regarding your second question:
How to represent by using annotation such that either CR (or) brand, range fields are mandatory? If CR is not present brand ,range should be there.
No, no such feature in Java.
But this situation may be a “code smell”, an indicator of a possible design flaw. If your logic allows either one “CR” or a pair of a “brand” and a “range”, then that means the CR and brand/range are substitutable. So perhaps they represent two variations of one thing. If so, then likely an interface is justified, to represent that higher level abstraction of a thing, with either of two concrete classes implementing that interface.
To continue our café example, we can define “beverage container” as our abstraction. Our concrete implementations are “water glass” or “coffee cup with saucer”.
class PlaceSetting {
@NotNull
private BeverageContainer bevCon; // Either a water glass or coffee cup is required for every place setting.
}
interface BeverageContainer {}
class WaterGlass implements BeverageContainer {
Water water ; // Optional, may be null.
}
class CupAndSaucer implements BeverageContainer {
@NotNull
CoffeeCup CoffeeCup ;
@NotNull
Saucer saucer ;
}
class CoffeeCup {
String coffee; // Optional, null allowed, for an empty coffee cup.
}
class Saucer { … }
Upvotes: 1