auphong2707/dl4se-code-review-dataset huggingface dataset:
Source:
public boolean equals(Object obj) { if (this == obj) return true; if (obj == null) return false; if (getClass() != obj.getClass()) return false; ReferencePointImpl other = (ReferencePointImpl) obj; if (path == null) { if (other.path != null) return false; } else if (!path.equals(other.path)) return false; return true; }

Target:
You can simplify the if-else block to ```Java if (path == null) { return other.path == null; } else { return path.equals(other.path); } ```
Source:
public SharedReferencePointMapper() { idToReferencePointMapping = new HashMap<String, IReferencePoint>(); referencePointToIDMapping = new HashMap<IReferencePoint, String>(); referencePointsOfUsers = new HashMap<User, List<String>>(); partiallySharedResourceMapping = new HashMap<IReferencePoint, Set<IResource>>(); completelySharedReferencePoints = new HashSet<IReferencePoint>(); partiallySharedReferencePoints = new HashSet<IReferencePoint>(); }

Target:
Minor - Unnecessary type declarations during initialization. There are a lot of these in this class, so I'm not going to address them all individually.
Source:
public synchronized void addMissingReferencePointsToUser(User user) { List<String> referencePoints = new ArrayList<String>(); for (String referencePoint : idToReferencePointMapping.keySet()) { referencePoints.add(referencePoint); } this.referencePointsOfUsers.put(user, referencePoints); }

Target:
Loop can be replaced by passing the collection to CTOR: ```suggestion List<String> referencePoints = new ArrayList<>(idToReferencePointMapping.keySet()); ```
Source:
private static IActivityListener createForwarder(final IActivityConsumer target) { return new IActivityListener() { @Override public void created(IActivity activity) { if (activity instanceof GitRequestActivity) { target.exec(rewriteGitRequestActivity((GitRequestActivity) activity)); } else if (activity instanceof GitCollectActivity) { target.exec(rewriteGitCollectActivity((GitCollectActivity) activity)); } else if (activity instanceof GitSendBundleActivity) { target.exec(rewriteGitSendBundleActivity((GitSendBundleActivity) activity)); } else { return; } } }; }

Target:
else branch is not needed
Source:
public synchronized void start() { session.addActivityConsumer(consumer, Priority.ACTIVE); session.addActivityProducer(this); }

Target:
There is no need using synchronized here and in the stop method.
Source:
void queueViewPortChange( @NotNull String path, @Nullable Editor editor, @Nullable LineRange range, @Nullable TextSelection selection) { QueuedViewPortChange requestedViewportChange = new QueuedViewPortChange(editor, range, selection); QueuedViewPortChange previouslyQueuedRequest = queuedViewPortChanges.put(path, requestedViewportChange); if (previouslyQueuedRequest != null) { if (log.isTraceEnabled()) { log.trace( "Dropping previously queued viewport change request for " + path + "; old request: " + previouslyQueuedRequest + ", new request: " + requestedViewportChange); } } }

