Skip to content

Provide an ImmutableRequestBuilder so addQueryParams/setQueryParams method argument are not mutated #1544

Open
@lpfeup

Description

@lpfeup

the addQueryParams/setQueryParams methods are assigning the passed argument directly to the class field queryParams. This has unwanted side-effects.

Code:

RequestBuilderBase.addQueryParams

RequestBuilderBase.setQueryParams

Example:

List<Param> params = new ArrayList<>();
params.add(new Param("testKey", "testVal"));
		
Request request = httpClient.prepareGet(url)
                           .setQueryParams(params)
                           .addQueryParam("testKey2", "testVal2") // params list is modified here
                           .build();

params.forEach(p -> System.out.println(p.getName() + ": " + p.getValue()));
// EXPECTED:
// testKey: testVal

// OUTPUT:
// testKey: testVal
// testKey2: testVal2

Another example:

// params as unmodifiable collection
List<Param> params = Collections.singletonList(new Param("testKey", "testVal"));
		
Request request = httpClient.prepareGet(url)
                           .setQueryParams(params)
                           .addQueryParam("testKey2", "testVal2")
                           .build();

// throws java.lang.UnsupportedOperationException on addQueryParam("testKey2", "testVal2")

I suggest replacing the assignments queryParams = params with copies as below:

queryParams = new ArrayList<>(params);

Would you be willing to accept a pull request?

Metadata

Metadata

Assignees

No one assigned

    Type

    No type

    Projects

    No projects

    Milestone

    No milestone

    Relationships

    None yet

    Development

    No branches or pull requests

    Issue actions