design patterns - best way to pass many arguments to a method in Java -
i have 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 refactor makesomeobject() method can elegantly pass multiple keyvalue pairs method call cleaner , easy read.
you make builder obj, give more fluent way of constructing obj using static method in 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 create obj instance } } then when need create obj
obj obj = objbuilder.obj() .witha("some string") .withb("some string") .withkeyvalue(new keyvalue("a", "b")) .withkeyvalue(new keyvalue("c", "d")) .build(); obviously using on static varargs method in question largely stylistic choice
Comments
Post a Comment