How much do we know about Object-Oriented Programming?

39
Software Craftsmanship by Sandro Mancuso Twitter: @sandromancuso http:// www.londonswcraft.com How much do we know about OOP/OOD?

description

This talk goes through many of the Object-Oriented Programming principles and characteristics. Things that all developers should have in mind while writing code.

Transcript of How much do we know about Object-Oriented Programming?

Page 1: How much do we know about Object-Oriented Programming?

Software Craftsmanship

by Sandro MancusoTwitter: @sandromancuso

http://www.londonswcraft.com

How much do we know about OOP/OOD?

Page 2: How much do we know about Object-Oriented Programming?

Inheritance >>

Before we startWhat can we expect from this session?

Page 3: How much do we know about Object-Oriented Programming?

Class Invariant >>

Inheritance

Page 4: How much do we know about Object-Oriented Programming?

public class Rectangle {    private int height;    private int width;     public Rectangle(int height, int width) {        this.height = height;        this.width = width;    }    public int getHeight() {        return this.height;    }    public void setHeight(int height) {        this.height = height;    }    public int getWidth() {        return this.width;    }    public void setWidth(int width) {        this.width = width;    }} 

public class Square extends Rectangle {     public Square(int size) {        super(size, size);    }      public int setHeight(int height) {        return super.setHeight(height);    }    public int setWidth(int width) {        return super.setWidth(width);    }}

What will happen when we call the setters?

Class Invariant

Invariant fix >>

Page 5: How much do we know about Object-Oriented Programming?

public class Square extends Rectangle {     public Square(int size) {        super(size, size);    }       public void setHeight(int height) {        super.setHeight(height);        super.setWidth(height);    }     public void setWidth(int width) {        super.setWidth(width);        super.height(width);    }}

• In isolation, Rectangle and Square are consistent valid;

• A sub-class is not a sub-class when:

• Needs to be adapted so it keeps its invariant

• State becomes invalid when used in the context of a super class.

Should Square extend Rectangle?

Class invariant – a fix but not a solution

LSP >>

Page 6: How much do we know about Object-Oriented Programming?

“Functions that use pointers or references to base classes must be able to use objects of derived classes without knowing it. “

LSP violation

public void drawShape(Shape s) {    if (s instanceof Square) {        drawSquare((Square) s);    } else if (s instanceof Circle){        drawCircle((Circle) s);    }}

Liskov Substitution Principle - LSPBehavioral subtyping

LSP violations >>

Page 7: How much do we know about Object-Oriented Programming?

A more subtle violation of LSP

Rectangle r = new Square();r.setHeight(5);r.setWidth(6);

Violations

- Without the fix, Square would be in an invalid state when used as a Rectangle;

- With the fix, the Square setter methods weaken (violate) Rectangle’s post conditions, which state that dimensions can be modified independently

Liskov Substitution Principle - LSP

Fixing the design >>

Page 8: How much do we know about Object-Oriented Programming?

What we’ve learnt?

We can not validate a model in isolation.

Looking at how the classes can be used by a client program, we realise that the model is broken.

A model should be validated just in terms of its clients.

Liskov Substitution Principle - LSP

public class Square {    int size;         public Square(int size) {        this.size = size;    }      public int getSize() {        return this.size;    }    public void setSize(int size) {        this.size = size;    }}

DbC >>

Page 9: How much do we know about Object-Oriented Programming?

- Term was coined by Bertrand Meyer in 1986

Based on the mutual obligations and benefits principle.

- Pre-condition: obligation for the client, benefit for the supplier

- Post-condition: obligation for the supplier, benefit for the client

- Invariant: Assumed on entry, guaranteed on exit

Design by Contract

DbC implications >>

Page 10: How much do we know about Object-Oriented Programming?

Subclasses are allowed to:• Weaken pre-conditions (but not strengthen them) • Strengthen post-conditions and invariants (not not weaken them) • This is the foundation of LSP

Design by Contract implications

public class ClassA {    public void someMethod() {…}}public class ClassB extends ClassA {    public void someMethod() { // Stronger pre-condition // Weaker post-condition & invariant }}

public class Client {    public void doSomething(ClassA a) { a.someMethod(); }}

What would happen if:

Client client = new Client();

client.doSomething(new ClassB()); // Would it be fair to the client?

Defensive Programming >>

Page 11: How much do we know about Object-Oriented Programming?

- DbC: It’s the client’s responsibility (obligation) to respect supplier’s pre-condition. Code should “fail-hard”

- Defensive Programming: Supplier takes the responsibility to validate pre-condition

In both cases, client needs to take an action.

DbC vs Defensive Programming

- Whatever you do, don’t hide bugs. If a pre-condition is not met, let the system blow or let the client handle it.

- Don’t code default behaviour unless this is part of the requirement.

Side effect >>

Page 12: How much do we know about Object-Oriented Programming?

A code is said to have side effect when it modifies some state or has an observable interaction with calling functions or outside world. (linked to DbC post-condition)

Side effect

Problems:

• Order of evaluation matters;

• Understanding requires knowledge about context;

• Hard to read and debug

• Nightmare for multi-threading applications

• Action at a distance anti-pattern

Very common in imperative programming and rare in functional programming.

Avoiding problems >>

Page 13: How much do we know about Object-Oriented Programming?

Side effect

Avoiding undesirable side effect problems:

• Use side effect free functions whenever possible

• Never use global variables

• Prefer returning a value instead of manipulating a parameter’s state

• Localise state changes, putting state and respective behaviour together

• Use “Tell don’t ask” design approach

• Prefer immutable classes

• CQRS – Command Query Responsibility Segregation

POLA/POLS >>

Page 14: How much do we know about Object-Oriented Programming?

Principle of least astonishment/surprise

• Applied to all type of interfaces, not just code.

• Methods should be self-documenting

• Methods should do the least surprising thing it could, given its name

The result of performing some operation should be obvious, consistent, and predictable, based upon the name of the operation, parameters and return value.

All programmers are API designers – Joshua Bloch

Problems when violated

• Bugs are created when a method does not do what it is supposed to do

• If you can’t find a good name, re-analyse your design

Violation >>

Page 15: How much do we know about Object-Oriented Programming?

Violation of POLA / POLS

public class EventProcessor {

