Reputation: 2013
I have a method
makeSomeObject(String a,String b,KeyValue...){}
//method call
Obj.makeSomeObject(stringa,stringb,new KeyValue(String1,String2),new KeyValue(String3,String4),new KeyValue(String4,String5));
How can I refactor my makeSomeObject() method so that I can elegantly pass multiple KeyValue pairs to it so that the method call is cleaner and easy to read.
Upvotes: 1
Views: 1794
Reputation: 5222
You could make a builder for Obj
, which will give you a more fluent way of constructing the Obj
than using the static method in your question.
public class ObjBuilder {
private String a;
private String b;
private List<KeyValue> keyValues = new ArrayList<>();
private ObjBuilder() {}
public static ObjBuilder obj() {
return new ObjBuilder();
}
public ObjBuilder withA(String a) {
this.a = a;
return this;
}
public ObjBuilder withB(String b) {
this.b = b;
return this;
}
public ObjBuilder withKeyValue(KeyValue keyValue) {
this.keyValues.add(keyValue);
return this;
}
public Obj build() {
// whatever Obj.makeSomeObject does to create the Obj instance
}
}
Then when you need to create an Obj
Obj obj = ObjBuilder.obj()
.withA("some String")
.withB("some String")
.withKeyValue(new KeyValue("A", "B"))
.withKeyValue(new KeyValue("C", "D"))
.build();
Obviously using this over the static varargs method in your question is largely a stylistic choice
Upvotes: 3
Reputation: 7052
Use a Map
Or a List
of KeyValue
makeSomeObject(String a,String b,Map<String,String> keyValue)
{
}
Map<String,String> keyValue=new HashMap<String,String> ();
keyValue.put(key1,value1);
keyValue.put(key2,value2);
.................
Obj.makeSomeObject(stringa,stringb,keyValue);
OR,
makeSomeObject(String a,String b,List<KeyValue> keyValues)
List list=new ArrayList<KeyValue>();
list.add(new KeyValue(a,b));
list.add(new KeyValue(c,d));
.........
Obj.makeSomeObject(stringa,stringb,list);
Upvotes: 2
Reputation: 2691
You can use variable argument
makeSomeObject(String a,String b,KeyValue... arguments) {}
Example:-
makeSomeMethod("firstString", "secondString", new KeyValue(1,"one"),new KeyValue(2, "two"));
public static void makeSomeMethod(String a,String b,KeyValue... keyValues){
for(KeyValue kv: keyValues)
//Anything you want with kv
System.out.println(kv.toString());
}
Upvotes: 1
Reputation: 419
If it has more than 3 (I personally do not prefer more than 3 as it causes readability issues for me), You can always wrap the args in the form of an object.
Class can have members like String a, String b, Map<K,V> vals
(please use better names for the members).
Upvotes: 2