Target:
Can remain if you remove the `toString` method.
Source:
public void run() { ISarosSession session = sessionManager.getSession(); JID jid = getSelectedJID(); if (session != null || jid == null) { return; } // TODO: Currently only Saros/S is known to have a working JoinSessionRequestHandler, // remove this once the situation changes / change this to it's own feature. if (!discoveryManager.isFeatureSupported(jid, SarosConstants.NAMESPACE_SERVER)) { return; } transmitter.sendPacketExtension( jid, JoinSessionRequestExtension.PROVIDER.create(new JoinSessionRequestExtension())); }

Target:
Is there a reason to check twice whether the selected user is a Saros server (here and in line 445 of `SarosView`)? Or am I misunderstanding the checks? This check is also missing the null-check for the result of ´discoveryManager.isFeatureSupported(...)`.
Source:
protected void executeCancellation() { if (!session.isHost() || session.getRemoteUsers().isEmpty()) sessionManager.stopSession(SessionEndReason.LOCAL_USER_LEFT); }

Target:
```suggestion if (session.isHost() && session.getRemoteUsers().isEmpty()) ``` you have to check if we are the host, otherwise the client disconnects on a canceled outgoing negotiation
Source:
public void setEnabled(boolean enabled) { if (this.enabled && !enabled) { if (LOG.isTraceEnabled()) { LOG.trace("Disabling filesystem listener"); } this.enabled = false; intellijWorkspace.removeResourceListener(this); } else if (!this.enabled && enabled) { if (LOG.isTraceEnabled()) { LOG.trace("Enabling filesystem listener"); } this.enabled = true; intellijWorkspace.addResourceListener(this); } }

Target:
the if around is not needed
Source:
public synchronized IProject get(IReferencePoint referencePoint) { if (referencePointToProjectMapper.containsKey(referencePoint)) { return referencePointToProjectMapper.get(referencePoint); } return null; }

Target:
check not needed as `HashMap.get(...)` returns null if mapping for given key is not present
Source:
private List<IRecord> create(BrowserAction action) { List<IRecord> records = new LinkedList<IRecord>(); // since the library fabric.js (used in the html whiteboard) does not // support parent hierarchies this function will always add the new // element to the root element ElementRecord parent = sxe.getDocumentRecord().getRoot(); ElementRecord newElement = parent.createNewElementRecord(null, action.getElementType()); newElement.setRid(action.getID()); records.add(newElement); records.addAll(setAttributes(newElement, action.getAttributes())); return records; }

Target:
ArrayList should be sufficient, this applies to all appearances in this patch set.
Source:
protected void cleanup(IProgressMonitor monitor, Map<String, IProject> projectMapping) { addProjectsToSession(projectMapping); for (IProject project : projectMapping.values()) activityQueuer.disableQueuing(project); super.cleanup(monitor, projectMapping); }

Target:
Why is this called in the cleanup and not at the end of the `transfer(...)` method? It should basically be the same order (only `checkCancellation(...)` would be called afterwards instead of beforehand). The only big difference would be that with the current implementation, the `addprojectToSession(...)` call is located in the `finally` block, meaning it also gets executed when the incoming project negotiation fails. This is probably the wrong behavior as it does not make much sense to add the "shared" resources to the session when the negotiation/resource sharing failed.
Source:
@Override public void start() { session.addActivityConsumer(this, Priority.ACTIVE); }

Target:
Do you use a formatter ? I haven seen this style when using our Eclipse formatter.
Source:
private void executeFolderRemoval(FolderDeletedActivity activity) throws IOException { SPath path = activity.getPath(); IFolder folder = path.getFolder(); this.editorManager.closeEditorsInFolder(path); folder.delete(IResource.NONE); }

Target:
this keyword is unnecessary
Source:
public void applyTextEdit(TextEditActivity edit) { content.delete(edit.getOffset(), edit.getReplacedText().length()); content.insert(edit.getOffset(), edit.getText()); }

Target:
Check which actions are needed? Only execute `content.delete(....)` if `edit.getReplacedText().length() > 0`, likewise with `content.insert(....)`?
Source:
public final void createNonCoreComponents(ISarosSession session, MutablePicoContainer container) { container.addComponent(ServerEditorManager.class); container.addComponent(FileActivityExecutor.class); container.addComponent(FolderActivityExecutor.class); container.addComponent(TextEditActivityExecutor.class); container.addComponent(NegotiationHandler.class); }

Target:
As you attach this class here I highly suggest to implement Startable or move this handler into application scope.
Source:
public void loadBuildData(@NotNull Properties properties) { loadBuildVersionAndTimeData(properties); loadBuildHostData(properties); loadBuildNumber(System.getenv(), properties); }

Target:
Change ``loadBuildNumber(System.getenv(), properties);`` to ``loadBuildNumber(properties);`` once the BuildServerDataProvider also has a reference to env...
Source:
public void testCompareBasic() throws Exception { // Test on all available basic repos to ensure that the output is identical. for (AvailableGitTestRepo testRepo : AvailableGitTestRepo.values()) { if (testRepo == AvailableGitTestRepo.GIT_COMMIT_ID) { continue; } mavenSandbox.withParentProject("my-basic-project", "jar").withNoChildProject().withGitRepoInParent(testRepo).create(); MavenProject targetProject = mavenSandbox.getParentProject(); verifyNativeAndJGit(testRepo, targetProject, DEFAULT_FORMAT_STRING); } }

Target:
please rewrite to not use continue, harder to track code.
Source:
public void setConfigurable(boolean configurable) { if (configurable) { this.configurable = configurable; } }

Target:
Why this if statement? This prevents the configurable element to be set to false!
Source:
@Override public E element() { lock.lock(); try { if (queue.isEmpty()) { throw new NoSuchElementException(); } return queue.peek(); } catch (IOException e) { QueueFile.<Error>getSneakyThrowable(e); return null; } finally { lock.unlock(); } }

Target:
throws
Source:
@Override public Iterator<E> iterator() { lock.lock(); try { return queue.iterator(); } finally { lock.unlock(); } }

Target:
is locking while creating this factory necessary? the iterator still iterates on the backing ObjectQueue (not a clone of it or anything).
Source:
@Override public boolean addAll(Collection<? extends E> c) { if (c.isEmpty()) { return false; } lock.lock(); try { for (E e : c) { queue.add(e); } nonEmpty.signal(); return true; } catch (IOException e) { QueueFile.<Error>getSneakyThrowable(e); return false; } finally { lock.unlock(); } }

Target:
throws
Source:
@Override public void clear() { lock.lock(); try { queue.clear(); } catch (IOException e) { QueueFile.<Error>getSneakyThrowable(e); } finally { lock.unlock(); } }

Target:
nit: throws for consistency and clarity.
Source:
@Test public void testMissingFileInitializes() throws Exception { testFile = File.createTempFile(FRESH_SERIALIZED_QUEUE, "test"); assertTrue(testFile.delete()); assertFalse(testFile.exists()); QueueFile queue = new QueueFile.Builder(testFile).build(); try { assertEquals(0, queue.size()); assertTrue(testFile.exists()); } finally { queue.close(); } }

Target:
i guess the close could in `cleanup()`? dunno which is preferable.
Source:
static File copyTestFile(String file) throws IOException { File newFile = File.createTempFile(file, "test"); InputStream in = QueueTestUtils.class.getResourceAsStream(file); BufferedSink sink = Okio.buffer(Okio.sink(newFile)); sink.writeAll(Okio.source(in)); sink.flush(); sink.close(); assertTrue(newFile.exists()); return newFile; }

Target:
Close will flush. Or even better, try-with-resources!
Source:
@Override public T next() { if (closed) throw new IllegalStateException("closed"); checkForComodification(); if (size() == 0) throw new NoSuchElementException(); if (nextElementIndex >= size()) throw new NoSuchElementException(); return entries.get(nextElementIndex++); }

Target:
Does this make the check on the previous line unnecessary?
Source:
@Test public void testIteratorRemoveDisallowsConcurrentModification() throws IOException { QueueFile queueFile = new QueueFile(file); for (int i = 0; i < 15; i++) { queueFile.add(values[i]); } Iterator<byte[]> iterator = queueFile.iterator(); iterator.next(); queueFile.remove(); try { iterator.remove(); fail("remove should not permit concurrent modifications."); } catch (ConcurrentModificationException ignored) { } }

Target:
can you switch the import to `org.junit.Assert.fail` and remove these two messages? If this fails the reason is already clear and I don't like being forced to provide a redundant message.
Source:
public final void remove(int n) throws IOException { try { queueFile.remove(n); if (listener != null) { for (int i = 0; i < n; i++) listener.onRemove(this); } } catch (IOException e) { throw new FileException("Failed to remove.", e, file); } }

Target:
braces for body
Source:
private StackExchangeApi() { }

Target:
make it protected. It was my fault to make all API constructors private. I fixed that. In master branch all API constructors are protected, so anyone can extend API in their code if they want. But couldn't instantiate directly, forcing them to use singleton
Source:
public boolean isOob(final OAuthConfig config) { return "oob".equals(config.getCallback()); }

Target:
May be make it static and invoke like ImgurApi.isOob() instead of ((ImgurApi) getApi()).isOob()?
Source:
public List<File> getContextScreenshots() { List<File> screenshots = currentContextScreenshots.get(); return Collections.unmodifiableList(screenshots == null ? Collections.emptyList() : screenshots); }

Target:
I would change the order: there is no need to call `unmodifiableList` for `emptyList`: ``` return screenshots == null ? Collections.emptyList() : Collections.unmodifiableList(screenshots); ```
Source:
private boolean isBoolean(String value) { return "true".equals(value) || "false".equals(value); }

Target:
Suppose makes sense to convert value to lower case before comparing.
Source:
CloseDriverCommand(WebDriver webDriver, SelenideProxyServer selenideProxyServer) { this.webDriver = webDriver; this.selenideProxyServer = selenideProxyServer; this.closeBrowserTimeoutMs = 5000; }

Target:
I suggest to remove this field at all. There is no need to limit lifetime of `CloseDriverCommand`. Let it work as long as it takes.
Source:
public void setLevel(Level newLevel) throws SecurityException { // We have to propagate our level to an internal data structure in the superclass super.setLevel(newLevel); LogContext.checkAccess(); loggerNode.setLevel(newLevel); }

Target:
This should be moved below the `LogContext.checkAccess()`.
Source:
private RedirectHandler getOrInstall(Logger logger) { synchronized (this) { for (Handler handler : logger.getHandlers()) { if (handler instanceof RedirectHandler) { return (RedirectHandler) handler; } } RedirectHandler redirectHandler = new RedirectHandler(logContext.getLogger(logger.getName())); logger.addHandler(redirectHandler); logger.setUseParentHandlers(false); return redirectHandler; } }

Target:
This doesn't seem quite right. If the `logger.setUseParentHandlers(true)` is set elsewhere this could override it.
Source:
protected void doPublish(final ExtLogRecord record) { record.copyAll(); synchronized (buffer) { if (isLoggable(record)) { if (buffer.size() == limit) { buffer.removeFirst(); } buffer.addLast(record); } for (Handler handler : getHandlers()) { if (handler.isLoggable(record)) { handler.publish(record); } } } }

Target:
Does this not duplicate an existing check?
Source:
public static void dropFunctions(final PrintWriter writer, final PgDiffArguments arguments, final PgSchema oldSchema, final PgSchema newSchema, final SearchPathHelper searchPathHelper) { if (oldSchema == null) { return; } // Drop functions that exist no more for (final PgFunction oldFunction : oldSchema.getFunctions()) { if (!newSchema.containsFunction(oldFunction.getSignature())) { searchPathHelper.outputSearchPath(writer); writer.println(); writer.println(oldFunction.getDropSQL(arguments)); } } }

Target:
the majority of your changes are simply passing arguments all around the codebase
Source:
private static String currenciesToJSON(final ArrayList<String> currencies) { HashMap map = new HashMap<>(); for (String e : currencies) map.put("currencies", e); System.out.println("map : " + map); return new Gson().toJson(map); }

Target:
Please use braces
Source:
public List<Integer> getProjects() { assert projects == null || !projects.isEmpty(); if (projects == null) { int fieldCount = target.getFieldCount(); List<Integer> res = new ArrayList<>(fieldCount); for (int i = 0; i < fieldCount; i++) { res.add(i); } return res; } return projects; }

Target:
Shouldn't we allow empty projects as distinct from null. I guess `null` means "all the table fields", empty projects would mean no columns are actually selected. For the query `SELECT current_date() FORM map`
Source:
public PhoneHome(Node node, String baseurl) { hazelcastNode = node; logger = hazelcastNode.getLogger(com.hazelcast.internal.util.phonehome.PhoneHome.class); basePhoneHomeUrl = baseurl; }

Target:
Please make this constructor package-private. We use it only from the tests, so there is no need to expose it publicly.
Source:
public int hashCode() { return operand != null ? operand.hashCode() : 0; }

Target:
Does the operand really can be null?
Source:
public void testPhoneHomeParameterCreator() { PhoneHomeParameterCreator phoneHomeParameterCreator = new PhoneHomeParameterCreator(); phoneHomeParameterCreator.addParam("1", "hazelcast"); phoneHomeParameterCreator.addParam("2", "phonehome"); Map<String, String> map = phoneHomeParameterCreator.getParameters(); assertEquals("?1=hazelcast&2=phonehome", phoneHomeParameterCreator.build()); assertNotNull(map); assertEquals(ImmutableMap.of("1", "hazelcast", "2", "phonehome"), map); assertNull(map.get("3")); }

Target:
Since we have the `assertEquals(ImmutableMap.of("1", "hazelcast", "2", "phonehome"), map);` check now, you can remove the `assertNotNull(map);` and the `assertNull(map.get("3"));` assertions, since these are unnecessary. The `assertEquals()` call covers these conditions.
Source:
public PhoneHomeParameterCreator createParameters() { PhoneHomeParameterCreator parameterCreator = new PhoneHomeParameterCreator(); MetricsCollector[] metricsCollectorArray = new MetricsCollector[]{new BuildInfoCollector(), new ClusterInfoCollector(), new ClientInfoCollector(), new MapInfoCollector(), new OSInfoCollector()}; List<MetricsCollector> metricsCollectorList = Arrays.asList(metricsCollectorArray); metricsCollectorList.forEach((metricsCollector -> parameterCreator. addMap(metricsCollector.computeMetrics(hazelcastNode)))); return parameterCreator; }

Target:
`Arrays.asList()` accepts variable-length argument list, so you can write `List<MetricsCollector> metricsCollectorList = Arrays.asList(new BuildInfoCollector(), new ClusterInfoCollector(), ...);` and drop the `metricsCollectorArray` variable. Also please let's make it a field instead of a local variable.
Source:
public void start() { if (!enabled) { logger.info(format("Diagnostics disabled. To enable add -D%s=true to the JVM arguments.", ENABLED.getName())); return; } if (stdout) { this.diagnosticsLog = new DiagnosticsStdout(this); } else { this.diagnosticsLog = new DiagnosticsLogFile(this); } this.scheduler = new ScheduledThreadPoolExecutor(1, new DiagnosticSchedulerThreadFactory()); logger.info("Diagnostics started"); }

Target:
Can you convert this into using a ternary operator? ``` this.diagnosticsLogs = stdOut ? new DiagnosticsStdout(this) : new DiagnosticsLogFile(this); ``` It makes the code less verbose.
Source:
public boolean schedule() { // If the fragment is already scheduled, we do not need to do anything else, because executor will re-check queue state // before exiting. if (scheduled.get()) { return false; } // Otherwise we schedule the fragment into the worker pool. boolean res = scheduled.compareAndSet(false, true); if (res) { fragmentPool.submit(this); } return res; }

Target:
It seems this check is not necessary because it is covered by the `scheduled.compareAndSet` logic.
Source:
protected Collection<Address> getPossibleAddressesForInitialJoin() { long deadLine = System.nanoTime() + SECONDS.toNanos(maximumWaitingTimeBeforeJoinSeconds); for (int i = 0; System.nanoTime() - deadLine < 0; i++) { Collection<Address> possibleAddresses = getPossibleAddresses(); if (!possibleAddresses.isEmpty()) { return possibleAddresses; } idleStrategy.idle(i); } return Collections.emptyList(); }

Target:
I'm not sure about this one. Please pull this out of this PR because it isn't related to timing and lets run some ad hoc examples to make sure we don't run into some nasty overflow/sign related problems.
Source:
public Object getArgument(int index) { assert index >= 0 && index <= arguments.size(); return arguments.get(index); }

Target:
`index < arguments.size()` ?
Source:
public Entry(int coreId, AffinityLock lock) { this.coreId = coreId; this.lock = lock; }

Target:
Private constructor
Source:
public IndexConfig setBitmapIndexOptions(BitmapIndexOptions bitmapIndexOptions) { this.bitmapIndexOptions.setUniqueKey(bitmapIndexOptions.getUniqueKey()); this.bitmapIndexOptions.setUniqueKeyTransformation(bitmapIndexOptions.getUniqueKeyTransformation()); return this; }

Target:
These two lines look dangerous to me because we mutate an object which was set earlier. Consider the following code: ``` IndexConfig config = new IndexConfig(); BitmapIndexOptions options = config1.getBitmapIndexOptions(); // ... config.setBitmapIndexOptions(<new options>); // "options" object changed unexpectedly ``` I would rather overwrite an object in the setter and perform a lazy initialization in getter as we do in other config classes (e.g. `IndexConfig.getAttributes()` copies this approach).
Source:
private void validateSetOptimizeQueriesOption(boolean optimizeQueries) { if (!setCacheDeserializedValuesExplicitlyInvoked) { return; } if ((cacheDeserializedValues == CacheDeserializedValues.INDEX_ONLY || cacheDeserializedValues == CacheDeserializedValues.NEVER) && optimizeQueries) { throw new ConfigurationException("Deprecated option 'optimize-queries' is being set to true, " + "but 'cacheDeserializedValues' was set to NEVER or INDEX_ONLY. " + "These are conflicting options. Please remove the `optimize-queries'"); } else if (cacheDeserializedValues == CacheDeserializedValues.ALWAYS && !optimizeQueries) { throw new ConfigurationException("Deprecated option 'optimize-queries' is being set to false, " + "but 'cacheDeserializedValues' was set to ALWAYS. " + "These are conflicting options. Please remove the `optimize-queries'"); } }

Target:
really minor: for symmetry with `validateCacheDeserializedValuesOption`, maybe use: `if (cacheDeserializedValues != CacheDeserializedValues.ALWAYS)`?
Source:
public DistributedObjectEvent(EventType eventType, String serviceName, String objectName, DistributedObject distributedObject, UUID source) { super(source); this.eventType = eventType; this.serviceName = serviceName; this.objectName = objectName; this.distributedObject = distributedObject; this.source = source; }

Target:
This line is unnecessary.
Source:
public void readData(ObjectDataInput in) throws IOException { name = in.readUTF(); type = IndexType.getById(in.readInt()); attributes = readNullableList(in); if (type == IndexType.BITMAP) { bitmapIndexOptions = in.readObject(); } }

Target:
If we do not write options unconditionally, we will not validate them on the server-side. Consider a user who submits `IndexConfig{type=HASH, bitmapOptions=<not null object>}`. This is an invalid config, but how do we know what was his real intention - to create a hash index or a bitmap index? I would rather read/write the object as is, and throw an exception on invalid config, rather than ignoring invalid state silently.
Source:
public void assertNoMBeans() { Set<ObjectInstance> instances = queryOurInstances(); assertEquals(Arrays.toString(instances.toArray()), 0, instances.size()); }

Target:
minor: `assertThat(instances, is(empty()))`?
Source:
void onServerClose(final String reason) { executor.executeIncoming(new Runnable() { @Override public String toString() { return "Server Closed EOF. " + MockedClientConnection.this; } @Override public void run() { MockedClientConnection.this.close(reason, new TargetDisconnectedException("Mocked Remote socket closed")); } }); executor.shutdownOutgoing(); System.out.println("<<<< <<<<"); }

Target:
Leftover?
Source:
public void clear() { takeWriteLock(); try { bitmap.clear(); if (internalKeys != null) { internalKeys.clear(); internalKeyCounter = 0; } if (internalObjectKeys != null) { internalObjectKeys.clear(); internalKeyCounter = 0; } } finally { releaseWriteLock(); } }

Target:
In case of "no remapping, raw attribute values are used as long keys" it seems both `internalKeys` and `internalObjectKeys` are `null` and then we don't reset `internalKeyCounter` to 0?
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())) { throw new NullPointerException("integer-valued unique key value is required"); } return ((Number) key).longValue(); }

