Object-Oriented Design Principles PMD (1)

● A static source code analyzer (written in: Java; license: BSD-style) https://pmd.github.io/ Péter Jeszenszky https://github.com/pmd/pmd Faculty of Informatics, University of Debrecen – Supported programming languages: ECMAScript [email protected] (JavaScript), Java, Scala, …

Last modified: April 16, 2021

3

Static Code Analysis PMD (2)

● Static code analysis is the process of analyzing program ● Tool integration: code without executing it. – Apache Maven: ● Apache Maven PMD Plugin (license: Apache License 2.0) – Analysis can be aimed at: detecting errors and bugs, checking https://maven.apache.org/plugins/maven-pmd-plugin/ whether the code conforms to a coding standard, … – Gradle: ● The PMD Plugin (license: Apache License 2.0) ● Static code analyzer, static code analysis tool: an automated https://docs.gradle.org/current/userguide/pmd_plugin.html tool for performing static code analysis. – Eclipse IDE: ● pmd-eclipse-plugin (license: BSD-style) https://marketplace.eclipse.org/content/pmd-eclipse-plugin – Examples: https://github.com/pmd/pmd-eclipse-plugin ● PMD Plug-in (license: Eclipse Public License 2.0) https://acanda.github.io/eclipse-pmd/ ● Checkstyle https://checkstyle.org/ https://github.com/checkstyle/checkstyle https://github.com/acanda/eclipse-pmd/ ● PMD https://pmd.github.io/ https://github.com/pmd/pmd – IntelliJ IDEA: ● SpotBugs https://spotbugs.github.io/ https://github.com/spotbugs/spotbugs ● PMDPlugin (license: MIT License) https://plugins.jetbrains.com/plugin/1137-pmdplugin https://github.com/amitdev/PMD-Intellij ● QAPlug (license: proprietary) https://qaplug.com/

2 4 DRY (1) DRY (3)

● Don't Repeat Yourself ● Categories of duplication: – – Imposed duplication: Developers feel they have no choice – “Every piece of knowledge must have a single, the environment seems to require duplication. unambiguous, authoritative representation within a – Inadvertent duplication: Developers don’t realize that they are system.” duplicating information. ● The opposite of DRY is WET: – Impatient duplication: Developers get lazy and duplicate because it seems easier. – “We enjoy typing”, “write everything twice”, “waste – Interdeveloper duplication: Multiple people on a team (or on everyone's time”, … different teams) duplicate a piece of information. ● Related concept: code duplication, duplicate code, copy- and-paste programming

5 7

DRY (2) DRY (4)

● Source: ● Duplicate code is identical (or very similar) – Andrew Hunt, David Thomas. The Pragmatic piece of source code that occurs more than Programmer: From Journeyman to Master. once in a program. Addison-Wesley, 1999. ● Not all code duplication is knowledge – David Thomas, Andrew Hunt. The Pragmatic duplication! Programmer: Your Journey to Mastery, 20th Anniversary Edition. Addison Wesley, 2019. https://pragprog.com/book/tpp20/the-pragmatic-pro grammer-20th-anniversary-edition ● Free chapter: DRY – The Evils of Duplication https://media.pragprog.com/titles/tpp20/dry.pdf

6 8 DRY (5) DRY (7)

● PMD support: Copy/Paste Detector (CPD) ● Example (continued): – Finding duplicated code with CPD – The violation can be eliminated by replacing the https://pmd.github.io/latest/pmd_userdocs_cpd.html length field with a method: – Supported programming languages: C/C++, C#, class Line { ECMAScript (JavaScript), Java, Kotlin, Python, Point start; Scala, … Point end; ● See: double length() { https://pmd.github.io/latest/pmd_userdocs_cpd.html#sup ported-languages return start.distanceTo(end); } }

9 11

DRY (6) DRY (8)

● DRY violations do not always take the form of ● Example (continued): duplicate code. – For performance reasons, one may choose to – DRY is about the duplication of knowledge. The violate the DRY principle. same piece of knowledge can be expressed in two ● In this case, the violation should be hidden from the totally different ways in two different places. outside world. – Example (Thomas & Hunt, 2019):

