Repository: TheAlgorithms/Java
Pull request #5373 (2024-08-23 21:01:42)

refactor: `PasswordGen`
Refactor PasswordGen.
Adding tests.

<!--
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/5373?dropdown=coverage&src=pr&el=h1&utm_medium=referral&utm_source=github&utm_content=comment&utm_campaign=pr+comments&utm_term=TheAlgorithms) Report
Attention: Patch coverage is `83.33333%` with `1 line` in your changes missing coverage. Please review.
> Project coverage is 46.26%. Comparing base [(`ce4eb55`)](https://app.codecov.io/gh/TheAlgorithms/Java/commit/ce4eb55e0e7c5216e2cba53217627f6bbe8b5083?dropdown=coverage&el=desc&utm_medium=referral&utm_source=github&utm_content=comment&utm_campaign=pr+comments&utm_term=TheAlgorithms) to head [(`3b9e22b`)](https://app.codecov.io/gh/TheAlgorithms/Java/commit/3b9e22b4b133a1ea4182fc690d03c58a57eec827?dropdown=coverage&el=desc&utm_medium=referral&utm_source=github&utm_content=comment&utm_campaign=pr+comments&utm_term=TheAlgorithms).

| [Files](https://app.codecov.io/gh/TheAlgorithms/Java/pull/5373?dropdown=coverage&src=pr&el=tree&utm_medium=referral&utm_source=github&utm_content=comment&utm_campaign=pr+comments&utm_term=TheAlgorithms) | Patch % | Lines |
|---|---|---|
| [...ain/java/com/thealgorithms/others/PasswordGen.java](https://app.codecov.io/gh/TheAlgorithms/Java/pull/5373?src=pr&el=tree&filepath=src%2Fmain%2Fjava%2Fcom%2Fthealgorithms%2Fothers%2FPasswordGen.java&utm_medium=referral&utm_source=github&utm_content=comment&utm_campaign=pr+comments&utm_term=TheAlgorithms#diff-c3JjL21haW4vamF2YS9jb20vdGhlYWxnb3JpdGhtcy9vdGhlcnMvUGFzc3dvcmRHZW4uamF2YQ==) | 83.33% | [0 Missing and 1 partial :warning: ](https://app.codecov.io/gh/TheAlgorithms/Java/pull/5373?src=pr&el=tree&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    #5373      +/-   ##
============================================
- Coverage     46.26%   46.26%   -0.01%     
- Complexity     2866     2868       +2     
============================================
  Files           525      525              
  Lines         15410    15407       -3     
  Branches       2916     2916              
============================================
- Hits           7130     7128       -2     
+ Misses         7981     7980       -1     
  Partials        299      299              
```

</details>

[:umbrella: View full report in Codecov by Sentry](https://app.codecov.io/gh/TheAlgorithms/Java/pull/5373?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/others/PasswordGen.java b/src/main/java/com/thealgorithms/others/PasswordGen.java
index 7d21f112..da9f21bc 100644
--- a/src/main/java/com/thealgorithms/others/PasswordGen.java
+++ b/src/main/java/com/thealgorithms/others/PasswordGen.java
@@ -12,21 +12,32 @@ import java.util.Random;
  * @date 2017.10.25
  */
 final class PasswordGen {
+    private static final String UPPERCASE_LETTERS = "ABCDEFGHIJKLMNOPQRSTUVWXYZ";
+    private static final String LOWERCASE_LETTERS = "abcdefghijklmnopqrstuvwxyz";
+    private static final String DIGITS = "0123456789";
+    private static final String SPECIAL_CHARACTERS = "!@#$%^&*(){}?";
+    private static final String ALL_CHARACTERS = UPPERCASE_LETTERS + LOWERCASE_LETTERS + DIGITS + SPECIAL_CHARACTERS;
+
     private PasswordGen() {
     }
 
-    static String generatePassword(int minLength, int maxLength) {
-        Random random = new Random();
-
-        String upper = "ABCDEFGHIJKLMNOPQRSTUVWXYZ";
-        String lower = "abcdefghijklmnopqrstuvwxyz";
-        String numbers = "0123456789";
-        String specialChars = "!@#$%^&*(){}?";
+    /**
+     * Generates a random password with a length between minLength and maxLength.
+     *
+     * @param minLength The minimum length of the password.
+     * @param maxLength The maximum length of the password.
+     * @return A randomly generated password.
+     * @throws IllegalArgumentException if minLength is greater than maxLength or if either is non-positive.
+     */
+    public static String generatePassword(int minLength, int maxLength) {
+        if (minLength > maxLength || minLength <= 0 || maxLength <= 0) {
+            throw new IllegalArgumentException("Incorrect length parameters: minLength must be <= maxLength and both must be > 0");
+        }
 
-        String allChars = upper + lower + numbers + specialChars;
+        Random random = new Random();
 
-        List<Character> letters = new ArrayList<Character>();
-        for (char c : allChars.toCharArray()) {
+        List<Character> letters = new ArrayList<>();
+        for (char c : ALL_CHARACTERS.toCharArray()) {
             letters.add(c);
         }
 
@@ -36,7 +47,7 @@ final class PasswordGen {
 
         // Note that size of the password is also random
         for (int i = random.nextInt(maxLength - minLength) + minLength; i > 0; --i) {
-            password.append(letters.get(random.nextInt(letters.size())));
+            password.append(ALL_CHARACTERS.charAt(random.nextInt(ALL_CHARACTERS.length())));
         }
 
         return password.toString();


Test patch:
diff --git a/src/test/java/com/thealgorithms/others/PasswordGenTest.java b/src/test/java/com/thealgorithms/others/PasswordGenTest.java
index 57de329c..76492556 100644
--- a/src/test/java/com/thealgorithms/others/PasswordGenTest.java
+++ b/src/test/java/com/thealgorithms/others/PasswordGenTest.java
@@ -1,5 +1,6 @@
 package com.thealgorithms.others;
 
+import static org.junit.jupiter.api.Assertions.assertEquals;
 import static org.junit.jupiter.api.Assertions.assertThrows;
 import static org.junit.jupiter.api.Assertions.assertTrue;
 
@@ -10,7 +11,7 @@ public class PasswordGenTest {
     @Test
     public void failGenerationWithSameMinMaxLengthTest() {
         int length = 10;
-        assertThrows(IllegalArgumentException.class, () -> { PasswordGen.generatePassword(length, length); });
+        assertThrows(IllegalArgumentException.class, () -> PasswordGen.generatePassword(length, length));
     }
 
     @Test
@@ -23,7 +24,7 @@ public class PasswordGenTest {
     public void failGenerationWithMinLengthSmallerThanMaxLengthTest() {
         int minLength = 10;
         int maxLength = 5;
-        assertThrows(IllegalArgumentException.class, () -> { PasswordGen.generatePassword(minLength, maxLength); });
+        assertThrows(IllegalArgumentException.class, () -> PasswordGen.generatePassword(minLength, maxLength));
     }
 
     @Test
@@ -31,4 +32,22 @@ public class PasswordGenTest {
         String tempPassword = PasswordGen.generatePassword(8, 16);
         assertTrue(tempPassword.length() != 0);
     }
+
+    @Test
+    public void testGeneratePasswordWithMinGreaterThanMax() {
+        Exception exception = assertThrows(IllegalArgumentException.class, () -> PasswordGen.generatePassword(12, 8));
+        assertEquals("Incorrect length parameters: minLength must be <= maxLength and both must be > 0", exception.getMessage());
+    }
+
+    @Test
+    public void testGeneratePasswordWithNegativeLength() {
+        Exception exception = assertThrows(IllegalArgumentException.class, () -> PasswordGen.generatePassword(-5, 10));
+        assertEquals("Incorrect length parameters: minLength must be <= maxLength and both must be > 0", exception.getMessage());
+    }
+
+    @Test
+    public void testGeneratePasswordWithZeroLength() {
+        Exception exception = assertThrows(IllegalArgumentException.class, () -> PasswordGen.generatePassword(0, 0));
+        assertEquals("Incorrect length parameters: minLength must be <= maxLength and both must be > 0", exception.getMessage());
+    }
 }