Target:
Maybe `IllegalArgumentException` is more appropriate here?
Source:
private long extractLongKey(QueryableEntry entry) { Object key = entry.getAttributeValue(keyAttribute); if (key == null) { 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(); }

Target:
It seems the checks are similar to the previous method and we should avoid code duplication.
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(); constructors[PERMISSION_CONFIG_DTO] = arg -> new PermissionConfigDTO(); constructors[SET_LICENSE] = arg -> new SetLicenseOperation(); constructors[CHANGE_CLUSTER_STATE] = arg -> new ChangeClusterStateOperation(); return new ArrayDataSerializableFactory(constructors); }

Target:
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?
Source:
public String toString() { return "DiscoveryConfig{" + "discoveryStrategyConfigs=" + discoveryStrategyConfigs + ", discoveryServiceProvider=" + discoveryServiceProvider + ", nodeFilter=" + nodeFilter + '\'' + ", nodeFilterClass='" + nodeFilterClass + '\'' + '}'; }

Target:
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.
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) { mapEventPublisher.publishEvent(descriptor.caller, descriptor.mapName, descriptor.eventType, descriptor.dataKey, descriptor.oldValue, descriptor.dataValue); } invalidateNearCache(invalidationKeys); disposeDeferredBlocks = true; super.afterRunInternal(); }

