DEV Community

Tuan
Tuan

Posted on • Edited on

Sử dụng Builder Pattern cho function có nhiều filter params trong Java

Nếu hàm chứa quá nhiều biến dùng để filter, đặc biệt dùng cho các api filter/sort của list thì việc sử dụng Builder Pattern giúp code đọc vào dễ hiểu và dễ maintain hơn.

public class FilterParams {
    private String param1;
    private int param2;

    private FilterParams(Builder builder) {
        this.param1 = builder.param1;
        this.param2 = builder.param2;
    }

    // Getter methods
    // ...

    public static class Builder {
        private String param1;
        private int param2;

        public Builder param1(String param1) {
            this.param1 = param1;
            return this;
        }

        public Builder param2(int param2) {
            this.param2 = param2;
            return this;
        }

        public FilterParams build() {
            return new FilterParams(this);
        }
    }
}

public void processWithFilters(FilterParams filters) {
    // Process based on the filters
}

// Usage:
FilterParams filters = new FilterParams.Builder()
        .param1("value1")
        .param2(123)
        .build();
processWithFilters(filters);

Enter fullscreen mode Exit fullscreen mode

Đơn giản code hơn với annotation @builder và @Getter của lombok

import lombok.Builder;
import lombok.Getter;

@Getter 
@Builder 
public class FilterParams {
   String param1;
   int param2;
}
Enter fullscreen mode Exit fullscreen mode

Qodo Takeover

Introducing Qodo Gen 1.0: Transform Your Workflow with Agentic AI

Rather than just generating snippets, our agents understand your entire project context, can make decisions, use tools, and carry out tasks autonomously.

Read full post

Top comments (0)

Qodo Takeover

Introducing Qodo Gen 1.0: Transform Your Workflow with Agentic AI

Rather than just generating snippets, our agents understand your entire project context, can make decisions, use tools, and carry out tasks autonomously.

Read full post