简体   繁体   中英

How to avoid passing large number of arguments in method using MVP approach

I have a registration screen with large number of registration fields, and when user click register button, I pass field values to presenter. In presenter I validate these values and create an object. The problem is a large number of arguments in register() method. I think that I should avoid this situation, but I have no idea how to do it.

Maybe you could explore the Builder pattern . It allows to keep the code clean when you need to pass a big number of arguments. It's also very useful when you don't know the exact number of arguments that will be passed, because some of them might not be mandatory.

In practice, you would have something like

MyObject myObject
void register() {
    myObject = MyObject.Builder(<mandatory arguments>)
               .argument1(<argument 1>)
               .argument2(<argument 2>)
               ...
               .create();
    if (myObject == null) fail();
    else dosomething();
}

One way I have done this previously is to use a TextWatcher on each field that has to be completed:

myEditText.addTextChangedListener(new TextWatcher() {
    @Override
    public void beforeTextChanged(CharSequence s, int start, int count, int after) {}

    @Override
    public void onTextChanged(CharSequence s, int start, int before, int count) {}

    @Override
    public void afterTextChanged(Editable s) {
        presenter.myEditTextChanged(s.toString());
    }
});

Then have the corresponding methods in the presenter update your entity. This way when the user finally clicks register all the details will already be waiting in your presenter.

It also has the advantage that you can do validation as the user progresses - ie the register button isn't enabled until all fields are valid.

If you are using ButterKnife, RxBinding or DataBinding the code is more succinct as well.

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