Target:
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.
Source:
public static <T> void decodeNullable(ClientMessage.ForwardFrameIterator iterator, Function<ClientMessage.ForwardFrameIterator, T> decodeFunction, Consumer<T> consumer) { if (nextFrameIsNullEndFrame(iterator)) { decode(iterator, decodeFunction, consumer); } }

Target:
It should be `if(! nextFrameIsNullEndFrame)`
Source:
public final boolean equals(Object o) { if (o instanceof LFUEvictionPolicyComparator) { return true; } return false; }

Target:
could be simplified as `return (o instanceof LFUEvictionPolicyComparator);`
Source:
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); } }

Target:
should read `&&` instead of `||`
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()); } restApiConfig.enableAllGroups(); return restApiConfig; }

Target:
This line should be removed, we don't want all groups to be enabled always.
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; }, true ); }

Target:
You should not need `deserializeResponse` as the response is not data.
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); mutationObserver.onReplicationPutRecord(newRecord.getKey(), newRecord, !populateIndexes); updateStatsOnPut(replicatedRecord.getHits(), nowInMillis); return newRecord; }

Target:
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.
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) { Object obj = recordAndDataValuePairs.get(i); if (obj != null) { putBackup((Record) obj); } } } else { for (Record<Data> record : dataRecords) { putBackup(record); } } }

