How can I ensure my bean is built correctly? - java

I'm building a JavaBean (only fields and getters/setters) using the builder pattern.
For the sake of this example, assume this is our bean:
public class Pizza {
private int size;
private boolean cheese;
private boolean pepperoni;
private boolean bacon;
private Pizza(Builder builder) {
size = builder.size;
cheese = builder.cheese;
pepperoni = builder.pepperoni;
bacon = builder.bacon;
}
public static class Builder {
//required
private final int size;
//optional
private boolean cheese = false;
private boolean pepperoni = false;
private boolean bacon = false;
public Builder(int size) {
this.size = size;
}
public Builder cheese(boolean value) {
cheese = value;
return this;
}
public Builder pepperoni(boolean value) {
pepperoni = value;
return this;
}
public Builder bacon(boolean value) {
bacon = value;
return this;
}
public Pizza build() {
return new Pizza(this);
}
}
}
Taken from here.
Now I've been trying to ensure that all of the fields in Pizza are non-null, with reflection, iterating over the fields of Pizza and checking they aren't null, but it appears (and I could be wrong here) that my fields aren't set before the check occurs. This code by Jon Skeet is what I altered to check the non-nullness of my fields (and instead of counting, I'm throwing exceptions).
I then tried to check the fields of my builder instead, but I have extra fields in the builder (for instance, I have an XMLParser field which may be null). Subsetting the builder fields by the pizza fields doesn't work as they have different 'package paths' (?), e.g. org.GiusepesPizzaria.pizza.size vs org.GiusepesPizzaria.builder.size
Is there a better way to check this? Before implementing the reflection method, I used this sort of construct:
if(builder.size ==null){
throw new BadPizzaException("Eh, what're ya doin'?"+
" Pizza Size was not set correctly");
}else{
size=builder.size;
}
But it ends up, if you have say ~10 fields to check, long winded, and clutters what should be a simple class.
So that's what I've tried. Is there a better method?

An interesting pattern to ensure that all variables are set is to use the Step Builder Pattern where the first setter only allows you to set the second, the second only allows the third and so on. When you're at the last step you can build the class and by then you'll know that all methods have been called.
A short extract from that post:
Panino solePanino = PaninoStepBuilder.newBuilder()
.paninoCalled("sole panino")
.breadType("baguette")
.fish("sole")
.addVegetable("tomato")
.addVegetable("lettece")
.noMoreVegetablesPlease()
.build();
Where you must start with what the panino is called and follow it up with the bread type.

Try this:
public class Pizza
{
private final boolean bacon;
private final boolean cheese;
private final boolean pepperoni;
private final int size;
private Pizza()
{
throw new UnsupportedOperationException();
}
Pizza(
final int theSize,
final boolean theCheese,
final boolean thePepperoni,
final boolean theBacon)
{
bacon = theBacon;
cheese = theCheese;
pepperoni = thePepperoni;
size = theSize;
}
}
// new file.
public class PizzaBuilder
{
private boolean bacon;
private boolean cheese;
private boolean pepperoni;
private int size;
public PizzaBuilder()
{
size = 9; // default size.
}
public void setHasBacon()
{
bacon = true;
}
public void setHasNoBacon()
{
bacon = false;
}
public void setHasCheese()
{
cheese = true;
}
public void setHasNoCheese()
{
cheese = false;
}
public void setHasPepperoni()
{
pepperoni = true;
}
public void setHasNoPepperoni()
{
pepperoni = false;
}
public void setSizeNineInch()
{
size = 9;
}
public void setSizeTwelveInch()
{
size = 12;
}
public Pizza buildPizza()
{
return new Pizza(size, cheese, pepperoni, bacon);
}
}
With the builder above, there is no chance that the builder will ever produce an invalid pizza.
Assumption: only 9 and 12 inch pizza's are supported. add more setSize as needed.
The builder uses what I refer to as NMSetters. This style setter allows you to set values but does not expose the implementation of said value. It seems likely that this is not an original invention on my part.

Related

Return enum into toString and accessor methods

