Repository: TheAlgorithms/Java
Pull request #5404 (2024-08-26 13:38:59)

refactor: `HammingDistance`
Class cleanup.
Readability improvements.

<!--
Thank you for your contribution!
In order to reduce the number of notifications sent to the maintainers, please:
- create your PR as draft, cf. https://docs.github.com/en/pull-requests/collaborating-with-pull-requests/proposing-changes-to-your-work-with-pull-requests/about-pull-requests#draft-pull-requests,
- make sure that all of the CI checks pass,
- mark your PR as ready for review, cf. https://docs.github.com/en/pull-requests/collaborating-with-pull-requests/proposing-changes-to-your-work-with-pull-requests/changing-the-stage-of-a-pull-request#marking-a-pull-request-as-ready-for-review
-->

<!-- For completed items, change [ ] to [x] -->

- [x] I have read [CONTRIBUTING.md](https://github.com/TheAlgorithms/Java/blob/master/CONTRIBUTING.md).
- [x] This pull request is all my own work -- I have not plagiarized it.
- [x] All filenames are in PascalCase.
- [x] All functions and variable names follow Java naming conventions.
- [x] All new algorithms have a URL in their comments that points to Wikipedia or other similar explanations.
- [x] All new code is formatted with `clang-format -i --style=file path/to/your/file.java`

codecov-commenter: ## [Codecov](https://app.codecov.io/gh/TheAlgorithms/Java/pull/5404?dropdown=coverage&src=pr&el=h1&utm_medium=referral&utm_source=github&utm_content=comment&utm_campaign=pr+comments&utm_term=TheAlgorithms) Report
All modified and coverable lines are covered by tests :white_check_mark:
> Project coverage is 48.02%. Comparing base [(`64ff9b2`)](https://app.codecov.io/gh/TheAlgorithms/Java/commit/64ff9b2efe0533027139a14ea8f66e63f483e541?dropdown=coverage&el=desc&utm_medium=referral&utm_source=github&utm_content=comment&utm_campaign=pr+comments&utm_term=TheAlgorithms) to head [(`d445810`)](https://app.codecov.io/gh/TheAlgorithms/Java/commit/d445810f4ca52c69203be0d470d0f935631a66a9?dropdown=coverage&el=desc&utm_medium=referral&utm_source=github&utm_content=comment&utm_campaign=pr+comments&utm_term=TheAlgorithms).

<details><summary>Additional details and impacted files</summary>


```diff
@@            Coverage Diff            @@
##             master    #5404   +/-   ##
=========================================
  Coverage     48.01%   48.02%           
- Complexity     2962     2963    +1     
=========================================
  Files           524      524           
  Lines         15275    15276    +1     
  Branches       2903     2904    +1     
=========================================
+ Hits           7334     7336    +2     
+ Misses         7638     7637    -1     
  Partials        303      303           
```

</details>

[:umbrella: View full report in Codecov by Sentry](https://app.codecov.io/gh/TheAlgorithms/Java/pull/5404?dropdown=coverage&src=pr&el=continue&utm_medium=referral&utm_source=github&utm_content=comment&utm_campaign=pr+comments&utm_term=TheAlgorithms).   
:loudspeaker: Have feedback on the report? [Share it here](https://about.codecov.io/codecov-pr-comment-feedback/?utm_medium=referral&utm_source=github&utm_content=comment&utm_campaign=pr+comments&utm_term=TheAlgorithms).


Patch:
diff --git a/src/main/java/com/thealgorithms/strings/HammingDistance.java b/src/main/java/com/thealgorithms/strings/HammingDistance.java
index 95c523cc..235e317d 100644
--- a/src/main/java/com/thealgorithms/strings/HammingDistance.java
+++ b/src/main/java/com/thealgorithms/strings/HammingDistance.java
@@ -1,34 +1,45 @@
 package com.thealgorithms.strings;
 
-/* In information theory, the Hamming distance between two strings of equal length
-is the number of positions at which the corresponding symbols are different.
-https://en.wikipedia.org/wiki/Hamming_distance
-*/
+/**
+ * Class for calculating the Hamming distance between two strings of equal length.
+ * <p>
+ * The Hamming distance is the number of positions at which the corresponding symbols are different.
+ * It is used in information theory, coding theory, and computer science.
+ * </p>
+ * @see <a href="https://en.wikipedia.org/wiki/Hamming_distance">Hamming distance - Wikipedia</a>
+ */
 public final class HammingDistance {
     private HammingDistance() {
     }
 
     /**
-     * calculate the hamming distance between two strings of equal length
+     * Calculates the Hamming distance between two strings of equal length.
+     * <p>
+     * The Hamming distance is defined only for strings of equal length. If the strings are not
+     * of equal length, this method throws an {@code IllegalArgumentException}.
+     * </p>
      *
      * @param s1 the first string
      * @param s2 the second string
-     * @return {@code int} hamming distance
-     * @throws Exception
+     * @return the Hamming distance between the two strings
+     * @throws IllegalArgumentException if the lengths of {@code s1} and {@code s2} are not equal
      */
-    public static int calculateHammingDistance(String s1, String s2) throws Exception {
+    public static int calculateHammingDistance(String s1, String s2) {
+        if (s1 == null || s2 == null) {
+            throw new IllegalArgumentException("Strings must not be null");
+        }
+
         if (s1.length() != s2.length()) {
-            throw new Exception("String lengths must be equal");
+            throw new IllegalArgumentException("String lengths must be equal");
         }
 
-        int stringLength = s1.length();
-        int counter = 0;
+        int distance = 0;
 
-        for (int i = 0; i < stringLength; i++) {
+        for (int i = 0; i < s1.length(); i++) {
             if (s1.charAt(i) != s2.charAt(i)) {
-                counter++;
+                distance++;
             }
         }
-        return counter;
+        return distance;
     }
 }


Test patch:
diff --git a/src/test/java/com/thealgorithms/strings/HammingDistanceTest.java b/src/test/java/com/thealgorithms/strings/HammingDistanceTest.java
index e0fbdb14..5c064034 100644
--- a/src/test/java/com/thealgorithms/strings/HammingDistanceTest.java
+++ b/src/test/java/com/thealgorithms/strings/HammingDistanceTest.java
@@ -3,22 +3,34 @@ package com.thealgorithms.strings;
 import static org.junit.jupiter.api.Assertions.assertEquals;
 import static org.junit.jupiter.api.Assertions.assertThrows;
 
+import java.util.stream.Stream;
 import org.junit.jupiter.api.Test;
+import org.junit.jupiter.params.ParameterizedTest;
+import org.junit.jupiter.params.provider.Arguments;
+import org.junit.jupiter.params.provider.CsvSource;
+import org.junit.jupiter.params.provider.MethodSource;
 
-public class HammingDistanceTest {
+class HammingDistanceTest {
 
-    @Test
-    void testHammingDistance() throws Exception {
-        assertEquals(HammingDistance.calculateHammingDistance("", ""), 0);
-        assertEquals(HammingDistance.calculateHammingDistance("java", "java"), 0);
-        assertEquals(HammingDistance.calculateHammingDistance("karolin", "kathrin"), 3);
-        assertEquals(HammingDistance.calculateHammingDistance("kathrin", "kerstin"), 4);
-        assertEquals(HammingDistance.calculateHammingDistance("00000", "11111"), 5);
+    @ParameterizedTest
+    @CsvSource({"'', '', 0", "'java', 'java', 0", "'karolin', 'kathrin', 3", "'kathrin', 'kerstin', 4", "'00000', '11111', 5", "'10101', '10100', 1"})
+    void testHammingDistance(String s1, String s2, int expected) {
+        assertEquals(expected, HammingDistance.calculateHammingDistance(s1, s2));
+    }
+
+    @ParameterizedTest
+    @MethodSource("provideNullInputs")
+    void testHammingDistanceWithNullInputs(String input1, String input2) {
+        assertThrows(IllegalArgumentException.class, () -> HammingDistance.calculateHammingDistance(input1, input2));
+    }
+
+    private static Stream<Arguments> provideNullInputs() {
+        return Stream.of(Arguments.of(null, "abc"), Arguments.of("abc", null), Arguments.of(null, null));
     }
 
     @Test
     void testNotEqualStringLengths() {
-        Exception exception = assertThrows(Exception.class, () -> HammingDistance.calculateHammingDistance("ab", "abc"));
+        Exception exception = assertThrows(IllegalArgumentException.class, () -> HammingDistance.calculateHammingDistance("ab", "abc"));
         assertEquals("String lengths must be equal", exception.getMessage());
     }
 }