Target:
Can the record be `null` here since we explicitly check for null before adding it in `PutAllOperation#toBackupListByRemovingEvictedRecords` and `MergeOperation#toBackupListByRemovingEvictedRecords`?
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) { found = true; } } return found; }

Target:
why not return here?
Source:
public ICredentialsFactory asCredentialsFactory(ClassLoader cl) { if (implementation != null) { return implementation; } else { try { ICredentialsFactory credentialsFactory = ClassLoaderUtil.newInstance(cl, className); credentialsFactory.init(properties); return credentialsFactory; } catch (Exception e) { throw new IllegalArgumentException("Could not create instance of '" + className + "', cause: " + e.getMessage(), e); } } }

Target:
Is it expected that we will create `credentialsFactory` every time? Maybe we should cache it?
Source:
public static <I, R> Aggregator<I, CanonicalizingHashSet<R>> distinct(String attributePath) { return new DistinctValuesAggregator<I, R>(attributePath); }

Target:
`CanonicalizingHashSet` is an internal class. It should not be visible in the public API. I think this part should stay as `Set`
Source:
public Data getResult() { if (result == null) { return ss.toData(newValue); } return result; }

Target:
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`?
Source:
protected Operation prepareOperation() { MapOperationProvider operationProvider = getMapOperationProvider(parameters.name); MapOperation op; if (parameters.ttl == DEFAULT_TTL) { 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; }

Target:
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(..); } } ```
Source:
public JavaKeyStoreSecureStoreConfig setPassword(String password) { checkNotNull(password, "Java Key Store password cannot be null!"); this.password = password; return this; }

Target:
There are keystore types which don't require a password or gets it from another channel (e.g. `WINDOWS-MY` type).
Source:
protected SplitBrainMergePolicy getMergePolicy(String dataStructureName) { CacheConfig cacheConfig = cacheService.getConfigs().get(dataStructureName); return mergePolicyProvider.getMergePolicy(cacheConfig.getMergePolicyConfig().getPolicy()); }

Target:
Minor: can you still use `cacheService.getMergePolicy(dataStructureName)` here?
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 && nullSafeEqual(c1.getDepth(), c2.getDepth())); }

Target:
minor: no reason to use `nullSafeEqual` for `int` comparison here (same below)
Source:
public boolean equals(Object obj) { if (id == null || !(obj instanceof DummyObject)) { return false; } DummyObject other = (DummyObject) obj; return other.id != null && id.equals(other.id); }

Target:
What if both object have id==null? Then they are not equal?
Source:
public static YamlNode load(InputStream inputStream, String rootName) { try { Object document = getLoad().loadFromInputStream(inputStream); inputStream.close(); return buildDom(rootName, document); } catch (Exception ex) { throw new YamlException("An error occurred while loading and parsing the YAML stream", ex); } }

Target:
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`
Source:
public PartitionWideEntryBackupOperation(String name, EntryBackupProcessor backupProcessor) { super(name, backupProcessor); Thread.dumpStack(); }

Target:
Leftover debug statement (most probably causes the test failures & large PR builder time).
Source:
public boolean apply(Map.Entry mapEntry) { Thread.dumpStack(); PREDICATE_APPLY_COUNT.incrementAndGet(); return true; }

Target:
debug leftover?
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() { new Thread() { @Override public void run() { sleepSeconds(5); offloadedOperation().sendResponse(response); } }.start(); } })); assertCompletesEventually(f); assertEquals(response, f.get()); }

Target:
minor: can be also converted to ``` new Thread(() -> { sleepSeconds(5); offloadedOperation().sendResponse(response); }).start(); ```
Source:
public static <K, V> Predicate<EventJournalMapEvent<K, V>> mapPutEvents() { return new MapPutEventsPredicate<>(); }

Target:
Although we require JDK8, we must remain JDK6 compatible so you must specify the types here.
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: return new DeserializingEntry<>(); default: return null; } } }; }

Target:
Remove the diamond operator.
Source:
public static <K, V> Function<EventJournalCacheEvent<K, V>, Entry<K, V>> cacheEventToEntry() { return new CacheEventToEntryProjection<>(); }

Target:
Missing types
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) { if (!Comparables.equal(components[i], that.components[i])) { return false; } } return true; }

Target:
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`?
Source:
public void addAllInternal(CanonicalizingHashSet<E> set) { // elements are already canonicalized map.putAll(set.map); }

Target:
minor: access can be package-private (in support of the method name's `Internal` suffix :-) ). same for `addInternal` below.
Source:
private boolean hasClientServerSocket() { if (!config.getAdvancedNetworkConfig().isEnabled()) { return true; } Map<EndpointQualifier, EndpointConfig> endpointConfigs = config.getAdvancedNetworkConfig().getEndpointConfigs(); EndpointConfig clientEndpointConfig = endpointConfigs.get(CLIENT); return clientEndpointConfig instanceof ServerSocketEndpointConfig; }

Target:
Isn't `clientEndpointConfig != null` enough here?
Source:
public int getActivePartitionCount() { // todo allocating a new Address each time ?? InetSocketAddress thisAddress = hazelcastInstance.getCluster().getLocalMember().getSocketAddress(MEMBER); return managedObject.getMemberPartitionsIfAssigned(new Address(thisAddress)).size(); }

Target:
TODO
Source:
private boolean isQuorumNeeded(Operation op) { if (op instanceof QuorumCheckAwareOperation && !((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); } }

Target:
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.
Source:
private boolean shouldTriggerMasterToAssignPartitions() { ClusterServiceImpl clusterService = node.getClusterService(); return partitionStateManager.isInitialized() && clusterService.isJoined() && node.getNodeExtension().isStartCompleted(); }

Target:
Should not this be `!partitionStateManager.isInitialized() && ...`?
Source:
public MapEvictionPolicy getMapEvictionPolicy() { if (mapEvictionPolicy != null) { return mapEvictionPolicy; } if (evictionPolicy == null) { return null; } return findMatchingMapEvictionPolicy(evictionPolicy); }

Target:
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; }
Source:
public ClientReliableTopicConfig setName(String name) { this.name = name; return this; }

Target:
Changing return types might not be possible in 3.x. See [this discussion](https://github.com/hazelcast/hazelcast/pull/11107).
Source:
public E get() throws InterruptedException, ExecutionException { String name = Thread.currentThread().getName(); System.out.println(">>> FATAL " + name); if (name.contains("client.thread")) { throw new IllegalStateException(">>> FATAL " + name); } return super.get(); }

Target:
is this left over for debugging?
Source:
public void info(Throwable thrown) { long startTime = System.nanoTime(); delegate.fine(thrown); logOnSlowLogging(startTime); }

Target:
`info` instead of `fine` here
Source:
public long getMaxIdle() { return 0; }

Target:
Should this maybe return `RecordStore.DEFAULT_TTL` (-1 --> use `MapConfig`'s default) instead of `0` (--> infinite max idle)?
Source:
protected Collection<MultiMapRecord> getNewRecordsCollection() { final MultiMapConfig.ValueCollectionType valueCollectionType = config.getValueCollectionType(); return createCollection(valueCollectionType); }

Target:
I would not declare the local variable. makes the method more complex than needs to be.
Source:
public boolean addValue(Data dataKey, MultiMapRecord value, int index) { MultiMapValue multiMapValue = getOrCreateMultiMapValue(dataKey); boolean added; 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; }

Target:
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);`
Source:
public Collection<MultiMapRecord> remove(Data dataKey, boolean copyOf) { MultiMapValue multiMapValue = multiMapValues.remove(dataKey); if (multiMapValue != null) { decrSize(multiMapValue.size()); return multiMapValue.getCollection(copyOf); } else { return null; } }

Target:
Redundant `else` blocks.
Source:
public boolean delete(Data dataKey) { MultiMapValue value = multiMapValues.remove(dataKey); if (value != null) { decrSize(value.size()); return true; } else { return false; } }

Target:
Redundant else block.
Source:
public void afterRun() throws Exception { super.afterRun(); if (recordStore.isWanReplicationEnabled()) { for (Data key : keys) { CacheRecord record = recordStore.getRecord(key); wanEventPublisher.publishWanUpdate(name, CacheEntryViews.createEntryView(key, expiryPolicy, record)); } } }

Target:
`CacheOperation#publishWanUpdate` can be used here.
Source:
protected void readInternal(ObjectDataInput in) throws IOException { super.readInternal(in); int s = in.readInt(); keys = new ArrayList<Data>(); while (s-- > 0) { keys.add(in.readData()); } expiryPolicy = in.readData(); }

Target:
`ArrayList` constructor can be called with `initialCapacity`.
Source:
public void testTTL_entryShouldNotBeReachableAfterTTL() { IMap<Integer, String> map = createSimpleMap(); map.put(1, "value0", 0, TimeUnit.SECONDS); sleepSeconds(1); assertFalse(map.containsKey(1)); }

Target:
this makes the entry infinite ttl.
Source:
public OAHashSet(int initialCapacity, float loadFactor) { checkNotNegative(initialCapacity, "Illegal initial capacity: " + initialCapacity); checkFalse(loadFactor <= 0 || 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]; }

Target:
Maybe we could check that load factor is also smaller than 1
Source:
public void changeConfigFile(String configName) { for (LoggerContext context: loggerContexts) { LogManager.getFactory().removeContext(context); } configFile = configName != null ? URI.create(configName) : null; clearLoadedLoggers(); }

Target:
Probably `loggerContexts.clear()` is missing after the loop.
Source:
public void afterRun() { if (recordStore != null) { if (!wanOriginated) { publishWanUpdate(key, cacheRecord); } } }

Target:
Minor: you can collapse the `if` blocks, same in `CacheRemoveBackupOperation`
Source:
public 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; }

Target:
`private static`?
Source:
public Array<T> getElementsContainingArea(Shape area, boolean entirelyContained) { return null; }

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

Target:
Should return an empty array instance
Source:
protected LanguageFilteringGraph(Graph g, List<String> preferredLanguages) { super(g); this.langs = preferredLanguages; this.toString = "LanguageFilteringGraph[wrapping " + ToString.graphToString(g) + "]"; }

Target:
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.
Source:
public GroupedPropertyList getPropertyList() throws Exception { if (propertyList == null) { propertyList = new GroupedPropertyList(individual, vreq, editing); } return propertyList; }

Target:
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.
Source:
public List<Future<?>> getFutures() { return futures; }

Target:
This can be "package-private", i.e. no access modifier.
Source:
public ObjectPropertyTemplateModel call() throws Exception { 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; }

Target:
No Exception thrown, `throws` can be removed.
Source:
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(); } openDrawer = Side.NONE; }

Target:
The left drawer closer has a null check right below, does the right side not need that?
Source:
protected void onStop() { Log.d(TAG, "Stopping activity"); unbindService(focusConnection); manager.cleanupMenus(); super.onStop(); }

Target:
Shouldn't need to do this both in onStop and onResume? Same with onPause and onStop