class Line { Point start; Point end; double length; // DRY violation }

10 12 class Line {

private Point start; private Point end; DRY (11) private double length;

public Line(Point start, Point end) { this.start = start; ● Representational duplication (Thomas & Hunt, this.end = end; calculateLength(); 2019): } – public void setStart(Point p) { This duplication is inevitable. this.start = p; calculateLength(); – Tools that help to cope with this kind of duplication: } ● Tools that generate code from schemas (e.g., JAXB, JPA) public void setEnd(Point p) { this.end = p; ● OpenAPI calculateLength(); } ● …

public Point getStart() { return start; }

public Point getEnd() { return end; }

public double getLength() { return length; }

private void calculateLength() { this.length = start.distanceTo(end); }13 15 }

DRY (10) KISS

● Representational duplication (Thomas & Hunt, ● “Keep it simple, stupid” 2019): – 1960s, U.S. Navy – Code often depends on the outside world: e.g., – The phrase is attributed to aeronautical engineer Kelly other libraries via APIs, data in external data Johnson (1910–1990). sources, that always introduces some kind of DRY ● The pursuit of simplicity: violation: code has to have knowledge that is also – Leonardo da Vinci (1452–1519): “Simplicity is the ultimate present in the external thing. sophistication.” ● It needs to know the API, or the schema, or the meaning – Ludwig Mies van der Rohe (1886–1969): “Less is more.” of error codes. – Albert Einstein (1879–1955): “Everything should be made as simple as possible, but not simpler.”

14 16 YAGNI (1) YAGNI (3)

● An acronym that stands for “You Aren't Gonna ● The costs of developing a feature that is not Need It”. need now (Martin Fowler): ● A principle of extreme programming (XP).

17 19

YAGNI (2) YAGNI (4)

● “Always implement things when you actually ● YAGNI only applies to capabilities built into the need them, never when you just foresee that software to support a presumptive feature, it you need them.” does not apply to effort to make the software – See: Ronald E. Jeffries. You’re NOT gonna need it! easier to modify. Apr 4, 1998. ● YAGNI is only a viable strategy if the code is https://ronjeffries.com/xprog/articles/practices/pracn otneed/ easy to change. ● See also: – Martin Fowler. Yagni. 26 May 2015. https://martinfowler.com/bliki/Yagni.html

18 20 Coupling (1) Coupling (3)

● Coupling: the degree to which a software ● Loose coupling: module depends on another software module. – It allows developers to write code that conforms to – In other words, coupling between software modules the open-closed principle (OCP), i.e., it makes code is a measure of how closely connected they are. extensible. – Coupling can either be loose or tight. – It makes code extensible, and extensibility makes it maintainable. ● Reference: – It allows parallel development. – Joseph Ingeno. Software Architect's Handbook. Packt Publishing, 2018. https://www.packtpub.com/application-development/ software-architects-handbook

21 23

Coupling (2) Law of Demeter (1)

● Tight coupling: ● The Law of Demeter was proposed by Ian Holland in 1987. – It increases complexity that makes modification of code more difficult, thus, it reduces maintainability. ● The law was named after the Demeter project in – It also reduces reusability. which Holland was working when he discovered it. ● Also known as: Don't Talk to Strangers – Craig Larman. Applying UML and Patterns: An Introduction to Object-Oriented Analysis and Design and Iterative Development. 3rd ed. Prentice Hall, 2005.

22 24 Law of Demeter (2) Law of Demeter (4)

● References: ● Class form: – Karl J. Lieberherr, Ian M. Holland, Arthur Joseph Riel. – A method M of class C may use only members Object-Oriented Programming: An Objective Sense of Style. (methods and data) of the following classes and their Proceedings on Object-oriented programming systems, base classes: languages and applications (OOPSLA), pp. 323– 334, 1988. https://doi.org/10.1145/62084.62113 ● C ● data-member classes of C – Ian M. Holland, Karl J. Lieberherr. Assuring Good Style for Object-Oriented Programs. IEEE Software, vol. 6, no 5, pp. ● argument classes of M 38– 48, 1989. https://doi.org/10.1109/52.35588 ● classes whose constructors are called in M – Karl Lieberherr. Law of Demeter: Principle of Least ● the classes of global variables used in M Knowledge. http://www.ccs.neu.edu/home/lieber/LoD.html – Can be checked at compile time.

25 27

Law of Demeter (3) Law of Demeter (5)

● Restricts the message-sending structure of ● Object form: methods. – A method M of object O may use only members – Informally, the law says that each method can send (methods and data) of the following objects: messages to only a limited set of objects. ● O ● The goal of the Law of Demeter is to organize ● data members of O and reduce the dependencies between classes. ● argument objects of M ● objects that are created/instantiated directly in M ● objects in global variables – Can be checked only at runtime.

26 28 Law of Demeter (6) Law of Demeter (8)

● The law promotes maintainability and ● Related PMD ruleset: comprehensibility. – Design (Java) – It effectively reduces the methods that can can be https://pmd.github.io/latest/pmd_rules_java_design. called inside a given method and therefore limits html the coupling of methods. ● See the LawOfDemeter rule: https://pmd.github.io/latest/pmd_rules_java_design.html#l – It enforces one kind of information hiding (structure awofdemeter hiding): the internal structure of an object is known only by the object itself.

29 31

Law of Demeter (7) Law of Demeter (9)

● An example of the violation of the law: ● Is method chaining allowed?

public class Foo { – Examples: public void example(Bar b) { ● Builder // This method call is ok, as b is a parameter of the method. C c = b.getC(); ● Fluent interfaces

// This method call violates the law, as we are using c, which we – See: Martin Fowler. FluentInterface. 20 December 2005. // got from B. https://martinfowler.com/bliki/FluentInterface.html c.doIt();

// This is also a violation, just expressed differently as a method // chain without temporary variables. b.getC().doIt();

// This method call is ok, because we create a new instance of D // locally. new D().doSomethingElse(); }

} 30 32 Law of Demeter (10) GoF Principles (2)

● Examples of method chaining: ● “Program to an interface, not an implementation.” // Builder design pattern: import java.util.StringJoiner; – See the creational ! String s = new StringJoiner(",", "[", "]") .add("George") .add("John") .add("Paul") .add("Ringo") .toString();

// : import java.time.LocalTime;

LocalTime time = LocalTime.now().plusHours(1).plusMinutes(45); 33 35

GoF Principles (1) GoF Principles (3)

● References: ● “Favor object composition over class – Erich Gamma, Richard Helm, Ralph Johnson, John inheritance.” Vlissides. Design Patterns: Elements of Reusable ● The two most common techniques for reusing Object-Oriented Software. Addison-Wesley, 1994. functionality in object-oriented systems: – Class inheritance (white-box reuse) – Object composition (black-box reuse) ● The term “white-box”/”black box” refers to visibility.

34 36 GoF Principles (4) GoF Principles (6)

● Advantages of inheritance: ● Disadvantages of class inheritance (continued): – Class inheritance is defined statically at compile- – Implementation dependencies can cause problems time and is straightforward to use, since it's when you're trying to reuse a subclass. supported directly by the programming language. ● Should any aspect of the inherited implementation not be – Class inheritance also makes it easier to modify the appropriate for new problem domains, the parent class implementation being reused. must be rewritten or replaced by something more appropriate. This dependency limits flexibility and ● When a subclass overrides some but not all operations, it ultimately reusability. can affect the operations it inherits as well, assuming they call the overridden operations.

37 39

GoF Principles (5) GoF Principles (7)

● Disadvantages of class inheritance: ● Object composition: – First, you can't change the implementations inherited from – Object composition is defined dynamically at run- parent classes at run-time, because inheritance is defined at compile-time. time through objects acquiring references to other objects. – Second, and generally worse, parent classes often define at least part of their subclasses' physical representation. – Composition requires objects to respect each ● Because inheritance exposes a subclass to details of its parent's others' interfaces, which in turn requires carefully implementation, it's often said that inheritance breaks encapsulation. designed interfaces that don't stop you from using ● The implementation of a subclass becomes so bound up with the one object with many others. implementation of its parent class that any change in the parent's implementation will force the subclass to change.

38 40 GoF Principles (8) SOLID (1)

● Advantages of object composition: ● Object oriented programming and design principles formulated, systematize, and popularized by Robert C. Martin (“Uncle Bob”). – Because objects are accessed solely through their interfaces, we don't break encapsulation. – Blog: https://blog.cleancoder.com/ – https://github.com/unclebob – Any object can be replaced at run-time by another as – Uncle Bob. Getting a SOLID start. 2009. long as it has the same type. https://sites.google.com/site/unclebobconsultingllc/getting-a-solid-start – Favoring object composition over class inheritance helps ● References: you keep each class encapsulated and focused on one – Robert C. Martin. Agile Software Development: Principles, Patterns, and task. Practices. Pearson Education, 2002. – Your classes and class hierarchies will remain small and ● Code samples are written in C++ and Java. will be less likely to grow into unmanageable monsters. – Robert C. Martin, Micah Martin. Agile Principles, Patterns, and Practices in C#. Prentice Hall, 2006.

41 43

GoF Principles (9) SOLID (2)

● Disadvantages of object composition: ● Single Responsibility Principle (SRP) – A design based on object composition will have ● Open/Closed Principle (OCP) more objects (if fewer classes), and the system's behavior will depend on their interrelationships ● Liskov Substitution Principle (LSP) instead of being defined in one class. ● Interface Segregation Principle (ISP) ● Dependency Inversion Principle (DIP)

42 44 SOLID – Single Responsibility SOLID – Single Responsibility Principle (1) Principle (3)

● Robert C. Martin stated the principle: ● An example of violating the principle: – “A class should have only one reason to change.” – The Rectangle class has two responsibilities: ● Related design patterns: decorator, chain of ● To provide a mathematical model of the geometry of a responsibility rectangle. ● To render the rectangle on a graphical user interface.

Rectangle Computational «use» «use» Graphical Geometry Applicaton Application +draw() +area(): double

«use»

«use» GUI 45 47

SOLID – Single Responsibility SOLID – Single Responsibility Principle (2) Principle (4)

● A responsibility is a reason to change. ● An example of violating the principle ● Each responsibility is an axis of change. When the (continued): requirements change, that change will be manifest – Problems: through a change in responsibility amongst the classes. ● The computational geometry application must include the ● If a class assumes more than responsibility, then there graphical user interface. will be more than one reason for it to change. ● If a change to the graphical application causes the ● If a class has more than one responsibility, then the Rectangle to change for some reason, that change responsibilities become coupled. Changes to one may force us to rebuild, retest, and redeploy the responsibility may impair or inhibit the ability of the class computational geometry application. to meet the others.

46 48 SOLID – Single Responsibility SOLID – Single Responsibility Principle (5) Principle (7)

● A reworked version of the previous model that ● Software is changed to satisfy actors. conforms to the principle: – The term “actor” is used here to refer to a group of people (e.g., users) that wants the software to be Computational Graphical «use» changed in the same way. Geometry Applicaton Application ● Thus, the principle can be rephrased as:

«use» «use» – A module should be responsible to one, and only one, actor. Geometric Rectangle Rectangle «use» «use» GUI +draw() +area(): double

49 51

SOLID – Single Responsibility SOLID – Single Responsibility Principle (6) Principle (8)

● The formulation of the principle has been refined over the ● Example (Robert C. Martin): years: – The Employee class below violates the SRP – „A class should have only one reason to change.” because the three methods are responsible to three ● Robert C. Martin. Agile Software Development: Principles, Patterns, and Practices. Pearson Education, 2002. p. 95. very different actors: – „… a class or module should have one, and only one, reason to ● calculatePay(): is specified by the accounting change.” department ● Robert C. Martin. Clean Code: A Handbook of Agile Software ● Craftsmanship. Prentice Hall, 2008. p. 138. reportHours(): is specified by the human resources department – “A module should be responsible to one, and only one, actor.” ● : is specified by the database administrators ● Robert C. Martin. Clean Architecture: A Craftsman's Guide to Software save() Structure and Design. Prentice Hall, 2017. p. 62. Employee +calculatePay() +reportHours() 50 52 +save() SOLID – Open-Closed Principle (1) SOLID – Open-Closed Principle (3)

● Bertrand Meyer coined the principle. ● An example of the violation of the principle: – See: Bertrand Meyer. Object-Oriented Software – Both the Client and Server classes are Construction. Prentice Hall, 1988. concrete. The Client class uses the Server ● “Software entities (classes, modules, functions, class. If we wish for a Client object to use a …) should be open for extension, but closed for different server object, then the Client class must modification.” be changed to name the new server class. ● Related design patterns: factory method, proxy,

strategy, template method, visitor «use» Client Server

53 55

SOLID – Open-Closed Principle (2) SOLID – Open-Closed Principle (4)

● Modules that conform to the principle have two ● A corresponding model that conforms to the primary attributes: principle: – Open for extension: this means that the behavior «use» «interface» of a module can be extended. Client Client Interface – Closed for modification: this means that extending the behavior of a module does not result in changes to the source or binary code of the module. Server

54 56 SOLID – Liskov Substitution SOLID – Interface Segregation Principle Principle (2)

● Barbara Liskov described the principle. ● Fat interface (Bjarne Stroustrup) – See: Barbara Liskov. Keynote Address – Data https://www.stroustrup.com/glossary.html#Gfat-i Abstraction and Hierarchy. 1987. nterface – “An interface with more member functions and ● If the type S is a subtype of the type T, then the friends than are logically necessary.” behavior of a program should not change when objects of type T are substituted with objects of type S in it.

57 59

SOLID – Interface Segregation SOLID – Interface Segregation Principle (1) Principle (3)

● Robert C. Martin formulated the principle: ● This principle deals with the disadvantages of “fat” interfaces. – “Classes should not be forced to depend on methods they do not use.” ● Classes that have “fat” interfaces are classes whose interfaces are not cohesive. In other words, the interfaces of the class can be broken into groups of methods. Each group serves a different set of clients. ● The ISP acknowledges that there are objects that require noncohesive interfaces; however, it suggests that clients should not know about them as a single class.

58 60 SOLID – Interface Segregation SOLID – Interface Segregation Principle (4) Principle (6)

● Interface pollution: ● Example: ATM (Robert C. Martin) – Polluting an interface with redundant methods. Transaction {abstract}

+execute()

Deposit Withdrawal Transfer Transaction Transaction Transaction

«interface» UI

+RequestDepositAmount() +RequestWithdrawalAmount() +RequestTransferAmount() 61 +RequestTargetAccountNo() 63

SOLID – Interface Segregation SOLID – Interface Segregation Principle (5) Principle (7)

Transaction ● When a client depends on a class that contains {abstract} methods that the client does not use, but that +execute() other clients do use, then that client will be Deposit Withdrawal Transfer affected by the changes that those other clients Transaction Transaction Transaction force upon the class.

«interface» «interface» «interface» ● This results in an inadvertent coupling between Deposit UI Withdrawal UI Transfer UI

+RequestDepositAmount() +RequestWithdrawalAmount() +RequestTransferAmount() all the clients. +RequestTargetAccountNo()

«interface» UI

+RequestDepositAmount() +RequestWithdrawalAmount() 62 +RequestTransferAmount() 64 +RequestTargetAccountNo() SOLID – Dependency Inversions SOLID – Dependency Inversions Principle (1) Principle (3)

● Robert C. Martin formulated the principle: ● It is the high level modules that contain the important policy decisions and business models of an application. These – “High level modules should not depend on low-level modules contain the identity of the application. Yes, when modules. Both should depend on abstractions.” these modules depend on lower level modules, changes to – the lower level modules can have direct effects on the higher “Abstractions should not depend on details. Details level modules and can force them to change in turn. should depend on abstractions.” ● This predicament is absurd! It is the high level, policy-settings modules that ought to be influencing the low level, detail modules. The modules that contain the high-level business rules should take precedence over, and be independent of, the modules that contain the implementation details.

65 67

SOLID – Dependency Inversions SOLID – Dependency Inversions Principle (2) Principle (4)

● Traditional software development methods tend ● It is the high-level, policy-setting modules that we to create software structures in which high-level want to be able to reuse. We are already quite good modules depend on low-level modules, and in at reusing low-level modules in the form of libraries. which policy depend on detail. ● When high-level modules depend on low-level

● modules, it becomes very difficult to reuse those Related design pattern: adapter high-level modules in different contexts. ● However, when the high-level modules are independent of the low-level modules, then the high- level modules can be reused quite simply.

66 68 SOLID – Dependency Inversions Presentation «interface» Presentation Presentation Principle (5) Layer Service Interface ● An example of the conventional use of the layers architectural pattern: Application «interface» Application Application Presentation Layer Service Layer Interface

Business Application Layer «interface» Business Business Layer Service Interface

Business layer Data Access

Data Access Layer Data Access Layer 69 71

SOLID – Dependency Inversions SOLID – Dependency Inversions Principle (6) Principle (8)

● A reworked version of the previous model that ● A reworked version of the previous model that conforms to the principle: conforms to the principle (continued): – Each of the upper-level layers declares an interface – Notice that the inversion here is not just one of for the services that it needs. dependencies, it is also one of interface ownership – The lower-level layers are then realized from these (inversion of ownership). interfaces. ● Hollywood principle: “Don't call us, we'll call you”. – Thus, the upper layers do not depend on the lower layers.

70 72 SOLID – Dependency Inversions SOLID – Dependency Inversions Principle (9) Principle (11)

● Depend on abstractions: ● A reworked version of the previous example that conforms to the principle: – A program should not depend on any concrete classes, instead, it should only depend on abstract classes and interfaces. «interface» Switch ● No variable should hold a pointer or reference to a concrete class. ● No class should derive from a concrete class. +isOn(): boolean +press() ● No method should override an implemented method of any of its base classes. – Certainly this heuristic is usually violated at least once in every ElectricPowerSwitch «interface» program. Switchable – +isOn(): boolean 0..1 If a concrete class is not going to change very much, and no +press() +turnOn() similar derivatives are going to be created (e.g., String), then it +turnOff() does little harm to depend on it.

LightBulb

73 75 +turnOn() +turnOff()

SOLID – Dependency Inversions (1) Principle (10)

● An example of the violation of the principle: ● References: – – Dhanji R. Prasanna. Dependency Injection: Design Patterns Using Source: Spring and Guice. Manning, 2009. https://springframework.guru/principles-of-object-ori https://www.manning.com/books/dependency-injection ented-design/dependency-inversion-principle/ – Krunal Patel, Nilang Patel. Java 9 Dependency Injection. Packt Publishing, 2018. https://www.packtpub.com/application-development/java-9-depend ElectricPowerSwitch LightBulb ency-injection – +isOn(): boolean 0..1 +turnOn() Mark Seemann. Dependency Injection in .NET. Manning, 2011. +press() +turnOff() https://www.manning.com/books/dependency-injection-in-dot-net – Steven van Deursen, Mark Seemann. Dependency Injection Principles, Practices, and Patterns. Manning, 2019. https://www.manning.com/books/dependency-injection-principles-p ractices-patterns

74 76 Dependency Injection (2) Dependency Injection (4)

● The term dependency injection (DI) was coined by ● An object can be seen as a service that are Martin Fowler. consumed by other objects as clients. – Martin Fowler. Containers and the ● Such a client-service relationship between Dependency Injection pattern. 2004. https://martinfowler.com/articles/injection.html objects is called a dependence. This relationship is transitive. ● It can be considered as a special case of the application of the architectural pattern called inversion of control (IoC). – Martin Fowler. InversionOfControl. 2005. https://martinfowler.com/bliki/InversionOfControl.html

77 79

Dependency Injection (3) Dependency Injection (5)

● Definition (Seemann): ● Dependency: a specific service that is required by another object to fulfill its function. – “Dependency Injection is a set of software design ● Dependent: a client object that needs a dependency (or principles and patterns that enables you to develop dependencies) in order to perform its function. loosely coupled code.” ● Object graph: a set of dependent objects and their ● Loose coupling makes code extensible, and dependencies. extensibility makes it maintainable. ● Injection: giving a client its dependency (or dependencies). ● DI container: a library or framework that provides reusable DI functionality. – DI containers are also known as Inversion of Control (IoC) containers.

78 80 Dependency Injection (6) Dependency Injection (8)

● DI container: a software library that provides DI ● Example: no dependency injection functionality. public interface SpellChecker { – DI containers are also known as Inversion of public boolean check(String text); Control (IoC) containers. } ● DI can be applied without using a DI container. public class TextEditor { ● Pure DI: the practice of applying DI without a DI private SpellChecker spellChecker; container. public TextEditor() { spellChecker = new HungarianSpellChecker(); }

// ...

81 } 83

Dependency Injection (7) Dependency Injection (9)

● DI as a subject is primarily concerned with ● Example: constructor injection reliably and efficiently building object graphs and the strategies, patterns, and best practices therein. public class TextEditor { private SpellChecker spellChecker; ● DI frameworks allow clients to delegate the public TextEditor(SpellChecker spellChecker) { responsibility of creating and injecting their this.spellChecker = spellChecker; dependencies to external code. } // ...

}

82 84 Dependency Injection (10) Dependency Injection (12)

● Example: setter injection ● Advantages of DI: – Extensibility – public class TextEditor { Maintainability: – private SpellChecker spellChecker; Testability: DI support unit testing.

● public TextEditor() {} Instead of real dependencies, test doubles can be injected into the system under test. public void setSpellChecker(SpellChecker spellChecker) { this.spellChecker = spellChecker; }

// ...

}

85 87

Dependency Injection (11) Dependency Injection in C++

● Example: interface injection ● Libraries and frameworks: – [Boost::ext].DI (license: Boost Software License)

public interface SpellCheckerSetter { https://boost-ext.github.io/di/

void setSpellChecker(SpellChecker spellChecker); https://github.com/boost-ext/di } – Fruit (license: Apache License 2.0) public class TextEditor implements SpellCheckerSetter { https://github.com/google/fruit private SpellChecker spellChecker; – Hypodermic (license: MIT License) public TextEditor() {} https://github.com/ybainier/Hypodermic @Override public void setSpellChecker(SpellChecker spellChecker) { this.spellChecker = spellChecker; }

// ...

} 86 88 Dependency Injection in Java (1) Dependency Injection in Java (3)

● JSR 330: Dependency Injection for Java ● Frameworks: https://www.jcp.org/en/jsr/detail?id=330 – Apache OpenWebBeans (license:Apache License 2.0) https://openwebbeans.apache.org/ – Provides standard annotations for dependency injection. https://github.com/apache/openwebbeans – It was introduced in Java EE 6 and is contained in the ● An implementation of JSR-365 in Java SE. javax.inject package. – Dagger (license: Apache License 2.0) https://dagger.dev/ https://github.com/google/dagger ● See: ● A compile-time framework for dependency injection based on JSR-330. https://javaee.github.io/javaee-spec/javadocs/javax/inject/package-s ummary.html – Guice (license: Apache License 2.0) https://github.com/google/guice – ● A lightweight DI framework. Originally, Giuce was the reference implementation of Implementations: Dagger, Guice, HK2, Spring Framework, … JSR-330. – Successor: Jakarta Dependency Injection (Jakarta EE) ● See: Natasha Mathur. Implementing Dependency Injection in Google Guice. September 9, 2018. https://jakarta.ee/specifications/dependency-injection/ https://hub.packtpub.com/implementing-dependency-injection-google-guice/

89 91

Dependency Injection in Java (2) Dependency Injection in Java (4)

● JSR 365: Contexts and Dependency Injection for Java 2.0 ● Frameworks (continued): https://www.jcp.org/en/jsr/detail?id=365 – GlassFish HK2 (license: Eclipse Public License 2.0/GPLv2 + Classpath Exception) https://eclipse-ee4j.github.io/glassfish-hk2/ – JSR-365 extends JSR-330 with more advanced features, such https://github.com/eclipse-ee4j/glassfish-hk2 as modules. ● An implementation of JSR-330 in Java SE for the GlassFish application server as – It was introduced in Java EE 8 and is contained in the well as other products. javax.enterprise.inject package and its sub-packages. – Spring Framework (license: Apache License 2.0) https://spring.io/projects/spring-framework – Implementations: Apache OpenWebBeans, Weld https://github.com/spring-projects/spring-framework – Further information: http://www.cdi-spec.org/ ● Spring Framework is a framework and inversion of control (IoC) container for developing enterprise applications in Java. It provides support for JSR-330. – Successor: Jakarta Contexts and Dependency Injection (Jakarta – Weld (license: Apache License 2.0) https://weld.cdi-spec.org/ EE) https://jakarta.ee/specifications/cdi/ https://github.com/weld/core https://projects.eclipse.org/projects/ee4j.cdi ● The reference implementation of JSR-365.

90 92 Dependency Injection in .NET

● Frameworks: – Castle Windsor (license: Apache License 2.0) http://www.castleproject.org/ https://github.com/castleproject/Windsor – Lamar (license: MIT License) https://github.com/jasperfx/lamar https://jasperfx.github.io/lamar/ – Ninject (license: Apache License 2.0) http://www.ninject.org/ https://github.com/ninject/ninject – Simple Injector (license: MIT License) https://simpleinjector.org/ https://github.com/simpleinjector/SimpleInjector – Spring.NET (license: Apache License 2.0) https://springframework.net/ https://github.com/spring-projects/spring-net – StructureMap (license: Apache License 2.0) http://structuremap.github.io/ https://github.com/structuremap/structuremap

93