auphong2707/dl4se-code-review-dataset huggingface dataset:
Source:
private long extractLongKey(Data entryKey, Object entryValue) { Object key = QueryableEntry.extractAttributeValue(extractors, serializationService, keyAttribute, entryKey, entryValue, null); if (key == null) { throw new NullPointerException("non-null unique key value is required"); } if (!Numbers.isLongRepresentable(key.getClass())) { START throw new NullPointerException("integer-valued unique key value is required"); END } return ((Number) key).longValue(); } Maybe `IllegalArgumentException` is more appropriate here?

Target:
private long extractLongKey(Data entryKey, Object entryValue) { Object key = extractAttributeValue(extractors, serializationService, keyAttribute, entryKey, entryValue, null); return extractLongKey(key); }
Source:
private long extractLongKey(QueryableEntry entry) { Object key = entry.getAttributeValue(keyAttribute); START if (key == null) { END throw new NullPointerException("non-null unique key value is required"); } if (!Numbers.isLongRepresentable(key.getClass())) { throw new NullPointerException("integer-valued unique key value is required"); } return ((Number) key).longValue(); } It seems the checks are similar to the previous method and we should avoid code duplication.

Target:
private long extractLongKey(QueryableEntry entry) { Object key = entry.getAttributeValue(keyAttribute); return extractLongKey(key); }
Source:
public DataSerializableFactory createFactory() { ConstructorFunction<Integer, IdentifiedDataSerializable>[] constructors = new ConstructorFunction[LEN]; constructors[UPDATE_MAP_CONFIG] = arg -> new UpdateMapConfigOperation(); constructors[UPDATE_PERMISSION_CONFIG_OPERATION] = arg -> new UpdatePermissionConfigOperation(); START constructors[PERMISSION_CONFIG_DTO] = arg -> new PermissionConfigDTO(); END constructors[SET_LICENSE] = arg -> new SetLicenseOperation(); constructors[CHANGE_CLUSTER_STATE] = arg -> new ChangeClusterStateOperation(); return new ArrayDataSerializableFactory(constructors); } Why do we keep the `PermissionConfigDTO` if we remove the `MapConfigDTO`? I assume we removed the latter because the client protocol changes take care of the serialization etc. Is it different for permissions?

Target:
public DataSerializableFactory createFactory() { ConstructorFunction<Integer, IdentifiedDataSerializable>[] constructors = new ConstructorFunction[LEN]; constructors[UPDATE_MAP_CONFIG] = arg -> new UpdateMapConfigOperation(); constructors[SET_LICENSE] = arg -> new SetLicenseOperation(); constructors[CHANGE_CLUSTER_STATE] = arg -> new ChangeClusterStateOperation(); constructors[UPDATE_PERMISSION_CONFIG_OPERATION] = arg -> new UpdatePermissionConfigOperation(); return new ArrayDataSerializableFactory(constructors); }
Source:
public String toString() { return "DiscoveryConfig{" + "discoveryStrategyConfigs=" + discoveryStrategyConfigs + ", discoveryServiceProvider=" + discoveryServiceProvider START + ", nodeFilter=" + nodeFilter + '\'' END + ", nodeFilterClass='" + nodeFilterClass + '\'' + '}'; } Single quotation marks are not needed on line 145. We use it only to escape class names which are strings. The same problem appears in other classes.

