简体   繁体   中英

best way to pass many arguments to a method in Java

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.

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);

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).

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

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());
}

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM