├── .editorconfig
├── .github
└── workflows
│ └── workflow.yml
├── .gitignore
├── .travis.yml
├── LICENSE
├── Makefile
├── README.md
├── build.gradle
├── gradle
└── wrapper
│ ├── gradle-wrapper.jar
│ └── gradle-wrapper.properties
├── gradlew
├── gradlew.bat
├── src
├── main
│ ├── java
│ │ └── tv
│ │ │ └── codely
│ │ │ └── solid_principles
│ │ │ ├── dependency_inversion_principle
│ │ │ ├── User.java
│ │ │ ├── stage_1_instantiating_from_clients
│ │ │ │ ├── HardcodedInMemoryUsersRepository.java
│ │ │ │ └── UserSearcher.java
│ │ │ ├── stage_2_0_dependency_injection
│ │ │ │ ├── HardcodedInMemoryUsersRepository.java
│ │ │ │ └── UserSearcher.java
│ │ │ ├── stage_2_1_dependency_injection_of_constant_parameters
│ │ │ │ ├── HardcodedInMemoryUsersRepository.java
│ │ │ │ └── UserSearcher.java
│ │ │ └── stage_3_dependency_inversion
│ │ │ │ ├── UserSearcher.java
│ │ │ │ └── UsersRepository.java
│ │ │ └── liskov_substitution_principle
│ │ │ ├── Rectangle.java
│ │ │ └── Square.java
│ └── resources
│ │ └── log4j2.properties
└── test
│ ├── java
│ └── tv
│ │ └── codely
│ │ └── solid_principles
│ │ ├── dependency_inversion_principle
│ │ ├── stage_1_instantiating_from_clients
│ │ │ └── UserSearcherShould.java
│ │ ├── stage_2_0_dependency_injection
│ │ │ └── UserSearcherShould.java
│ │ ├── stage_2_1_dependency_injection_of_constant_parameters
│ │ │ └── UserSearcherShould.java
│ │ └── stage_3_dependency_inversion
│ │ │ ├── CodelyTvStaffUsersRepository.java
│ │ │ ├── EmptyUsersRepository.java
│ │ │ ├── UserMother.java
│ │ │ └── UserSearcherShould.java
│ │ └── liskov_substitution_principle
│ │ ├── RectangleShould.java
│ │ └── SquareShould.java
│ └── resources
│ └── log4j2.properties
└── var
└── log
└── .gitkeep
/.editorconfig:
--------------------------------------------------------------------------------
1 | root = true
2 |
3 | [*]
4 | charset = utf-8
5 | end_of_line = lf
6 | insert_final_newline = true
7 | trim_trailing_whitespace = true
8 |
9 | [*.java]
10 | indent_size = 4
11 | indent_style = space
12 |
--------------------------------------------------------------------------------
/.github/workflows/workflow.yml:
--------------------------------------------------------------------------------
1 | name: Main Workflow
2 |
3 | on: [push]
4 |
5 | jobs:
6 | build:
7 |
8 | runs-on: ubuntu-latest
9 |
10 | steps:
11 | - uses: actions/checkout@v1
12 | - name: Set up JDK 1.8
13 | uses: actions/setup-java@v1
14 | with:
15 | java-version: 1.8
16 | - name: Assemble
17 | run: ./gradlew assemble --warning-mode all
18 | - name: Check
19 | run: ./gradlew check --warning-mode all
20 |
21 |
--------------------------------------------------------------------------------
/.gitignore:
--------------------------------------------------------------------------------
1 | # Gradle
2 | .gradle
3 | build/
4 | /out
5 | # Ignore Gradle GUI config
6 | gradle-app.setting
7 |
8 | var/log/*
9 | !var/log/.gitkeep
10 |
--------------------------------------------------------------------------------
/.travis.yml:
--------------------------------------------------------------------------------
1 | language: java
2 |
3 | jdk:
4 | - openjdk11
5 | - oraclejdk11
6 |
7 | os:
8 | - linux
9 | - osx
10 |
11 | before_cache:
12 | - rm -f $HOME/.gradle/caches/modules-2/modules-2.lock
13 | - rm -fr $HOME/.gradle/caches/*/plugin-resolution/
14 |
15 | cache:
16 | directories:
17 | - $HOME/.gradle/caches/
18 | - $HOME/.gradle/wrapper/
19 |
20 | # Run commands before TravisCI install step only in some cases
21 | # More info: https://docs.travis-ci.com/user/multi-os/#example-multi-os-build-matrix
22 | before_install:
23 | - if [[ "$TRAVIS_OS_NAME" == "osx" ]]; then brew update; fi
24 |
25 | # Override default install process on TravisCI
26 | # Avoid default `gradlew assemble` execution. Be explicit about it on the `script` section.
27 | # More info: https://github.com/travis-ci/travis-ci/issues/8667
28 | install: true
29 |
30 | # Build pipeline
31 | # Compile before running the tests in order to easily check which task could be failing.
32 | script:
33 | - ./gradlew assemble --warning-mode all
34 | - ./gradlew check --warning-mode all
35 |
--------------------------------------------------------------------------------
/LICENSE:
--------------------------------------------------------------------------------
1 | MIT License
2 |
3 | Copyright (c) 2018 CodelyTV
4 |
5 | Permission is hereby granted, free of charge, to any person obtaining a copy
6 | of this software and associated documentation files (the "Software"), to deal
7 | in the Software without restriction, including without limitation the rights
8 | to use, copy, modify, merge, publish, distribute, sublicense, and/or sell
9 | copies of the Software, and to permit persons to whom the Software is
10 | furnished to do so, subject to the following conditions:
11 |
12 | The above copyright notice and this permission notice shall be included in all
13 | copies or substantial portions of the Software.
14 |
15 | THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR
16 | IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY,
17 | FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE
18 | AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER
19 | LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM,
20 | OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE
21 | SOFTWARE.
22 |
--------------------------------------------------------------------------------
/Makefile:
--------------------------------------------------------------------------------
1 | .PONY: all build test
2 |
3 | all: build
4 |
5 | build:
6 | @./gradlew assemble --warning-mode all
7 |
8 | test:
9 | @./gradlew check --warning-mode all
10 |
--------------------------------------------------------------------------------
/README.md:
--------------------------------------------------------------------------------
1 | # ☕⚛ SOLID principles examples in Java
2 |
3 |
4 |
5 |
6 | > ⚛ Learn SOLID principles by examples
7 |
8 | [](https://codely.tv)
9 | [](https://github.com/CodelyTV/java-solid-examples/actions)
10 |
11 | ## ℹ️ Introduction
12 |
13 | This is a repository intended to serve as illustrative examples for the course ["Principios SOLID Aplicados" (Spanish)](https://pro.codely.tv/library/principios-solid-aplicados/77070/about/?utm_source=github&utm_medium=social&utm_campaign=java-solid-examples).
14 |
15 | ## 🏁 How To Start
16 |
17 | 1. Install Java 8: `brew cask install corretto8`
18 | 2. Set it as your default JVM: `export JAVA_HOME='/Library/Java/JavaVirtualMachines/amazon-corretto-8.jdk/Contents/Home'`
19 | 3. Clone this repository: `git clone https://github.com/CodelyTV/java-solid-examples`.
20 | 4. Execute some [Gradle lifecycle tasks](https://docs.gradle.org/current/userguide/java_plugin.html#lifecycle_tasks) in order to check everything is OK:
21 | 1. Create [the project JAR](https://docs.gradle.org/current/userguide/java_plugin.html#sec:jar): `make build`
22 | 2. Run the tests and plugins verification tasks: `make test`
23 | 5. Start playing around with the different examples of each SOLID principle. You have explanations here and in the test code 🙂
24 |
25 | ## ☝️ How to update dependencies
26 |
27 | * Gradle (current version: 5.6 - [releases](https://gradle.org/releases/)):
28 | `./gradlew wrapper --gradle-version=5.6 --distribution-type=bin` or modifying the [gradle-wrapper.properties](gradle/wrapper/gradle-wrapper.properties#L3)
29 | * JUnit (current version: 5.5.1 - [releases](https://junit.org/junit5/docs/snapshot/release-notes/index.html)):
30 | [`build.gradle:11`](build.gradle#L11-L12)
31 |
32 | ## 💡 Related repositories
33 |
34 | ### ☕ Java
35 |
36 | * 📂 [Java Basic Skeleton](https://github.com/CodelyTV/java-basic-skeleton)
37 | * ⚛ [Java OOP Examples](https://github.com/CodelyTV/java-oop-examples)
38 | * 🧱 [Java SOLID Examples](https://github.com/CodelyTV/java-solid-examples)
39 | * 🥦 [Java DDD Example](https://github.com/CodelyTV/java-ddd-example)
40 |
41 | ### 🐘 PHP
42 |
43 | * 📂 [PHP Basic Skeleton](https://github.com/CodelyTV/php-basic-skeleton)
44 | * 🎩 [PHP DDD Skeleton](https://github.com/CodelyTV/php-ddd-skeleton)
45 | * 🥦 [PHP DDD Example](https://github.com/CodelyTV/php-ddd-example)
46 |
47 | ### 🧬 Scala
48 |
49 | * 📂 [Scala Basic Skeleton](https://github.com/CodelyTV/scala-basic-skeleton)
50 | * ⚡ [Scala Basic Skeleton (g8 template)](https://github.com/CodelyTV/scala-basic-skeleton.g8)
51 | * ⚛ [Scala Examples](https://github.com/CodelyTV/scala-examples)
52 | * 🥦 [Scala DDD Example](https://github.com/CodelyTV/scala-ddd-example)
53 |
54 |
55 | ## Liskov Substitution Principle (LSP)
56 |
57 | * Package: `tv.codely.solid_principles.liskov_substitution_principle`
58 | * [Production code](src/main/java/tv/codely/solid_principles/liskov_substitution_principle)
59 | * [Tests code with explanations](src/test/java/tv/codely/solid_principles/liskov_substitution_principle)
60 |
61 | ## Dependency Inversion Principle (DIP)
62 |
63 | * Package: `tv.codely.solid_principles.dependency_inversion_principle`
64 | * [Production code](src/main/java/tv/codely/solid_principles/dependency_inversion_principle)
65 | * [Tests code with explanations](src/test/java/tv/codely/solid_principles/dependency_inversion_principle)
66 |
67 | ## About
68 |
69 | This hopefully helpful examples have been implemented by [CodelyTV](https://github.com/CodelyTV) and [contributors](https://github.com/CodelyTV/solid-principles-java-examples/graphs/contributors).
70 |
71 | Pull Requests are welcome. We would suggest oppening an issue before actually coding your Pull Request in order to ask for feedback 🙂
72 |
73 | ## License
74 |
75 | The MIT License (MIT). Please see [License](LICENSE) for more information.
76 |
--------------------------------------------------------------------------------
/build.gradle:
--------------------------------------------------------------------------------
1 | apply plugin: 'java'
2 |
3 | sourceCompatibility = 1.8
4 | targetCompatibility = 1.8
5 |
6 | repositories {
7 | mavenCentral()
8 | }
9 |
10 | dependencies {
11 | implementation 'org.apache.logging.log4j:log4j-core:2.12.1'
12 | implementation 'com.vlkan.log4j2:log4j2-logstash-layout:0.19'
13 |
14 | testCompile 'org.junit.jupiter:junit-jupiter-api:5.5.1'
15 | testRuntimeOnly 'org.junit.jupiter:junit-jupiter-engine:5.5.1'
16 | }
17 |
18 | test {
19 | useJUnitPlatform()
20 |
21 | testLogging {
22 | events "passed", "skipped", "failed"
23 | }
24 | }
25 |
--------------------------------------------------------------------------------
/gradle/wrapper/gradle-wrapper.jar:
--------------------------------------------------------------------------------
https://raw.githubusercontent.com/CodelyTV/java-solid-examples/44600ce024ef957a05e0c4fbe9a76b283b0f84a1/gradle/wrapper/gradle-wrapper.jar
--------------------------------------------------------------------------------
/gradle/wrapper/gradle-wrapper.properties:
--------------------------------------------------------------------------------
1 | distributionBase=GRADLE_USER_HOME
2 | distributionPath=wrapper/dists
3 | distributionUrl=https\://services.gradle.org/distributions/gradle-5.6-bin.zip
4 | zipStoreBase=GRADLE_USER_HOME
5 | zipStorePath=wrapper/dists
6 |
--------------------------------------------------------------------------------
/gradlew:
--------------------------------------------------------------------------------
1 | #!/usr/bin/env sh
2 |
3 | ##############################################################################
4 | ##
5 | ## Gradle start up script for UN*X
6 | ##
7 | ##############################################################################
8 |
9 | # Attempt to set APP_HOME
10 | # Resolve links: $0 may be a link
11 | PRG="$0"
12 | # Need this for relative symlinks.
13 | while [ -h "$PRG" ] ; do
14 | ls=`ls -ld "$PRG"`
15 | link=`expr "$ls" : '.*-> \(.*\)$'`
16 | if expr "$link" : '/.*' > /dev/null; then
17 | PRG="$link"
18 | else
19 | PRG=`dirname "$PRG"`"/$link"
20 | fi
21 | done
22 | SAVED="`pwd`"
23 | cd "`dirname \"$PRG\"`/" >/dev/null
24 | APP_HOME="`pwd -P`"
25 | cd "$SAVED" >/dev/null
26 |
27 | APP_NAME="Gradle"
28 | APP_BASE_NAME=`basename "$0"`
29 |
30 | # Add default JVM options here. You can also use JAVA_OPTS and GRADLE_OPTS to pass JVM options to this script.
31 | DEFAULT_JVM_OPTS=""
32 |
33 | # Use the maximum available, or set MAX_FD != -1 to use that value.
34 | MAX_FD="maximum"
35 |
36 | warn () {
37 | echo "$*"
38 | }
39 |
40 | die () {
41 | echo
42 | echo "$*"
43 | echo
44 | exit 1
45 | }
46 |
47 | # OS specific support (must be 'true' or 'false').
48 | cygwin=false
49 | msys=false
50 | darwin=false
51 | nonstop=false
52 | case "`uname`" in
53 | CYGWIN* )
54 | cygwin=true
55 | ;;
56 | Darwin* )
57 | darwin=true
58 | ;;
59 | MINGW* )
60 | msys=true
61 | ;;
62 | NONSTOP* )
63 | nonstop=true
64 | ;;
65 | esac
66 |
67 | CLASSPATH=$APP_HOME/gradle/wrapper/gradle-wrapper.jar
68 |
69 | # Determine the Java command to use to start the JVM.
70 | if [ -n "$JAVA_HOME" ] ; then
71 | if [ -x "$JAVA_HOME/jre/sh/java" ] ; then
72 | # IBM's JDK on AIX uses strange locations for the executables
73 | JAVACMD="$JAVA_HOME/jre/sh/java"
74 | else
75 | JAVACMD="$JAVA_HOME/bin/java"
76 | fi
77 | if [ ! -x "$JAVACMD" ] ; then
78 | die "ERROR: JAVA_HOME is set to an invalid directory: $JAVA_HOME
79 |
80 | Please set the JAVA_HOME variable in your environment to match the
81 | location of your Java installation."
82 | fi
83 | else
84 | JAVACMD="java"
85 | which java >/dev/null 2>&1 || die "ERROR: JAVA_HOME is not set and no 'java' command could be found in your PATH.
86 |
87 | Please set the JAVA_HOME variable in your environment to match the
88 | location of your Java installation."
89 | fi
90 |
91 | # Increase the maximum file descriptors if we can.
92 | if [ "$cygwin" = "false" -a "$darwin" = "false" -a "$nonstop" = "false" ] ; then
93 | MAX_FD_LIMIT=`ulimit -H -n`
94 | if [ $? -eq 0 ] ; then
95 | if [ "$MAX_FD" = "maximum" -o "$MAX_FD" = "max" ] ; then
96 | MAX_FD="$MAX_FD_LIMIT"
97 | fi
98 | ulimit -n $MAX_FD
99 | if [ $? -ne 0 ] ; then
100 | warn "Could not set maximum file descriptor limit: $MAX_FD"
101 | fi
102 | else
103 | warn "Could not query maximum file descriptor limit: $MAX_FD_LIMIT"
104 | fi
105 | fi
106 |
107 | # For Darwin, add options to specify how the application appears in the dock
108 | if $darwin; then
109 | GRADLE_OPTS="$GRADLE_OPTS \"-Xdock:name=$APP_NAME\" \"-Xdock:icon=$APP_HOME/media/gradle.icns\""
110 | fi
111 |
112 | # For Cygwin, switch paths to Windows format before running java
113 | if $cygwin ; then
114 | APP_HOME=`cygpath --path --mixed "$APP_HOME"`
115 | CLASSPATH=`cygpath --path --mixed "$CLASSPATH"`
116 | JAVACMD=`cygpath --unix "$JAVACMD"`
117 |
118 | # We build the pattern for arguments to be converted via cygpath
119 | ROOTDIRSRAW=`find -L / -maxdepth 1 -mindepth 1 -type d 2>/dev/null`
120 | SEP=""
121 | for dir in $ROOTDIRSRAW ; do
122 | ROOTDIRS="$ROOTDIRS$SEP$dir"
123 | SEP="|"
124 | done
125 | OURCYGPATTERN="(^($ROOTDIRS))"
126 | # Add a user-defined pattern to the cygpath arguments
127 | if [ "$GRADLE_CYGPATTERN" != "" ] ; then
128 | OURCYGPATTERN="$OURCYGPATTERN|($GRADLE_CYGPATTERN)"
129 | fi
130 | # Now convert the arguments - kludge to limit ourselves to /bin/sh
131 | i=0
132 | for arg in "$@" ; do
133 | CHECK=`echo "$arg"|egrep -c "$OURCYGPATTERN" -`
134 | CHECK2=`echo "$arg"|egrep -c "^-"` ### Determine if an option
135 |
136 | if [ $CHECK -ne 0 ] && [ $CHECK2 -eq 0 ] ; then ### Added a condition
137 | eval `echo args$i`=`cygpath --path --ignore --mixed "$arg"`
138 | else
139 | eval `echo args$i`="\"$arg\""
140 | fi
141 | i=$((i+1))
142 | done
143 | case $i in
144 | (0) set -- ;;
145 | (1) set -- "$args0" ;;
146 | (2) set -- "$args0" "$args1" ;;
147 | (3) set -- "$args0" "$args1" "$args2" ;;
148 | (4) set -- "$args0" "$args1" "$args2" "$args3" ;;
149 | (5) set -- "$args0" "$args1" "$args2" "$args3" "$args4" ;;
150 | (6) set -- "$args0" "$args1" "$args2" "$args3" "$args4" "$args5" ;;
151 | (7) set -- "$args0" "$args1" "$args2" "$args3" "$args4" "$args5" "$args6" ;;
152 | (8) set -- "$args0" "$args1" "$args2" "$args3" "$args4" "$args5" "$args6" "$args7" ;;
153 | (9) set -- "$args0" "$args1" "$args2" "$args3" "$args4" "$args5" "$args6" "$args7" "$args8" ;;
154 | esac
155 | fi
156 |
157 | # Escape application args
158 | save () {
159 | for i do printf %s\\n "$i" | sed "s/'/'\\\\''/g;1s/^/'/;\$s/\$/' \\\\/" ; done
160 | echo " "
161 | }
162 | APP_ARGS=$(save "$@")
163 |
164 | # Collect all arguments for the java command, following the shell quoting and substitution rules
165 | eval set -- $DEFAULT_JVM_OPTS $JAVA_OPTS $GRADLE_OPTS "\"-Dorg.gradle.appname=$APP_BASE_NAME\"" -classpath "\"$CLASSPATH\"" org.gradle.wrapper.GradleWrapperMain "$APP_ARGS"
166 |
167 | # by default we should be in the correct project dir, but when run from Finder on Mac, the cwd is wrong
168 | if [ "$(uname)" = "Darwin" ] && [ "$HOME" = "$PWD" ]; then
169 | cd "$(dirname "$0")"
170 | fi
171 |
172 | exec "$JAVACMD" "$@"
173 |
--------------------------------------------------------------------------------
/gradlew.bat:
--------------------------------------------------------------------------------
1 | @if "%DEBUG%" == "" @echo off
2 | @rem ##########################################################################
3 | @rem
4 | @rem Gradle startup script for Windows
5 | @rem
6 | @rem ##########################################################################
7 |
8 | @rem Set local scope for the variables with windows NT shell
9 | if "%OS%"=="Windows_NT" setlocal
10 |
11 | set DIRNAME=%~dp0
12 | if "%DIRNAME%" == "" set DIRNAME=.
13 | set APP_BASE_NAME=%~n0
14 | set APP_HOME=%DIRNAME%
15 |
16 | @rem Add default JVM options here. You can also use JAVA_OPTS and GRADLE_OPTS to pass JVM options to this script.
17 | set DEFAULT_JVM_OPTS=
18 |
19 | @rem Find java.exe
20 | if defined JAVA_HOME goto findJavaFromJavaHome
21 |
22 | set JAVA_EXE=java.exe
23 | %JAVA_EXE% -version >NUL 2>&1
24 | if "%ERRORLEVEL%" == "0" goto init
25 |
26 | echo.
27 | echo ERROR: JAVA_HOME is not set and no 'java' command could be found in your PATH.
28 | echo.
29 | echo Please set the JAVA_HOME variable in your environment to match the
30 | echo location of your Java installation.
31 |
32 | goto fail
33 |
34 | :findJavaFromJavaHome
35 | set JAVA_HOME=%JAVA_HOME:"=%
36 | set JAVA_EXE=%JAVA_HOME%/bin/java.exe
37 |
38 | if exist "%JAVA_EXE%" goto init
39 |
40 | echo.
41 | echo ERROR: JAVA_HOME is set to an invalid directory: %JAVA_HOME%
42 | echo.
43 | echo Please set the JAVA_HOME variable in your environment to match the
44 | echo location of your Java installation.
45 |
46 | goto fail
47 |
48 | :init
49 | @rem Get command-line arguments, handling Windows variants
50 |
51 | if not "%OS%" == "Windows_NT" goto win9xME_args
52 |
53 | :win9xME_args
54 | @rem Slurp the command line arguments.
55 | set CMD_LINE_ARGS=
56 | set _SKIP=2
57 |
58 | :win9xME_args_slurp
59 | if "x%~1" == "x" goto execute
60 |
61 | set CMD_LINE_ARGS=%*
62 |
63 | :execute
64 | @rem Setup the command line
65 |
66 | set CLASSPATH=%APP_HOME%\gradle\wrapper\gradle-wrapper.jar
67 |
68 | @rem Execute Gradle
69 | "%JAVA_EXE%" %DEFAULT_JVM_OPTS% %JAVA_OPTS% %GRADLE_OPTS% "-Dorg.gradle.appname=%APP_BASE_NAME%" -classpath "%CLASSPATH%" org.gradle.wrapper.GradleWrapperMain %CMD_LINE_ARGS%
70 |
71 | :end
72 | @rem End local scope for the variables with windows NT shell
73 | if "%ERRORLEVEL%"=="0" goto mainEnd
74 |
75 | :fail
76 | rem Set variable GRADLE_EXIT_CONSOLE if you need the _script_ return code instead of
77 | rem the _cmd.exe /c_ return code!
78 | if not "" == "%GRADLE_EXIT_CONSOLE%" exit 1
79 | exit /b 1
80 |
81 | :mainEnd
82 | if "%OS%"=="Windows_NT" endlocal
83 |
84 | :omega
85 |
--------------------------------------------------------------------------------
/src/main/java/tv/codely/solid_principles/dependency_inversion_principle/User.java:
--------------------------------------------------------------------------------
1 | package tv.codely.solid_principles.dependency_inversion_principle;
2 |
3 | import java.util.Objects;
4 |
5 | final public class User {
6 | private Integer id;
7 | private String name;
8 |
9 | public User(Integer id, String name) {
10 | this.id = id;
11 | this.name = name;
12 | }
13 |
14 | @Override
15 | public boolean equals(Object other) {
16 | if (this == other) return true;
17 |
18 | if (!(other instanceof User)) return false;
19 |
20 | User otherUser = (User) other;
21 | return Objects.equals(id, otherUser.id) && Objects.equals(name, otherUser.name);
22 | }
23 |
24 | @Override
25 | public int hashCode() {
26 | return Objects.hash(id, name);
27 | }
28 | }
29 |
--------------------------------------------------------------------------------
/src/main/java/tv/codely/solid_principles/dependency_inversion_principle/stage_1_instantiating_from_clients/HardcodedInMemoryUsersRepository.java:
--------------------------------------------------------------------------------
1 | package tv.codely.solid_principles.dependency_inversion_principle.stage_1_instantiating_from_clients;
2 |
3 | import tv.codely.solid_principles.dependency_inversion_principle.User;
4 |
5 | import java.util.Collections;
6 | import java.util.HashMap;
7 | import java.util.Map;
8 | import java.util.Optional;
9 |
10 | final class HardcodedInMemoryUsersRepository {
11 | private Map users = Collections.unmodifiableMap(new HashMap() {
12 | {
13 | put(1, new User(1, "Rafa"));
14 | put(2, new User(2, "Javi"));
15 | }
16 | });
17 |
18 | public Optional search(Integer id) {
19 | return Optional.ofNullable(users.get(id));
20 | }
21 | }
22 |
--------------------------------------------------------------------------------
/src/main/java/tv/codely/solid_principles/dependency_inversion_principle/stage_1_instantiating_from_clients/UserSearcher.java:
--------------------------------------------------------------------------------
1 | package tv.codely.solid_principles.dependency_inversion_principle.stage_1_instantiating_from_clients;
2 |
3 | import tv.codely.solid_principles.dependency_inversion_principle.User;
4 |
5 | import java.util.Optional;
6 |
7 | final class UserSearcher {
8 | private HardcodedInMemoryUsersRepository usersRepository =
9 | new HardcodedInMemoryUsersRepository();
10 |
11 | public Optional search(Integer id) {
12 | return usersRepository.search(id);
13 | }
14 | }
15 |
--------------------------------------------------------------------------------
/src/main/java/tv/codely/solid_principles/dependency_inversion_principle/stage_2_0_dependency_injection/HardcodedInMemoryUsersRepository.java:
--------------------------------------------------------------------------------
1 | package tv.codely.solid_principles.dependency_inversion_principle.stage_2_0_dependency_injection;
2 |
3 | import tv.codely.solid_principles.dependency_inversion_principle.User;
4 |
5 | import java.util.Collections;
6 | import java.util.HashMap;
7 | import java.util.Map;
8 | import java.util.Optional;
9 |
10 | final class HardcodedInMemoryUsersRepository {
11 | private Map users = Collections.unmodifiableMap(new HashMap() {
12 | {
13 | put(1, new User(1, "Rafa"));
14 | put(2, new User(2, "Javi"));
15 | }
16 | });
17 |
18 | public Optional search(Integer id) {
19 | return Optional.ofNullable(users.get(id));
20 | }
21 | }
22 |
--------------------------------------------------------------------------------
/src/main/java/tv/codely/solid_principles/dependency_inversion_principle/stage_2_0_dependency_injection/UserSearcher.java:
--------------------------------------------------------------------------------
1 | package tv.codely.solid_principles.dependency_inversion_principle.stage_2_0_dependency_injection;
2 |
3 | import tv.codely.solid_principles.dependency_inversion_principle.User;
4 |
5 | import java.util.Optional;
6 |
7 | final class UserSearcher {
8 | private HardcodedInMemoryUsersRepository usersRepository;
9 |
10 | public UserSearcher(HardcodedInMemoryUsersRepository usersRepository) {
11 | this.usersRepository = usersRepository;
12 | }
13 |
14 | public Optional search(Integer id) {
15 | return usersRepository.search(id);
16 | }
17 | }
18 |
--------------------------------------------------------------------------------
/src/main/java/tv/codely/solid_principles/dependency_inversion_principle/stage_2_1_dependency_injection_of_constant_parameters/HardcodedInMemoryUsersRepository.java:
--------------------------------------------------------------------------------
1 | package tv.codely.solid_principles.dependency_inversion_principle.stage_2_1_dependency_injection_of_constant_parameters;
2 |
3 | import tv.codely.solid_principles.dependency_inversion_principle.User;
4 |
5 | import java.util.Map;
6 | import java.util.Optional;
7 |
8 | final class HardcodedInMemoryUsersRepository {
9 | private Map users;
10 |
11 | public HardcodedInMemoryUsersRepository(Map users) {
12 | this.users = users;
13 | }
14 |
15 | public Optional search(Integer id) {
16 | return Optional.ofNullable(users.get(id));
17 | }
18 | }
19 |
--------------------------------------------------------------------------------
/src/main/java/tv/codely/solid_principles/dependency_inversion_principle/stage_2_1_dependency_injection_of_constant_parameters/UserSearcher.java:
--------------------------------------------------------------------------------
1 | package tv.codely.solid_principles.dependency_inversion_principle.stage_2_1_dependency_injection_of_constant_parameters;
2 |
3 | import tv.codely.solid_principles.dependency_inversion_principle.User;
4 |
5 | import java.util.Optional;
6 |
7 | final class UserSearcher {
8 | private HardcodedInMemoryUsersRepository usersRepository;
9 |
10 | public UserSearcher(HardcodedInMemoryUsersRepository usersRepository) {
11 | this.usersRepository = usersRepository;
12 | }
13 |
14 | public Optional search(Integer id) {
15 | return usersRepository.search(id);
16 | }
17 | }
18 |
--------------------------------------------------------------------------------
/src/main/java/tv/codely/solid_principles/dependency_inversion_principle/stage_3_dependency_inversion/UserSearcher.java:
--------------------------------------------------------------------------------
1 | package tv.codely.solid_principles.dependency_inversion_principle.stage_3_dependency_inversion;
2 |
3 | import tv.codely.solid_principles.dependency_inversion_principle.User;
4 |
5 | import java.util.Optional;
6 |
7 | final class UserSearcher {
8 | private UsersRepository usersRepository;
9 |
10 | public UserSearcher(UsersRepository usersRepository) {
11 | this.usersRepository = usersRepository;
12 | }
13 |
14 | public Optional search(Integer id) {
15 | return usersRepository.search(id);
16 | }
17 | }
18 |
--------------------------------------------------------------------------------
/src/main/java/tv/codely/solid_principles/dependency_inversion_principle/stage_3_dependency_inversion/UsersRepository.java:
--------------------------------------------------------------------------------
1 | package tv.codely.solid_principles.dependency_inversion_principle.stage_3_dependency_inversion;
2 |
3 | import tv.codely.solid_principles.dependency_inversion_principle.User;
4 |
5 | import java.util.Optional;
6 |
7 | public interface UsersRepository {
8 | Optional search(Integer id);
9 | }
10 |
--------------------------------------------------------------------------------
/src/main/java/tv/codely/solid_principles/liskov_substitution_principle/Rectangle.java:
--------------------------------------------------------------------------------
1 | package tv.codely.solid_principles.liskov_substitution_principle;
2 |
3 | class Rectangle {
4 | private Integer length;
5 | private Integer width;
6 |
7 | Rectangle(Integer length, Integer width) {
8 | this.length = length;
9 | this.width = width;
10 | }
11 |
12 | void setLength(Integer length) {
13 | this.length = length;
14 | }
15 |
16 | void setWidth(Integer width) {
17 | this.width = width;
18 | }
19 |
20 | Integer getArea() {
21 | return this.length * this.width;
22 | }
23 | }
24 |
--------------------------------------------------------------------------------
/src/main/java/tv/codely/solid_principles/liskov_substitution_principle/Square.java:
--------------------------------------------------------------------------------
1 | package tv.codely.solid_principles.liskov_substitution_principle;
2 |
3 | final class Square extends Rectangle {
4 | Square(Integer lengthAndWidth) {
5 | super(lengthAndWidth, lengthAndWidth);
6 | }
7 |
8 | @Override
9 | public void setLength(Integer length) {
10 | super.setLength(length);
11 | super.setWidth(length);
12 | }
13 |
14 | @Override
15 | public void setWidth(Integer width) {
16 | super.setWidth(width);
17 | super.setLength(width);
18 | }
19 | }
20 |
--------------------------------------------------------------------------------
/src/main/resources/log4j2.properties:
--------------------------------------------------------------------------------
1 | name = CodelyTvJavaSolidExamples
2 | property.filename = logs
3 | appenders = console, file
4 |
5 | status = warn
6 |
7 | appender.console.name = CONSOLE
8 | appender.console.type = CONSOLE
9 | appender.console.target = SYSTEM_OUT
10 |
11 | appender.console.logstash.type = LogstashLayout
12 | appender.console.logstash.dateTimeFormatPattern = yyyy-MM-dd'T'HH:mm:ss.SSSZZZ
13 | appender.console.logstash.eventTemplateUri = classpath:LogstashJsonEventLayoutV1.json
14 | appender.console.logstash.prettyPrintEnabled = true
15 | appender.console.logstash.stackTraceEnabled = true
16 |
17 | appender.file.type = File
18 | appender.file.name = LOGFILE
19 | appender.file.fileName=var/log/java-solid-examples.log
20 | appender.file.logstash.type=LogstashLayout
21 | appender.file.logstash.dateTimeFormatPattern = yyyy-MM-dd'T'HH:mm:ss.SSSZZZ
22 | appender.file.logstash.eventTemplateUri = classpath:LogstashJsonEventLayoutV1.json
23 | appender.file.logstash.prettyPrintEnabled = false
24 | appender.file.logstash.stackTraceEnabled = true
25 |
26 | loggers = file
27 | logger.file.name = tv.codely.solid_principles
28 | logger.file.level = info
29 | logger.file.appenderRefs = file
30 | logger.file.appenderRef.file.ref = LOGFILE
31 |
32 | rootLogger.level = info
33 | rootLogger.appenderRefs = stdout
34 | rootLogger.appenderRef.stdout.ref = CONSOLE
35 |
--------------------------------------------------------------------------------
/src/test/java/tv/codely/solid_principles/dependency_inversion_principle/stage_1_instantiating_from_clients/UserSearcherShould.java:
--------------------------------------------------------------------------------
1 | package tv.codely.solid_principles.dependency_inversion_principle.stage_1_instantiating_from_clients;
2 |
3 | import org.junit.jupiter.api.Test;
4 | import tv.codely.solid_principles.dependency_inversion_principle.User;
5 |
6 | import java.util.Optional;
7 |
8 | import static org.junit.jupiter.api.Assertions.assertEquals;
9 |
10 | final class UserSearcherShould {
11 | @Test
12 | void find_existing_users() {
13 | UserSearcher userSearcher = new UserSearcher();
14 |
15 | // We would be coupled to the actual HardcodedInMemoryUsersRepository implementation.
16 | // We don't have the option to set test users as we would have to do if we had a real database repository.
17 | Integer existingUserId = 1;
18 | Optional expectedUser = Optional.of(new User(1, "Rafa"));
19 |
20 | assertEquals(expectedUser, userSearcher.search(existingUserId));
21 | }
22 |
23 | @Test
24 | void not_find_non_existing_users() {
25 | UserSearcher userSearcher = new UserSearcher();
26 |
27 | Integer nonExistingUserId = 5;
28 | Optional expectedEmptyResult = Optional.empty();
29 |
30 | assertEquals(expectedEmptyResult, userSearcher.search(nonExistingUserId));
31 | }
32 | }
33 |
--------------------------------------------------------------------------------
/src/test/java/tv/codely/solid_principles/dependency_inversion_principle/stage_2_0_dependency_injection/UserSearcherShould.java:
--------------------------------------------------------------------------------
1 | package tv.codely.solid_principles.dependency_inversion_principle.stage_2_0_dependency_injection;
2 |
3 | import org.junit.jupiter.api.Test;
4 | import tv.codely.solid_principles.dependency_inversion_principle.User;
5 |
6 | import java.util.Optional;
7 |
8 | import static org.junit.jupiter.api.Assertions.assertEquals;
9 |
10 | final class UserSearcherShould {
11 | @Test
12 | void find_existing_users() {
13 | // Now we're injecting the HardcodedInMemoryUsersRepository instance through the UserSearcher constructor.
14 | // 👍 Win: We've moved away from the UserSearcher the instantiation logic of the HardcodedInMemoryUsersRepository class allowing us to centralize it.
15 | // 👍 Win: We're exposing the couplings of the UserSearcher class.
16 | HardcodedInMemoryUsersRepository usersRepository = new HardcodedInMemoryUsersRepository();
17 | UserSearcher userSearcher = new UserSearcher(usersRepository);
18 |
19 | Integer existingUserId = 1;
20 | Optional expectedUser = Optional.of(new User(1, "Rafa"));
21 |
22 | assertEquals(expectedUser, userSearcher.search(existingUserId));
23 | }
24 |
25 | @Test
26 | void not_find_non_existing_users() {
27 | HardcodedInMemoryUsersRepository usersRepository = new HardcodedInMemoryUsersRepository();
28 | UserSearcher userSearcher = new UserSearcher(usersRepository);
29 |
30 | Integer nonExistingUserId = 5;
31 | Optional expectedEmptyResult = Optional.empty();
32 |
33 | assertEquals(expectedEmptyResult, userSearcher.search(nonExistingUserId));
34 | }
35 | }
36 |
--------------------------------------------------------------------------------
/src/test/java/tv/codely/solid_principles/dependency_inversion_principle/stage_2_1_dependency_injection_of_constant_parameters/UserSearcherShould.java:
--------------------------------------------------------------------------------
1 | package tv.codely.solid_principles.dependency_inversion_principle.stage_2_1_dependency_injection_of_constant_parameters;
2 |
3 | import org.junit.jupiter.api.Test;
4 | import tv.codely.solid_principles.dependency_inversion_principle.User;
5 |
6 | import java.util.Collections;
7 | import java.util.HashMap;
8 | import java.util.Map;
9 | import java.util.Optional;
10 |
11 | import static org.junit.jupiter.api.Assertions.assertEquals;
12 |
13 | final class UserSearcherShould {
14 | @Test
15 | void find_existing_users() {
16 | // Now we're also injecting the constant parameters needed by the HardcodedInMemoryUsersRepository through its constructor.
17 | // 👍 Win: We can send different parameters depending on the environment.
18 | // That is, in our production environment we would have actual users,
19 | // while in our tests cases we will set only the needed ones to run our test cases
20 | int rafaId = 1;
21 | User rafa = new User(rafaId, "Rafa");
22 |
23 | Map users = Collections.unmodifiableMap(new HashMap() {
24 | {
25 | put(rafaId, rafa);
26 | }
27 | });
28 | HardcodedInMemoryUsersRepository usersRepository = new HardcodedInMemoryUsersRepository(users);
29 | UserSearcher userSearcher = new UserSearcher(usersRepository);
30 |
31 | Optional expectedUser = Optional.of(rafa);
32 |
33 | assertEquals(expectedUser, userSearcher.search(rafaId));
34 | }
35 |
36 | @Test
37 | void not_find_non_existing_users() {
38 | Map users = Collections.emptyMap();
39 | HardcodedInMemoryUsersRepository usersRepository = new HardcodedInMemoryUsersRepository(users);
40 | UserSearcher userSearcher = new UserSearcher(usersRepository);
41 |
42 | // 👍 Win: Now we don't have to be coupled of the actual HardcodedInMemoryUsersRepository users.
43 | // We can send a random user ID in order to force an empty result because we've set an empty map as the system users.
44 | Integer nonExistingUserId = 1;
45 | Optional expectedEmptyResult = Optional.empty();
46 |
47 | assertEquals(expectedEmptyResult, userSearcher.search(nonExistingUserId));
48 | }
49 | }
50 |
--------------------------------------------------------------------------------
/src/test/java/tv/codely/solid_principles/dependency_inversion_principle/stage_3_dependency_inversion/CodelyTvStaffUsersRepository.java:
--------------------------------------------------------------------------------
1 | package tv.codely.solid_principles.dependency_inversion_principle.stage_3_dependency_inversion;
2 |
3 | import tv.codely.solid_principles.dependency_inversion_principle.User;
4 |
5 | import java.util.Collections;
6 | import java.util.HashMap;
7 | import java.util.Map;
8 | import java.util.Optional;
9 |
10 | // ℹ️ User repository for test usage. It is used as a _Test double_, more specifically, it's a _Mother_.
11 | // More info on the difference between Mothers and Mocks: https://martinfowler.com/articles/mocksArentMothers.html
12 | final class CodelyTvStaffUsersRepository implements UsersRepository {
13 | private Map users = Collections.unmodifiableMap(new HashMap() {
14 | {
15 | put(UserMother.RAFA_ID, UserMother.rafa());
16 | put(UserMother.JAVI_ID, UserMother.javi());
17 | }
18 | });
19 |
20 | @Override
21 | public Optional search(Integer id) {
22 | return Optional.ofNullable(users.get(id));
23 | }
24 | }
25 |
26 |
--------------------------------------------------------------------------------
/src/test/java/tv/codely/solid_principles/dependency_inversion_principle/stage_3_dependency_inversion/EmptyUsersRepository.java:
--------------------------------------------------------------------------------
1 | package tv.codely.solid_principles.dependency_inversion_principle.stage_3_dependency_inversion;
2 |
3 | import tv.codely.solid_principles.dependency_inversion_principle.User;
4 |
5 | import java.util.Optional;
6 |
7 | // ℹ️ User repository for test usage. It is used as a _Test double_, more specifically, it's a _Fake_.
8 | // More info on the main types of Test doubles: https://testing.googleblog.com/2013/07/testing-on-toilet-know-your-test-doubles.html
9 | final class EmptyUsersRepository implements UsersRepository {
10 | @Override
11 | public Optional search(Integer id) {
12 | return Optional.empty();
13 | }
14 | }
15 |
--------------------------------------------------------------------------------
/src/test/java/tv/codely/solid_principles/dependency_inversion_principle/stage_3_dependency_inversion/UserMother.java:
--------------------------------------------------------------------------------
1 | package tv.codely.solid_principles.dependency_inversion_principle.stage_3_dependency_inversion;
2 |
3 | import tv.codely.solid_principles.dependency_inversion_principle.User;
4 |
5 | final class UserMother {
6 | static final int RAFA_ID = 1;
7 | static final int JAVI_ID = 2;
8 |
9 | private static final String RAFA_NAME = "Rafa";
10 | private static final String JAVI_NAME = "Javi";
11 |
12 | static User rafa() {
13 | return new User(RAFA_ID, RAFA_NAME);
14 | }
15 |
16 | static User javi() {
17 | return new User(JAVI_ID, JAVI_NAME);
18 | }
19 | }
20 |
--------------------------------------------------------------------------------
/src/test/java/tv/codely/solid_principles/dependency_inversion_principle/stage_3_dependency_inversion/UserSearcherShould.java:
--------------------------------------------------------------------------------
1 | package tv.codely.solid_principles.dependency_inversion_principle.stage_3_dependency_inversion;
2 |
3 | import org.junit.jupiter.api.Test;
4 | import tv.codely.solid_principles.dependency_inversion_principle.User;
5 |
6 | import java.util.Optional;
7 |
8 | import static org.junit.jupiter.api.Assertions.assertEquals;
9 |
10 | final class UserSearcherShould {
11 | @Test
12 | void find_existing_users() {
13 | // Now we're injecting to the UserSearcher use case different implementation of the new UserRepository interface.
14 | // 👍 Win: We can replace the actual implementation of the UsersRepository used by the UserSearcher.
15 | // That is, we'll not have to modify a single line of the UserSearcher class despite of changing our whole infrastructure.
16 | // This is a big win in terms of being more tolerant to changes.
17 | // 👍 Win: It also make it easier for us to test the UserSearcher without using the actual implementation of the repository used in production.
18 | // This is another big win because this way we can have test such as the following ones which doesn't actually go to the database in order to retrieve the system users.
19 | // This has a huge impact in terms of the time to wait until all of our test suite is being executed (quicker feedback loop for developers 💪).
20 | // 👍 Win: We can reuse the test environment repository using test doubles. See CodelyTvStaffUsersRepository for its particularities
21 | UsersRepository codelyTvStaffUsersRepository = new CodelyTvStaffUsersRepository();
22 | UserSearcher userSearcher = new UserSearcher(codelyTvStaffUsersRepository);
23 |
24 | Optional expectedUser = Optional.of(UserMother.rafa());
25 |
26 | assertEquals(expectedUser, userSearcher.search(UserMother.RAFA_ID));
27 | }
28 |
29 | @Test
30 | void not_find_non_existing_users() {
31 | // 👍 Win: Our test are far more readable because they doesn't have to deal with the internal implementation of the UserRepository.
32 | // The test is 100% focused on orchestrating the Arrange/Act/Assert or Given/When/Then flow.
33 | // More info: http://wiki.c2.com/?ArrangeActAssert and https://www.martinfowler.com/bliki/GivenWhenThen.html
34 | UsersRepository emptyUsersRepository = new EmptyUsersRepository();
35 | UserSearcher userSearcher = new UserSearcher(emptyUsersRepository);
36 |
37 | Integer nonExistingUserId = 1;
38 | Optional expectedEmptyResult = Optional.empty();
39 |
40 | assertEquals(expectedEmptyResult, userSearcher.search(nonExistingUserId));
41 | }
42 | }
43 |
--------------------------------------------------------------------------------
/src/test/java/tv/codely/solid_principles/liskov_substitution_principle/RectangleShould.java:
--------------------------------------------------------------------------------
1 | package tv.codely.solid_principles.liskov_substitution_principle;
2 |
3 | import org.junit.jupiter.api.Test;
4 |
5 | import static org.junit.jupiter.api.Assertions.assertEquals;
6 |
7 | final class RectangleShould {
8 | @Test
9 | void calculate_its_area() {
10 | Integer rectangleLength = 2;
11 | Integer rectangleWidth = 2;
12 | Rectangle rectangle = new Rectangle(rectangleLength, rectangleWidth);
13 |
14 | Integer expectedArea = 4;
15 |
16 | assertEquals(expectedArea, rectangle.getArea());
17 | }
18 | }
19 |
--------------------------------------------------------------------------------
/src/test/java/tv/codely/solid_principles/liskov_substitution_principle/SquareShould.java:
--------------------------------------------------------------------------------
1 | package tv.codely.solid_principles.liskov_substitution_principle;
2 |
3 | import org.junit.jupiter.api.Test;
4 |
5 | import static org.junit.jupiter.api.Assertions.assertNotEquals;
6 |
7 | final class SquareShould {
8 | @Test
9 | void not_respect_the_liskov_substitution_principle_breaking_the_rectangle_laws_while_modifying_its_length() {
10 | Integer squareLengthAndWidth = 2;
11 | Square square = new Square(squareLengthAndWidth);
12 |
13 | Integer newSquareLength = 4;
14 | square.setLength(newSquareLength);
15 |
16 | Integer expectedAreaTakingIntoAccountRectangleLaws = 8;
17 |
18 | assertNotEquals(expectedAreaTakingIntoAccountRectangleLaws, square.getArea());
19 | }
20 | }
21 |
--------------------------------------------------------------------------------
/src/test/resources/log4j2.properties:
--------------------------------------------------------------------------------
1 | name = CodelyTvJavaSolidExamples
2 | property.filename = logs
3 | appenders = console, file
4 |
5 | status = warn
6 |
7 | appender.console.name = CONSOLE
8 | appender.console.type = CONSOLE
9 | appender.console.target = SYSTEM_OUT
10 |
11 | appender.console.layout.type = PatternLayout
12 | appender.console.layout.pattern = [%level] [%date{HH:mm:ss.SSS}] [%class{0}#%method:%line] %message \(%mdc\) %n%throwable
13 | appender.console.filter.threshold.type = ThresholdFilter
14 | appender.console.filter.threshold.level = info
15 |
16 | appender.file.type = File
17 | appender.file.name = LOGFILE
18 | appender.file.fileName=var/log/java-solid-examples-test.log
19 | appender.file.logstash.type=LogstashLayout
20 | appender.file.logstash.dateTimeFormatPattern = yyyy-MM-dd'T'HH:mm:ss.SSSZZZ
21 | appender.file.logstash.eventTemplateUri = classpath:LogstashJsonEventLayoutV1.json
22 | appender.file.logstash.prettyPrintEnabled = false
23 | appender.file.logstash.stackTraceEnabled = true
24 |
25 | loggers = file
26 | logger.file.name = tv.codely.solid_principles
27 | logger.file.level = info
28 | logger.file.appenderRefs = file
29 | logger.file.appenderRef.file.ref = LOGFILE
30 |
31 | rootLogger.level = info
32 | rootLogger.appenderRefs = stdout
33 | rootLogger.appenderRef.stdout.ref = CONSOLE
34 |
--------------------------------------------------------------------------------
/var/log/.gitkeep:
--------------------------------------------------------------------------------
https://raw.githubusercontent.com/CodelyTV/java-solid-examples/44600ce024ef957a05e0c4fbe9a76b283b0f84a1/var/log/.gitkeep
--------------------------------------------------------------------------------