Target:
public String toString() { return "DiscoveryConfig{" + "discoveryStrategyConfigs=" + discoveryStrategyConfigs + ", discoveryServiceProvider=" + discoveryServiceProvider + ", nodeFilter=" + nodeFilter + ", nodeFilterClass='" + nodeFilterClass + '\'' + '}'; }
Source:
protected void afterRunInternal() { // Publish listener events // This should happen in after-run to avoid surfacing exceptions during predicate attribute conversion. // Single Map.put() behaves the same. see. https://github.com/hazelcast/hazelcast/issues/15415 for (EventDescriptor descriptor : unpublishedEvents) { START mapEventPublisher.publishEvent(descriptor.caller, descriptor.mapName, END descriptor.eventType, descriptor.dataKey, descriptor.oldValue, descriptor.dataValue); } invalidateNearCache(invalidationKeys); disposeDeferredBlocks = true; super.afterRunInternal(); } Can we catch and log exceptions inside `publishEvent` method of `MapEventPublisherImpl`? Reasonings: 1. Centralize place for all map operations, since some other map operations have still same issue. 2. We can catch exceptions per listener basis to minimize blast of possible failure. For instance, we have attached 100 listener to map but only one of them is throwing exceptions, this failure shouldn't block event flow to other listener.

Target:
protected void afterRunInternal() { invalidateNearCache(invalidationKeys); super.afterRunInternal(); }
Source:
public static <T> void decodeNullable(ClientMessage.ForwardFrameIterator iterator, Function<ClientMessage.ForwardFrameIterator, T> decodeFunction, Consumer<T> consumer) { START if (nextFrameIsNullEndFrame(iterator)) { END decode(iterator, decodeFunction, consumer); } } It should be `if(! nextFrameIsNullEndFrame)`

Target:
public static <T> void decodeNullable(ClientMessage.ForwardFrameIterator iterator, Function<ClientMessage.ForwardFrameIterator, T> decodeFunction, Consumer<T> consumer) { if (!nextFrameIsNullEndFrame(iterator)) { decode(iterator, decodeFunction, consumer); } }
Source:
public final boolean equals(Object o) { START if (o instanceof LFUEvictionPolicyComparator) { END return true; } return false; } could be simplified as `return (o instanceof LFUEvictionPolicyComparator);`

Target:
public final boolean equals(Object o) { if (o == null) { return false; } return getClass().equals(o.getClass()); }
Source:
static void registerMethod(MetricsRegistry metricsRegistry, Object osBean, String methodName, String name) { if (OperatingSystemMXBeanSupport.GET_FREE_PHYSICAL_MEMORY_SIZE_DISABLED START || methodName.equals("getFreePhysicalMemorySize")) { END metricsRegistry.registerStaticProbe(osBean, name, MANDATORY, (LongProbeFunction<Object>) source -> -1); } else { registerMethod(metricsRegistry, osBean, methodName, name, 1); } } should read `&&` instead of `||`

Target:
static void registerMethod(MetricsRegistry metricsRegistry, Object osBean, String methodName, String name) { if (OperatingSystemMXBeanSupport.GET_FREE_PHYSICAL_MEMORY_SIZE_DISABLED && methodName.equals("getFreePhysicalMemorySize")) { metricsRegistry.registerStaticProbe(osBean, name, MANDATORY, (LongProbeFunction<Object>) source -> -1); } else { registerMethod(metricsRegistry, osBean, methodName, name, 1); } }
Source:
private static RestApiConfig initRestApiConfig(Config config) { AdvancedNetworkConfig advancedNetworkConfig = config.getAdvancedNetworkConfig(); boolean isAdvancedNetwork = advancedNetworkConfig.isEnabled(); RestApiConfig restApiConfig = config.getNetworkConfig().getRestApiConfig(); if (isAdvancedNetwork && advancedNetworkConfig.getEndpointConfigs().get(EndpointQualifier.REST) != null) { RestServerEndpointConfig restServerEndpointConfig = advancedNetworkConfig.getRestEndpointConfig(); restApiConfig.setEnabled(true).setEnabledGroups(restServerEndpointConfig.getEnabledGroups()); } START restApiConfig.enableAllGroups(); END return restApiConfig; } This line should be removed, we don't want all groups to be enabled always.

Target:
private static RestApiConfig initRestApiConfig(Config config) { AdvancedNetworkConfig advancedNetworkConfig = config.getAdvancedNetworkConfig(); boolean isAdvancedNetwork = advancedNetworkConfig.isEnabled(); RestApiConfig restApiConfig = config.getNetworkConfig().getRestApiConfig(); if (isAdvancedNetwork && advancedNetworkConfig.getEndpointConfigs().get(REST) != null) { RestServerEndpointConfig restServerEndpointConfig = advancedNetworkConfig.getRestEndpointConfig(); restApiConfig.setEnabled(true).setEnabledGroups(restServerEndpointConfig.getEnabledGroups()); } return restApiConfig; }
Source:
public CompletableFuture<Boolean> matchMCConfig(Member member, String eTag) { checkNotNull(member); checkNotNull(eTag); ClientInvocation invocation = new ClientInvocation( client, MCMatchMCConfigCodec.encodeRequest(eTag), null, member.getAddress() ); return new ClientDelegatingFuture<>( invocation.invoke(), serializationService, clientMessage -> { MCMatchMCConfigCodec.ResponseParameters response = MCMatchMCConfigCodec.decodeResponse(clientMessage); return response.response; }, START true END ); } You should not need `deserializeResponse` as the response is not data.

Target:
public CompletableFuture<Boolean> matchMCConfig(Member member, String eTag) { checkNotNull(member); checkNotNull(eTag); ClientInvocation invocation = new ClientInvocation( client, MCMatchMCConfigCodec.encodeRequest(eTag), null, member.getAddress() ); return new ClientDelegatingFuture<>( invocation.invoke(), serializationService, clientMessage -> { MCMatchMCConfigCodec.ResponseParameters response = MCMatchMCConfigCodec.decodeResponse(clientMessage); return response.response; }, false ); }
Source:
public Record putReplicatedRecord(Record replicatedRecord, long nowInMillis, boolean populateIndexes) { Record newRecord = createRecord(replicatedRecord, nowInMillis); markRecordStoreExpirable(replicatedRecord.getTtl(), replicatedRecord.getMaxIdle()); // Note that newRecord may not know its key yet, key assignment // is done after storage put in some cases so better to // use key of replicatedRecord when doing storage.put storage.put(replicatedRecord.getKey(), newRecord); START mutationObserver.onReplicationPutRecord(newRecord.getKey(), newRecord, !populateIndexes); END updateStatsOnPut(replicatedRecord.getHits(), nowInMillis); return newRecord; } Here we change the meaning of `populateIndexes`. `onReplicationPutRecord` accepts it as a `backup` parameter and `IndexingMutationObserver` uses it internally as the original meaning of the `populateIndex`. `populateIndex` here can be false for other reasons too. Maybe passing around a `MutationEvent` parameter object carrying index and backup info (we need to think about others too) would be more flexible and extensible.

Target:
public Record putReplicatedRecord(Record replicatedRecord, long nowInMillis, boolean populateIndexes) { Record newRecord = createRecord(replicatedRecord, nowInMillis); markRecordStoreExpirable(replicatedRecord.getTtl(), replicatedRecord.getMaxIdle()); // Note that newRecord may not know its key yet, key assignment // is done after storage put in some cases so better to // use key of replicatedRecord when doing storage.put storage.put(replicatedRecord.getKey(), newRecord); mutationObserver.onReplicationPutRecord(newRecord.getKey(), newRecord, populateIndexes); updateStatsOnPut(replicatedRecord.getHits(), nowInMillis); return newRecord; }
Source:
protected void runInternal() { if (dataRecords == null) { // If dataRecords is null and we are in // `runInternal` method, means this operation // has not been serialized/deserialized // and is running directly on caller node for (int i = 0; i < recordAndDataValuePairs.size(); i += 2) { START Object obj = recordAndDataValuePairs.get(i); END if (obj != null) { putBackup((Record) obj); } } } else { for (Record<Data> record : dataRecords) { putBackup(record); } } } Can the record be `null` here since we explicitly check for null before adding it in `PutAllOperation#toBackupListByRemovingEvictedRecords` and `MergeOperation#toBackupListByRemovingEvictedRecords`?

Target:
protected void runInternal() { if (dataRecords != null) { for (Record<Data> record : dataRecords) { putBackup(record); } } else { // If dataRecords is null and we are in // `runInternal` method, means this operation // has not been serialized/deserialized // and is running directly on caller node. for (int i = 0; i < recordAndDataValuePairs.size(); i += 2) { putBackup((Record) recordAndDataValuePairs.get(i)); } } }
Source:
private boolean isEnabled(HazelcastInstance client) { HazelcastClientInstanceImpl clientInstanceImpl = getHazelcastClientInstanceImpl(client); ClientListenerService listenerService = clientInstanceImpl.getListenerService(); Collection<EventHandler> values = ((SmartClientListenerService) listenerService).getEventHandlers().values(); boolean found = false; for (EventHandler value : values) { if (value instanceof SmartClientInvocationService.BackupEventHandler) { START found = true; END } } return found; } why not return here?

Target:
private boolean isEnabled(HazelcastInstance client) { HazelcastClientInstanceImpl clientInstanceImpl = getHazelcastClientInstanceImpl(client); ClientListenerService listenerService = clientInstanceImpl.getListenerService(); Collection<EventHandler> values = ((SmartClientListenerService) listenerService).getEventHandlers().values(); for (EventHandler value : values) { if (value instanceof SmartClientInvocationService.BackupEventHandler) { return true; } } return false; }
Source:
public ICredentialsFactory asCredentialsFactory(ClassLoader cl) { if (implementation != null) { return implementation; } else { try { ICredentialsFactory credentialsFactory = ClassLoaderUtil.newInstance(cl, className); START credentialsFactory.init(properties); END return credentialsFactory; } catch (Exception e) { throw new IllegalArgumentException("Could not create instance of '" + className + "', cause: " + e.getMessage(), e); } } } Is it expected that we will create `credentialsFactory` every time? Maybe we should cache it?

Target:
public ICredentialsFactory asCredentialsFactory(ClassLoader cl) { if (implementation == null) { try { implementation = ClassLoaderUtil.newInstance(cl, className); implementation.init(properties); } catch (Exception e) { throw new IllegalArgumentException("Could not create instance of '" + className + "', cause: " + e.getMessage(), e); } } return implementation; }
Source:
START public static <I, R> Aggregator<I, CanonicalizingHashSet<R>> distinct(String attributePath) { END return new DistinctValuesAggregator<I, R>(attributePath); } `CanonicalizingHashSet` is an internal class. It should not be visible in the public API. I think this part should stay as `Set`

Target:
public static <I, R> Aggregator<I, Set<R>> distinct(String attributePath) { return new DistinctValuesAggregator<>(attributePath); }
Source:
public Data getResult() { START if (result == null) { END return ss.toData(newValue); } return result; } Caller should do invalidations on its own end. Returning a not null result from server hides actual issue (also will cause unexpected serialization costs). Do you mind to investigate `NearCachedMapProxyImpl` and apply same logic to `NearCachedClientMapProxy`?

Target:
public Data getResult() { return result; }
Source:
protected Operation prepareOperation() { MapOperationProvider operationProvider = getMapOperationProvider(parameters.name); MapOperation op; START if (parameters.ttl == DEFAULT_TTL) { END op = operationProvider.createPutIfAbsentOperation(parameters.name, parameters.key, parameters.value); } else { op = operationProvider.createPutIfAbsentWithExpiryOperation(parameters.name, parameters.key, parameters.value, parameters.ttl, DEFAULT_MAX_IDLE); } op.setThreadId(parameters.threadId); return op; } Could this repeated logic in message tasks & member-side map proxy be hidden within `MapOperationProvider` eg: ``` MapOperation createPutIfAbsentOperation(String name, Data dataKey, Data value, long ttl, long maxIdle) { if (ttl == DEFAULT_TTL) { return new PutIfAbsentOperation(..); } else { return new PutIfAbsentWithExpiryOperation(..); } } ```

Target:
protected Operation prepareOperation() { MapOperationProvider operationProvider = getMapOperationProvider(parameters.name); MapOperation op = operationProvider.createPutIfAbsentOperation(parameters.name, parameters.key, parameters.value, parameters.ttl, DEFAULT_MAX_IDLE); op.setThreadId(parameters.threadId); return op; }
Source:
public JavaKeyStoreSecureStoreConfig setPassword(String password) { START checkNotNull(password, "Java Key Store password cannot be null!"); END this.password = password; return this; } There are keystore types which don't require a password or gets it from another channel (e.g. `WINDOWS-MY` type).

Target:
public JavaKeyStoreSecureStoreConfig setPassword(String password) { // null password allowed this.password = password; return this; }
Source:
protected SplitBrainMergePolicy getMergePolicy(String dataStructureName) { START CacheConfig cacheConfig = cacheService.getConfigs().get(dataStructureName); END return mergePolicyProvider.getMergePolicy(cacheConfig.getMergePolicyConfig().getPolicy()); } Minor: can you still use `cacheService.getMergePolicy(dataStructureName)` here?

Target:
protected SplitBrainMergePolicy getMergePolicy(String dataStructureName) { return cacheService.getMergePolicy(dataStructureName); }
Source:
private static boolean isCompatible(MerkleTreeConfig c1, MerkleTreeConfig c2) { boolean c1Disabled = c1 == null || !c1.isEnabled(); boolean c2Disabled = c2 == null || !c2.isEnabled(); return c1 == c2 || (c1Disabled && c2Disabled) || (c1 != null && c2 != null START && nullSafeEqual(c1.getDepth(), c2.getDepth())); END } minor: no reason to use `nullSafeEqual` for `int` comparison here (same below)

Target:
private static boolean isCompatible(MerkleTreeConfig c1, MerkleTreeConfig c2) { boolean c1Disabled = c1 == null || !c1.isEnabled(); boolean c2Disabled = c2 == null || !c2.isEnabled(); return c1 == c2 || (c1Disabled && c2Disabled) || (c1 != null && c2 != null && c1.getDepth() == c2.getDepth()); }
Source:
public boolean equals(Object obj) { START if (id == null || !(obj instanceof DummyObject)) { END return false; } DummyObject other = (DummyObject) obj; return other.id != null && id.equals(other.id); } What if both object have id==null? Then they are not equal?

Target:
public boolean equals(Object obj) { if (!(obj instanceof DummyObject)) { return false; } DummyObject other = (DummyObject) obj; if (id == other.id) { return true; } return id != null && id.equals(other.id); }
Source:
public static YamlNode load(InputStream inputStream, String rootName) { try { Object document = getLoad().loadFromInputStream(inputStream); START inputStream.close(); END return buildDom(rootName, document); } catch (Exception ex) { throw new YamlException("An error occurred while loading and parsing the YAML stream", ex); } } Is it possible to close this one and the ones below on the same method where it is created? To avoid further problems such as when adding new methods. I see some code paths also close it, e.g. `YamlClientConfigBuilder#build` and ` YamlClientFailoverConfigBuilder#build` but not `YamlConfigBuilder#build`

Target:
public static YamlNode load(InputStream inputStream, String rootName) { try { Object document = getLoad().loadFromInputStream(inputStream); return buildDom(rootName, document); } catch (Exception ex) { throw new YamlException("An error occurred while loading and parsing the YAML stream", ex); } }
Source:
public PartitionWideEntryBackupOperation(String name, EntryBackupProcessor backupProcessor) { super(name, backupProcessor); START Thread.dumpStack(); END } Leftover debug statement (most probably causes the test failures & large PR builder time).

Target:
public PartitionWideEntryBackupOperation(String name, EntryBackupProcessor backupProcessor) { super(name, backupProcessor); }
Source:
public boolean apply(Map.Entry mapEntry) { START Thread.dumpStack(); END PREDICATE_APPLY_COUNT.incrementAndGet(); return true; } debug leftover?

Target:
public boolean apply(Map.Entry mapEntry) { PREDICATE_APPLY_COUNT.incrementAndGet(); return true; }
Source:
public void whenCompletesEventually() throws Exception { final String response = "someresponse"; InternalCompletableFuture<String> f = localOperationService.invokeOnPartition(new OffloadingOperation(op -> new Offload(op) { @Override public void start() { START new Thread() { END @Override public void run() { sleepSeconds(5); offloadedOperation().sendResponse(response); } }.start(); } })); assertCompletesEventually(f); assertEquals(response, f.get()); } minor: can be also converted to ``` new Thread(() -> { sleepSeconds(5); offloadedOperation().sendResponse(response); }).start(); ```

Target:
public void whenCompletesEventually() throws Exception { final String response = "someresponse"; InternalCompletableFuture<String> f = localOperationService.invokeOnPartition(new OffloadingOperation(op -> new Offload(op) { @Override public void start() { new Thread(() -> { sleepSeconds(5); offloadedOperation().sendResponse(response); }).start(); } })); assertCompletesEventually(f); assertEquals(response, f.get()); }
Source:
public static <K, V> Predicate<EventJournalMapEvent<K, V>> mapPutEvents() { START return new MapPutEventsPredicate<>(); END } Although we require JDK8, we must remain JDK6 compatible so you must specify the types here.

Target:
public static <K, V> Predicate<EventJournalMapEvent<K, V>> mapPutEvents() { return new MapPutEventsPredicate<K, V>(); }
Source:
public DataSerializableFactory createFactory() { return new DataSerializableFactory() { @Override public IdentifiedDataSerializable create(int typeId) { switch (typeId) { case EVENT_JOURNAL_INITIAL_SUBSCRIBER_STATE: return new EventJournalInitialSubscriberState(); case DESERIALIZING_ENTRY: START return new DeserializingEntry<>(); END default: return null; } } }; } Remove the diamond operator.

Target:
public DataSerializableFactory createFactory() { return new DataSerializableFactory() { @Override public IdentifiedDataSerializable create(int typeId) { switch (typeId) { case EVENT_JOURNAL_INITIAL_SUBSCRIBER_STATE: return new EventJournalInitialSubscriberState(); case DESERIALIZING_ENTRY: return new DeserializingEntry(); default: return null; } } }; }
Source:
public static <K, V> Function<EventJournalCacheEvent<K, V>, Entry<K, V>> cacheEventToEntry() { START return new CacheEventToEntryProjection<>(); END } Missing types

Target:
public static <K, V> Function<EventJournalCacheEvent<K, V>, Entry<K, V>> cacheEventToEntry() { return new CacheEventToEntryProjection<K, V>(); }
Source:
public boolean equals(Object o) { if (o == null || getClass() != o.getClass()) { return false; } CompositeValue that = (CompositeValue) o; assert components.length == that.components.length; for (int i = 0; i < components.length; ++i) { START if (!Comparables.equal(components[i], that.components[i])) { END return false; } } return true; } Do we need to adapt the behaviour of `CompositeValue#hashCode` because of this? In another words, can it happen that `compareTo` returns `0` but `equals` returns `false`?

Target:
public boolean equals(Object o) { if (o == null || getClass() != o.getClass()) { return false; } CompositeValue that = (CompositeValue) o; // We are not using Comparables.equal here since an externally // canonicalized composite value is expected here, otherwise we can't // guarantee hashCode is working properly. return Arrays.equals(components, that.components); }
Source:
START public void addAllInternal(CanonicalizingHashSet<E> set) { END // elements are already canonicalized map.putAll(set.map); } minor: access can be package-private (in support of the method name's `Internal` suffix :-) ). same for `addInternal` below.

Target:
void addAllInternal(CanonicalizingHashSet<E> set) { // elements are already canonicalized map.putAll(set.map); }
Source:
private boolean hasClientServerSocket() { if (!config.getAdvancedNetworkConfig().isEnabled()) { return true; } Map<EndpointQualifier, EndpointConfig> endpointConfigs = config.getAdvancedNetworkConfig().getEndpointConfigs(); EndpointConfig clientEndpointConfig = endpointConfigs.get(CLIENT); START return clientEndpointConfig instanceof ServerSocketEndpointConfig; END } Isn't `clientEndpointConfig != null` enough here?

Target:
private boolean hasClientServerSocket() { if (!config.getAdvancedNetworkConfig().isEnabled()) { return true; } Map<EndpointQualifier, EndpointConfig> endpointConfigs = config.getAdvancedNetworkConfig().getEndpointConfigs(); EndpointConfig clientEndpointConfig = endpointConfigs.get(CLIENT); return clientEndpointConfig != null; }
Source:
START public int getActivePartitionCount() { END // todo allocating a new Address each time ?? InetSocketAddress thisAddress = hazelcastInstance.getCluster().getLocalMember().getSocketAddress(MEMBER); return managedObject.getMemberPartitionsIfAssigned(new Address(thisAddress)).size(); } TODO

Target:
public int getActivePartitionCount() { // todo allocating a new Address each time ?? InetSocketAddress thisAddress = hazelcastInstance.getCluster().getLocalMember().getSocketAddress(); return managedObject.getMemberPartitionsIfAssigned(new Address(thisAddress)).size(); }
Source:
private boolean isQuorumNeeded(Operation op) { START if (op instanceof QuorumCheckAwareOperation END && !((QuorumCheckAwareOperation) op).shouldCheckQuorum()) { return false; } QuorumType type = config.getType(); switch (type) { case WRITE: return isWriteOperation(op); case READ: return isReadOperation(op); case READ_WRITE: return isReadOperation(op) || isWriteOperation(op); default: throw new IllegalStateException("Unhandled quorum type: " + type); } } I think we should check this only if otherwise - based on the type of the operation and the quorum - the quorum is needed. The current implementations are almost free, but if future implementations of the `shouldCheckQuorum()` methods are doing any logic, we may waste some cycles unnecessarily, regardless of the operation and the quorum type, e.g. `MutatingOperation` and `READ` quorum.

Target:
private boolean isQuorumNeeded(Operation op) { QuorumType type = config.getType(); switch (type) { case WRITE: return isWriteOperation(op) && shouldCheckQuorum(op); case READ: return isReadOperation(op) && shouldCheckQuorum(op); case READ_WRITE: return (isReadOperation(op) || isWriteOperation(op)) && shouldCheckQuorum(op); default: throw new IllegalStateException("Unhandled quorum type: " + type); } }
Source:
private boolean shouldTriggerMasterToAssignPartitions() { ClusterServiceImpl clusterService = node.getClusterService(); START return partitionStateManager.isInitialized() && clusterService.isJoined() && node.getNodeExtension().isStartCompleted(); END } Should not this be `!partitionStateManager.isInitialized() && ...`?

Target:
private boolean shouldTriggerMasterToAssignPartitions() { ClusterServiceImpl clusterService = node.getClusterService(); return !partitionStateManager.isInitialized() && clusterService.isJoined() && node.getNodeExtension().isStartCompleted(); }
Source:
START public MapEvictionPolicy getMapEvictionPolicy() { END if (mapEvictionPolicy != null) { return mapEvictionPolicy; } if (evictionPolicy == null) { return null; } return findMatchingMapEvictionPolicy(evictionPolicy); } can we move this picking right eviction policy logic to [MapContainer#initEvictor](https://github.com/hazelcast/hazelcast/blob/c4be8465df8fc2ae6b78f0feae66c196eb03d84c/hazelcast/src/main/java/com/hazelcast/map/impl/MapContainer.java#L165) by only having plain getter/setters here? Like this: ``` public EvictionPolicy getEvictionPolicy() { return evictionPolicy; } public MapConfig setEvictionPolicy(EvictionPolicy evictionPolicy) { this.evictionPolicy = checkNotNull(evictionPolicy, "evictionPolicy cannot be null"); return this; } public MapEvictionPolicy getMapEvictionPolicy() { return mapEvictionPolicy; } public MapConfig setMapEvictionPolicy(MapEvictionPolicy mapEvictionPolicy) { this.mapEvictionPolicy = checkNotNull(mapEvictionPolicy, "mapEvictionPolicy cannot be null"); return this; }

Target:
public MapEvictionPolicy getMapEvictionPolicy() { return mapEvictionPolicy; }
Source:
START public ClientReliableTopicConfig setName(String name) { END this.name = name; return this; } Changing return types might not be possible in 3.x. See [this discussion](https://github.com/hazelcast/hazelcast/pull/11107).

Target:
public void setName(String name) { this.name = name; }
Source:
public E get() throws InterruptedException, ExecutionException { String name = Thread.currentThread().getName(); START System.out.println(">>> FATAL " + name); END if (name.contains("client.thread")) { throw new IllegalStateException(">>> FATAL " + name); } return super.get(); } is this left over for debugging?

Target:
public E get() throws InterruptedException, ExecutionException { assert (!Thread.currentThread().getName().contains("client.thread")); return super.get(); }
Source:
public void info(Throwable thrown) { long startTime = System.nanoTime(); START delegate.fine(thrown); END logOnSlowLogging(startTime); } `info` instead of `fine` here

Target:
public void info(Throwable thrown) { long startTime = System.nanoTime(); delegate.info(thrown); logOnSlowLogging(startTime); }
Source:
public long getMaxIdle() { START return 0; END } Should this maybe return `RecordStore.DEFAULT_TTL` (-1 --> use `MapConfig`'s default) instead of `0` (--> infinite max idle)?

Target:
public Long getMaxIdle() { return null; }
Source:
protected Collection<MultiMapRecord> getNewRecordsCollection() { START final MultiMapConfig.ValueCollectionType valueCollectionType = config.getValueCollectionType(); END return createCollection(valueCollectionType); } I would not declare the local variable. makes the method more complex than needs to be.

Target:
protected Collection<MultiMapRecord> getNewRecordsCollection() { return createCollection(config.getValueCollectionType()); }
Source:
public boolean addValue(Data dataKey, MultiMapRecord value, int index) { MultiMapValue multiMapValue = getOrCreateMultiMapValue(dataKey); START boolean added; END if (index < 0) { added = multiMapValue.getCollection(false).add(value); } else { ((List<MultiMapRecord>) multiMapValue.getCollection(false)).add(index, value); added = true; } if (added) { incSize(1); } return added; } Its nitpicking and mostly personal taste, but I find it difficult to follow the boolean changes in the code, and more error prone. How about removing it, and having multiple method-exit points (`return`). eg. `return multiMapValue.getCollection(false).add(value);`

Target:
public boolean addValue(Data dataKey, MultiMapRecord value, int index) { MultiMapValue multiMapValue = getOrCreateMultiMapValue(dataKey); if (index < 0) { boolean added = multiMapValue.getCollection(false).add(value); if (added) { incSize(1); } return added; } else { ((List<MultiMapRecord>) multiMapValue.getCollection(false)).add(index, value); incSize(1); return true; } }
Source:
public Collection<MultiMapRecord> remove(Data dataKey, boolean copyOf) { MultiMapValue multiMapValue = multiMapValues.remove(dataKey); if (multiMapValue != null) { decrSize(multiMapValue.size()); return multiMapValue.getCollection(copyOf); START } else { END return null; } } Redundant `else` blocks.

Target:
public Collection<MultiMapRecord> remove(Data dataKey, boolean copyOf) { MultiMapValue multiMapValue = multiMapValues.remove(dataKey); if (multiMapValue != null) { decrSize(multiMapValue.size()); return multiMapValue.getCollection(copyOf); } return null; }
Source:
public boolean delete(Data dataKey) { MultiMapValue value = multiMapValues.remove(dataKey); if (value != null) { decrSize(value.size()); return true; START } else { END return false; } } Redundant else block.

Target:
public boolean delete(Data dataKey) { MultiMapValue value = multiMapValues.remove(dataKey); if (value != null) { decrSize(value.size()); return true; } return false; }
Source:
public void afterRun() throws Exception { super.afterRun(); if (recordStore.isWanReplicationEnabled()) { START for (Data key : keys) { END CacheRecord record = recordStore.getRecord(key); wanEventPublisher.publishWanUpdate(name, CacheEntryViews.createEntryView(key, expiryPolicy, record)); } } } `CacheOperation#publishWanUpdate` can be used here.

Target:
public void afterRun() throws Exception { super.afterRun(); if (recordStore.isWanReplicationEnabled()) { for (Data key : keys) { CacheRecord record = recordStore.getRecord(key); publishWanUpdate(key, record); } } }
Source:
protected void readInternal(ObjectDataInput in) throws IOException { super.readInternal(in); int s = in.readInt(); START keys = new ArrayList<Data>(); END while (s-- > 0) { keys.add(in.readData()); } expiryPolicy = in.readData(); } `ArrayList` constructor can be called with `initialCapacity`.

Target:
protected void readInternal(ObjectDataInput in) throws IOException { super.readInternal(in); int s = in.readInt(); keys = new ArrayList<Data>(s); while (s-- > 0) { keys.add(in.readData()); } expiryPolicy = in.readData(); }
Source:
public void testTTL_entryShouldNotBeReachableAfterTTL() { IMap<Integer, String> map = createSimpleMap(); START map.put(1, "value0", 0, TimeUnit.SECONDS); END sleepSeconds(1); assertFalse(map.containsKey(1)); } this makes the entry infinite ttl.

Target:
public void testTTL_entryShouldNotBeReachableAfterTTL() { IMap<Integer, String> map = createSimpleMap(); map.put(1, "value0", 1, TimeUnit.SECONDS); sleepSeconds(1); assertFalse(map.containsKey(1)); }
Source:
public OAHashSet(int initialCapacity, float loadFactor) { checkNotNegative(initialCapacity, "Illegal initial capacity: " + initialCapacity); START checkFalse(loadFactor <= 0 || Float.isNaN(loadFactor), "Illegal load factor: " + loadFactor); END this.capacity = QuickMath.nextPowerOfTwo(initialCapacity); this.loadFactor = loadFactor; this.resizeThreshold = (int) (capacity * loadFactor); this.mask = capacity - 1; this.hashes = new int[capacity]; this.table = new Object[capacity]; } Maybe we could check that load factor is also smaller than 1

Target:
public OAHashSet(int initialCapacity, float loadFactor) { checkNotNegative(initialCapacity, "Illegal initial capacity: " + initialCapacity); checkFalse(loadFactor <= 0 || loadFactor >= 1 || Float.isNaN(loadFactor), "Illegal load factor: " + loadFactor); this.capacity = QuickMath.nextPowerOfTwo(initialCapacity); this.loadFactor = loadFactor; this.resizeThreshold = (int) (capacity * loadFactor); this.mask = capacity - 1; this.hashes = new int[capacity]; this.table = new Object[capacity]; }
Source:
public void changeConfigFile(String configName) { START for (LoggerContext context: loggerContexts) { END LogManager.getFactory().removeContext(context); } configFile = configName != null ? URI.create(configName) : null; clearLoadedLoggers(); } Probably `loggerContexts.clear()` is missing after the loop.

Target:
public void changeConfigFile(String configName) { for (LoggerContext context: loggerContexts) { LogManager.getFactory().removeContext(context); } configFile = configName != null ? URI.create(configName) : null; clearLoadedLoggers(); loggerContexts.clear(); }
Source:
public void afterRun() { if (recordStore != null) { START if (!wanOriginated) { END publishWanUpdate(key, cacheRecord); } } } Minor: you can collapse the `if` blocks, same in `CacheRemoveBackupOperation`

Target:
public void afterRun() { if (recordStore != null && !wanOriginated) { publishWanUpdate(key, cacheRecord); } }
Source:
START public String getDownloadId() { END String downloadId = "source"; InputStream is = null; try { is = getClass().getClassLoader().getResourceAsStream("hazelcast-download.properties"); if (is != null) { final Properties properties = new Properties(); properties.load(is); downloadId = properties.getProperty("hazelcastDownloadId"); } } catch (IOException ignored) { ignore(ignored); } finally { closeResource(is); } return downloadId; } `private static`?

Target:
private String getDownloadId() { String downloadId = "source"; InputStream is = null; try { is = getClass().getClassLoader().getResourceAsStream("hazelcast-download.properties"); if (is != null) { final Properties properties = new Properties(); properties.load(is); downloadId = properties.getProperty("hazelcastDownloadId"); } } catch (IOException ignored) { ignore(ignored); } finally { closeResource(is); } return downloadId; }
Source:
public Array<T> getElementsContainingArea(Shape area, boolean entirelyContained) { START return null; END } Should return an empty array instance

Target:
public Array<T> getElementsContainingArea(Shape area, boolean entirelyContained) { return new Array<>(); }
Source:
public Array<T> getElementsContainingArea(Shape area, QuadTreeSearchDirection searchDirection, boolean entirelyContained) { START return null; END } Should return an empty array instance

Target:
public Array<T> getElementsContainingArea(Shape area, QuadTreeSearchDirection searchDirection, boolean entirelyContained) { return new Array<>(); }
Source:
protected LanguageFilteringGraph(Graph g, List<String> preferredLanguages) { super(g); this.langs = preferredLanguages; START this.toString = "LanguageFilteringGraph[wrapping " END + ToString.graphToString(g) + "]"; } Is it correct to assume that the state of the graph, `g`, will change over time? If so, capturing the state of `g` at the point of construction may produce a misleading result when calling `toString()` in the future... as opposed to moving this line:37 down into the body of `toString()` method.

Target:
protected LanguageFilteringGraph(Graph g, List<String> preferredLanguages) { super(g); this.langs = preferredLanguages; }
Source:
START public GroupedPropertyList getPropertyList() throws Exception { END if (propertyList == null) { propertyList = new GroupedPropertyList(individual, vreq, editing); } return propertyList; } Not a good idea to add a generic exception here. Should at least be limited to throwing the exceptions that occur in the method, but also consider whether they can be handled within the method and not changing the signature.

Target:
public GroupedPropertyList getPropertyList() { if (propertyList == null) { propertyList = new GroupedPropertyList(individual, vreq, editing); } return propertyList; }
Source:
START public List<Future<?>> getFutures() { END return futures; } This can be "package-private", i.e. no access modifier.

Target:
List<Future<?>> getFutures() { return futures; }
Source:
START public ObjectPropertyTemplateModel call() throws Exception { END ObjectPropertyTemplateModel tm = ObjectPropertyTemplateModel.getObjectPropertyTemplateModel( op, subject, vreq, editing, populatedObjectPropertyList); if (!tm.isEmpty() || (editing && !tm.getAddUrl().isEmpty())) { List<Map<String, String>> l = tm.getStatementData(); } return tm; } No Exception thrown, `throws` can be removed.

Target:
public ObjectPropertyTemplateModel call() { ObjectPropertyTemplateModel tm = ObjectPropertyTemplateModel.getObjectPropertyTemplateModel(op, subject, vreq, editing, populatedObjectPropertyList); if (!tm.isEmpty() || (editing && !tm.getAddUrl().isEmpty())) { tm.getStatementData(); } return tm; }
Source:
private void closeDrawer(Side side) { START if (side==Side.RIGHT||side==Side.BOTH) { END rightDrawer.closeDrawers(); } if (leftDrawer!=null&&(side==Side.LEFT||side==Side.BOTH)) { leftDrawer.closeDrawers(); } openDrawer = Side.NONE; } The left drawer closer has a null check right below, does the right side not need that?

Target:
private void closeDrawer(Side side) { if (side==Side.RIGHT||side==Side.BOTH) { rightDrawer.closeDrawers(); } if (leftDrawer!=null&&(side==Side.LEFT||side==Side.BOTH)) { leftDrawer.closeDrawers(); } }
Source:
protected void onStop() { Log.d(TAG, "Stopping activity"); unbindService(focusConnection); START manager.cleanupMenus(); END super.onStop(); } Shouldn't need to do this both in onStop and onResume? Same with onPause and onStop

Target:
protected void onStop() { Log.d(TAG, "Stopping activity"); unbindService(focusConnection); super.onStop(); }
Source:
public void observerMethodNotOverridingNotifyMethodTreatedAsDefinitionError() { START deployer.deploy(CONFIGURATOR); END } I can see compilation problem for `ExtensionAddingCustomObserver` but to your question - well maybe it would be safer to wrap this to try/catch block and do undeploy in the case of test failure (deployment will pass). This would also mean you can remove `@ShouldThrowException`.

Target:
public void observerMethodNotOverridingNotifyMethodTreatedAsDefinitionError() { }
Source:
public void syntheticEventInvokedAndReturningSourceTest() { assertTrue(extension.timesInvoked() == 3); Map<Type, Extension> map = extension.getSources(); START assertTrue(map.get(Peach.class) instanceof ProcessSyntheticObserverMethodObserver); END assertTrue(map.get(Banana.class) instanceof ProcessSyntheticObserverMethodObserver); assertTrue(map.get(Melon.class) instanceof ProcessSyntheticObserverMethodObserver); } I would use `assertEquals` comparing Class of given extension.

Target:
public void syntheticEventInvokedAndReturningSourceTest() { assertEquals(extension.timesInvoked(), new Integer(3)); Map<Type, Extension> map = extension.getSources(); assertEquals(map.get(Peach.class).getClass(), ProcessSyntheticObserverMethodObserver.class); assertEquals(map.get(Banana.class).getClass(), ProcessSyntheticObserverMethodObserver.class); assertEquals(map.get(Melon.class).getClass(), ProcessSyntheticObserverMethodObserver.class); }
Source:
public Object intercept(InvocationContext ctx) throws Exception { try { beanManager.getContext(RequestScoped.class).isActive(); START isRequestContextActive.set(true); END return ctx.proceed(); } catch (ContextNotActiveException e) { } return ctx.proceed(); } I would probably merge the two lines into one: `isRequestContextActive.set(beanManager.getContext(RequestScoped.class).isActive());` Same goes for the other interceptor (`AfterActivationInterceptor`). Though its just my preference I guess :)

Target:
public Object intercept(InvocationContext ctx) throws Exception { try { isRequestContextActive.set(beanManager.getContext(RequestScoped.class).isActive()); return ctx.proceed(); } catch (ContextNotActiveException e) { } return ctx.proceed(); }
Source:
public DefaultMultiFactorAuthenticationSupportingWebApplicationService(final String id, final String originalUrl, final String artifactId, final ResponseType responseType, final HttpClient httpClient, @NotNull final String authnMethod) { super(cleanupUrl(id), originalUrl, artifactId, httpClient); START this.wrapperService = new SimpleWebApplicationServiceImpl(id, originalUrl, artifactId, responseType, httpClient); END this.authenticationMethod = authnMethod; } You have got a factory that creates DefaultMultiFactorAuthenticationSupportingWebApplicationService objects, right? It needs to be passed into the factory, and from the factory down here.

Target:
public DefaultMultiFactorAuthenticationSupportingWebApplicationService(final String id, final String originalUrl, final String artifactId, final ResponseType responseType, final HttpClient httpClient, @NotNull final String authnMethod) { super(cleanupUrl(id), originalUrl, artifactId, httpClient); this.wrapperService = new SimpleWebApplicationServiceImpl(id, httpClient); this.authenticationMethod = authnMethod; this.responseType = responseType; }
Source:
public String translate(final WebApplicationService targetService, final String triggerValue) { for (final Pattern pattern : translationMap.keySet()) { if (pattern.matcher(triggerValue).matches()) { return this.translationMap.get(pattern); } } if (this.ignoreIfNoMatchIsFound) { return defaultMfaMethod; } START throw new UnrecognizedAuthenticationMethodException("MFA Method for " + triggerValue, targetService.getId()); END } This needs to be just the triggerValue, not a message. As in `throw new UnrecognizedAuthenticationMethodException(triggerValue, targetService.getId());`

Target:
public String translate(final WebApplicationService targetService, final String triggerValue) { for (final Pattern pattern : translationMap.keySet()) { if (pattern.matcher(triggerValue).matches()) { return this.translationMap.get(pattern); } } if (this.defaultMfaMethod != null) { return defaultMfaMethod; } throw new UnrecognizedAuthenticationMethodException(triggerValue, targetService.getId()); }
Source:
public void testNoCredentials() { START assertNull(this.action.createCredentials(requestContext, null, "helloWorld")); END } This isn't going to return null, so it would be better not to wrap it with `assertNull`.

Target:
public void testNoCredentials() { this.action.createCredentials(requestContext, null, "helloWorld"); }
Source:
public void testNoCredentialId() { START assertNull(this.action.createCredentials(requestContext, getCredentials(), null)); END } This isn't going to return null, so it would be better not to wrap it with `assertNull`.

Target:
public void testNoCredentialId() { this.action.createCredentials(requestContext, getCredentials(), null); }
Source:
public void testNoAuthentication() { START assertNull(this.action.createCredentials(requestContext, getCredentials(), "usrPsw")); END } This isn't going to return null, so it would be better not to wrap it with `assertNull`.

Target:
public void testNoAuthentication() { this.action.createCredentials(requestContext, getCredentials(), "usrPsw"); }
Source:
public void signal(String sessionId, SignalProperties props) throws OpenTokException , RequestException, InvalidArgumentException { START if (sessionId == null || sessionId == "" ) { END throw new InvalidArgumentException("Session string null or empty"); } try { this.client.signal(sessionId,null,props); } catch (Exception e) { throw e; } } Should we use `isEmpty()` instead of the empty string comparison?

Target:
public void signal(String sessionId, SignalProperties props) throws OpenTokException , RequestException, InvalidArgumentException { if (sessionId == null || sessionId.isEmpty() ) { throw new InvalidArgumentException("Session string null or empty"); } try { this.client.signal(sessionId,null,props); } catch (Exception e) { throw e; } }
Source:
public void signal(String sessionId, String connectionId, SignalProperties props) throws OpenTokException , RequestException , InvalidArgumentException { START if (sessionId == null || sessionId == "" || connectionId == null || connectionId == "") { END throw new InvalidArgumentException("Session or Connection string null or empty"); } try { this.client.signal(sessionId, connectionId, props); } catch (Exception e) { throw e; } } Should we use `isEmpty()` instead of the empty string comparison?

Target:
public void signal(String sessionId, String connectionId, SignalProperties props) throws OpenTokException , RequestException , InvalidArgumentException { if (sessionId == null || sessionId.isEmpty() || connectionId == null || connectionId.isEmpty()) { throw new InvalidArgumentException("Session or Connection string null or empty"); } try { this.client.signal(sessionId, connectionId, props); } catch (Exception e) { throw e; } }
Source:
private OpenTok(int apiKey, String apiSecret, HttpClient httpClient) { this.apiKey = apiKey; this.apiSecret = apiSecret; START this.client=httpClient; END } spacing

Target:
private OpenTok(int apiKey, String apiSecret, HttpClient httpClient) { this.apiKey = apiKey; this.apiSecret = apiSecret.trim(); this.client = httpClient; }
Source:
private void createServer(Module module, boolean queryParamsAsFormParams) throws Exception { Injector injector = bootstrapTest() .withModules( START new ApplicationNameModule("test-application"), END new TestingNodeModule(), explicitJaxrsModule(), new JsonModule(), new ReportingModule(), new TestingHttpServerModule(), module) .setRequiredConfigurationProperty("jaxrs.query-params-as-form-params", String.valueOf(queryParamsAsFormParams)) .initialize(); lifeCycleManager = injector.getInstance(LifeCycleManager.class); server = injector.getInstance(TestingHttpServer.class); } Don't need this with bootstrapTest()

Target:
private void createServer(Module module, boolean queryParamsAsFormParams) throws Exception { Injector injector = bootstrapTest() .withModules( new TestingNodeModule(), explicitJaxrsModule(), new JsonModule(), new ReportingModule(), new TestingHttpServerModule(), module) .setRequiredConfigurationProperty("jaxrs.query-params-as-form-params", String.valueOf(queryParamsAsFormParams)) .initialize(); lifeCycleManager = injector.getInstance(LifeCycleManager.class); server = injector.getInstance(TestingHttpServer.class); }
Source:
public int getFreeThreadCount() { START return executor.getMaxThreads() + executor.getIdleThreads() - executor.getThreads(); END } it is not obvious. thx

Target:
public int getFreeThreadCount() { return (executor.getMaxThreads() - executor.getThreads()) + executor.getIdleThreads() ; }
Source:
public XmlUserList() { binder = new XmlBinder<User>(User.class); try { START serializer = XmlBinder.class.getDeclaredMethod("serializeObjectToWriter", Object.class, XMLStreamWriter.class); END deserializer = XmlBinder.class.getDeclaredMethod("deserializeToValue", Element.class, Class.class); } catch (NoSuchMethodException e) { throw new RuntimeException("Cannot create object.", e); } serializer.setAccessible(true); deserializer.setAccessible(true); } Ой. А нельзя метод public сделать?

Target:
public XmlUserList() { binder = new XmlBinder<User>(User.class); }
Source:
START protected BigIntegerExtension() { END super(BigInteger.class); } Должен быть public

Target:
public BigIntegerExtension() { super(BigInteger.class); }