Compare commits

...

11 Commits

Author SHA1 Message Date
0a2c87d49a docs: update .all-contributorsrc [skip ci] 2020-08-01 08:07:21 +00:00
15eb49e574 docs: update README.md [skip ci] 2020-08-01 08:07:20 +00:00
661f9e1373 Merge pull request from iluwatar/all-contributors/add-charlesfinley
docs: add charlesfinley as a contributor
2020-08-01 10:42:44 +03:00
7908d38604 docs: update .all-contributorsrc [skip ci] 2020-08-01 07:41:48 +00:00
41020982de docs: update README.md [skip ci] 2020-08-01 07:41:47 +00:00
43569ecd66 Merge pull request from charlesfinley/master
Fixes Issue  - Unit Test assertEquals parameters are reversed
2020-08-01 10:39:20 +03:00
fb6507ceda Corrected assertEquals order for expected, actual. 2020-07-31 22:52:23 -04:00
29f799c815 Corrected assertEquals order for expected, actual. 2020-07-31 22:50:48 -04:00
55bb1f11e0 fix typo 2020-07-30 21:57:07 +03:00
8364b289b4 explanation for Abstract Document 2020-07-30 21:39:11 +03:00
417f21ed3d Code cleanup ()
* Code cleanup

* Fix flux tests

* Fix checkstyle errors

* Fix compile error
2020-07-30 20:28:47 +03:00
251 changed files with 1350 additions and 1180 deletions
.all-contributorsrcREADME.md
abstract-document
README.md
src
main
java
com
iluwatar
test
java
com
iluwatar
abstract-factory/src/test/java/com/iluwatar/abstractfactory
acyclic-visitor/src/test/java/com/iluwatar/acyclicvisitor
adapter
README.md
src
main
java
com
ambassador/src/test/java/com/iluwatar/ambassador
arrange-act-assert/src/test/java/com/iluwatar/arrangeactassert
async-method-invocation/src/main/java/com/iluwatar/async/method/invocation
business-delegate/src/main/java/com/iluwatar/business/delegate
bytecode/src
main
java
com
iluwatar
test
java
com
iluwatar
caching/src/main/java/com/iluwatar/caching
chain
README.md
src
main
java
com
iluwatar
collection-pipeline/src
main
java
com
iluwatar
collectionpipeline
test
java
com
iluwatar
collectionpipeline
command
commander/src/main/java/com/iluwatar/commander
composite
README.md
src
main
java
converter/src
main
java
com
iluwatar
test
java
com
iluwatar
cqrs/src/main/java/com/iluwatar/cqrs
dao
README.md
src
main
test
java
data-bus/src/main/java/com/iluwatar/databus/members
data-mapper/src/main/java/com/iluwatar/datamapper
data-transfer-object
README.md
src
main
java
com
iluwatar
decorator
README.md
src
main
java
com
iluwatar
test
java
com
iluwatar
delegation/src/test/java/com/iluwatar/delegation/simple
dependency-injection
README.md
src
main
test
java
com
iluwatar
dependency
injection
dirty-flag/src/main/java/com/iluwatar/dirtyflag
double-buffer/src/main/java/com/iluwatar/doublebuffer
double-checked-locking/src/test/java/com/iluwatar/doublechecked/locking
double-dispatch/src/main/java/com/iluwatar/doubledispatch
event-aggregator/src
main
java
com
test
java
com
iluwatar
event
event-asynchronous/src/main/java/com/iluwatar/event/asynchronous
event-driven-architecture/src/main/java/com/iluwatar/eda
event-queue/src/main/java/com/iluwatar/event/queue
extension-objects/src/main/java/concreteextensions
facade
README.md
src
test
java
factory-method/src/main/java/com/iluwatar/factory/method
feature-toggle/src/main/java/com/iluwatar/featuretoggle
fluentinterface/src/main/java/com/iluwatar/fluentinterface
app
fluentiterable
flux/src/main/java/com/iluwatar/flux
flyweight/src/main/java/com/iluwatar/flyweight
front-controller/src/test/java/com/iluwatar/front/controller/utils
half-sync-half-async/src/main/java/com/iluwatar/halfsynchalfasync
hexagonal/src
main
test
java
com
iluwatar
hexagonal
intercepting-filter/src/main/java/com/iluwatar/intercepting/filter
interpreter/src/main/java/com/iluwatar/interpreter
iterator
layers
README.md
src
main
java
test
java
com
iluwatar
lazy-loading/src/main/java/com/iluwatar/lazy/loading
leader-followers/src/main/java/com.iluwatar.leaderfollowers
master-worker-pattern/src/main/java/com/iluwatar/masterworker/system/systemmaster
mediator/src
main
java
com
iluwatar
mediator
test
java
com
iluwatar
memento
README.md
src
main
java
com
iluwatar
model-view-controller/src
main
test
java
com
iluwatar
model
view
model-view-presenter/src/main/java/com/iluwatar/model/view/presenter
monad/src/main/java/com/iluwatar/monad
multiton
null-object
README.md
src
main
java
com
iluwatar
nullobject
test
java
com
iluwatar
nullobject
object-mother/src/main/java/com/iluwatar/objectmother
object-pool
README.md
src
main
java
com
observer
README.md
src
main
java
com
iluwatar
observer
test
java
com
iluwatar
page-object
src
test-automation
partial-response/src/main/java/com/iluwatar/partialresponse
poison-pill
README.md
src
main
java
com
iluwatar
test
java
com
iluwatar
private-class-data/src
main
java
com
iluwatar
test
java
com
iluwatar
privateclassdata
producer-consumer/src/main/java/com/iluwatar/producer/consumer
prototype/src/main/java/com/iluwatar/prototype
proxy/src/test/java/com/iluwatar/proxy/utils
reactor/src/main/java/com/iluwatar/reactor
reader-writer-lock/src
main
java
test
java
com
iluwatar
reader
writer
repository
README.md
src
main
java
com
iluwatar
test
resource-acquisition-is-initialization/src/test/java/com/iluwatar/resource/acquisition/is/initialization
role-object/src/main/java/com/iluwatar/roleobject
saga/src
semaphore/src/main/java/com/iluwatar/semaphore
servant/src/main/java/com/iluwatar/servant
serverless/src
main
java
com
iluwatar
test
java
com
iluwatar
service-layer
README.md
src
main
java
com
iluwatar
servicelayer
service-locator/src/main/java/com/iluwatar/servicelocator
sharding/src/main/java/com/iluwatar/sharding
singleton
specification
state
README.md
src
main
test
java
com
iluwatar
step-builder/src/main/java/com/iluwatar/stepbuilder
strategy/src/test/java/com/iluwatar/strategy
template-method/src/test/java/com/iluwatar/templatemethod
throttling
README.md
src
main
java
com
iluwatar
test
java
com
iluwatar
tls/src
tolerant-reader
README.md
src
main
java
com
iluwatar
tolerantreader
twin/src/test/java/com/iluwatar/twin
typeobjectpattern/src/main/java/com/iluwatar/typeobject
unit-of-work
README.md
src
main
java
com
iluwatar
update-method/src/main/java/com/iluwatar/updatemethod
value-object/src/main/java/com/iluwatar/value/object
visitor
README.md
src
main
java
com
iluwatar
visitor
test
java
com
iluwatar