As the code showed below, I'm trying to make user input the speed (1,2,3) into the enum and return the input back into toString method.
private enum speed
{
SMALL(1),
MEDIUM(2),
FAST(3);
private int speedValue;
private speed (int speedValue)
{
this.speedValue = speedValue;
}
public int getSpeed()
{
return speedValue;
}
public static Optional<speed> get(int speedValue)
{
return Arrays.stream(speed.values())
.filter(spe -> spe.speedValue == speedValue)
.findFirst();
}
}
private boolean on;
The problem is when I put this.speed = speed or any other stuff, the speed class will be missing with error "speed cannot be resolved or is not a field"
This happened the same in the toString class.
public Fan(speed seed, boolean on)
{
speed.get() = seed; //what shall i put here
this.on = on;
}
public boolean getOn()
{
return this.on;
}
public String toString()
{
return speed; //what shall i put here
}
public static void main(String[] args) {
Scanner sc = new Scanner(System.in);
System.out.println("Please enter speed");
int sp = sc.nextInt();
System.out.println("On/Off");
boolean on = sc.nextBoolean();
Optional<speed>spe = speed.get(sp); //getting enum integer values
System.out.println(spe.get());
Fan fan = new Fan(sp, on)
Is there any solution that I would be able to return the integer value of enum into the public class and toString class?
With private enum speed {...} you declare the enum type speed, but you never declare a field of this type.
If you want to have a field named speed of this enum type you must declare it with private speed speed;.
This looks confusing and therefore I suggest that you follow the Java naming conventions where names of classes start with an uppercase letter (and enum types are classes).
That means your enum type should be written as
public enum Speed {
SMALL(1),
MEDIUM(2),
FAST(3);
private int speedValue;
private Speed (int speedValue) {
this.speedValue = speedValue;
}
public int getSpeed() {
return speedValue;
}
public static Optional<Speed> get(int speedValue) {
return Arrays.stream(Speed.values())
.filter(spe -> spe.speedValue == speedValue)
.findFirst();
}
}
Your Fan class needs these fields:
private boolean on;
private Speed speed;
The constructor is
public Fan(Speed seed, boolean on) {
speed = seed;
this.on = on;
}
or, assuming that the parameter name seed is a spelling mistake and it should be speed instead:
public Fan(Speed speed, boolean on) {
this.speed = speed;
this.on = on;
}
The other methods:
public boolean getOn() {
return this.on;
}
public String toString() {
return speed.toString();
}
public static void main(String[] args) {
Scanner sc = new Scanner(System.in);
System.out.println("Please enter speed");
int sp = sc.nextInt();
System.out.println("On/Off");
boolean on = sc.nextBoolean();
Optional<Speed> spe = Speed.get(sp); //getting enum integer values
System.out.println(spe.get());
Fan fan = new Fan(spe.get(), on);
// note that the above line produces not output. Why should it?
// if you want to see the result of f.toString() you need to print it out:
System.out.println(fan.toString());
// or shorter (since println() calls toString() automatically):
System.out.println(fan);
}
Note 1: I also changed the placement of the opening braces ({) to follow general Java conventions - for seasoned Java programmers this looks less surprising.
Note 2: as Mark Rotteveel correctly remarks: the Fan class has a public constructor and therefore the Speed enum should also be declared public. Otherwise no one outside of the Fan class will be able to construct a new Fan object.

Customized JTextfield - Only Integer with Limitation

I have a class which only allows integers with limited amount. The problem is, class is doing its work but when I use multiple objects, it only takes the last objects limitation number and applies to others.
I also couldn't get rid of static warnings.
Code is ;
public class LimitedIntegerTF extends JTextField {
private static final long serialVersionUID = 1L;
private static int limitInt;
public LimitedIntegerTF() {
super();
}
public LimitedIntegerTF(int limitInt) {
super();
setLimit(limitInt);
}
#SuppressWarnings("static-access")
public final void setLimit(int newVal)
{
this.limitInt = newVal;
}
public final int getLimit()
{
return limitInt;
}
#Override
protected Document createDefaultModel() {
return new UpperCaseDocument();
}
#SuppressWarnings("serial")
static class UpperCaseDocument extends PlainDocument {
#Override
public void insertString(int offset, String strWT, AttributeSet a)
throws BadLocationException {
if(offset < limitInt){
if (strWT == null) {
return;
}
char[] chars = strWT.toCharArray();
boolean check = true;
for (int i = 0; i < chars.length; i++) {
try {
Integer.parseInt(String.valueOf(chars[i]));
} catch (NumberFormatException exc) {
check = false;
break;
}
}
if (check)
super.insertString(offset, new String(chars),a);
}
}
}
}
How I call it on another class ;
final LimitedIntegerTF no1 = new LimitedIntegerTF(5);
final LimitedIntegerTF no2 = new LimitedIntegerTF(7);
final LimitedIntegerTF no3 = new LimitedIntegerTF(10);
The result is no1, no2, and no3 has (10) as a limitation.
Example:
no1: 1234567890 should be max len 12345
no2: 1234567890 should be max len 1234567
no3: 1234567890 it's okay
It's because your limitInt is static, which means it has the same value for all instances of that class (What does the 'static' keyword do in a class?). Make it non-static, and each instance of your class will have their own value for it.
If you want to use limitInt in the inner class UpperCaseDocument, then make that class non-static as well. However, if you do that, each instance of UpperCaseDocument will also have an instance of LimitedIntegerTF associated with it.

Logic error possibly misunderstanding in java assignment

I've been having numerous problems getting this project to work correctly but I'm currently stuck on getting this class to work properly. Whats its suppose to do is take the current station from the radio class and pass it along to this class. The problem is i'm trying to select between AM and FM but every time i run it, it only displays the AM station. I don't understand why it automatically gets set to that station.
public class AutoRadioSystem
{
private Radio selectedRadio;
private AMRadio radioAM;
private FMRadio radioFM;
private XMRadio radioXM;
//is this the correct place to initialize these?
Radio amRadio = new AMRadio();
Radio fmRadio = new FMRadio();
public AutoRadioSystem()
{
//even making the selected radio FM still produces values for AM
selectedRadio = radioFM;
}
// this is where my problem currently lies and probably much more. Shouldn't it return 0.0 without any station being selected.
public double getCurrentStation()
{
if (selectedRadio == radioAM)
{
return amRadio.getCurrentStaion();
}
else if (selectedRadio == radioFM)
{
return fmRadio.getCurrentStaion();
}
return 0.0;
}
//I'm not sure if i'm setting this up correctly to switch the radio from am to fm
public void selectRadio()
{
if (selectedRadio == radioAM)
selectedRadio = radioFM;
}
public static void main (String [] args) {
AutoRadioSystem c = new AutoRadioSystem();
c.selectRadio();
double b = c.getCurrentStation();
System.out.println(b);
}
}
public class AMRadio extends Radio
{
private static final double Max_Station = 1605;
private static final double Min_Station = 535;
private static final double Increment = 10;
public AMRadio()
{
currentStation = Min_Station;
}
public double getMax_Station()
{
return this.Max_Station;
}
public double getMin_Station()
{
return this.Min_Station;
}
public double getIncrement()
{
return this.Increment;
}
public String toString()
{
String message = ("AM " + this.currentStation);
return message;
}
}
public class FMRadio extends Radio
{
private static final double Max_Station = 108.0;
private static final double Min_Station = 88.0;
private static final double Increment = .01;
public FMRadio()
{
currentStation = Min_Station;
}
public double getMax_Station()
{
return this.Max_Station;
}
public double getMin_Station()
{
return this.Min_Station;
}
public double getIncrement()
{
return this.Increment;
}
public String toString()
{
String message = ("FM " + this.currentStation);
return message;
}
}
public abstract class Radio
{
double currentStation;
RadioSelectionBar radioSelectionBar;
public Radio()
{
}
public abstract double getMax_Station();
public abstract double getMin_Station();
public abstract double getIncrement();
public void up()
{
}
public void down()
{
}
public double getCurrentStaion()
{
return this.currentStation;
}
public void setCurrentStation(double freq)
{
this.currentStation = freq;
}
public void setStation(int buttonNumber, double station)
{
}
public double getStation(int buttonNumber)
{
return 0.0;
}
public String toString()
{
String message = ("" + currentStation);
return message;
}
}
The problem is, in .getCurrentStation(), both selectedRadio & radioAM is not init and is null.
The mistake begin with:
public void selectRadio()
{
if (selectedRadio == radioAM)
{
selectedRadio = radioFM;
}
}
Here, the selectedRadio = null, so it's never get assign value.
Edit: I believe you're just begin with this, so a little more details will help.
You make mistake when declare two field, amRadio & radioAM then init one of them and use another.
You didn't set value to selectedRadio and compare it, this always return false
The best place to init value for an instance is the constructor method, here is AutoRadioSystem()
You may want to change the code to like this:
private Radio selectedRadio;
public AutoRadioSystem()
{
selectedRadio = new FMRadio();
}
// To compare, using instanceOf, but better design will use enum value instead, up to you
I think I've found the problem
You have 2 fields for each Radio overload
private AMRadio radioAM;
...
Radio amRadio = new AMRadio();
but the one you're comparing to: radioAM never gets instantiated, and therefore is always null.
When you call
if (selectedRadio == radioAM)
both selectedRadio and radioAM are null, so of course they would be equal
unless you intend radioAM and amRadio to be completely different instances, than you shouldn't have 2 fields like that.
Since you're using polymorphism, you might want to use the latter one
Radio amRadio = new AMRadio();
All properties selectedRadio, radioAM and RadioFM are null. The code in the constructor has no effect because selectedRadio = RadioFM. This means that selectedRadio its value does not change and remains zero.
Therefore selectedRadio == radioAM (null == null) in getCurrentStation is always true.This will always apply the first if-block in your method getCurrentStation and will always return the "amradio".
Caio

Immutable objects builder

Would it be considered a good practice to store the builder instance inside the instance that it has built? The thing is that I quite often find myself in a situation when I need to create a very similiar object to the one that I already have. Presumable this object has many 8-10 fields. Normally, with a mutable object I would have just used setter.
For instance, lets take the classic Bloch's NutricionFacts example:
public class NutritionFacts {
private final int servingSize;
private final int servings;
private final int calories;
private final int fat;
private final int sodium;
private final int carbohydrate;
private final Builder builder;
public static class Builder {
// Required parameters
private final int servingSize;
private final int servings;
// Optional parameters - initialized to default values
private int calories = 0;
private int fat = 0;
private int carbohydrate = 0;
private int sodium = 0;
public Builder(int servingSize, int servings) {
this.servingSize = servingSize;
this.servings = servings;
}
public Builder calories(int val)
{ calories = val; return this; }
public Builder fat(int val)
{ fat = val; return this; }
public Builder carbohydrate(int val)
{ carbohydrate = val; return this; }
public Builder sodium(int val)
{ sodium = val; return this; }
public NutritionFacts build() {
return new NutritionFacts(this);
}
}
private NutritionFacts(Builder builder) {
servingSize = builder.servingSize;
servings = builder.servings;
calories = builder.calories;
fat = builder.fat;
sodium = builder.sodium;
carbohydrate = builder.carbohydrate;
this.builder = builder;
}
}
I have modified it a bit so I can access the builder instance if I want to make a simmiliar copy in the future?
What do you think?
What happens if you reuse the Builder to build a second instance? The Builder in the first instance would then produce instances similar to the second instance. Probably not what you expected.
I would suggest an option to create the Builder with a template instance.
public Builder(NutritionFacts template) {
this.servingSize = template.getServingSize();
...
}

Named Parameter idiom in Java

How to implement Named Parameter idiom in Java? (especially for constructors)
I am looking for an Objective-C like syntax and not like the one used in JavaBeans.
A small code example would be fine.
The best Java idiom I've seem for simulating keyword arguments in constructors is the Builder pattern, described in Effective Java 2nd Edition.
The basic idea is to have a Builder class that has setters (but usually not getters) for the different constructor parameters. There's also a build() method. The Builder class is often a (static) nested class of the class that it's used to build. The outer class's constructor is often private.
The end result looks something like:
public class Foo {
public static class Builder {
public Foo build() {
return new Foo(this);
}
public Builder setSize(int size) {
this.size = size;
return this;
}
public Builder setColor(Color color) {
this.color = color;
return this;
}
public Builder setName(String name) {
this.name = name;
return this;
}
// you can set defaults for these here
private int size;
private Color color;
private String name;
}
public static Builder builder() {
return new Builder();
}
private Foo(Builder builder) {
size = builder.size;
color = builder.color;
name = builder.name;
}
private final int size;
private final Color color;
private final String name;
// The rest of Foo goes here...
}
To create an instance of Foo you then write something like:
Foo foo = Foo.builder()
.setColor(red)
.setName("Fred")
.setSize(42)
.build();
The main caveats are:
Setting up the pattern is pretty verbose (as you can see). Probably not worth it except for classes you plan on instantiating in many places.
There's no compile-time checking that all of the parameters have been specified exactly once. You can add runtime checks, or you can use this only for optional parameters and make required parameters normal parameters to either Foo or the Builder's constructor. (People generally don't worry about the case where the same parameter is being set multiple times.)
You may also want to check out this blog post (not by me).
This is worth of mentioning:
Foo foo = new Foo() {{
color = red;
name = "Fred";
size = 42;
}};
the so called double-brace initializer. It is actually an anonymous class with instance initializer.
Java 8 style:
public class Person {
String name;
int age;
private Person(String name, int age) {
this.name = name;
this.age = age;
}
static PersonWaitingForName create() {
return name -> age -> new Person(name, age);
}
static interface PersonWaitingForName {
PersonWaitingForAge name(String name);
}
static interface PersonWaitingForAge {
Person age(int age);
}
public static void main(String[] args) {
Person charlotte = Person.create()
.name("Charlotte")
.age(25);
}
}
named parameters
fix order of arguments
static check -> no nameless Person possible
hard to switch arguments of same type by accident (like it is possible in telescop constructors)
You could also try to follow advice from here.
int value;
int location;
boolean overwrite;
doIt(value=13, location=47, overwrite=true);
It's verbose on the call site, but overall gives the lowest overhead.
I would like to point out that this style addresses both the named parameter and the properties features without the get and set prefix which other language have. Its not conventional in Java realm but its simpler and shorter, especially if you have handled other languages.
class Person {
String name;
int age;
// name property
// getter
public String name() { return name; }
// setter
public Person name(String val) {
name = val;
return this;
}
// age property
// getter
public int age() { return age; }
// setter
public Person age(int val) {
age = val;
return this;
}
public static void main(String[] args) {
// addresses named parameter
Person jacobi = new Person().name("Jacobi Adane").age(3);
// addresses property style
System.out.println(jacobi.name());
System.out.println(jacobi.age());
// updates property values
jacobi.name("Lemuel Jacobi Adane");
jacobi.age(4);
System.out.println(jacobi.name());
System.out.println(jacobi.age());
}
}
If you are using Java 6, you can use the variable parameters and import static to produce a much better result. Details of this are found in:
http://zinzel.blogspot.com/2010/07/creating-methods-with-named-parameters.html
In short, you could have something like:
go();
go(min(0));
go(min(0), max(100));
go(max(100), min(0));
go(prompt("Enter a value"), min(0), max(100));
What about
public class Tiger {
String myColor;
int myLegs;
public Tiger color(String s)
{
myColor = s;
return this;
}
public Tiger legs(int i)
{
myLegs = i;
return this;
}
}
Tiger t = new Tiger().legs(4).color("striped");
Java does not support Objective-C-like named parameters for constructors or method arguments. Furthermore, this is really not the Java way of doing things. In java, the typical pattern is verbosely named classes and members. Classes and variables should be nouns and method named should be verbs. I suppose you could get creative and deviate from the Java naming conventions and emulate the Objective-C paradigm in a hacky way but this wouldn't be particularly appreciated by the average Java developer charged with maintaining your code. When working in any language, it behooves you to stick to the conventions of the language and community, especially when working on a team.
I feel like the "comment-workaround" deserves it's own answer (hidden in existing answers and mentioned in comments here).
someMethod(/* width */ 1024, /* height */ 768);
You could use a usual constructor and static methods that give the arguments a name:
public class Something {
String name;
int size;
float weight;
public Something(String name, int size, float weight) {
this.name = name;
this.size = size;
this.weight = weight;
}
public static String name(String name) {
return name;
}
public static int size(int size) {
return size;
}
public float weight(float weight) {
return weight;
}
}
Usage:
import static Something.*;
Something s = new Something(name("pen"), size(20), weight(8.2));
Limitations compared to real named parameters:
argument order is relevant
variable argument lists are not possible with a single constructor
you need a method for every argument
not really better than a comment (new Something(/*name*/ "pen", /*size*/ 20, /*weight*/ 8.2))
If you have the choice look at Scala 2.8. http://www.scala-lang.org/node/2075
Using Java 8's lambdas you can get even closer to real named parameters.
foo($ -> {$.foo = -10; $.bar = "hello"; $.array = new int[]{1, 2, 3, 4};});
Do note that this probably violates a couple dozen "java best practices" (like anything that makes use of the $ symbol).
public class Main {
public static void main(String[] args) {
// Usage
foo($ -> {$.foo = -10; $.bar = "hello"; $.array = new int[]{1, 2, 3, 4};});
// Compare to roughly "equivalent" python call
// foo(foo = -10, bar = "hello", array = [1, 2, 3, 4])
}
// Your parameter holder
public static class $foo {
private $foo() {}
public int foo = 2;
public String bar = "test";
public int[] array = new int[]{};
}
// Some boilerplate logic
public static void foo(Consumer<$foo> c) {
$foo foo = new $foo();
c.accept(foo);
foo_impl(foo);
}
// Method with named parameters
private static void foo_impl($foo par) {
// Do something with your parameters
System.out.println("foo: " + par.foo + ", bar: " + par.bar + ", array: " + Arrays.toString(par.array));
}
}
Pros:
Considerably shorter than any builder pattern I've seen so far
Works for both methods and constructors
Completely type safe
It looks very close to actual named parameters in other programming languages
It's about as safe as your typical builder pattern (can set parameters multiple times)
Cons:
Your boss will probably lynch you for this
It's harder to tell what's going on
You can use project Lombok's #Builder annotation to simulate named parameters in Java. This will generate a builder for you which you can use to create new instances of any class (both classes you've written and those coming from external libraries).
This is how to enable it on a class:
#Getter
#Builder
public class User {
private final Long id;
private final String name;
}
Afterwards you can use this by:
User userInstance = User.builder()
.id(1L)
.name("joe")
.build();
If you'd like to create such a Builder for a class coming from a library, create an annotated static method like this:
class UserBuilder {
#Builder(builderMethodName = "builder")
public static LibraryUser newLibraryUser(Long id, String name) {
return new LibraryUser(id, name);
}
}
This will generate a method named "builder" which can be called by:
LibraryUser user = UserBuilder.builder()
.id(1L)
.name("joe")
.build();
This is a variant of the Builder Pattern as described by Lawrence above.
I find myself using this a lot (at the apropriate places).
The main difference is, that in this case the Builder is immuatable. This has the advantage that it can be reused and is thread-safe.
So you can use this to make one default Builder and then in the various places where you need it you can configure it and build your object.
This makes most sense, if you are building the same object over and over again, because then you can make the builder static and don't have to worry about changing it's settings.
On the other hand if you have to build objects with changing paramaters this has quiet some overhead. (but hey, you can combine static / dynamic generation with custom build methods)
Here is the example code:
public class Car {
public enum Color { white, red, green, blue, black };
private final String brand;
private final String name;
private final Color color;
private final int speed;
private Car( CarBuilder builder ){
this.brand = builder.brand;
this.color = builder.color;
this.speed = builder.speed;
this.name = builder.name;
}
public static CarBuilder with() {
return DEFAULT;
}
private static final CarBuilder DEFAULT = new CarBuilder(
null, null, Color.white, 130
);
public static class CarBuilder {
final String brand;
final String name;
final Color color;
final int speed;
private CarBuilder( String brand, String name, Color color, int speed ) {
this.brand = brand;
this.name = name;
this.color = color;
this.speed = speed;
}
public CarBuilder brand( String newBrand ) {
return new CarBuilder( newBrand, name, color, speed );
}
public CarBuilder name( String newName ) {
return new CarBuilder( brand, newName, color, speed );
}
public CarBuilder color( Color newColor ) {
return new CarBuilder( brand, name, newColor, speed );
}
public CarBuilder speed( int newSpeed ) {
return new CarBuilder( brand, name, color, newSpeed );
}
public Car build() {
return new Car( this );
}
}
public static void main( String [] args ) {
Car porsche = Car.with()
.brand( "Porsche" )
.name( "Carrera" )
.color( Color.red )
.speed( 270 )
.build()
;
// -- or with one default builder
CarBuilder ASSEMBLY_LINE = Car.with()
.brand( "Jeep" )
.name( "Cherokee" )
.color( Color.green )
.speed( 180 )
;
for( ;; ) ASSEMBLY_LINE.build();
// -- or with custom default builder:
CarBuilder MERCEDES = Car.with()
.brand( "Mercedes" )
.color( Color.black )
;
Car c230 = MERCEDES.name( "C230" ).speed( 180 ).build(),
clk = MERCEDES.name( "CLK" ).speed( 240 ).build();
}
}
Any solution in Java is likely going to be pretty verbose, but it's worth mentioning that tools like Google AutoValues and Immutables will generate builder classes for you automatically using JDK compile time annotation processing.
For my case, I wanted named parameters to use in a Java enum, so a builder pattern wouldn't work because enum instances can't be instantiated by other classes. I came up with an approach similar #deamon's answer but adds compile-time checking of parameter ordering (at the expense of more code)
Here's client code:
Person p = new Person( age(16), weight(100), heightInches(65) );
And the implementation:
class Person {
static class TypedContainer<T> {
T val;
TypedContainer(T val) { this.val = val; }
}
static Age age(int age) { return new Age(age); }
static class Age extends TypedContainer<Integer> {
Age(Integer age) { super(age); }
}
static Weight weight(int weight) { return new Weight(weight); }
static class Weight extends TypedContainer<Integer> {
Weight(Integer weight) { super(weight); }
}
static Height heightInches(int height) { return new Height(height); }
static class Height extends TypedContainer<Integer> {
Height(Integer height) { super(height); }
}
private final int age;
private final int weight;
private final int height;
Person(Age age, Weight weight, Height height) {
this.age = age.val;
this.weight = weight.val;
this.height = height.val;
}
public int getAge() { return age; }
public int getWeight() { return weight; }
public int getHeight() { return height; }
}
Here is a compiler-checked Builder pattern. Caveats:
this can't prevent double assignment of an argument
you can't have a nice .build() method
one generic parameter per field
So you need something outside the class that will fail if not passed Builder<Yes, Yes, Yes>. See the getSum static method as an example.
class No {}
class Yes {}
class Builder<K1, K2, K3> {
int arg1, arg2, arg3;
Builder() {}
static Builder<No, No, No> make() {
return new Builder<No, No, No>();
}
#SuppressWarnings("unchecked")
Builder<Yes, K2, K3> arg1(int val) {
arg1 = val;
return (Builder<Yes, K2, K3>) this;
}
#SuppressWarnings("unchecked")
Builder<K1, Yes, K3> arg2(int val) {
arg2 = val;
return (Builder<K1, Yes, K3>) this;
}
#SuppressWarnings("unchecked")
Builder<K1, K2, Yes> arg3(int val) {
this.arg3 = val;
return (Builder<K1, K2, Yes>) this;
}
static int getSum(Builder<Yes, Yes, Yes> build) {
return build.arg1 + build.arg2 + build.arg3;
}
public static void main(String[] args) {
// Compiles!
int v1 = getSum(make().arg1(44).arg3(22).arg2(11));
// Builder.java:40: error: incompatible types:
// Builder<Yes,No,Yes> cannot be converted to Builder<Yes,Yes,Yes>
int v2 = getSum(make().arg1(44).arg3(22));
System.out.println("Got: " + v1 + " and " + v2);
}
}
Caveats explained. Why no build method? The trouble is that it's going to be in the Builder class, and it will be parameterized with K1, K2, K3, etc. As the method itself has to compile, everything it calls must compile. So, generally, we can't put a compilation test in a method of the class itself.
For a similar reason, we can't prevent double assignment using a builder model.
The idiom supported by the karg library may be worth considering:
class Example {
private static final Keyword<String> GREETING = Keyword.newKeyword();
private static final Keyword<String> NAME = Keyword.newKeyword();
public void greet(KeywordArgument...argArray) {
KeywordArguments args = KeywordArguments.of(argArray);
String greeting = GREETING.from(args, "Hello");
String name = NAME.from(args, "World");
System.out.println(String.format("%s, %s!", greeting, name));
}
public void sayHello() {
greet();
}
public void sayGoodbye() {
greet(GREETING.of("Goodbye");
}
public void campItUp() {
greet(NAME.of("Sailor");
}
}
You can imitate named parameters applying this pattern:
public static class CarParameters {
// to make it shorter getters and props are omitted
public ModelParameter setName(String name) {
this.name = name;
return new ModelParameter();
}
public class ModelParameter {
public PriceParameter setModel(String model) {
CarParameters.this.model = model;
return new PriceParameter();
}
}
public class PriceParameter {
public YearParameter setPrice(double price) {
CarParameters.this.price = price;
return new YearParameter();
}
}
public class YearParameter {
public ColorParameter setYear(int year) {
CarParameters.this.year = year;
return new ColorParameter();
}
}
public class ColorParameter {
public CarParameters setColor(Color color) {
CarParameters.this.color = color;
return new CarParameters();
}
}
}
and then you can pass it to your method as this:
factory.create(new CarParameters()
.setName("Ford")
.setModel("Focus")
.setPrice(20000)
.setYear(2011)
.setColor(BLUE));
You can read more here https://medium.com/#ivorobioff/named-parameters-in-java-9072862cfc8c
Now that we're all on Java 17 ;-), using records is a super-easy way to imitate this idiom:
public class OrderTemplate() {
private int tradeSize, limitDistance, backoffDistance;
public record TradeSize( int value ) {}
public record LimitDistance( int value ) {}
public record BackoffDistance( int value ) {}
public OrderTemplate( TradeSize t, LimitDistance d, BackoffDistance b ) {
this.tradeSize = t.value();
this.limitDistance = d.value();
this.backoffDistance = b.value();
}
}
Then you can call:
var t = new OrderTemplate( new TradeSize(30), new LimitDistance(182), new BackoffDistance(85) );
Which I've found extremely easy to read and I've completely stopped getting all the int parameters mixed up ("was it size first or distance...").
package org.xxx.lang;
/**
* A hack to work around the fact that java does not support
* named parameters in function calls.
*
* Its easy to swap a few String parameters, for example.
* Some IDEs are better than others than showing the parameter names.
* This will enforce a compiler error on an inadvertent swap.
*
* #param <T>
*/
public class Datum<T> {
public final T v;
public Datum(T v) {
this.v = v;
}
public T v() {
return v;
}
public T value() {
return v;
}
public String toString() {
return v.toString();
}
}
Example
class Catalog extends Datum<String> {
public Catalog(String v) {
super(v);
}
}
class Schema extends Datum<String> {
public Schema(String v) {
super(v);
}
}
class Meta {
public void getTables(String catalog, String schema, String tablePattern) {
// pseudo DatabaseMetaData.getTables();
}
}
class MetaChecked {
public void getTables(Catalog catalog, Schema schema, String tablePattern) {
// pseudo DatabaseMetaData.getTables();
}
}
#Test
public void test() {
Catalog c = new Catalog("test");
assertEquals("test",c.v);
assertEquals("test",c.v());
assertEquals("test",c.value());
String t = c.v;
assertEquals("test",t);
}
public void uncheckedExample() {
new Meta().getTables("schema","catalog","%");
new Meta().getTables("catalog","schema","%"); // ooops
}
public void checkedExample() {
// new MetaChecked().getTables(new Schema("schema"),new Catalog("catalog"),"%"); // won't compile
new MetaChecked().getTables(new Catalog("catalog"), new Schema("schema"),"%");
}
maybe can use this:
HashMapFlow<String,Object> args2 = HashMapFlow.of( "name", "Aton", "age", 21 );
Integer age = args2.get("age",51);
System.out.println(args2.get("name"));
System.out.println(age);
System.out.println((Integer)args2.get("dayOfBirth",26));
class:
import java.util.HashMap;
public class HashMapFlow<K,V> extends HashMap {
public static <K, V> HashMapFlow<K, V> of(Object... args) {
HashMapFlow<K, V> map = new HashMapFlow();
for( int i = 0; i < args.length; i+=2) {
map.put((K)args[i], (V)args[i+1]);
}
return map;
}
public <T> T get(Object key, V defaultValue) {
V result = (V)get(key);
if( result == null ) {
result = defaultValue;
}
return (T)result;
}
public HashMapFlow add(K key, V value) {
put(key,value);
return this;
}
}
#irreputable came up with a nice solution. However - it might leave your Class instance in a invalid state, as no validation and consistency checking will happen. Hence I prefer to combine this with the Builder solution, avoiding the extra subclass to be created, although it would still subclass the builder class. Additionally, because the extra builder class makes it more verbose, I added one more method using a lambda. I added some of the other builder approaches for completeness.
Starting with a class as follows:
public class Foo {
static public class Builder {
public int size;
public Color color;
public String name;
public Builder() { size = 0; color = Color.RED; name = null; }
private Builder self() { return this; }
public Builder size(int size) {this.size = size; return self();}
public Builder color(Color color) {this.color = color; return self();}
public Builder name(String name) {this.name = name; return self();}
public Foo build() {return new Foo(this);}
}
private final int size;
private final Color color;
private final String name;
public Foo(Builder b) {
this.size = b.size;
this.color = b.color;
this.name = b.name;
}
public Foo(java.util.function.Consumer<Builder> bc) {
Builder b = new Builder();
bc.accept(b);
this.size = b.size;
this.color = b.color;
this.name = b.name;
}
static public Builder with() {
return new Builder();
}
public int getSize() { return this.size; }
public Color getColor() { return this.color; }
public String getName() { return this.name; }
}
Then using this applying the different methods:
Foo m1 = new Foo(
new Foo.Builder ()
.size(1)
.color(BLUE)
.name("Fred")
);
Foo m2 = new Foo.Builder()
.size(1)
.color(BLUE)
.name("Fred")
.build();
Foo m3 = Foo.with()
.size(1)
.color(BLUE)
.name("Fred")
.build();
Foo m4 = new Foo(
new Foo.Builder() {{
size = 1;
color = BLUE;
name = "Fred";
}}
);
Foo m5 = new Foo(
(b)->{
b.size = 1;
b.color = BLUE;
b.name = "Fred";
}
);
It looks like in part a total rip-off from what #LaurenceGonsalves already posted, but you will see the small difference in convention chosen.
I am wonder, if JLS would ever implement named parameters, how they would do it? Would they be extending on one of the existing idioms by providing a short-form support for it? Also how does Scala support named parameters?
Hmmm - enough to research, and maybe a new question.

Categories

Resources