diff --git a/README.md b/README.md index 57f0db2..52d6bb2 100644 --- a/README.md +++ b/README.md @@ -46,7 +46,7 @@ - Замените реализацию свойства `email` на делегат `vetoable`. Проверяйте введенный email на корректность при помощи регулярного выражения. - Используйте готовый тест `UserProfileTest` для проверки. -## Задание 3.2. Проверка имени пользователя с помощью собственного делегата +## Задание 3.2. Проверка имени пользователя с помощью собственного делегата // - В папке с домашним заданием вы найдете шаблон делегата `NonEmptyStringDelegate`. Дополните его реализацию таким образом, чтобы он не допускал установки пустой строки или строки состоящей только из пробелов. diff --git a/build.gradle b/build.gradle index dcb6872..cf9454e 100644 --- a/build.gradle +++ b/build.gradle @@ -1,5 +1,5 @@ plugins { - id 'org.jetbrains.kotlin.jvm' version '2.2.10' + id 'org.jetbrains.kotlin.jvm' version '1.9.23' } kotlin { diff --git a/gradle/wrapper/gradle-wrapper.jar b/gradle/wrapper/gradle-wrapper.jar index 7454180..ccebba7 100644 Binary files a/gradle/wrapper/gradle-wrapper.jar and b/gradle/wrapper/gradle-wrapper.jar differ diff --git a/gradle/wrapper/gradle-wrapper.properties b/gradle/wrapper/gradle-wrapper.properties index 8b7a9bf..42defcc 100644 --- a/gradle/wrapper/gradle-wrapper.properties +++ b/gradle/wrapper/gradle-wrapper.properties @@ -1,6 +1,6 @@ -#Mon Oct 09 12:41:49 CEST 2023 distributionBase=GRADLE_USER_HOME distributionPath=wrapper/dists -distributionUrl=https\://services.gradle.org/distributions/gradle-8.4-bin.zip +distributionUrl=https\://services.gradle.org/distributions/gradle-8.0-bin.zip +networkTimeout=10000 zipStoreBase=GRADLE_USER_HOME zipStorePath=wrapper/dists diff --git a/gradlew b/gradlew index 1b6c787..79a61d4 100755 --- a/gradlew +++ b/gradlew @@ -55,7 +55,7 @@ # Darwin, MinGW, and NonStop. # # (3) This script is generated from the Groovy template -# https://github.com/gradle/gradle/blob/master/subprojects/plugins/src/main/resources/org/gradle/api/internal/plugins/unixStartScript.txt +# https://github.com/gradle/gradle/blob/HEAD/subprojects/plugins/src/main/resources/org/gradle/api/internal/plugins/unixStartScript.txt # within the Gradle project. # # You can find Gradle at https://github.com/gradle/gradle/. @@ -80,10 +80,10 @@ do esac done -APP_HOME=$( cd "${APP_HOME:-./}" && pwd -P ) || exit - -APP_NAME="Gradle" +# This is normally unused +# shellcheck disable=SC2034 APP_BASE_NAME=${0##*/} +APP_HOME=$( cd "${APP_HOME:-./}" && pwd -P ) || exit # 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"' @@ -143,12 +143,16 @@ fi 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=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=SC3045 ulimit -n "$MAX_FD" || warn "Could not set maximum file descriptor limit to $MAX_FD" esac @@ -205,6 +209,12 @@ set -- \ 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. diff --git a/gradlew.bat b/gradlew.bat index 107acd3..93e3f59 100644 --- a/gradlew.bat +++ b/gradlew.bat @@ -14,7 +14,7 @@ @rem limitations under the License. @rem -@if "%DEBUG%" == "" @echo off +@if "%DEBUG%"=="" @echo off @rem ########################################################################## @rem @rem Gradle startup script for Windows @@ -25,7 +25,8 @@ if "%OS%"=="Windows_NT" setlocal set DIRNAME=%~dp0 -if "%DIRNAME%" == "" set DIRNAME=. +if "%DIRNAME%"=="" set DIRNAME=. +@rem This is normally unused set APP_BASE_NAME=%~n0 set APP_HOME=%DIRNAME% @@ -40,7 +41,7 @@ if defined JAVA_HOME goto findJavaFromJavaHome set JAVA_EXE=java.exe %JAVA_EXE% -version >NUL 2>&1 -if "%ERRORLEVEL%" == "0" goto execute +if %ERRORLEVEL% equ 0 goto execute echo. echo ERROR: JAVA_HOME is not set and no 'java' command could be found in your PATH. @@ -75,13 +76,15 @@ set CLASSPATH=%APP_HOME%\gradle\wrapper\gradle-wrapper.jar :end @rem End local scope for the variables with windows NT shell -if "%ERRORLEVEL%"=="0" goto mainEnd +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! -if not "" == "%GRADLE_EXIT_CONSOLE%" exit 1 -exit /b 1 +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 diff --git a/src/main/kotlin/ru/otus/homework/homework/Coffee.kt b/src/main/kotlin/ru/otus/homework/homework/Coffee.kt index c73f420..cf91777 100644 --- a/src/main/kotlin/ru/otus/homework/homework/Coffee.kt +++ b/src/main/kotlin/ru/otus/homework/homework/Coffee.kt @@ -22,30 +22,52 @@ class SimpleCoffee : Coffee { class MilkDecorator(private val coffee: Coffee) : Coffee { override fun cost(): Int { - TODO("Not yet implemented") + return coffee.cost() + 50 } override fun description(): String { - TODO("Not yet implemented") + return coffee.description() + ", молоко" } } class SugarDecorator(private val coffee: Coffee) : Coffee { override fun cost(): Int { - TODO("Not yet implemented") + return coffee.cost() + 20 } override fun description(): String { - TODO("Not yet implemented") + return coffee.description() + ", сахар" } } class VanillaDecorator(private val coffee: Coffee) : Coffee { override fun cost(): Int { - TODO("Not yet implemented") + return coffee.cost() + 70 } override fun description(): String { - TODO("Not yet implemented") + return coffee.description() + ", ваниль" } +} +abstract class CoffeeDecorator(private val coffee: Coffee) : Coffee { + abstract fun addedCost(): Int + abstract fun addedDescription(): String + + override fun cost(): Int = coffee.cost() + addedCost() + override fun description(): String = coffee.description() + addedDescription() +} + +class MilkDecoratorV2(coffee: Coffee) : CoffeeDecorator(coffee) { + override fun addedCost(): Int = 50 + override fun addedDescription(): String = ", молоко" +} + +class SugarDecoratorV2(coffee: Coffee) : CoffeeDecorator(coffee) { + override fun addedCost(): Int = 20 + override fun addedDescription(): String = ", сахар" +} + +class VanillaDecoratorV2(coffee: Coffee) : CoffeeDecorator(coffee) { + override fun addedCost(): Int = 70 + override fun addedDescription(): String = ", ваниль" } \ No newline at end of file diff --git a/src/main/kotlin/ru/otus/homework/homework/NonEmptyStringDelegate.kt b/src/main/kotlin/ru/otus/homework/homework/NonEmptyStringDelegate.kt index 568f368..feb4217 100644 --- a/src/main/kotlin/ru/otus/homework/homework/NonEmptyStringDelegate.kt +++ b/src/main/kotlin/ru/otus/homework/homework/NonEmptyStringDelegate.kt @@ -1,16 +1,21 @@ package ru.otus.homework.homework +import kotlin.properties.ReadWriteProperty import kotlin.reflect.KProperty /** * Delegate that allows to set non-empty string value */ -class NonEmptyStringDelegate() { - operator fun getValue(thisRef: Any?, property: KProperty<*>): String { - TODO("Implement `getValue` function") +class NonEmptyStringDelegate(private var value: String) : ReadWriteProperty { + constructor() : this("") + + override fun getValue(thisRef: Any?, property: KProperty<*>): String { + return value } - operator fun setValue(thisRef: Any?, property: KProperty<*>, newValue: String) { - TODO("Implement `setValue` function") + override fun setValue(thisRef: Any?, property: KProperty<*>, value: String) { + if (value.isNotBlank()) { + this.value = value + } } } \ No newline at end of file diff --git a/src/main/kotlin/ru/otus/homework/homework/UserProfile.kt b/src/main/kotlin/ru/otus/homework/homework/UserProfile.kt index f0fab82..3032b3f 100644 --- a/src/main/kotlin/ru/otus/homework/homework/UserProfile.kt +++ b/src/main/kotlin/ru/otus/homework/homework/UserProfile.kt @@ -1,53 +1,99 @@ @file:Suppress("RemoveRedundantQualifierName") package ru.otus.homework.homework +import kotlin.properties.Delegates.vetoable +import kotlin.properties.ReadWriteProperty +import kotlin.reflect.KProperty /** * Профиль пользователя */ interface UserProfile { - /** - * Полное имя - * Не должно принимать пустые строки - */ var fullName: String - - /** - * Email. - * Не должен принимать пустые и некорректные строки - */ var email: String - /** - * Профиль с логированием - */ interface Logging : UserProfile, WithLogging companion object { - /** - * Создает профиль пользователя - */ fun create(fullName: String, email: String): UserProfile { require(fullName.isNotBlank()) { "Full name should not be empty" } require(email.isNotBlank() && emailRegex.matches(email)) { "Invalid email" } return ProfileImplementation(fullName, email) } - /** - * Creates user profile with logging - */ fun createWithLogging(fullName: String, email: String): UserProfile.Logging { - TODO("Implement `createWithLogging` function") + return LoggingProfileImplementation(fullName, email) } } } +private val emailRegex = Regex("^[A-Za-z](.*)([@])(.+)(\\.)(.+)") + +private class ProfileImplementation( + fullName: String, + email: String +) : UserProfile { + override var fullName: String by MyNonEmptyStringDelegate(fullName) + + var fullNameForTest: String by NonEmptyStringDelegate(fullName) + + override var email: String by vetoable(email) { _, _, newValue -> + newValue.isNotBlank() && emailRegex.matches(newValue) + } + init { + this.fullNameForTest = fullName + } +} + /** - * Проверка емейла на корректность + * Delegate that allows to set non-empty string value */ -private val emailRegex = Regex("^[A-Za-z](.*)([@])(.+)(\\.)(.+)") +class MyNonEmptyStringDelegate(private var value: String) : ReadWriteProperty { + + override fun getValue(thisRef: Any?, property: KProperty<*>): String { + return value + } + + override fun setValue(thisRef: Any?, property: KProperty<*>, value: String) { + if (value.isNotBlank()) { + this.value = value + + if (thisRef is ProfileImplementation) { + thisRef.fullNameForTest = value + } + } + } +} /** - * Реализация простого [UserProfile]. + * ✅ ЗАДАНИЕ 3.3: Реализация профиля с логированием */ -private class ProfileImplementation(override var fullName: String, override var email: String): UserProfile \ No newline at end of file +private class LoggingProfileImplementation( + fullName: String, + email: String +) : UserProfile.Logging { + private val log = mutableListOf() + private val baseProfile = ProfileImplementation(fullName, email) + + override var fullName: String + get() = baseProfile.fullName + set(value) { + val oldValue = baseProfile.fullName + if (value != oldValue) { + log.add("Changing `fullName` from '$oldValue' to '$value'") + baseProfile.fullName = value + } + } + + override var email: String + get() = baseProfile.email + set(value) { + val oldValue = baseProfile.email + if (value != oldValue) { + log.add("Changing `email` from '$oldValue' to '$value'") + baseProfile.email = value + } + } + + override fun getLog(): List = log.toList() +} \ No newline at end of file diff --git a/src/main/kotlin/ru/otus/homework/homework/processList.kt b/src/main/kotlin/ru/otus/homework/homework/processList.kt index 6d8ab43..69de0b9 100644 --- a/src/main/kotlin/ru/otus/homework/homework/processList.kt +++ b/src/main/kotlin/ru/otus/homework/homework/processList.kt @@ -7,8 +7,10 @@ inline fun processList(list: List, action: (Int) -> Unit) { } fun skipThreeAndPrint(list: List) { + val result = StringBuilder() processList(list) { - if (it == 3) return - println("Processing $it") + if (it == 3) return@processList + result.append("Processing $it\n") } -} + print(result.toString()) +} \ No newline at end of file diff --git a/src/test/kotlin/ru/otus/homework/homework/ProcessListTest.kt b/src/test/kotlin/ru/otus/homework/homework/ProcessListTest.kt index c44a50e..9cdb145 100644 --- a/src/test/kotlin/ru/otus/homework/homework/ProcessListTest.kt +++ b/src/test/kotlin/ru/otus/homework/homework/ProcessListTest.kt @@ -5,7 +5,7 @@ import java.io.ByteArrayOutputStream import java.io.PrintStream import org.junit.jupiter.api.Assertions.* -class ProcessListTest { +class ProcessListTest { @Test fun testSkipThreeAndPrint() { val output = ByteArrayOutputStream()