    public void processEvent(Event event) throws EventProcessorException { try { doSomethingWith(event); event.setState(PROCESSED); // violation } catch (Exception e) { event.setState(FAILED); // violation throw new EventProcessorException(e); } }}

Possible undesired side effect.

SRP >>

Page 16: How much do we know about Object-Oriented Programming?

Single Responsibility Principle - SRP

How do we know a class or method has a single responsibility?

- Outside view

- Inside view

SRP violations >>

What about the “else” keyword? What does it imply when we use it?

Page 17: How much do we know about Object-Oriented Programming?

Single Responsibility Principle - SRP

Where do things go wrong?

- SRP violations are most seen in systems developed without TDD and refactoring.

- Classes closer to the system interface have a more generic and broader responsibility

- Failure do identify responsibility / delegation ratio

Cohesion >>

Page 18: How much do we know about Object-Oriented Programming?

CohesionThe cornerstone of Object-Oriented Programming

Class level >>

Cambridge Dictionary

Cohesion (noun) : when the members of a group or society are united.Cohesive (adjective) : united and working together effectively.

WikipediaIn computer programming, cohesion is a measure of how strongly-related and focused the various responsibilities of a software module are.

LCOM4: Lack of Cohesion Methods (metrics used by Sonar)

Page 19: How much do we know about Object-Oriented Programming?

Cohesion at class levelThe cornerstone of Object-Oriented Programming

Method level >>

• Coincidental (worst): Methods grouped arbitrarily and have no significant relationship (E.g. Util classes with methods handling strings, lists, mathematical calculations)

• Logical: Methods grouped because they logically are categorized to do the same thing, even if different by nature (E.g. grouping all I/O handling routine, all database selects, inserts, etc.).

• Temporal: Methods grouped by when they are processed at a particular time in program execution (E.g. validates data, persist the data, create audit information, notifies user via email).

• Procedural: Methods grouped because they always follow a certain sequence of execution. (Verify is user exist, performs login, write logs, retrieve user's detail)

• Communicational: Methods grouped because they work on the same data (E.g. Insert, delete, validate, update a client entity).

• Sequential: Methods grouped because the output of one method can be used as an input of other methods. (reads a file, process the file).

• Functional (best):  Methods grouped because they all contribute to a single well-defined task. (parsing XML)

Page 20: How much do we know about Object-Oriented Programming?

Cohesion at method levelThe cornerstone of Object-Oriented Programming

God object >>

• Coincidental (worst): Performs multiple operations and some times they are not related to each other.

• Conditional: According to an if statement, different attributes are modified or different values are set to the different attributes .

• Iterative: Several attributes (Array variables) are modified as a result of a looping.

• Communicational: More than one attribute is modified according to only one input.

• Sequential: More than one variable (object) modification result in the change to only one attribute.

• Functional (best): Method modifies fewer than 2 attributes

Page 21: How much do we know about Object-Oriented Programming?

God Object

Coupling >>

Page 22: How much do we know about Object-Oriented Programming?

Coupling

Types >>

Coupling or dependency is the degree to which each program module relies on each one of the other modules

- Low coupling often correlates with high cohesion, and vice versa.

- Sign of good design and well maintainable code.

Page 23: How much do we know about Object-Oriented Programming?

Coupling general types

other types >>

• Content coupling (high): One module modifies or relies on the internal workings of another module (e.g., accessing local data of another module).

• Common coupling: When two modules share the same global data (e.g., a global variable).

• External coupling: Occurs when two modules share an externally imposed data format, communication protocol, or device interface.

• Control coupling: One module controlling the flow of another, by passing it information on what to do (e.g., passing a what-to-do flag).

• Stamp coupling (Data-structured coupling): When modules share a composite data structure and use only a part of it, possibly a different part (e.g., passing a whole record to a function that only needs one field of it).

• Data coupling: When modules share data through, for example, parameters. Each datum is an elementary piece, and these are the only data shared (e.g., passing an integer to a function that computes a square root).

• Message coupling (low): It can be achieved by state decentralization (as in objects) and component communication is done via parameters or message passing.

Page 24: How much do we know about Object-Oriented Programming?

Coupling – other types

Ripple effect >>

• Subclass Coupling: Describes the relationship between a child and its parent. The child is connected to its parent, but the parent isn't connected to the child.

• Temporal coupling: When two actions are bundled together into one module just because they happen to occur at the same time.

Page 25: How much do we know about Object-Oriented Programming?

Coupling – The ripple effect

ISP >>

Page 26: How much do we know about Object-Oriented Programming?

Interface Segregation Principle - ISP

ISP >>

Page 27: How much do we know about Object-Oriented Programming?

Interface Segregation Principle - ISP

Role interface >>

Page 28: How much do we know about Object-Oriented Programming?

Role Interface

DIP >>

• Defined by looking at a specific interaction between consumers and suppliers

• A supplier component may implement several role interfaces one for each pattern of interaction

• Opposed to Header Interface, that contains all the public methods of a class. Good when alternative implementations may be used

• Coined by Martin Fowler in 2006

Page 29: How much do we know about Object-Oriented Programming?

Dependency Inversion Principle - DIP

DIP >>

• High-level modules should not depend on low-level modules. Both should depend on abstractions

• Abstractions should not depend upon details. Details should depend upon abstractions

Violation

What if we want to write it to disk? How can we reuse Copier?

Page 30: How much do we know about Object-Oriented Programming?

Dependency Inversion Principle - DIP

IoC & DI >>

High and low-level modules now depend on an abstraction

Page 31: How much do we know about Object-Oriented Programming?

DIP, IoC and DI

Encapsulation Jump >>

• DIP: One of the SOLID principles. Refers to decoupling high-level modules from low-level modules, inverting/reversing their dependencies.

• IoC: Abstract principle where the caller’s code deals with the program’s execution order, but the business knowledge is encapsulated by the called subroutines. Can be implemented via:

• Abstract Factory / Factory method

• Service Locator Pattern

• DI: It’s a design pattern used for separating behaviour from dependency resolution.

• Involves a dependent consumer, definition of dependencies and an injector (container)

• Injection types are:

• Constructor / Setter injection

• Interface injection

• Field injection

• Bijection

Page 32: How much do we know about Object-Oriented Programming?

Encapsulation

Information Hiding >>

• Restrict access to some of the object’s components

• Facilitates the bundling of data with the methods operating on that data

Information Hiding

!=

Data encapsulation

Page 33: How much do we know about Object-Oriented Programming?

Information Hiding & Protected Variation

OCP >>

Information Hiding: Hide information about the design from other modules, at the points of difficult or likely to change.

David Parnas

Information hiding is Protected Variation, not data encapsulation

To minimise change impacts, we aim for low coupling. To design for low coupling, we design for protected variations.

Craig Larman

Protected Variation: Identify points of predicted variation and create a stable interface around them.

Alistair Cockburn

Page 34: How much do we know about Object-Oriented Programming?

Open Closed Principle (OCP)

LoD >>

Software entities (classes, modules, functions, etc) should be open for extension, but closed for modification

Achieved via

• Inheritance and override (Bertand Meyer – 1988)

• Use of abstract classes to define the interface and multiple concrete implementations

• Achieved by template method, proxy, delegate, chain of responsibility, specification and other patterns.

Misconception: Closed to modification does not mean that we cannot change a class. It means that we should avoid modifications that affect clients.

Is it still a good idea today?

Page 35: How much do we know about Object-Oriented Programming?

Law of Demeter - LoD

Feature Envy >>

Also known as:

• Principle of Least Knowledge (PLK)

• Don’t talk to strangers

• Train wreck

Violation

context.getCar().getEngine().getPiston().getSparkPlug(),doSomething();

parent.getChildren().delete(child);

Page 36: How much do we know about Object-Oriented Programming?

Feature Envy

Other topics >>

public void doSomething() { BigDecimal baseMonthlySalary = employee.getBaseMontlySalary(); int overtimeInHours = employee.getOverTimeInHours(); BigDecimal overtimeHourRate = employee.getOvertimeHourRate(); BigDecimal salaryToBePaid = baseMonthlySalary +

(overtimeInHours * overtimeHourRate); // Do more stuff with the salary}

public void doSomething() { BigDecimal salaryToBePaid = employee.getMonthlySalaryToBePaid(); // Do more stuff with the salary}

A better implementation

Page 37: How much do we know about Object-Oriented Programming?

A few other related topics

Wrap up >>

• DRY – Don’t Repeat Yourself

• CQRS – Command Query Responsibility Segregation

• Tell don’t ask

• Object orgy – loss of the benefits of encapsulation

• BDUF – Big Design Up Front

• DDD - Domain Driven Design

• Patterns – GoF, JEE Patterns, DDD patterns

• Anti-patterns

• Code smells – symptom that indicates a deeper problem

• Missing concept

• TDD – Test Driven Development

• BDD – Behaviour Driven Development

Page 38: How much do we know about Object-Oriented Programming?

Wrap up

There is always a good reason to break a rule or law, but it really needs to be a good one.

The critical design tool for software development is a mind well educated in design principles. It is not the UML or any other technology

Craig Larman

Most software engineers don’t set out to create “bad designs”. Yet most softwareeventually degrades to the point where someone will declare the design to be unsound.Why does this happen? Was the design poor to begin with, or did the design actuallydegrade like a piece of rotten meat? At the heart of this issue is our lack of a good workingdefinition of “bad” design.

Uncle Bob Martin

Questions >>

Page 39: How much do we know about Object-Oriented Programming?

Questions

London Software Craftsmanship Community – LSCC – http://www.londonswcraft.com

Twitter: @sandromancuso