@ -1038,6 +1038,24 @@
"contributions": [ "contributions": [
"translation" "translation"
] ]
},
{
"login": "charlesfinley",
"name": "Matt Dolan",
"avatar_url": "https://avatars1.githubusercontent.com/u/6307904?v=4",
"profile": "https://github.com/charlesfinley",
"contributions": [
"code"
]
},
{
"login": "MananS77",
"name": "Manan",
"avatar_url": "https://avatars3.githubusercontent.com/u/21033516?v=4",
"profile": "https://github.com/MananS77",
"contributions": [
"review"
]
} }
], ],
"contributorsPerLine": 4, "contributorsPerLine": 4,

@ -9,7 +9,7 @@
[![Join the chat at https://gitter.im/iluwatar/java-design-patterns](https://badges.gitter.im/Join%20Chat.svg)](https://gitter.im/iluwatar/java-design-patterns?utm_source=badge&utm_medium=badge&utm_campaign=pr-badge&utm_content=badge) [![Join the chat at https://gitter.im/iluwatar/java-design-patterns](https://badges.gitter.im/Join%20Chat.svg)](https://gitter.im/iluwatar/java-design-patterns?utm_source=badge&utm_medium=badge&utm_campaign=pr-badge&utm_content=badge)
[![Sonarcloud Status](https://sonarcloud.io/api/project_badges/measure?project=iluwatar_java-design-patterns&metric=alert_status)](https://sonarcloud.io/dashboard?id=iluwatar_java-design-patterns) [![Sonarcloud Status](https://sonarcloud.io/api/project_badges/measure?project=iluwatar_java-design-patterns&metric=alert_status)](https://sonarcloud.io/dashboard?id=iluwatar_java-design-patterns)
<!-- ALL-CONTRIBUTORS-BADGE:START - Do not remove or modify this section --> <!-- ALL-CONTRIBUTORS-BADGE:START - Do not remove or modify this section -->
[![All Contributors](https://img.shields.io/badge/all_contributors-114-orange.svg?style=flat-square)](#contributors-) [![All Contributors](https://img.shields.io/badge/all_contributors-116-orange.svg?style=flat-square)](#contributors-)
<!-- ALL-CONTRIBUTORS-BADGE:END --> <!-- ALL-CONTRIBUTORS-BADGE:END -->
# Introduction # Introduction
@ -239,6 +239,8 @@ This project is licensed under the terms of the MIT license.
<tr> <tr>
<td align="center"><a href="https://webpro.nl"><img src="https://avatars1.githubusercontent.com/u/456426?v=4" width="100px;" alt=""/><br /><sub><b>Lars Kappert</b></sub></a><br /><a href="#content-webpro" title="Content">🖋</a></td> <td align="center"><a href="https://webpro.nl"><img src="https://avatars1.githubusercontent.com/u/456426?v=4" width="100px;" alt=""/><br /><sub><b>Lars Kappert</b></sub></a><br /><a href="#content-webpro" title="Content">🖋</a></td>
<td align="center"><a href="https://xiaod.info"><img src="https://avatars2.githubusercontent.com/u/21277644?v=4" width="100px;" alt=""/><br /><sub><b>Mike Liu</b></sub></a><br /><a href="#translation-xiaod-dev" title="Translation">🌍</a></td> <td align="center"><a href="https://xiaod.info"><img src="https://avatars2.githubusercontent.com/u/21277644?v=4" width="100px;" alt=""/><br /><sub><b>Mike Liu</b></sub></a><br /><a href="#translation-xiaod-dev" title="Translation">🌍</a></td>
<td align="center"><a href="https://github.com/charlesfinley"><img src="https://avatars1.githubusercontent.com/u/6307904?v=4" width="100px;" alt=""/><br /><sub><b>Matt Dolan</b></sub></a><br /><a href="https://github.com/iluwatar/java-design-patterns/commits?author=charlesfinley" title="Code">💻</a></td>
<td align="center"><a href="https://github.com/MananS77"><img src="https://avatars3.githubusercontent.com/u/21033516?v=4" width="100px;" alt=""/><br /><sub><b>Manan</b></sub></a><br /><a href="https://github.com/iluwatar/java-design-patterns/pulls?q=is%3Apr+reviewed-by%3AMananS77" title="Reviewed Pull Requests">👀</a></td>
</tr> </tr>
</table> </table>

@ -9,21 +9,182 @@ tags:
--- ---
## Intent ## Intent
Achieve flexibility of untyped languages and keep the type-safety
Use dynamic properties and achieve flexibility of untyped languages while keeping type-safety.
## Explanation
The Abstract Document pattern enables handling additional, non-static properties. This pattern
uses concept of traits to enable type safety and separate properties of different classes into
set of interfaces.
Real world example
> Consider a car that consists of multiple parts. However we don't know if the specific car really has all the parts, or just some of them. Our cars are dynamic and extremely flexible.
In plain words
> Abstract Document pattern allows attaching properties to objects without them knowing about it.
Wikipedia says
> An object-oriented structural design pattern for organizing objects in loosely typed key-value stores and exposing
the data using typed views. The purpose of the pattern is to achieve a high degree of flexibility between components
in a strongly typed language where new properties can be added to the object-tree on the fly, without losing the
support of type-safety. The pattern makes use of traits to separate different properties of a class into different
interfaces.
**Programmatic Example**
Let's first define the base classes `Document` and `AbstractDocument`. They basically make the object hold a property
map and any amount of child objects.
```java
public interface Document {
Void put(String key, Object value);
Object get(String key);
<T> Stream<T> children(String key, Function<Map<String, Object>, T> constructor);
}
public abstract class AbstractDocument implements Document {
private final Map<String, Object> properties;
protected AbstractDocument(Map<String, Object> properties) {
Objects.requireNonNull(properties, "properties map is required");
this.properties = properties;
}
@Override
public Void put(String key, Object value) {
properties.put(key, value);
return null;
}
@Override
public Object get(String key) {
return properties.get(key);
}
@Override
public <T> Stream<T> children(String key, Function<Map<String, Object>, T> constructor) {
return Stream.ofNullable(get(key))
.filter(Objects::nonNull)
.map(el -> (List<Map<String, Object>>) el)
.findAny()
.stream()
.flatMap(Collection::stream)
.map(constructor);
}
...
}
```
Next we define an enum `Property` and a set of interfaces for type, price, model and parts. This allows us to create
static looking interface to our `Car` class.
```java
public enum Property {
PARTS, TYPE, PRICE, MODEL
}
public interface HasType extends Document {
default Optional<String> getType() {
return Optional.ofNullable((String) get(Property.TYPE.toString()));
}
}
public interface HasPrice extends Document {
default Optional<Number> getPrice() {
return Optional.ofNullable((Number) get(Property.PRICE.toString()));
}
}
public interface HasModel extends Document {
default Optional<String> getModel() {
return Optional.ofNullable((String) get(Property.MODEL.toString()));
}
}
public interface HasParts extends Document {
default Stream<Part> getParts() {
return children(Property.PARTS.toString(), Part::new);
}
}
```
Now we are ready to introduce the `Car`.
```java
public class Car extends AbstractDocument implements HasModel, HasPrice, HasParts {
public Car(Map<String, Object> properties) {
super(properties);
}
}
```
And finally here's how we construct and use the `Car` in a full example.
```java
LOGGER.info("Constructing parts and car");
var wheelProperties = Map.of(
Property.TYPE.toString(), "wheel",
Property.MODEL.toString(), "15C",
Property.PRICE.toString(), 100L);
var doorProperties = Map.of(
Property.TYPE.toString(), "door",
Property.MODEL.toString(), "Lambo",
Property.PRICE.toString(), 300L);
var carProperties = Map.of(
Property.MODEL.toString(), "300SL",
Property.PRICE.toString(), 10000L,
Property.PARTS.toString(), List.of(wheelProperties, doorProperties));
var car = new Car(carProperties);
LOGGER.info("Here is our car:");
LOGGER.info("-> model: {}", car.getModel().orElseThrow());
LOGGER.info("-> price: {}", car.getPrice().orElseThrow());
LOGGER.info("-> parts: ");
car.getParts().forEach(p -> LOGGER.info("\t{}/{}/{}",
p.getType().orElse(null),
p.getModel().orElse(null),
p.getPrice().orElse(null))
);
// Constructing parts and car
// Here is our car:
// model: 300SL
// price: 10000
// parts:
// wheel/15C/100
// door/Lambo/300
```
## Class diagram ## Class diagram
![alt text](./etc/abstract-document.png "Abstract Document Traits and Domain") ![alt text](./etc/abstract-document.png "Abstract Document Traits and Domain")
## Applicability ## Applicability
Use the Abstract Document Pattern when Use the Abstract Document Pattern when
* there is a need to add new properties on the fly * There is a need to add new properties on the fly
* you want a flexible way to organize domain in tree like structure * You want a flexible way to organize domain in tree like structure
* you want more loosely coupled system * You want more loosely coupled system
## Credits ## Credits
* [Wikipedia: Abstract Document Pattern](https://en.wikipedia.org/wiki/Abstract_Document_Pattern) * [Wikipedia: Abstract Document Pattern](https://en.wikipedia.org/wiki/Abstract_Document_Pattern)
* [Martin Fowler: Dealing with properties](http://martinfowler.com/apsupp/properties.pdf) * [Martin Fowler: Dealing with properties](http://martinfowler.com/apsupp/properties.pdf)
* [Pattern-Oriented Software Architecture Volume 4: A Pattern Language for Distributed Computing (v. 4)](https://www.amazon.com/gp/product/0470059028/ref=as_li_qf_asin_il_tl?ie=UTF8&tag=javadesignpat-20&creative=9325&linkCode=as2&creativeASIN=0470059028&linkId=e3aacaea7017258acf184f9f3283b492)

@ -32,7 +32,6 @@ import java.util.stream.Stream;
*/ */
public interface HasParts extends Document { public interface HasParts extends Document {
default Stream<Part> getParts() { default Stream<Part> getParts() {
return children(Property.PARTS.toString(), Part::new); return children(Property.PARTS.toString(), Part::new);
} }

@ -32,7 +32,6 @@ import java.util.Optional;
*/ */
public interface HasPrice extends Document { public interface HasPrice extends Document {
default Optional<Number> getPrice() { default Optional<Number> getPrice() {
return Optional.ofNullable((Number) get(Property.PRICE.toString())); return Optional.ofNullable((Number) get(Property.PRICE.toString()));
} }

@ -32,7 +32,6 @@ import java.util.Optional;
*/ */
public interface HasType extends Document { public interface HasType extends Document {
default Optional<String> getType() { default Optional<String> getType() {
return Optional.ofNullable((String) get(Property.TYPE.toString())); return Optional.ofNullable((String) get(Property.TYPE.toString()));
} }

@ -47,7 +47,7 @@ public class AbstractDocumentTest {
} }
} }
private DocumentImplementation document = new DocumentImplementation(new HashMap<>()); private final DocumentImplementation document = new DocumentImplementation(new HashMap<>());
@Test @Test
public void shouldPutAndGetValue() { public void shouldPutAndGetValue() {

@ -36,7 +36,7 @@ import org.junit.jupiter.api.Test;
*/ */
public class AbstractFactoryTest { public class AbstractFactoryTest {
private App app = new App(); private final App app = new App();
private KingdomFactory elfFactory; private KingdomFactory elfFactory;
private KingdomFactory orcFactory; private KingdomFactory orcFactory;

@ -37,7 +37,7 @@ import uk.org.lidalia.slf4jtest.TestLoggerFactory;
*/ */
public class ConfigureForDosVisitorTest { public class ConfigureForDosVisitorTest {
private TestLogger logger = TestLoggerFactory.getTestLogger(ConfigureForDosVisitor.class); private final TestLogger logger = TestLoggerFactory.getTestLogger(ConfigureForDosVisitor.class);
@Test @Test
public void testVisitForZoom() { public void testVisitForZoom() {

@ -56,7 +56,7 @@ And captain expects an implementation of `RowingBoat` interface to be able to mo
```java ```java
public class Captain { public class Captain {
private RowingBoat rowingBoat; private final RowingBoat rowingBoat;
// default constructor and setter for rowingBoat // default constructor and setter for rowingBoat
public Captain(RowingBoat rowingBoat) { public Captain(RowingBoat rowingBoat) {
this.rowingBoat = rowingBoat; this.rowingBoat = rowingBoat;
@ -75,7 +75,7 @@ public class FishingBoatAdapter implements RowingBoat {
private static final Logger LOGGER = LoggerFactory.getLogger(FishingBoatAdapter.class); private static final Logger LOGGER = LoggerFactory.getLogger(FishingBoatAdapter.class);
private FishingBoat boat; private final FishingBoat boat;
public FishingBoatAdapter() { public FishingBoatAdapter() {
boat = new FishingBoat(); boat = new FishingBoat();

@ -29,7 +29,7 @@ package com.iluwatar.adapter;
*/ */
public class FishingBoatAdapter implements RowingBoat { public class FishingBoatAdapter implements RowingBoat {
private FishingBoat boat; private final FishingBoat boat;
public FishingBoatAdapter() { public FishingBoatAdapter() {
boat = new FishingBoat(); boat = new FishingBoat();

@ -48,7 +48,7 @@ class RemoteServiceTest {
} }
private static class StaticRandomProvider implements RandomProvider { private static class StaticRandomProvider implements RandomProvider {
private double value; private final double value;
StaticRandomProvider(double value) { StaticRandomProvider(double value) {
this.value = value; this.value = value;

@ -60,7 +60,7 @@ public class CashAAATest {
//Act //Act
cash.plus(4); cash.plus(4);
//Assert //Assert
assertEquals(cash.count(), 7); assertEquals(7, cash.count());
} }
@Test @Test
@ -71,7 +71,7 @@ public class CashAAATest {
var result = cash.minus(5); var result = cash.minus(5);
//Assert //Assert
assertTrue(result); assertTrue(result);
assertEquals(cash.count(), 3); assertEquals(3, cash.count());
} }
@Test @Test
@ -82,7 +82,7 @@ public class CashAAATest {
var result = cash.minus(6); var result = cash.minus(6);
//Assert //Assert
assertFalse(result); assertFalse(result);
assertEquals(cash.count(), 1); assertEquals(1, cash.count());
} }
@Test @Test
@ -94,6 +94,6 @@ public class CashAAATest {
var result = cash.minus(3); var result = cash.minus(3);
//Assert //Assert
assertTrue(result); assertTrue(result);
assertEquals(cash.count(), 8); assertEquals(8, cash.count());
} }
} }

@ -44,16 +44,16 @@ public class CashAntiAAATest {
var cash = new Cash(3); var cash = new Cash(3);
//test plus //test plus
cash.plus(4); cash.plus(4);
assertEquals(cash.count(), 7); assertEquals(7, cash.count());
//test minus //test minus
cash = new Cash(8); cash = new Cash(8);
assertTrue(cash.minus(5)); assertTrue(cash.minus(5));
assertEquals(cash.count(), 3); assertEquals(3, cash.count());
assertFalse(cash.minus(6)); assertFalse(cash.minus(6));
assertEquals(cash.count(), 3); assertEquals(3, cash.count());
//test update //test update
cash.plus(5); cash.plus(5);
assertTrue(cash.minus(5)); assertTrue(cash.minus(5));
assertEquals(cash.count(), 3); assertEquals(3, cash.count());
} }
} }

@ -100,7 +100,7 @@ public class ThreadAsyncExecutor implements AsyncExecutor {
void setValue(T value) { void setValue(T value) {
this.value = value; this.value = value;
this.state = COMPLETED; this.state = COMPLETED;
this.callback.ifPresent(ac -> ac.onComplete(value, Optional.<Exception>empty())); this.callback.ifPresent(ac -> ac.onComplete(value, Optional.empty()));
synchronized (lock) { synchronized (lock) {
lock.notifyAll(); lock.notifyAll();
} }

@ -28,7 +28,7 @@ package com.iluwatar.business.delegate;
*/ */
public class Client { public class Client {
private BusinessDelegate businessDelegate; private final BusinessDelegate businessDelegate;
public Client(BusinessDelegate businessDelegate) { public Client(BusinessDelegate businessDelegate) {
this.businessDelegate = businessDelegate; this.businessDelegate = businessDelegate;

@ -28,5 +28,5 @@ package com.iluwatar.business.delegate;
*/ */
public enum ServiceType { public enum ServiceType {
EJB, JMS; EJB, JMS
} }

@ -30,9 +30,9 @@ import java.util.Stack;
*/ */
public class VirtualMachine { public class VirtualMachine {
private Stack<Integer> stack = new Stack<>(); private final Stack<Integer> stack = new Stack<>();
private Wizard[] wizards = new Wizard[2]; private final Wizard[] wizards = new Wizard[2];
/** /**
* Constructor. * Constructor.

@ -104,7 +104,7 @@ public class VirtualMachineTest {
bytecode[2] = LITERAL.getIntValue(); bytecode[2] = LITERAL.getIntValue();
bytecode[3] = 50; // health amount bytecode[3] = 50; // health amount
bytecode[4] = SET_HEALTH.getIntValue(); bytecode[4] = SET_HEALTH.getIntValue();
bytecode[5] = LITERAL.getIntValue();; bytecode[5] = LITERAL.getIntValue();
bytecode[6] = wizardNumber; bytecode[6] = wizardNumber;
bytecode[7] = GET_HEALTH.getIntValue(); bytecode[7] = GET_HEALTH.getIntValue();

@ -29,7 +29,7 @@ package com.iluwatar.caching;
public enum CachingPolicy { public enum CachingPolicy {
THROUGH("through"), AROUND("around"), BEHIND("behind"), ASIDE("aside"); THROUGH("through"), AROUND("around"), BEHIND("behind"), ASIDE("aside");
private String policy; private final String policy;
CachingPolicy(String policy) { CachingPolicy(String policy) {
this.policy = policy; this.policy = policy;

@ -65,7 +65,7 @@ Then the request handler hierarchy
```java ```java
public abstract class RequestHandler { public abstract class RequestHandler {
private static final Logger LOGGER = LoggerFactory.getLogger(RequestHandler.class); private static final Logger LOGGER = LoggerFactory.getLogger(RequestHandler.class);
private RequestHandler next; private final RequestHandler next;
public RequestHandler(RequestHandler next) { public RequestHandler(RequestHandler next) {
this.next = next; this.next = next;

@ -33,7 +33,7 @@ public abstract class RequestHandler {
private static final Logger LOGGER = LoggerFactory.getLogger(RequestHandler.class); private static final Logger LOGGER = LoggerFactory.getLogger(RequestHandler.class);
private RequestHandler next; private final RequestHandler next;
public RequestHandler(RequestHandler next) { public RequestHandler(RequestHandler next) {
this.next = next; this.next = next;

@ -87,10 +87,7 @@ public class Car {
} else if (!model.equals(other.model)) { } else if (!model.equals(other.model)) {
return false; return false;
} }
if (year != other.year) { return year == other.year;
return false;
}
return true;
} }
public String getMake() { public String getMake() {

@ -29,7 +29,7 @@ import java.util.List;
* A Person class that has the list of cars that the person owns and use. * A Person class that has the list of cars that the person owns and use.
*/ */
public class Person { public class Person {
private List<Car> cars; private final List<Car> cars;
/** /**
* Constructor to create an instance of person. * Constructor to create an instance of person.

@ -37,7 +37,7 @@ import org.slf4j.LoggerFactory;
public class AppTest { public class AppTest {
private static final Logger LOGGER = LoggerFactory.getLogger(AppTest.class); private static final Logger LOGGER = LoggerFactory.getLogger(AppTest.class);
private List<Car> cars = CarFactory.createCars(); private final List<Car> cars = CarFactory.createCars();
@Test @Test
public void testGetModelsAfter2000UsingFor() { public void testGetModelsAfter2000UsingFor() {

@ -36,8 +36,8 @@ public class Wizard {
private static final Logger LOGGER = LoggerFactory.getLogger(Wizard.class); private static final Logger LOGGER = LoggerFactory.getLogger(Wizard.class);
private Deque<Command> undoStack = new LinkedList<>(); private final Deque<Command> undoStack = new LinkedList<>();
private Deque<Command> redoStack = new LinkedList<>(); private final Deque<Command> redoStack = new LinkedList<>();
public Wizard() {} public Wizard() {}

@ -30,7 +30,7 @@ public enum Size {
SMALL("small"), NORMAL("normal"); SMALL("small"), NORMAL("normal");
private String title; private final String title;
Size(String title) { Size(String title) {
this.title = title; this.title = title;

@ -30,7 +30,7 @@ public enum Visibility {
VISIBLE("visible"), INVISIBLE("invisible"); VISIBLE("visible"), INVISIBLE("invisible");
private String title; private final String title;
Visibility(String title) { Visibility(String title) {
this.title = title; this.title = title;

@ -35,8 +35,8 @@ public class Wizard {
private static final Logger LOGGER = LoggerFactory.getLogger(Wizard.class); private static final Logger LOGGER = LoggerFactory.getLogger(Wizard.class);
private Deque<Command> undoStack = new LinkedList<>(); private final Deque<Command> undoStack = new LinkedList<>();
private Deque<Command> redoStack = new LinkedList<>(); private final Deque<Command> redoStack = new LinkedList<>();
public Wizard() { public Wizard() {
// comment to ignore sonar issue: LEVEL critical // comment to ignore sonar issue: LEVEL critical

@ -33,7 +33,7 @@ import java.util.Hashtable;
*/ */
public class EmployeeDatabase extends Database<Order> { public class EmployeeDatabase extends Database<Order> {
private Hashtable<String, Order> data; private final Hashtable<String, Order> data;
public EmployeeDatabase() { public EmployeeDatabase() {
this.data = new Hashtable<>(); this.data = new Hashtable<>();

@ -33,7 +33,7 @@ import java.util.Hashtable;
*/ */
public class MessagingDatabase extends Database<MessageRequest> { public class MessagingDatabase extends Database<MessageRequest> {
private Hashtable<String, MessageRequest> data; private final Hashtable<String, MessageRequest> data;
public MessagingDatabase() { public MessagingDatabase() {
this.data = new Hashtable<>(); this.data = new Hashtable<>();

@ -34,7 +34,7 @@ import java.util.Hashtable;
public class PaymentDatabase extends Database<PaymentRequest> { public class PaymentDatabase extends Database<PaymentRequest> {
private Hashtable<String, PaymentRequest> data; private final Hashtable<String, PaymentRequest> data;
public PaymentDatabase() { public PaymentDatabase() {
this.data = new Hashtable<>(); this.data = new Hashtable<>();

@ -35,7 +35,7 @@ import java.util.List;
public class QueueDatabase extends Database<QueueTask> { public class QueueDatabase extends Database<QueueTask> {
private Queue<QueueTask> data; private final Queue<QueueTask> data;
public List<Exception> exceptionsList; public List<Exception> exceptionsList;
public QueueDatabase(Exception... exc) { public QueueDatabase(Exception... exc) {

@ -34,7 +34,7 @@ import java.util.Hashtable;
public class ShippingDatabase extends Database<ShippingRequest> { public class ShippingDatabase extends Database<ShippingRequest> {
private Hashtable<String, ShippingRequest> data; private final Hashtable<String, ShippingRequest> data;
public ShippingDatabase() { public ShippingDatabase() {
this.data = new Hashtable<>(); this.data = new Hashtable<>();

@ -34,7 +34,7 @@ Taking our sentence example from above. Here we have the base class and differen
```java ```java
public abstract class LetterComposite { public abstract class LetterComposite {
private List<LetterComposite> children = new ArrayList<>(); private final List<LetterComposite> children = new ArrayList<>();
public void add(LetterComposite letter) { public void add(LetterComposite letter) {
children.add(letter); children.add(letter);
@ -59,7 +59,7 @@ public abstract class LetterComposite {
public class Letter extends LetterComposite { public class Letter extends LetterComposite {
private char character; private final char character;
public Letter(char c) { public Letter(char c) {
this.character = c; this.character = c;

@ -28,7 +28,7 @@ package com.iluwatar.composite;
*/ */
public class Letter extends LetterComposite { public class Letter extends LetterComposite {
private char character; private final char character;
public Letter(char c) { public Letter(char c) {
this.character = c; this.character = c;

@ -31,7 +31,7 @@ import java.util.List;
*/ */
public abstract class LetterComposite { public abstract class LetterComposite {
private List<LetterComposite> children = new ArrayList<>(); private final List<LetterComposite> children = new ArrayList<>();
public void add(LetterComposite letter) { public void add(LetterComposite letter) {
children.add(letter); children.add(letter);

@ -29,10 +29,10 @@ import java.util.Objects;
* User class. * User class.
*/ */
public class User { public class User {
private String firstName; private final String firstName;
private String lastName; private final String lastName;
private boolean isActive; private final boolean isActive;
private String userId; private final String userId;
/** /**
* Constructor. * Constructor.

@ -30,10 +30,10 @@ import java.util.Objects;
*/ */
public class UserDto { public class UserDto {
private String firstName; private final String firstName;
private String lastName; private final String lastName;
private boolean isActive; private final boolean isActive;
private String email; private final String email;
/** /**
* Constructor. * Constructor.

@ -34,7 +34,7 @@ import org.junit.jupiter.api.Test;
*/ */
public class ConverterTest { public class ConverterTest {
private UserConverter userConverter = new UserConverter(); private final UserConverter userConverter = new UserConverter();
/** /**
* Tests whether a converter created of opposite functions holds equality as a bijection. * Tests whether a converter created of opposite functions holds equality as a bijection.

@ -34,7 +34,7 @@ import org.hibernate.SessionFactory;
*/ */
public class CommandServiceImpl implements ICommandService { public class CommandServiceImpl implements ICommandService {
private SessionFactory sessionFactory = HibernateUtil.getSessionFactory(); private final SessionFactory sessionFactory = HibernateUtil.getSessionFactory();
private Author getAuthorByUsername(String username) { private Author getAuthorByUsername(String username) {
Author author; Author author;

@ -38,7 +38,7 @@ import org.hibernate.transform.Transformers;
*/ */
public class QueryServiceImpl implements IQueryService { public class QueryServiceImpl implements IQueryService {
private SessionFactory sessionFactory = HibernateUtil.getSessionFactory(); private final SessionFactory sessionFactory = HibernateUtil.getSessionFactory();
@Override @Override
public Author getAuthorByUsername(String username) { public Author getAuthorByUsername(String username) {

@ -112,7 +112,7 @@ public interface CustomerDao {
public class InMemoryCustomerDao implements CustomerDao { public class InMemoryCustomerDao implements CustomerDao {
private Map<Integer, Customer> idToCustomer = new HashMap<>(); private final Map<Integer, Customer> idToCustomer = new HashMap<>();
@Override @Override
public Stream<Customer> getAll() { public Stream<Customer> getAll() {

@ -44,7 +44,7 @@ import org.slf4j.LoggerFactory;
*/ */
public class App { public class App {
private static final String DB_URL = "jdbc:h2:~/dao"; private static final String DB_URL = "jdbc:h2:~/dao";
private static Logger log = LoggerFactory.getLogger(App.class); private static final Logger log = LoggerFactory.getLogger(App.class);
private static final String ALL_CUSTOMERS = "customerDao.getAllCustomers(): "; private static final String ALL_CUSTOMERS = "customerDao.getAllCustomers(): ";
/** /**

@ -36,7 +36,7 @@ import java.util.stream.Stream;
*/ */
public class InMemoryCustomerDao implements CustomerDao { public class InMemoryCustomerDao implements CustomerDao {
private Map<Integer, Customer> idToCustomer = new HashMap<>(); private final Map<Integer, Customer> idToCustomer = new HashMap<>();
/** /**
* An eagerly evaluated stream of customers stored in memory. * An eagerly evaluated stream of customers stored in memory.

@ -50,7 +50,7 @@ public class DbCustomerDaoTest {
private static final String DB_URL = "jdbc:h2:~/dao"; private static final String DB_URL = "jdbc:h2:~/dao";
private DbCustomerDao dao; private DbCustomerDao dao;
private Customer existingCustomer = new Customer(1, "Freddy", "Krueger"); private final Customer existingCustomer = new Customer(1, "Freddy", "Krueger");
/** /**
* Creates customers schema. * Creates customers schema.

@ -41,7 +41,7 @@ public class MessageCollectorMember implements Member {
private final String name; private final String name;
private List<String> messages = new ArrayList<>(); private final List<String> messages = new ArrayList<>();
public MessageCollectorMember(String name) { public MessageCollectorMember(String name) {
this.name = name; this.name = name;

@ -38,7 +38,7 @@ import org.slf4j.LoggerFactory;
*/ */
public final class App { public final class App {
private static Logger log = LoggerFactory.getLogger(App.class); private static final Logger log = LoggerFactory.getLogger(App.class);
private static final String STUDENT_STRING = "App.main(), student : "; private static final String STUDENT_STRING = "App.main(), student : ";

@ -33,7 +33,7 @@ import java.util.Optional;
public final class StudentDataMapperImpl implements StudentDataMapper { public final class StudentDataMapperImpl implements StudentDataMapper {
/* Note: Normally this would be in the form of an actual database */ /* Note: Normally this would be in the form of an actual database */
private List<Student> students = new ArrayList<>(); private final List<Student> students = new ArrayList<>();
@Override @Override
public Optional<Student> find(int studentId) { public Optional<Student> find(int studentId) {

@ -64,7 +64,7 @@ Customer resource class acts as the server for customer information.
```java ```java
public class CustomerResource { public class CustomerResource {
private List<CustomerDto> customers; private final List<CustomerDto> customers;
public CustomerResource(List<CustomerDto> customers) { public CustomerResource(List<CustomerDto> customers) {
this.customers = customers; this.customers = customers;

@ -30,7 +30,7 @@ import java.util.List;
* has all customer details. * has all customer details.
*/ */
public class CustomerResource { public class CustomerResource {
private List<CustomerDto> customers; private final List<CustomerDto> customers;
/** /**
* Initialise resource with existing customers. * Initialise resource with existing customers.

@ -70,7 +70,7 @@ public class ClubbedTroll implements Troll {
private static final Logger LOGGER = LoggerFactory.getLogger(ClubbedTroll.class); private static final Logger LOGGER = LoggerFactory.getLogger(ClubbedTroll.class);
private Troll decorated; private final Troll decorated;
public ClubbedTroll(Troll decorated) { public ClubbedTroll(Troll decorated) {
this.decorated = decorated; this.decorated = decorated;

@ -33,7 +33,7 @@ public class ClubbedTroll implements Troll {
private static final Logger LOGGER = LoggerFactory.getLogger(ClubbedTroll.class); private static final Logger LOGGER = LoggerFactory.getLogger(ClubbedTroll.class);
private Troll decorated; private final Troll decorated;
public ClubbedTroll(Troll decorated) { public ClubbedTroll(Troll decorated) {
this.decorated = decorated; this.decorated = decorated;

@ -68,7 +68,7 @@ public class SimpleTrollTest {
private class InMemoryAppender extends AppenderBase<ILoggingEvent> { private class InMemoryAppender extends AppenderBase<ILoggingEvent> {
private List<ILoggingEvent> log = new LinkedList<>(); private final List<ILoggingEvent> log = new LinkedList<>();
public InMemoryAppender(Class clazz) { public InMemoryAppender(Class clazz) {
((Logger) LoggerFactory.getLogger(clazz)).addAppender(this); ((Logger) LoggerFactory.getLogger(clazz)).addAppender(this);

@ -86,7 +86,7 @@ public class DelegateTest {
*/ */
private class InMemoryAppender extends AppenderBase<ILoggingEvent> { private class InMemoryAppender extends AppenderBase<ILoggingEvent> {
private List<ILoggingEvent> log = new LinkedList<>(); private final List<ILoggingEvent> log = new LinkedList<>();
public InMemoryAppender() { public InMemoryAppender() {
((Logger) LoggerFactory.getLogger("root")).addAppender(this); ((Logger) LoggerFactory.getLogger("root")).addAppender(this);

@ -62,7 +62,7 @@ public interface Wizard {
public class AdvancedWizard implements Wizard { public class AdvancedWizard implements Wizard {
private Tobacco tobacco; private final Tobacco tobacco;
public AdvancedWizard(Tobacco tobacco) { public AdvancedWizard(Tobacco tobacco) {
this.tobacco = tobacco; this.tobacco = tobacco;

@ -29,7 +29,7 @@ package com.iluwatar.dependency.injection;
*/ */
public class AdvancedWizard implements Wizard { public class AdvancedWizard implements Wizard {
private Tobacco tobacco; private final Tobacco tobacco;
public AdvancedWizard(Tobacco tobacco) { public AdvancedWizard(Tobacco tobacco) {
this.tobacco = tobacco; this.tobacco = tobacco;

@ -31,7 +31,7 @@ import javax.inject.Inject;
*/ */
public class GuiceWizard implements Wizard { public class GuiceWizard implements Wizard {
private Tobacco tobacco; private final Tobacco tobacco;
@Inject @Inject
public GuiceWizard(Tobacco tobacco) { public GuiceWizard(Tobacco tobacco) {

@ -29,7 +29,7 @@ package com.iluwatar.dependency.injection;
*/ */
public class SimpleWizard implements Wizard { public class SimpleWizard implements Wizard {
private OldTobyTobacco tobacco = new OldTobyTobacco(); private final OldTobyTobacco tobacco = new OldTobyTobacco();
public void smoke() { public void smoke() {
tobacco.smoke(this); tobacco.smoke(this);

@ -37,7 +37,7 @@ import java.util.List;
*/ */
public class InMemoryAppender extends AppenderBase<ILoggingEvent> { public class InMemoryAppender extends AppenderBase<ILoggingEvent> {
private List<ILoggingEvent> log = new LinkedList<>(); private final List<ILoggingEvent> log = new LinkedList<>();
public InMemoryAppender(Class clazz) { public InMemoryAppender(Class clazz) {
((Logger) LoggerFactory.getLogger(clazz)).addAppender(this); ((Logger) LoggerFactory.getLogger(clazz)).addAppender(this);

@ -34,7 +34,7 @@ import java.util.List;
public class World { public class World {
private List<String> countries; private List<String> countries;
private DataFetcher df; private final DataFetcher df;
public World() { public World() {
this.countries = new ArrayList<String>(); this.countries = new ArrayList<String>();

@ -33,7 +33,7 @@ public class FrameBuffer implements Buffer {
public static final int WIDTH = 10; public static final int WIDTH = 10;
public static final int HEIGHT = 8; public static final int HEIGHT = 8;
private Pixel[] pixels = new Pixel[WIDTH * HEIGHT]; private final Pixel[] pixels = new Pixel[WIDTH * HEIGHT];
public FrameBuffer() { public FrameBuffer() {
clearAll(); clearAll();

@ -31,7 +31,7 @@ public enum Pixel {
WHITE(0), WHITE(0),
BLACK(1); BLACK(1);
private int color; private final int color;
Pixel(int color) { Pixel(int color) {
this.color = color; this.color = color;

@ -35,7 +35,7 @@ public class Scene {
private static final Logger LOGGER = LoggerFactory.getLogger(Scene.class); private static final Logger LOGGER = LoggerFactory.getLogger(Scene.class);
private Buffer[] frameBuffers; private final Buffer[] frameBuffers;
private int current; private int current;

@ -109,7 +109,7 @@ public class InventoryTest {
private class InMemoryAppender extends AppenderBase<ILoggingEvent> { private class InMemoryAppender extends AppenderBase<ILoggingEvent> {
private List<ILoggingEvent> log = new LinkedList<>(); private final List<ILoggingEvent> log = new LinkedList<>();
public InMemoryAppender(Class clazz) { public InMemoryAppender(Class clazz) {
((Logger) LoggerFactory.getLogger(clazz)).addAppender(this); ((Logger) LoggerFactory.getLogger(clazz)).addAppender(this);

@ -28,10 +28,10 @@ package com.iluwatar.doubledispatch;
*/ */
public class Rectangle { public class Rectangle {
private int left; private final int left;
private int top; private final int top;
private int right; private final int right;
private int bottom; private final int bottom;
/** /**
* Constructor. * Constructor.

@ -31,7 +31,7 @@ public enum Event {
STARK_SIGHTED("Stark sighted"), WARSHIPS_APPROACHING("Warships approaching"), TRAITOR_DETECTED( STARK_SIGHTED("Stark sighted"), WARSHIPS_APPROACHING("Warships approaching"), TRAITOR_DETECTED(
"Traitor detected"); "Traitor detected");
private String description; private final String description;
Event(String description) { Event(String description) {
this.description = description; this.description = description;

@ -31,7 +31,7 @@ import java.util.List;
*/ */
public abstract class EventEmitter { public abstract class EventEmitter {
private List<EventObserver> observers; private final List<EventObserver> observers;
public EventEmitter() { public EventEmitter() {
observers = new LinkedList<>(); observers = new LinkedList<>();

@ -36,7 +36,7 @@ public enum Weekday {
SATURDAY("Saturday"), SATURDAY("Saturday"),
SUNDAY("Sunday"); SUNDAY("Sunday");
private String description; private final String description;
Weekday(String description) { Weekday(String description) {
this.description = description; this.description = description;

@ -74,7 +74,7 @@ public class KingJoffreyTest {
} }
private class InMemoryAppender extends AppenderBase<ILoggingEvent> { private class InMemoryAppender extends AppenderBase<ILoggingEvent> {
private List<ILoggingEvent> log = new LinkedList<>(); private final List<ILoggingEvent> log = new LinkedList<>();
public InMemoryAppender(Class<?> clazz) { public InMemoryAppender(Class<?> clazz) {
((Logger) LoggerFactory.getLogger(clazz)).addAppender(this); ((Logger) LoggerFactory.getLogger(clazz)).addAppender(this);

@ -33,9 +33,9 @@ public class Event implements IEvent, Runnable {
private static final Logger LOGGER = LoggerFactory.getLogger(Event.class); private static final Logger LOGGER = LoggerFactory.getLogger(Event.class);
private int eventId; private final int eventId;
private int eventTime; private final int eventTime;
private boolean isSynchronous; private final boolean isSynchronous;
private Thread thread; private Thread thread;
private boolean isComplete = false; private boolean isComplete = false;
private ThreadCompleteListener eventListener; private ThreadCompleteListener eventListener;

@ -43,8 +43,8 @@ public class EventManager implements ThreadCompleteListener {
public static final int MAX_ID = MAX_RUNNING_EVENTS; public static final int MAX_ID = MAX_RUNNING_EVENTS;
public static final int MAX_EVENT_TIME = 1800; // in seconds / 30 minutes. public static final int MAX_EVENT_TIME = 1800; // in seconds / 30 minutes.
private int currentlyRunningSyncEvent = -1; private int currentlyRunningSyncEvent = -1;
private Random rand; private final Random rand;
private Map<Integer, Event> eventPool; private final Map<Integer, Event> eventPool;
private static final String DOES_NOT_EXIST = " does not exist."; private static final String DOES_NOT_EXIST = " does not exist.";

@ -32,7 +32,7 @@ import com.iluwatar.eda.model.User;
*/ */
public class UserCreatedEvent extends AbstractEvent { public class UserCreatedEvent extends AbstractEvent {
private User user; private final User user;
public UserCreatedEvent(User user) { public UserCreatedEvent(User user) {
this.user = user; this.user = user;

@ -32,7 +32,7 @@ import com.iluwatar.eda.model.User;
*/ */
public class UserUpdatedEvent extends AbstractEvent { public class UserUpdatedEvent extends AbstractEvent {
private User user; private final User user;
public UserUpdatedEvent(User user) { public UserUpdatedEvent(User user) {
this.user = user; this.user = user;

@ -32,7 +32,7 @@ import java.util.Map;
*/ */
public class EventDispatcher { public class EventDispatcher {
private Map<Class<? extends Event>, Handler<? extends Event>> handlers; private final Map<Class<? extends Event>, Handler<? extends Event>> handlers;
public EventDispatcher() { public EventDispatcher() {
handlers = new HashMap<>(); handlers = new HashMap<>();

@ -32,7 +32,7 @@ import com.iluwatar.eda.event.UserUpdatedEvent;
*/ */
public class User { public class User {
private String username; private final String username;
public User(String username) { public User(String username) {
this.username = username; this.username = username;

@ -49,7 +49,7 @@ public class Audio {
private volatile Thread updateThread = null; private volatile Thread updateThread = null;
private PlayMessage[] pendingAudio = new PlayMessage[MAX_PENDING]; private final PlayMessage[] pendingAudio = new PlayMessage[MAX_PENDING];
// Visible only for testing purposes // Visible only for testing purposes
Audio() { Audio() {

@ -35,7 +35,7 @@ public class Commander implements CommanderExtension {
private static final Logger LOGGER = LoggerFactory.getLogger(Commander.class); private static final Logger LOGGER = LoggerFactory.getLogger(Commander.class);
private CommanderUnit unit; private final CommanderUnit unit;
public Commander(CommanderUnit commanderUnit) { public Commander(CommanderUnit commanderUnit) {
this.unit = commanderUnit; this.unit = commanderUnit;

@ -35,7 +35,7 @@ public class Sergeant implements SergeantExtension {
private static final Logger LOGGER = LoggerFactory.getLogger(Sergeant.class); private static final Logger LOGGER = LoggerFactory.getLogger(Sergeant.class);
private SergeantUnit unit; private final SergeantUnit unit;
public Sergeant(SergeantUnit sergeantUnit) { public Sergeant(SergeantUnit sergeantUnit) {
this.unit = sergeantUnit; this.unit = sergeantUnit;

@ -34,7 +34,7 @@ import units.SoldierUnit;
public class Soldier implements SoldierExtension { public class Soldier implements SoldierExtension {
private static final Logger LOGGER = LoggerFactory.getLogger(Soldier.class); private static final Logger LOGGER = LoggerFactory.getLogger(Soldier.class);
private SoldierUnit unit; private final SoldierUnit unit;
public Soldier(SoldierUnit soldierUnit) { public Soldier(SoldierUnit soldierUnit) {
this.unit = soldierUnit; this.unit = soldierUnit;

@ -83,7 +83,7 @@ public abstract class DwarvenMineWorker {
public abstract String name(); public abstract String name();
static enum Action { enum Action {
GO_TO_SLEEP, WAKE_UP, GO_HOME, GO_TO_MINE, WORK GO_TO_SLEEP, WAKE_UP, GO_HOME, GO_TO_MINE, WORK
} }
} }

@ -110,7 +110,7 @@ public class DwarvenGoldmineFacadeTest {
private class InMemoryAppender extends AppenderBase<ILoggingEvent> { private class InMemoryAppender extends AppenderBase<ILoggingEvent> {
private List<ILoggingEvent> log = new LinkedList<>(); private final List<ILoggingEvent> log = new LinkedList<>();
public InMemoryAppender() { public InMemoryAppender() {
((Logger) LoggerFactory.getLogger("root")).addAppender(this); ((Logger) LoggerFactory.getLogger("root")).addAppender(this);

@ -32,7 +32,7 @@ import java.util.Map;
*/ */
public class ElfBlacksmith implements Blacksmith { public class ElfBlacksmith implements Blacksmith {
private static Map<WeaponType, ElfWeapon> ELFARSENAL; private static final Map<WeaponType, ElfWeapon> ELFARSENAL;
static { static {
ELFARSENAL = new HashMap<>(WeaponType.values().length); ELFARSENAL = new HashMap<>(WeaponType.values().length);

@ -28,7 +28,7 @@ package com.iluwatar.factory.method;
*/ */
public class ElfWeapon implements Weapon { public class ElfWeapon implements Weapon {
private WeaponType weaponType; private final WeaponType weaponType;
public ElfWeapon(WeaponType weaponType) { public ElfWeapon(WeaponType weaponType) {
this.weaponType = weaponType; this.weaponType = weaponType;

@ -32,7 +32,7 @@ import java.util.Map;
*/ */
public class OrcBlacksmith implements Blacksmith { public class OrcBlacksmith implements Blacksmith {
private static Map<WeaponType, OrcWeapon> ORCARSENAL; private static final Map<WeaponType, OrcWeapon> ORCARSENAL;
static { static {
ORCARSENAL = new HashMap<>(WeaponType.values().length); ORCARSENAL = new HashMap<>(WeaponType.values().length);

@ -28,7 +28,7 @@ package com.iluwatar.factory.method;
*/ */
public class OrcWeapon implements Weapon { public class OrcWeapon implements Weapon {
private WeaponType weaponType; private final WeaponType weaponType;
public OrcWeapon(WeaponType weaponType) { public OrcWeapon(WeaponType weaponType) {
this.weaponType = weaponType; this.weaponType = weaponType;

@ -30,7 +30,7 @@ public enum WeaponType {
SHORT_SWORD("short sword"), SPEAR("spear"), AXE("axe"), UNDEFINED(""); SHORT_SWORD("short sword"), SPEAR("spear"), AXE("axe"), UNDEFINED("");
private String title; private final String title;
WeaponType(String title) { WeaponType(String title) {
this.title = title; this.title = title;

@ -42,7 +42,7 @@ import java.util.Properties;
*/ */
public class PropertiesFeatureToggleVersion implements Service { public class PropertiesFeatureToggleVersion implements Service {
private boolean isEnhanced; private final boolean isEnhanced;
/** /**
* Creates an instance of {@link PropertiesFeatureToggleVersion} using the passed {@link * Creates an instance of {@link PropertiesFeatureToggleVersion} using the passed {@link

@ -29,7 +29,7 @@ package com.iluwatar.featuretoggle.user;
*/ */
public class User { public class User {
private String name; private final String name;
/** /**
* Default Constructor setting the username. * Default Constructor setting the username.

@ -35,8 +35,8 @@ import java.util.List;
*/ */
public class UserGroup { public class UserGroup {
private static List<User> freeGroup = new ArrayList<>(); private static final List<User> freeGroup = new ArrayList<>();
private static List<User> paidGroup = new ArrayList<>(); private static final List<User> paidGroup = new ArrayList<>();
/** /**

@ -94,7 +94,7 @@ public class App {
.filter(positives()) .filter(positives())
.first(4) .first(4)
.last(2) .last(2)
.map(number -> "String[" + valueOf(number) + "]") .map(number -> "String[" + number + "]")
.asList(); .asList();
prettyPrint("The lazy list contains the last two of the first four positive numbers " prettyPrint("The lazy list contains the last two of the first four positive numbers "
+ "mapped to Strings: ", lastTwoOfFirstFourStringMapped); + "mapped to Strings: ", lastTwoOfFirstFourStringMapped);

@ -198,7 +198,7 @@ public class LazyFluentIterable<E> implements FluentIterable<E> {
@Override @Override
public Iterator<T> iterator() { public Iterator<T> iterator() {
return new DecoratingIterator<T>(null) { return new DecoratingIterator<T>(null) {
Iterator<E> oldTypeIterator = iterable.iterator(); final Iterator<E> oldTypeIterator = iterable.iterator();
@Override @Override
public T computeNext() { public T computeNext() {

@ -28,7 +28,7 @@ package com.iluwatar.flux.action;
*/ */
public abstract class Action { public abstract class Action {
private ActionType type; private final ActionType type;
public Action(ActionType type) { public Action(ActionType type) {
this.type = type; this.type = type;

@ -28,6 +28,6 @@ package com.iluwatar.flux.action;
*/ */
public enum ActionType { public enum ActionType {
MENU_ITEM_SELECTED, CONTENT_CHANGED; MENU_ITEM_SELECTED, CONTENT_CHANGED
} }

@ -31,7 +31,7 @@ public enum Content {
PRODUCTS("Products - This page lists the company's products."), COMPANY( PRODUCTS("Products - This page lists the company's products."), COMPANY(
"Company - This page displays information about the company."); "Company - This page displays information about the company.");
private String title; private final String title;
Content(String title) { Content(String title) {
this.title = title; this.title = title;

@ -28,7 +28,7 @@ package com.iluwatar.flux.action;
*/ */
public class ContentAction extends Action { public class ContentAction extends Action {
private Content content; private final Content content;
public ContentAction(Content content) { public ContentAction(Content content) {
super(ActionType.CONTENT_CHANGED); super(ActionType.CONTENT_CHANGED);

@ -29,7 +29,7 @@ package com.iluwatar.flux.action;
*/ */
public class MenuAction extends Action { public class MenuAction extends Action {
private MenuItem menuItem; private final MenuItem menuItem;
public MenuAction(MenuItem menuItem) { public MenuAction(MenuItem menuItem) {
super(ActionType.MENU_ITEM_SELECTED); super(ActionType.MENU_ITEM_SELECTED);

@ -30,7 +30,7 @@ public enum MenuItem {
HOME("Home"), PRODUCTS("Products"), COMPANY("Company"); HOME("Home"), PRODUCTS("Products"), COMPANY("Company");
private String title; private final String title;
MenuItem(String title) { MenuItem(String title) {
this.title = title; this.title = title;

@ -39,7 +39,7 @@ public final class Dispatcher {
private static Dispatcher instance = new Dispatcher(); private static Dispatcher instance = new Dispatcher();
private List<Store> stores = new LinkedList<>(); private final List<Store> stores = new LinkedList<>();
private Dispatcher() { private Dispatcher() {
} }

@ -33,7 +33,7 @@ import java.util.List;
*/ */
public abstract class Store { public abstract class Store {
private List<View> views = new LinkedList<>(); private final List<View> views = new LinkedList<>();
public abstract void onAction(Action action); public abstract void onAction(Action action);

Some files were not shown because too many files have changed in this diff Show More