Batch operations preferred over looping Info

A single API is used inside a loop to process several items, but a batch API operation exists. Use the batch operation to be more efficient.

Detector ID
java/batches-preferred-over-loops@v1.0
Category
Common Weakness Enumeration (CWE) external icon

Noncompliant example

1public void deleteObjectsNoncompliant(AmazonS3 s3Client, List<DeleteObjectsRequest.KeyVersion> keys,
2                                      String bucketName) throws SdkClientException {
3    // Noncompliant: creates a separate request per item.
4    for (final DeleteObjectsRequest.KeyVersion key : keys) {
5        final DeleteObjectRequest deleteObjectRequest = new DeleteObjectRequest(bucketName, key.getKey());
6        s3Client.deleteObject(deleteObjectRequest);
7    }
8}

Compliant example

1public void deleteObjectsCompliant(AmazonS3 s3Client, List<DeleteObjectsRequest.KeyVersion> keys,
2                                   String bucketName) throws SdkClientException {
3    if(keys.size() <= 1000) {
4        // Compliant: uses the batch operation instead of creating a separate request per item.
5        final DeleteObjectsRequest deleteObjectRequest = new DeleteObjectsRequest(bucketName).withKeys(keys);
6        DeleteObjectsResult deleteObjectsResult = s3Client.deleteObjects(deleteObjectRequest);
7        final int numDeleted = deleteObjectsResult.getDeletedObjects().size();
8        log.info("Successfully deleted: " + numDeleted);
9    } else {
10        // To delete more than 1000 objects, deleteObjects needs to be called more than once.
11        throw new IllegalArgumentException("Need multiple batch calls for >1000 objects.");
12    }
13}