diff --git a/.github/workflows/check_lesson_17_java_pr.yaml b/.github/workflows/check_lesson_17_java_pr.yaml new file mode 100644 index 000000000..367e0e09a --- /dev/null +++ b/.github/workflows/check_lesson_17_java_pr.yaml @@ -0,0 +1,28 @@ +name: Check Lesson 17 Java Pull Request + +on: + pull_request: + branches: [ "main" ] + paths: + - "lesson_17/bank/**" + +jobs: + build: + + runs-on: ubuntu-latest + permissions: + contents: read + pull-requests: write + + steps: + - uses: actions/checkout@v4 + + - name: Set up JDK + uses: actions/setup-java@v4 + with: + java-version: '21' + distribution: 'temurin' + + - name: Build Lesson 17 with Java + working-directory: ./lesson_17/bank + run: ./gradlew check \ No newline at end of file diff --git a/.github/workflows/check_push.yml b/.github/workflows/check_push.yml index c3ad4b188..054de1e25 100644 --- a/.github/workflows/check_push.yml +++ b/.github/workflows/check_push.yml @@ -19,6 +19,10 @@ on: - "lesson_12/structs_ts/**" - "lesson_13/maps_java/**" - "lesson_13/maps_ts/**" + - "lesson_14/exceptions/**" + - "lesson_15/tdd/**" + - "lesson_16/objects/**" + - "lesson_17/bank/**" jobs: build: runs-on: ubuntu-latest @@ -141,3 +145,22 @@ jobs: run: | npm ci npm run compile + + - name: Build Lesson 14 with Java + working-directory: ./lesson_14/exceptions + run: ./gradlew assemble + + - name: Build Lesson 15 with Java + working-directory: ./lesson_15/tdd + run: | + ./gradlew assemble + ./gradlew spotlessCheck + + - name: Build Lesson 16 with Java + working-directory: ./lesson_16/objects + run: ./gradlew check + + - name: Build Lesson 17 with Java + working-directory: ./lesson_17/bank + run: ./gradlew check + diff --git a/lesson_17/README.md b/lesson_17/README.md index 9c1718058..142fb57c3 100644 --- a/lesson_17/README.md +++ b/lesson_17/README.md @@ -16,4 +16,27 @@ Please review the following resources before lecture: ## Homework -- TODO(anthonydmays): Make 'em work!!! \ No newline at end of file +- [ ] Complete [Applying SOLID principles](#applying-solid-principles-bank-atm) exercise. +- [ ] Review [OOP Project](/project_oop/) documentation and complete user stories. + +## Applying SOLID Principles (Bank ATM) + +Your task for this assignment is add enhancements to an ATM simulator. The [BankAtm][bankatm-file] is at the center of the model, allowing us to add one or more `CheckingAccount` instances and make withdrawals or deposits via cash or check. You will need to implement at least two of the following functional enhancements to the `BankAtm` class WITHOUT adding a new method. Note that you can update existing methods, however. + +### Functional Requirements + +* We want to support a `SavingsAccount` that works just like the `CheckingAccount`, but doesn't allow you to write checks against the account. +* We want the `BankAtm` class to support the concept of a `BusinessCheckingAccount`. A business account requires that at least one of the owning accounts is a business. +* In addition to supporting checks and cash, we also want to support the concept of another monetary instrument called a `MoneyOrder`. Unlike a `Check`, a `MoneyOrder` withdraws funds from a source account immediately on creation for the purposes of this simulation.. +* For traceability, all of the transactions in the `BankAtm` class should logged. Create an `AuditLog` class that keeps a record of all debits and credits to any account and integrate it with the `BankAtm` class. +* ~~For the `depositFunds` method that accepts a cash amount, we'd like the ability to deposit funds in a variety of currencies. Add a parameter that accepts a currency type and a new object that encapsulates the currency converter logic for converting a cash amount to the account currency type.~~ + +### Technical Requirements + +* You must integrate new features into the `BankAtm` without adding a new public method. Existing public methods may be modified without breaking existing functionality. +* You must update the `BankAtm` tests and may modify or add other applicable tests. +* Feel free to add the minimal number of classes, interfaces, or abstract classes needed to fulfill each requirement. +* You must update existing javadocs and may add new documentation for new types and methods you introduce. + +[bank-folder]: ./bank/ +[bankatm-file]: ./bank/bank_app/src/main/java/com/codedifferently/lesson17/bank/BankAtm.java \ No newline at end of file diff --git a/lesson_17/bank/.gitattributes b/lesson_17/bank/.gitattributes new file mode 100644 index 000000000..097f9f98d --- /dev/null +++ b/lesson_17/bank/.gitattributes @@ -0,0 +1,9 @@ +# +# https://help.github.com/articles/dealing-with-line-endings/ +# +# Linux start script should use lf +/gradlew text eol=lf + +# These are Windows script files and should use crlf +*.bat text eol=crlf + diff --git a/lesson_17/bank/.gitignore b/lesson_17/bank/.gitignore new file mode 100644 index 000000000..1b6985c00 --- /dev/null +++ b/lesson_17/bank/.gitignore @@ -0,0 +1,5 @@ +# Ignore Gradle project-specific cache directory +.gradle + +# Ignore Gradle build output directory +build diff --git a/lesson_17/bank/bank_app/build.gradle.kts b/lesson_17/bank/bank_app/build.gradle.kts new file mode 100644 index 000000000..5f768d848 --- /dev/null +++ b/lesson_17/bank/bank_app/build.gradle.kts @@ -0,0 +1,85 @@ +plugins { + // Apply the application plugin to add support for building a CLI application in Java. + application + eclipse + jacoco + id("io.freefair.lombok") version "8.10.2" + id("com.diffplug.spotless") version "6.25.0" + id("org.springframework.boot") version "3.4.0" + id("com.adarshr.test-logger") version "4.0.0" +} + +apply(plugin = "io.spring.dependency-management") + +repositories { + // Use Maven Central for resolving dependencies. + mavenCentral() +} + +dependencies { + // Use JUnit Jupiter for testing. + testImplementation("org.junit.jupiter:junit-jupiter:5.11.3") + testImplementation("org.springframework.boot:spring-boot-starter-test") + testImplementation("org.assertj:assertj-core:3.26.3") + testImplementation("at.favre.lib:bcrypt:0.10.2") + + // This dependency is used by the application. + implementation("com.google.guava:guava:33.3.1-jre") + implementation("com.google.code.gson:gson:2.11.0") + implementation("org.projectlombok:lombok:1.18.30") + implementation("org.springframework.boot:spring-boot-starter") +} + +application { + // Define the main class for the application. + mainClass.set("com.codedifferently.lesson17.Lesson17") +} + +tasks.named("test") { + // Use JUnit Platform for unit tests. + useJUnitPlatform() + finalizedBy(tasks.jacocoTestReport) +} + +tasks.jacocoTestReport { + dependsOn(tasks.test) + reports { + xml.required = true + } +} + +tasks.jacocoTestCoverageVerification { + violationRules { + rule { + limit { + minimum = "0.8".toBigDecimal() + } + } + } +} + +tasks.check { + dependsOn(tasks.jacocoTestCoverageVerification) +} + +configure { + + format("misc", { + // define the files to apply `misc` to + target("*.gradle", ".gitattributes", ".gitignore") + + // define the steps to apply to those files + trimTrailingWhitespace() + indentWithTabs() // or spaces. Takes an integer argument if you don't like 4 + endWithNewline() + }) + + java { + // don't need to set target, it is inferred from java + + // apply a specific flavor of google-java-format + googleJavaFormat() + // fix formatting of type annotations + formatAnnotations() + } +} diff --git a/lesson_17/bank/bank_app/src/main/java/com/codedifferently/lesson17/Lesson17.java b/lesson_17/bank/bank_app/src/main/java/com/codedifferently/lesson17/Lesson17.java new file mode 100644 index 000000000..c11084e57 --- /dev/null +++ b/lesson_17/bank/bank_app/src/main/java/com/codedifferently/lesson17/Lesson17.java @@ -0,0 +1,15 @@ +package com.codedifferently.lesson17; + +import org.springframework.boot.SpringApplication; +import org.springframework.boot.autoconfigure.SpringBootApplication; +import org.springframework.context.annotation.Configuration; + +@Configuration +@SpringBootApplication(scanBasePackages = "com.codedifferently") +public class Lesson17 { + + public static void main(String[] args) { + var application = new SpringApplication(Lesson17.class); + application.run(args); + } +} diff --git a/lesson_17/bank/bank_app/src/main/java/com/codedifferently/lesson17/bank/BankAtm.java b/lesson_17/bank/bank_app/src/main/java/com/codedifferently/lesson17/bank/BankAtm.java new file mode 100644 index 000000000..8cbcd3cc0 --- /dev/null +++ b/lesson_17/bank/bank_app/src/main/java/com/codedifferently/lesson17/bank/BankAtm.java @@ -0,0 +1,88 @@ +package com.codedifferently.lesson17.bank; + +import com.codedifferently.lesson17.bank.exceptions.AccountNotFoundException; +import java.util.HashMap; +import java.util.Map; +import java.util.Set; +import java.util.UUID; + +/** Represents a bank ATM. */ +public class BankAtm { + + private final Map customerById = new HashMap<>(); + private final Map accountByNumber = new HashMap<>(); + + /** + * Adds a checking account to the bank. + * + * @param account The account to add. + */ + public void addAccount(CheckingAccount account) { + accountByNumber.put(account.getAccountNumber(), account); + account + .getOwners() + .forEach( + owner -> { + customerById.put(owner.getId(), owner); + }); + } + + /** + * Finds all accounts owned by a customer. + * + * @param customerId The ID of the customer. + * @return The unique set of accounts owned by the customer. + */ + public Set findAccountsByCustomerId(UUID customerId) { + return customerById.containsKey(customerId) + ? customerById.get(customerId).getAccounts() + : Set.of(); + } + + /** + * Deposits funds into an account. + * + * @param accountNumber The account number. + * @param amount The amount to deposit. + */ + public void depositFunds(String accountNumber, double amount) { + CheckingAccount account = getAccountOrThrow(accountNumber); + account.deposit(amount); + } + + /** + * Deposits funds into an account using a check. + * + * @param accountNumber The account number. + * @param check The check to deposit. + */ + public void depositFunds(String accountNumber, Check check) { + CheckingAccount account = getAccountOrThrow(accountNumber); + check.depositFunds(account); + } + + /** + * Withdraws funds from an account. + * + * @param accountNumber + * @param amount + */ + public void withdrawFunds(String accountNumber, double amount) { + CheckingAccount account = getAccountOrThrow(accountNumber); + account.withdraw(amount); + } + + /** + * Gets an account by its number or throws an exception if not found. + * + * @param accountNumber The account number. + * @return The account. + */ + private CheckingAccount getAccountOrThrow(String accountNumber) { + CheckingAccount account = accountByNumber.get(accountNumber); + if (account == null || account.isClosed()) { + throw new AccountNotFoundException("Account not found"); + } + return account; + } +} diff --git a/lesson_17/bank/bank_app/src/main/java/com/codedifferently/lesson17/bank/Check.java b/lesson_17/bank/bank_app/src/main/java/com/codedifferently/lesson17/bank/Check.java new file mode 100644 index 000000000..061fa4a5c --- /dev/null +++ b/lesson_17/bank/bank_app/src/main/java/com/codedifferently/lesson17/bank/Check.java @@ -0,0 +1,82 @@ +package com.codedifferently.lesson17.bank; + +import com.codedifferently.lesson17.bank.exceptions.CheckVoidedException; + +/** Represents a check. */ +public class Check { + + private final String checkNumber; + private final double amount; + private final CheckingAccount account; + private boolean isVoided = false; + + /** + * Creates a new check. + * + * @param checkNumber The check number. + * @param amount The amount of the check. + * @param account The account the check is drawn on. + */ + public Check(String checkNumber, double amount, CheckingAccount account) { + if (amount < 0) { + throw new IllegalArgumentException("Check amount must be positive"); + } + this.checkNumber = checkNumber; + this.amount = amount; + this.account = account; + } + + /** + * Gets the voided status of the check. + * + * @return True if the check is voided, and false otherwise. + */ + public boolean getIsVoided() { + return isVoided; + } + + /** Voids the check. */ + public void voidCheck() { + isVoided = true; + } + + /** + * Deposits the check into an account. + * + * @param toAccount The account to deposit the check into. + */ + public void depositFunds(CheckingAccount toAccount) { + if (isVoided) { + throw new CheckVoidedException("Check is voided"); + } + account.withdraw(amount); + toAccount.deposit(amount); + voidCheck(); + } + + @Override + public int hashCode() { + return checkNumber.hashCode(); + } + + @Override + public boolean equals(Object obj) { + if (obj instanceof Check other) { + return checkNumber.equals(other.checkNumber); + } + return false; + } + + @Override + public String toString() { + return "Check{" + + "checkNumber='" + + checkNumber + + '\'' + + ", amount=" + + amount + + ", account=" + + account.getAccountNumber() + + '}'; + } +} diff --git a/lesson_17/bank/bank_app/src/main/java/com/codedifferently/lesson17/bank/CheckingAccount.java b/lesson_17/bank/bank_app/src/main/java/com/codedifferently/lesson17/bank/CheckingAccount.java new file mode 100644 index 000000000..5d8aeb74d --- /dev/null +++ b/lesson_17/bank/bank_app/src/main/java/com/codedifferently/lesson17/bank/CheckingAccount.java @@ -0,0 +1,131 @@ +package com.codedifferently.lesson17.bank; + +import com.codedifferently.lesson17.bank.exceptions.InsufficientFundsException; +import java.util.Set; + +/** Represents a checking account. */ +public class CheckingAccount { + + private final Set owners; + private final String accountNumber; + private double balance; + private boolean isActive; + + /** + * Creates a new checking account. + * + * @param accountNumber The account number. + * @param owners The owners of the account. + * @param initialBalance The initial balance of the account. + */ + public CheckingAccount(String accountNumber, Set owners, double initialBalance) { + this.accountNumber = accountNumber; + this.owners = owners; + this.balance = initialBalance; + isActive = true; + } + + /** + * Gets the account number. + * + * @return The account number. + */ + public String getAccountNumber() { + return accountNumber; + } + + /** + * Gets the owners of the account. + * + * @return The owners of the account. + */ + public Set getOwners() { + return owners; + } + + /** + * Deposits funds into the account. + * + * @param amount The amount to deposit. + */ + public void deposit(double amount) throws IllegalStateException { + if (isClosed()) { + throw new IllegalStateException("Cannot deposit to a closed account"); + } + if (amount <= 0) { + throw new IllegalArgumentException("Deposit amount must be positive"); + } + balance += amount; + } + + /** + * Withdraws funds from the account. + * + * @param amount + * @throws InsufficientFundsException + */ + public void withdraw(double amount) throws InsufficientFundsException { + if (isClosed()) { + throw new IllegalStateException("Cannot withdraw from a closed account"); + } + if (amount <= 0) { + throw new IllegalStateException("Withdrawal amount must be positive"); + } + if (balance < amount) { + throw new InsufficientFundsException("Account does not have enough funds for withdrawal"); + } + balance -= amount; + } + + /** + * Gets the balance of the account. + * + * @return The balance of the account. + */ + public double getBalance() { + return balance; + } + + /** Closes the account. */ + public void closeAccount() throws IllegalStateException { + if (balance > 0) { + throw new IllegalStateException("Cannot close account with a positive balance"); + } + isActive = false; + } + + /** + * Checks if the account is closed. + * + * @return True if the account is closed, otherwise false. + */ + public boolean isClosed() { + return !isActive; + } + + @Override + public int hashCode() { + return accountNumber.hashCode(); + } + + @Override + public boolean equals(Object obj) { + if (obj instanceof CheckingAccount other) { + return accountNumber.equals(other.accountNumber); + } + return false; + } + + @Override + public String toString() { + return "CheckingAccount{" + + "accountNumber='" + + accountNumber + + '\'' + + ", balance=" + + balance + + ", isActive=" + + isActive + + '}'; + } +} diff --git a/lesson_17/bank/bank_app/src/main/java/com/codedifferently/lesson17/bank/Customer.java b/lesson_17/bank/bank_app/src/main/java/com/codedifferently/lesson17/bank/Customer.java new file mode 100644 index 000000000..af0847134 --- /dev/null +++ b/lesson_17/bank/bank_app/src/main/java/com/codedifferently/lesson17/bank/Customer.java @@ -0,0 +1,78 @@ +package com.codedifferently.lesson17.bank; + +import java.util.HashSet; +import java.util.Set; +import java.util.UUID; + +/** Represents a customer of the bank. */ +public class Customer { + + private final UUID id; + private final String name; + private final Set accounts = new HashSet<>(); + + /** + * Creates a new customer. + * + * @param id The ID of the customer. + * @param name The name of the customer. + */ + public Customer(UUID id, String name) { + this.id = id; + this.name = name; + } + + /** + * Gets the ID of the customer. + * + * @return The ID of the customer. + */ + public UUID getId() { + return id; + } + + /** + * Gets the name of the customer. + * + * @return The name of the customer. + */ + public String getName() { + return name; + } + + /** + * Adds a checking account to the customer. + * + * @param account The account to add. + */ + public void addAccount(CheckingAccount account) { + accounts.add(account); + } + + /** + * Gets the accounts owned by the customer. + * + * @return The unique set of accounts owned by the customer. + */ + public Set getAccounts() { + return accounts; + } + + @Override + public int hashCode() { + return id.hashCode(); + } + + @Override + public boolean equals(Object obj) { + if (obj instanceof Customer other) { + return id.equals(other.id); + } + return false; + } + + @Override + public String toString() { + return "Customer{" + "id=" + id + ", name='" + name + '\'' + '}'; + } +} diff --git a/lesson_17/bank/bank_app/src/main/java/com/codedifferently/lesson17/bank/exceptions/AccountNotFoundException.java b/lesson_17/bank/bank_app/src/main/java/com/codedifferently/lesson17/bank/exceptions/AccountNotFoundException.java new file mode 100644 index 000000000..b03386e17 --- /dev/null +++ b/lesson_17/bank/bank_app/src/main/java/com/codedifferently/lesson17/bank/exceptions/AccountNotFoundException.java @@ -0,0 +1,10 @@ +package com.codedifferently.lesson17.bank.exceptions; + +public class AccountNotFoundException extends RuntimeException { + + public AccountNotFoundException() {} + + public AccountNotFoundException(String message) { + super(message); + } +} diff --git a/lesson_17/bank/bank_app/src/main/java/com/codedifferently/lesson17/bank/exceptions/CheckVoidedException.java b/lesson_17/bank/bank_app/src/main/java/com/codedifferently/lesson17/bank/exceptions/CheckVoidedException.java new file mode 100644 index 000000000..d51443d4a --- /dev/null +++ b/lesson_17/bank/bank_app/src/main/java/com/codedifferently/lesson17/bank/exceptions/CheckVoidedException.java @@ -0,0 +1,10 @@ +package com.codedifferently.lesson17.bank.exceptions; + +public class CheckVoidedException extends RuntimeException { + + public CheckVoidedException() {} + + public CheckVoidedException(String message) { + super(message); + } +} diff --git a/lesson_17/bank/bank_app/src/main/java/com/codedifferently/lesson17/bank/exceptions/InsufficientFundsException.java b/lesson_17/bank/bank_app/src/main/java/com/codedifferently/lesson17/bank/exceptions/InsufficientFundsException.java new file mode 100644 index 000000000..75de59329 --- /dev/null +++ b/lesson_17/bank/bank_app/src/main/java/com/codedifferently/lesson17/bank/exceptions/InsufficientFundsException.java @@ -0,0 +1,10 @@ +package com.codedifferently.lesson17.bank.exceptions; + +public class InsufficientFundsException extends RuntimeException { + + public InsufficientFundsException() {} + + public InsufficientFundsException(String message) { + super(message); + } +} diff --git a/lesson_17/bank/bank_app/src/test/java/com/codedifferently/lesson17/Lesson17Test.java b/lesson_17/bank/bank_app/src/test/java/com/codedifferently/lesson17/Lesson17Test.java new file mode 100644 index 000000000..1579e4bf9 --- /dev/null +++ b/lesson_17/bank/bank_app/src/test/java/com/codedifferently/lesson17/Lesson17Test.java @@ -0,0 +1,16 @@ +package com.codedifferently.lesson17; + +import static org.assertj.core.api.Assertions.assertThat; + +import org.junit.jupiter.api.Test; +import org.springframework.boot.test.context.SpringBootTest; +import org.springframework.boot.test.context.SpringBootTest.UseMainMethod; + +@SpringBootTest(useMainMethod = UseMainMethod.WHEN_AVAILABLE) +class Lesson17Test { + + @Test + void testInstantiate() { + assertThat(new Lesson17()).isNotNull(); + } +} diff --git a/lesson_17/bank/bank_app/src/test/java/com/codedifferently/lesson17/bank/BankAtmTest.java b/lesson_17/bank/bank_app/src/test/java/com/codedifferently/lesson17/bank/BankAtmTest.java new file mode 100644 index 000000000..fa4a913a2 --- /dev/null +++ b/lesson_17/bank/bank_app/src/test/java/com/codedifferently/lesson17/bank/BankAtmTest.java @@ -0,0 +1,110 @@ +package com.codedifferently.lesson17.bank; + +import static org.assertj.core.api.Assertions.assertThat; +import static org.assertj.core.api.Assertions.assertThatExceptionOfType; + +import com.codedifferently.lesson17.bank.exceptions.AccountNotFoundException; +import com.codedifferently.lesson17.bank.exceptions.CheckVoidedException; +import java.util.Set; +import java.util.UUID; +import org.junit.jupiter.api.BeforeEach; +import org.junit.jupiter.api.Test; + +class BankAtmTest { + + private BankAtm classUnderTest; + private CheckingAccount account1; + private CheckingAccount account2; + private Customer customer1; + private Customer customer2; + + @BeforeEach + void setUp() { + classUnderTest = new BankAtm(); + customer1 = new Customer(UUID.randomUUID(), "John Doe"); + customer2 = new Customer(UUID.randomUUID(), "Jane Smith"); + account1 = new CheckingAccount("123456789", Set.of(customer1), 100.0); + account2 = new CheckingAccount("987654321", Set.of(customer1, customer2), 200.0); + customer1.addAccount(account1); + customer1.addAccount(account2); + customer2.addAccount(account2); + classUnderTest.addAccount(account1); + classUnderTest.addAccount(account2); + } + + @Test + void testAddAccount() { + // Arrange + Customer customer3 = new Customer(UUID.randomUUID(), "Alice Johnson"); + CheckingAccount account3 = new CheckingAccount("555555555", Set.of(customer3), 300.0); + customer3.addAccount(account3); + + // Act + classUnderTest.addAccount(account3); + + // Assert + Set accounts = classUnderTest.findAccountsByCustomerId(customer3.getId()); + assertThat(accounts).containsOnly(account3); + } + + @Test + void testFindAccountsByCustomerId() { + // Act + Set accounts = classUnderTest.findAccountsByCustomerId(customer1.getId()); + + // Assert + assertThat(accounts).containsOnly(account1, account2); + } + + @Test + void testDepositFunds() { + // Act + classUnderTest.depositFunds(account1.getAccountNumber(), 50.0); + + // Assert + assertThat(account1.getBalance()).isEqualTo(150.0); + } + + @Test + void testDepositFunds_Check() { + // Arrange + Check check = new Check("987654321", 100.0, account1); + + // Act + classUnderTest.depositFunds("987654321", check); + + // Assert + assertThat(account1.getBalance()).isEqualTo(0); + assertThat(account2.getBalance()).isEqualTo(300.0); + } + + @Test + void testDepositFunds_DoesntDepositCheckTwice() { + Check check = new Check("987654321", 100.0, account1); + + classUnderTest.depositFunds("987654321", check); + + assertThatExceptionOfType(CheckVoidedException.class) + .isThrownBy(() -> classUnderTest.depositFunds("987654321", check)) + .withMessage("Check is voided"); + } + + @Test + void testWithdrawFunds() { + // Act + classUnderTest.withdrawFunds(account2.getAccountNumber(), 50.0); + + // Assert + assertThat(account2.getBalance()).isEqualTo(150.0); + } + + @Test + void testWithdrawFunds_AccountNotFound() { + String nonExistingAccountNumber = "999999999"; + + // Act & Assert + assertThatExceptionOfType(AccountNotFoundException.class) + .isThrownBy(() -> classUnderTest.withdrawFunds(nonExistingAccountNumber, 50.0)) + .withMessage("Account not found"); + } +} diff --git a/lesson_17/bank/bank_app/src/test/java/com/codedifferently/lesson17/bank/CheckTest.java b/lesson_17/bank/bank_app/src/test/java/com/codedifferently/lesson17/bank/CheckTest.java new file mode 100644 index 000000000..6b62d39ba --- /dev/null +++ b/lesson_17/bank/bank_app/src/test/java/com/codedifferently/lesson17/bank/CheckTest.java @@ -0,0 +1,78 @@ +package com.codedifferently.lesson17.bank; + +import static org.assertj.core.api.Assertions.assertThat; +import static org.assertj.core.api.Assertions.assertThatExceptionOfType; + +import com.codedifferently.lesson17.bank.exceptions.CheckVoidedException; +import org.junit.jupiter.api.BeforeEach; +import org.junit.jupiter.api.Test; + +class CheckTest { + + private CheckingAccount account1; + private CheckingAccount account2; + private Check classUnderTest; + + @BeforeEach + void setUp() { + account1 = new CheckingAccount("123456789", null, 100.0); + account2 = new CheckingAccount("987654321", null, 200.0); + classUnderTest = new Check("123456789", 50.0, account1); + } + + @Test + void testDepositFunds() { + // Act + classUnderTest.depositFunds(account2); + + // Assert + assertThat(account1.getBalance()).isEqualTo(50.0); + assertThat(account2.getBalance()).isEqualTo(250.0); + } + + @Test + void testDepositFunds_CheckVoided() { + // Arrange + classUnderTest.voidCheck(); + + // Act & Assert + assertThatExceptionOfType(CheckVoidedException.class) + .isThrownBy(() -> classUnderTest.depositFunds(account2)) + .withMessage("Check is voided"); + } + + @Test + void testConstructor_CantCreateCheckWithNegativeAmount() { + // Act & Assert + assertThatExceptionOfType(IllegalArgumentException.class) + .isThrownBy(() -> new Check("123456789", -50.0, account1)) + .withMessage("Check amount must be positive"); + } + + @Test + void testHashCode() { + // Arrange + Check otherCheck = new Check("123456789", 100.0, account1); + + // Assert + assertThat(classUnderTest.hashCode()).isEqualTo(otherCheck.hashCode()); + } + + @Test + void testEquals() { + // Arrange + Check otherCheck = new Check("123456789", 100.0, account1); + Check differentCheck = new Check("987654321", 100.0, account1); + + // Assert + assertThat(classUnderTest.equals(otherCheck)).isTrue(); + assertThat(classUnderTest.equals(differentCheck)).isFalse(); + } + + @Test + void testToString() { + // Assert + assertThat(classUnderTest.toString()) + .isEqualTo("Check{checkNumber='123456789', amount=50.0, account=123456789}"); + } +} diff --git a/lesson_17/bank/bank_app/src/test/java/com/codedifferently/lesson17/bank/CheckingAccountTest.java b/lesson_17/bank/bank_app/src/test/java/com/codedifferently/lesson17/bank/CheckingAccountTest.java new file mode 100644 index 000000000..f155d8e5b --- /dev/null +++ b/lesson_17/bank/bank_app/src/test/java/com/codedifferently/lesson17/bank/CheckingAccountTest.java @@ -0,0 +1,106 @@ +package com.codedifferently.lesson17.bank; + +import static org.assertj.core.api.Assertions.assertThatExceptionOfType; +import static org.junit.jupiter.api.Assertions.assertEquals; +import static org.junit.jupiter.api.Assertions.assertFalse; +import static org.junit.jupiter.api.Assertions.assertTrue; + +import com.codedifferently.lesson17.bank.exceptions.InsufficientFundsException; +import java.util.HashSet; +import java.util.Set; +import java.util.UUID; +import org.junit.jupiter.api.BeforeEach; +import org.junit.jupiter.api.Test; + +class CheckingAccountTest { + + private CheckingAccount classUnderTest; + private Set owners; + + @BeforeEach + void setUp() { + owners = new HashSet<>(); + owners.add(new Customer(UUID.randomUUID(), "John Doe")); + owners.add(new Customer(UUID.randomUUID(), "Jane Smith")); + classUnderTest = new CheckingAccount("123456789", owners, 100.0); + } + + @Test + void getAccountNumber() { + assertEquals("123456789", classUnderTest.getAccountNumber()); + } + + @Test + void getOwners() { + assertEquals(owners, classUnderTest.getOwners()); + } + + @Test + void deposit() { + classUnderTest.deposit(50.0); + assertEquals(150.0, classUnderTest.getBalance()); + } + + @Test + void deposit_withNegativeAmount() { + assertThatExceptionOfType(IllegalArgumentException.class) + .isThrownBy(() -> classUnderTest.deposit(-50.0)); + } + + @Test + void withdraw() { + classUnderTest.withdraw(50.0); + assertEquals(50.0, classUnderTest.getBalance()); + } + + @Test + void withdraw_withNegativeAmount() { + assertThatExceptionOfType(IllegalStateException.class) + .isThrownBy(() -> classUnderTest.withdraw(-50.0)) + .withMessage("Withdrawal amount must be positive"); + } + + @Test + void withdraw_withInsufficientBalance() { + assertThatExceptionOfType(InsufficientFundsException.class) + .isThrownBy(() -> classUnderTest.withdraw(150.0)) + .withMessage("Account does not have enough funds for withdrawal"); + } + + @Test + void getBalance() { + assertEquals(100.0, classUnderTest.getBalance()); + } + + @Test + void closeAccount_withPositiveBalance() { + assertThatExceptionOfType(IllegalStateException.class) + .isThrownBy(() -> classUnderTest.closeAccount()); + } + + @Test + void isClosed() { + assertFalse(classUnderTest.isClosed()); + classUnderTest.withdraw(100); + classUnderTest.closeAccount(); + assertTrue(classUnderTest.isClosed()); + } + + @Test + void equals() { + CheckingAccount otherAccount = new CheckingAccount("123456789", owners, 200.0); + assertEquals(classUnderTest, otherAccount); + } + + @Test + void hashCodeTest() { + CheckingAccount otherAccount = new CheckingAccount("123456789", owners, 200.0); + assertEquals(classUnderTest.hashCode(), otherAccount.hashCode()); + } + + @Test + void toStringTest() { + String expected = "CheckingAccount{accountNumber='123456789', balance=100.0, isActive=true}"; + assertEquals(expected, classUnderTest.toString()); + } +} diff --git a/lesson_17/bank/gradle/wrapper/gradle-wrapper.jar b/lesson_17/bank/gradle/wrapper/gradle-wrapper.jar new file mode 100644 index 000000000..a4b76b953 Binary files /dev/null and b/lesson_17/bank/gradle/wrapper/gradle-wrapper.jar differ diff --git a/lesson_17/bank/gradle/wrapper/gradle-wrapper.properties b/lesson_17/bank/gradle/wrapper/gradle-wrapper.properties new file mode 100644 index 000000000..e2847c820 --- /dev/null +++ b/lesson_17/bank/gradle/wrapper/gradle-wrapper.properties @@ -0,0 +1,7 @@ +distributionBase=GRADLE_USER_HOME +distributionPath=wrapper/dists +distributionUrl=https\://services.gradle.org/distributions/gradle-8.11.1-bin.zip +networkTimeout=10000 +validateDistributionUrl=true +zipStoreBase=GRADLE_USER_HOME +zipStorePath=wrapper/dists diff --git a/lesson_17/bank/gradlew b/lesson_17/bank/gradlew new file mode 100755 index 000000000..f5feea6d6 --- /dev/null +++ b/lesson_17/bank/gradlew @@ -0,0 +1,252 @@ +#!/bin/sh + +# +# Copyright © 2015-2021 the original authors. +# +# Licensed under the Apache License, Version 2.0 (the "License"); +# you may not use this file except in compliance with the License. +# You may obtain a copy of the License at +# +# https://www.apache.org/licenses/LICENSE-2.0 +# +# Unless required by applicable law or agreed to in writing, software +# distributed under the License is distributed on an "AS IS" BASIS, +# WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. +# See the License for the specific language governing permissions and +# limitations under the License. +# +# SPDX-License-Identifier: Apache-2.0 +# + +############################################################################## +# +# Gradle start up script for POSIX generated by Gradle. +# +# Important for running: +# +# (1) You need a POSIX-compliant shell to run this script. If your /bin/sh is +# noncompliant, but you have some other compliant shell such as ksh or +# bash, then to run this script, type that shell name before the whole +# command line, like: +# +# ksh Gradle +# +# Busybox and similar reduced shells will NOT work, because this script +# requires all of these POSIX shell features: +# * functions; +# * expansions «$var», «${var}», «${var:-default}», «${var+SET}», +# «${var#prefix}», «${var%suffix}», and «$( cmd )»; +# * compound commands having a testable exit status, especially «case»; +# * various built-in commands including «command», «set», and «ulimit». +# +# Important for patching: +# +# (2) This script targets any POSIX shell, so it avoids extensions provided +# by Bash, Ksh, etc; in particular arrays are avoided. +# +# The "traditional" practice of packing multiple parameters into a +# space-separated string is a well documented source of bugs and security +# problems, so this is (mostly) avoided, by progressively accumulating +# options in "$@", and eventually passing that to Java. +# +# Where the inherited environment variables (DEFAULT_JVM_OPTS, JAVA_OPTS, +# and GRADLE_OPTS) rely on word-splitting, this is performed explicitly; +# see the in-line comments for details. +# +# There are tweaks for specific operating systems such as AIX, CygWin, +# Darwin, MinGW, and NonStop. +# +# (3) This script is generated from the Groovy template +# https://github.com/gradle/gradle/blob/HEAD/platforms/jvm/plugins-application/src/main/resources/org/gradle/api/internal/plugins/unixStartScript.txt +# within the Gradle project. +# +# You can find Gradle at https://github.com/gradle/gradle/. +# +############################################################################## + +# Attempt to set APP_HOME + +# Resolve links: $0 may be a link +app_path=$0 + +# Need this for daisy-chained symlinks. +while + APP_HOME=${app_path%"${app_path##*/}"} # leaves a trailing /; empty if no leading path + [ -h "$app_path" ] +do + ls=$( ls -ld "$app_path" ) + link=${ls#*' -> '} + case $link in #( + /*) app_path=$link ;; #( + *) app_path=$APP_HOME$link ;; + esac +done + +# This is normally unused +# shellcheck disable=SC2034 +APP_BASE_NAME=${0##*/} +# Discard cd standard output in case $CDPATH is set (https://github.com/gradle/gradle/issues/25036) +APP_HOME=$( cd -P "${APP_HOME:-./}" > /dev/null && printf '%s +' "$PWD" ) || exit + +# Use the maximum available, or set MAX_FD != -1 to use that value. +MAX_FD=maximum + +warn () { + echo "$*" +} >&2 + +die () { + echo + echo "$*" + echo + exit 1 +} >&2 + +# OS specific support (must be 'true' or 'false'). +cygwin=false +msys=false +darwin=false +nonstop=false +case "$( uname )" in #( + CYGWIN* ) cygwin=true ;; #( + Darwin* ) darwin=true ;; #( + MSYS* | MINGW* ) msys=true ;; #( + NONSTOP* ) nonstop=true ;; +esac + +CLASSPATH=$APP_HOME/gradle/wrapper/gradle-wrapper.jar + + +# Determine the Java command to use to start the JVM. +if [ -n "$JAVA_HOME" ] ; then + if [ -x "$JAVA_HOME/jre/sh/java" ] ; then + # IBM's JDK on AIX uses strange locations for the executables + JAVACMD=$JAVA_HOME/jre/sh/java + else + JAVACMD=$JAVA_HOME/bin/java + fi + if [ ! -x "$JAVACMD" ] ; then + die "ERROR: JAVA_HOME is set to an invalid directory: $JAVA_HOME + +Please set the JAVA_HOME variable in your environment to match the +location of your Java installation." + fi +else + JAVACMD=java + if ! command -v java >/dev/null 2>&1 + then + die "ERROR: JAVA_HOME is not set and no 'java' command could be found in your PATH. + +Please set the JAVA_HOME variable in your environment to match the +location of your Java installation." + fi +fi + +# Increase the maximum file descriptors if we can. +if ! "$cygwin" && ! "$darwin" && ! "$nonstop" ; then + case $MAX_FD in #( + max*) + # In POSIX sh, ulimit -H is undefined. That's why the result is checked to see if it worked. + # shellcheck disable=SC2039,SC3045 + MAX_FD=$( ulimit -H -n ) || + warn "Could not query maximum file descriptor limit" + esac + case $MAX_FD in #( + '' | soft) :;; #( + *) + # In POSIX sh, ulimit -n is undefined. That's why the result is checked to see if it worked. + # shellcheck disable=SC2039,SC3045 + ulimit -n "$MAX_FD" || + warn "Could not set maximum file descriptor limit to $MAX_FD" + esac +fi + +# Collect all arguments for the java command, stacking in reverse order: +# * args from the command line +# * the main class name +# * -classpath +# * -D...appname settings +# * --module-path (only if needed) +# * DEFAULT_JVM_OPTS, JAVA_OPTS, and GRADLE_OPTS environment variables. + +# For Cygwin or MSYS, switch paths to Windows format before running java +if "$cygwin" || "$msys" ; then + APP_HOME=$( cygpath --path --mixed "$APP_HOME" ) + CLASSPATH=$( cygpath --path --mixed "$CLASSPATH" ) + + JAVACMD=$( cygpath --unix "$JAVACMD" ) + + # Now convert the arguments - kludge to limit ourselves to /bin/sh + for arg do + if + case $arg in #( + -*) false ;; # don't mess with options #( + /?*) t=${arg#/} t=/${t%%/*} # looks like a POSIX filepath + [ -e "$t" ] ;; #( + *) false ;; + esac + then + arg=$( cygpath --path --ignore --mixed "$arg" ) + fi + # Roll the args list around exactly as many times as the number of + # args, so each arg winds up back in the position where it started, but + # possibly modified. + # + # NB: a `for` loop captures its iteration list before it begins, so + # changing the positional parameters here affects neither the number of + # iterations, nor the values presented in `arg`. + shift # remove old arg + set -- "$@" "$arg" # push replacement arg + done +fi + + +# Add default JVM options here. You can also use JAVA_OPTS and GRADLE_OPTS to pass JVM options to this script. +DEFAULT_JVM_OPTS='"-Xmx64m" "-Xms64m"' + +# Collect all arguments for the java command: +# * DEFAULT_JVM_OPTS, JAVA_OPTS, JAVA_OPTS, and optsEnvironmentVar are not allowed to contain shell fragments, +# and any embedded shellness will be escaped. +# * For example: A user cannot expect ${Hostname} to be expanded, as it is an environment variable and will be +# treated as '${Hostname}' itself on the command line. + +set -- \ + "-Dorg.gradle.appname=$APP_BASE_NAME" \ + -classpath "$CLASSPATH" \ + org.gradle.wrapper.GradleWrapperMain \ + "$@" + +# Stop when "xargs" is not available. +if ! command -v xargs >/dev/null 2>&1 +then + die "xargs is not available" +fi + +# Use "xargs" to parse quoted args. +# +# With -n1 it outputs one arg per line, with the quotes and backslashes removed. +# +# In Bash we could simply go: +# +# readarray ARGS < <( xargs -n1 <<<"$var" ) && +# set -- "${ARGS[@]}" "$@" +# +# but POSIX shell has neither arrays nor command substitution, so instead we +# post-process each arg (as a line of input to sed) to backslash-escape any +# character that might be a shell metacharacter, then use eval to reverse +# that process (while maintaining the separation between arguments), and wrap +# the whole thing up as a single "set" statement. +# +# This will of course break if any of these variables contains a newline or +# an unmatched quote. +# + +eval "set -- $( + printf '%s\n' "$DEFAULT_JVM_OPTS $JAVA_OPTS $GRADLE_OPTS" | + xargs -n1 | + sed ' s~[^-[:alnum:]+,./:=@_]~\\&~g; ' | + tr '\n' ' ' + )" '"$@"' + +exec "$JAVACMD" "$@" diff --git a/lesson_17/bank/gradlew.bat b/lesson_17/bank/gradlew.bat new file mode 100644 index 000000000..9d21a2183 --- /dev/null +++ b/lesson_17/bank/gradlew.bat @@ -0,0 +1,94 @@ +@rem +@rem Copyright 2015 the original author or authors. +@rem +@rem Licensed under the Apache License, Version 2.0 (the "License"); +@rem you may not use this file except in compliance with the License. +@rem You may obtain a copy of the License at +@rem +@rem https://www.apache.org/licenses/LICENSE-2.0 +@rem +@rem Unless required by applicable law or agreed to in writing, software +@rem distributed under the License is distributed on an "AS IS" BASIS, +@rem WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. +@rem See the License for the specific language governing permissions and +@rem limitations under the License. +@rem +@rem SPDX-License-Identifier: Apache-2.0 +@rem + +@if "%DEBUG%"=="" @echo off +@rem ########################################################################## +@rem +@rem Gradle startup script for Windows +@rem +@rem ########################################################################## + +@rem Set local scope for the variables with windows NT shell +if "%OS%"=="Windows_NT" setlocal + +set DIRNAME=%~dp0 +if "%DIRNAME%"=="" set DIRNAME=. +@rem This is normally unused +set APP_BASE_NAME=%~n0 +set APP_HOME=%DIRNAME% + +@rem Resolve any "." and ".." in APP_HOME to make it shorter. +for %%i in ("%APP_HOME%") do set APP_HOME=%%~fi + +@rem Add default JVM options here. You can also use JAVA_OPTS and GRADLE_OPTS to pass JVM options to this script. +set DEFAULT_JVM_OPTS="-Xmx64m" "-Xms64m" + +@rem Find java.exe +if defined JAVA_HOME goto findJavaFromJavaHome + +set JAVA_EXE=java.exe +%JAVA_EXE% -version >NUL 2>&1 +if %ERRORLEVEL% equ 0 goto execute + +echo. 1>&2 +echo ERROR: JAVA_HOME is not set and no 'java' command could be found in your PATH. 1>&2 +echo. 1>&2 +echo Please set the JAVA_HOME variable in your environment to match the 1>&2 +echo location of your Java installation. 1>&2 + +goto fail + +:findJavaFromJavaHome +set JAVA_HOME=%JAVA_HOME:"=% +set JAVA_EXE=%JAVA_HOME%/bin/java.exe + +if exist "%JAVA_EXE%" goto execute + +echo. 1>&2 +echo ERROR: JAVA_HOME is set to an invalid directory: %JAVA_HOME% 1>&2 +echo. 1>&2 +echo Please set the JAVA_HOME variable in your environment to match the 1>&2 +echo location of your Java installation. 1>&2 + +goto fail + +:execute +@rem Setup the command line + +set CLASSPATH=%APP_HOME%\gradle\wrapper\gradle-wrapper.jar + + +@rem Execute Gradle +"%JAVA_EXE%" %DEFAULT_JVM_OPTS% %JAVA_OPTS% %GRADLE_OPTS% "-Dorg.gradle.appname=%APP_BASE_NAME%" -classpath "%CLASSPATH%" org.gradle.wrapper.GradleWrapperMain %* + +:end +@rem End local scope for the variables with windows NT shell +if %ERRORLEVEL% equ 0 goto mainEnd + +:fail +rem Set variable GRADLE_EXIT_CONSOLE if you need the _script_ return code instead of +rem the _cmd.exe /c_ return code! +set EXIT_CODE=%ERRORLEVEL% +if %EXIT_CODE% equ 0 set EXIT_CODE=1 +if not ""=="%GRADLE_EXIT_CONSOLE%" exit %EXIT_CODE% +exit /b %EXIT_CODE% + +:mainEnd +if "%OS%"=="Windows_NT" endlocal + +:omega diff --git a/lesson_17/bank/settings.gradle.kts b/lesson_17/bank/settings.gradle.kts new file mode 100644 index 000000000..e921324fe --- /dev/null +++ b/lesson_17/bank/settings.gradle.kts @@ -0,0 +1,11 @@ +/* + * This file was generated by the Gradle 'init' task. + * + * The settings file is used to specify which projects to include in your build. + * + * Detailed information about configuring a multi-project build in Gradle can be found + * in the user manual at https://docs.gradle.org/8.0.2/userguide/multi_project_builds.html + */ + +rootProject.name = "lesson_13" +include("bank_app") diff --git a/lesson_21/README.md b/lesson_21/README.md new file mode 100644 index 000000000..198ebfb7a --- /dev/null +++ b/lesson_21/README.md @@ -0,0 +1,12 @@ +# Lesson 21: Computer Languages ([Slides](https://code-differently.github.io/code-differently-25-q1/slides/#/lesson_21)) + +## Pre-work + +Please review the following resources before lecture: + +* [Programming Paradigms Explained (Video)](https://www.youtube.com/watch?v=H5uA6p_pK-Y) +* [Ditch your Favorite Programming Paradigm (Video)](https://www.youtube.com/watch?v=UOkOA6W-vwc) + +## Homework + +- TODO(anthonydmays): Figure this out \ No newline at end of file