SlideShare une entreprise Scribd logo
1  sur  15
Value Objects
Make your code simpler
Who am I
Product Developer - Systems Architect - Freelancer - Development Manager
Past experience
Senior Developer for Cleverbug
Lecturer at the Digital Skills Academy
Director of Tercet, software development consultancy
Current position
Software Development Manager for OliveMedia
Barry O Sullivan
Design Patterns
When developing systems, there are common patterns of problems that
emerge.
Design patterns are common, named solutions to these problems.
The ValueObject pattern is one of these patterns.
It’s simple, easy to integrate and can bring a lot of clarity to your code with
minimal investment or technical overhead.
So lets get to it . . .
The Problem
public function change_name($firstname, $lastname)
{
if (!is_string($firstname) || $firstname == “”) {
throw new InvalidNameException(“Firstname is invalid”);
}
if (!is_string($lastname) || $lastname == “”) {
throw new InvalidNameException(“Lastname is invalid”);
}
$this->firstname = $firstname;
$this->lastname = $lastname;
}
Have you ever written code like this?
Guarding
This is called Guarding.
You are guarding against bad input
The idea is that you can’t trust the data sent by other
objects/developers, it might be invalid and break your
system, or worse, it might seem to work until it breaks
later. Guarding protects you against inconsistent state.
Guarding is as old as software development, it’s even
recommended in the Mythical Man Month, which is
nearly 40yrs old.
Too much guarding
The problem arises when you start adding this logic everywhere.
You end up with
• Duplicated code
• Messy Logic
• Poor legibility
Which leads to a system that’s very
difficult to modify and understand.
This leads to more bugs, not less.
The Solution
How do we solve this problem?
With encapsulation!
You create a class that represents the value.
On creation, it gets passed the basic types and it checks if they’re valid.
• If they are not, an exception is thrown.
• If they are, then the object is successfully created.
That’s the basic gist of it. Everywhere you need to ensure
data integrity, use one of these and you can guarantee
That the data is valid.
Example, Name as a ValueObject
class Name implements ValueObject
{
private $firstname;
private $lastname;
public function __construct($firstname, $lastname)
{
if (!is_string($firstname) || $firstname == “”) {
throw new InvalidNameException(“Firstname ‘$firstname’ is invalid”);
}
if (!is_string($lastname) || $lastname == “”) {
throw new InvalidNameException(“Lastname ‘$lastname is invalid”);
}
$this->firstname = $firstname;
$this->lastname = $lastname;
}
………
Using the Name ValueObject
//Controller method to change name
public function change_name()
{
$user = $this->user_repository->fetch($this->user_id);
$name = new Name(Input::get(‘firstname’), Input::get(‘lastname’));
$user->change_name($name);
$this->user_repository->store($user);
}
. . . . . .
//Then in our User class
public function change_name(Name $name)
{
$this->name = $name;
}
ValueObjects represent the value
Key Concept:
A value object represents the value,
not the data contained within it.
You shouldn’t care about the internal data when using VOs for business logic.
When you want to reference a value, use a value object.
The only place the internals matter is when you’re encoding/decoding them for
transmission (JSON/HTML) or storage (MySQL/REDIS), nowhere else.
ValueObjects in the wild
1. They are immutable
Once set, you cannot change their values.
In other words, you cannot change their state.
If you need to change one, simply create a new one and replace the
reference to the old one.
2. They are comparable
Two value objects of the same type can be
compared to check their values. This makes
business rules easier to build and check.
(Works a treat with the specification pattern)
Some examples of ValueObjects
• Email address
• Price (Amount + Currency)
• ID
• Country Code
• TestScore
• Discount
• Perspiration
NB: Usually you would not use a ValueObject to represent a user, since a user
can change state. User should be an entity that uses VOs internally.
Quick Recap:
ValueObjects . . .
• Encapsulate a self contained value
• Allow you to guard against bad input
• Represent the value, not the data within
• Are immutable
• Make code and system design much easier, leading to
more structured system that’s easier to maintain.
More reading
If you’re interested in learning more about this
pattern and others like it, I’d recommend
looking into “Domain Driven Design”,
specifically Eric Evans book.
It’s a how-to book on using this pattern and
others like it to build large scale, distributed
micro-services.
Thanks for listening
Any questions?
Barry O Sullivan – barry@tercet.io - http://barryosullivan.me

Contenu connexe

Tendances

Advanced Object-Oriented/SOLID Principles
Advanced Object-Oriented/SOLID PrinciplesAdvanced Object-Oriented/SOLID Principles
Advanced Object-Oriented/SOLID PrinciplesJon Kruger
 
object oriented programming(PYTHON)
object oriented programming(PYTHON)object oriented programming(PYTHON)
object oriented programming(PYTHON)Jyoti shukla
 
"SOLID" Object Oriented Design Principles
"SOLID" Object Oriented Design Principles"SOLID" Object Oriented Design Principles
"SOLID" Object Oriented Design PrinciplesSerhiy Oplakanets
 
SOLID, DRY, SLAP design principles
SOLID, DRY, SLAP design principlesSOLID, DRY, SLAP design principles
SOLID, DRY, SLAP design principlesSergey Karpushin
 
Extending the Xbase Typesystem
Extending the Xbase TypesystemExtending the Xbase Typesystem
Extending the Xbase TypesystemSebastian Zarnekow
 
Object oreinted php | OOPs
Object oreinted php | OOPsObject oreinted php | OOPs
Object oreinted php | OOPsRavi Bhadauria
 
Introduction to Core Java Programming
Introduction to Core Java ProgrammingIntroduction to Core Java Programming
Introduction to Core Java ProgrammingRaveendra R
 
Beyond design patterns and principles - writing good OO code
Beyond design patterns and principles - writing good OO codeBeyond design patterns and principles - writing good OO code
Beyond design patterns and principles - writing good OO codeMatthias Noback
 
GeekAustin PHP Class - Session 6
GeekAustin PHP Class - Session 6GeekAustin PHP Class - Session 6
GeekAustin PHP Class - Session 6jimbojsb
 
Java essentials for hadoop
Java essentials for hadoopJava essentials for hadoop
Java essentials for hadoopSeo Gyansha
 
What does OOP stand for?
What does OOP stand for?What does OOP stand for?
What does OOP stand for?Colin Riley
 
Introduction to OOP with PHP
Introduction to OOP with PHPIntroduction to OOP with PHP
Introduction to OOP with PHPMichael Peacock
 
Java design patterns
Java design patternsJava design patterns
Java design patternsShawn Brito
 
Introduction to Object Oriented Concepts
Introduction to Object Oriented Concepts Introduction to Object Oriented Concepts
Introduction to Object Oriented Concepts Mamoun Nawahdah
 
Pursuing practices of Domain-Driven Design in PHP
Pursuing practices of Domain-Driven Design in PHPPursuing practices of Domain-Driven Design in PHP
Pursuing practices of Domain-Driven Design in PHPGiorgio Sironi
 

Tendances (20)

Advanced Object-Oriented/SOLID Principles
Advanced Object-Oriented/SOLID PrinciplesAdvanced Object-Oriented/SOLID Principles
Advanced Object-Oriented/SOLID Principles
 
object oriented programming(PYTHON)
object oriented programming(PYTHON)object oriented programming(PYTHON)
object oriented programming(PYTHON)
 
"SOLID" Object Oriented Design Principles
"SOLID" Object Oriented Design Principles"SOLID" Object Oriented Design Principles
"SOLID" Object Oriented Design Principles
 
SOLID, DRY, SLAP design principles
SOLID, DRY, SLAP design principlesSOLID, DRY, SLAP design principles
SOLID, DRY, SLAP design principles
 
Extending the Xbase Typesystem
Extending the Xbase TypesystemExtending the Xbase Typesystem
Extending the Xbase Typesystem
 
[OOP - Lec 06] Classes and Objects
[OOP - Lec 06] Classes and Objects[OOP - Lec 06] Classes and Objects
[OOP - Lec 06] Classes and Objects
 
Hibernate using jpa
Hibernate using jpaHibernate using jpa
Hibernate using jpa
 
Object oreinted php | OOPs
Object oreinted php | OOPsObject oreinted php | OOPs
Object oreinted php | OOPs
 
Introduction to Core Java Programming
Introduction to Core Java ProgrammingIntroduction to Core Java Programming
Introduction to Core Java Programming
 
Beyond design patterns and principles - writing good OO code
Beyond design patterns and principles - writing good OO codeBeyond design patterns and principles - writing good OO code
Beyond design patterns and principles - writing good OO code
 
GeekAustin PHP Class - Session 6
GeekAustin PHP Class - Session 6GeekAustin PHP Class - Session 6
GeekAustin PHP Class - Session 6
 
Java essentials for hadoop
Java essentials for hadoopJava essentials for hadoop
Java essentials for hadoop
 
OOPS Characteristics (With Examples in PHP)
OOPS Characteristics (With Examples in PHP)OOPS Characteristics (With Examples in PHP)
OOPS Characteristics (With Examples in PHP)
 
What does OOP stand for?
What does OOP stand for?What does OOP stand for?
What does OOP stand for?
 
Introduction to OOP with PHP
Introduction to OOP with PHPIntroduction to OOP with PHP
Introduction to OOP with PHP
 
Java design patterns
Java design patternsJava design patterns
Java design patterns
 
Java Basic
Java Basic Java Basic
Java Basic
 
Introduction to JPA Framework
Introduction to JPA FrameworkIntroduction to JPA Framework
Introduction to JPA Framework
 
Introduction to Object Oriented Concepts
Introduction to Object Oriented Concepts Introduction to Object Oriented Concepts
Introduction to Object Oriented Concepts
 
Pursuing practices of Domain-Driven Design in PHP
Pursuing practices of Domain-Driven Design in PHPPursuing practices of Domain-Driven Design in PHP
Pursuing practices of Domain-Driven Design in PHP
 

En vedette

Serializing Value Objects-Ara Hacopian
Serializing Value Objects-Ara HacopianSerializing Value Objects-Ara Hacopian
Serializing Value Objects-Ara HacopianSmartLogic
 
#pugMi - DDD - Value objects
#pugMi - DDD - Value objects#pugMi - DDD - Value objects
#pugMi - DDD - Value objectsSimone Gentili
 
Value Objects, Full Throttle (to be updated for spring TC39 meetings)
Value Objects, Full Throttle (to be updated for spring TC39 meetings)Value Objects, Full Throttle (to be updated for spring TC39 meetings)
Value Objects, Full Throttle (to be updated for spring TC39 meetings)Brendan Eich
 
Value objects in JS - an ES7 work in progress
Value objects in JS - an ES7 work in progressValue objects in JS - an ES7 work in progress
Value objects in JS - an ES7 work in progressBrendan Eich
 
A System Is Not a Tree
A System Is Not a TreeA System Is Not a Tree
A System Is Not a TreeKevlin Henney
 
Aggregates, Entities and Value objects - Devnology 2010 community day
Aggregates, Entities and Value objects - Devnology 2010 community dayAggregates, Entities and Value objects - Devnology 2010 community day
Aggregates, Entities and Value objects - Devnology 2010 community dayRick van der Arend
 

En vedette (8)

Values
ValuesValues
Values
 
Serializing Value Objects-Ara Hacopian
Serializing Value Objects-Ara HacopianSerializing Value Objects-Ara Hacopian
Serializing Value Objects-Ara Hacopian
 
#pugMi - DDD - Value objects
#pugMi - DDD - Value objects#pugMi - DDD - Value objects
#pugMi - DDD - Value objects
 
Value Objects, Full Throttle (to be updated for spring TC39 meetings)
Value Objects, Full Throttle (to be updated for spring TC39 meetings)Value Objects, Full Throttle (to be updated for spring TC39 meetings)
Value Objects, Full Throttle (to be updated for spring TC39 meetings)
 
Value objects in JS - an ES7 work in progress
Value objects in JS - an ES7 work in progressValue objects in JS - an ES7 work in progress
Value objects in JS - an ES7 work in progress
 
Persisting Value Objects
Persisting Value ObjectsPersisting Value Objects
Persisting Value Objects
 
A System Is Not a Tree
A System Is Not a TreeA System Is Not a Tree
A System Is Not a Tree
 
Aggregates, Entities and Value objects - Devnology 2010 community day
Aggregates, Entities and Value objects - Devnology 2010 community dayAggregates, Entities and Value objects - Devnology 2010 community day
Aggregates, Entities and Value objects - Devnology 2010 community day
 

Similaire à Value Objects

The quest for global design principles (SymfonyLive Berlin 2015)
The quest for global design principles (SymfonyLive Berlin 2015)The quest for global design principles (SymfonyLive Berlin 2015)
The quest for global design principles (SymfonyLive Berlin 2015)Matthias Noback
 
How I Learned to Stop Worrying and Love Legacy Code - Ox:Agile 2018
How I Learned to Stop Worrying and Love Legacy Code - Ox:Agile 2018How I Learned to Stop Worrying and Love Legacy Code - Ox:Agile 2018
How I Learned to Stop Worrying and Love Legacy Code - Ox:Agile 2018Mike Harris
 
The quest for global design principles - PHP Benelux 2016
The quest for global design principles - PHP Benelux 2016The quest for global design principles - PHP Benelux 2016
The quest for global design principles - PHP Benelux 2016Matthias Noback
 
AJS UNIT-1 2021-converted.pdf
AJS UNIT-1 2021-converted.pdfAJS UNIT-1 2021-converted.pdf
AJS UNIT-1 2021-converted.pdfSreeVani74
 
Building Better Applications with Data::Manager
Building Better Applications with Data::ManagerBuilding Better Applications with Data::Manager
Building Better Applications with Data::ManagerJay Shirley
 
What You Missed in Computer Science
What You Missed in Computer ScienceWhat You Missed in Computer Science
What You Missed in Computer ScienceTaylor Lovett
 
The Quest for Global Design Principles
The Quest for Global Design PrinciplesThe Quest for Global Design Principles
The Quest for Global Design PrinciplesMatthias Noback
 
New Ideas for Old Code - Greach
New Ideas for Old Code - GreachNew Ideas for Old Code - Greach
New Ideas for Old Code - GreachHamletDRC
 
ER diagram slides for datanase stujdy-1.pdf
ER diagram slides for datanase stujdy-1.pdfER diagram slides for datanase stujdy-1.pdf
ER diagram slides for datanase stujdy-1.pdfSadiaSharmin40
 
Data weave 2.0 language fundamentals
Data weave 2.0 language fundamentalsData weave 2.0 language fundamentals
Data weave 2.0 language fundamentalsManjuKumara GH
 
Writing maintainable Oracle PL/SQL code
Writing maintainable Oracle PL/SQL codeWriting maintainable Oracle PL/SQL code
Writing maintainable Oracle PL/SQL codeDonald Bales
 
Writing Maintainable Code
Writing Maintainable CodeWriting Maintainable Code
Writing Maintainable CodeDonald Bales
 
Introduction to Machine Learning
Introduction to Machine LearningIntroduction to Machine Learning
Introduction to Machine LearningRahul Jain
 
Professional Code Reviews - Bogdan Gusiev
Professional Code Reviews - Bogdan GusievProfessional Code Reviews - Bogdan Gusiev
Professional Code Reviews - Bogdan GusievRuby Meditation
 
AEM Clean Code - Miklos Csere
AEM Clean Code - Miklos Csere AEM Clean Code - Miklos Csere
AEM Clean Code - Miklos Csere Miklos Csere
 
Roy Osherove on Unit Testing Good Practices and Horrible Mistakes
Roy Osherove on Unit Testing Good Practices and Horrible MistakesRoy Osherove on Unit Testing Good Practices and Horrible Mistakes
Roy Osherove on Unit Testing Good Practices and Horrible MistakesRoy Osherove
 
JavaScript Fundamentals & JQuery
JavaScript Fundamentals & JQueryJavaScript Fundamentals & JQuery
JavaScript Fundamentals & JQueryJamshid Hashimi
 

Similaire à Value Objects (20)

Value objects
Value objectsValue objects
Value objects
 
The quest for global design principles (SymfonyLive Berlin 2015)
The quest for global design principles (SymfonyLive Berlin 2015)The quest for global design principles (SymfonyLive Berlin 2015)
The quest for global design principles (SymfonyLive Berlin 2015)
 
How I Learned to Stop Worrying and Love Legacy Code - Ox:Agile 2018
How I Learned to Stop Worrying and Love Legacy Code - Ox:Agile 2018How I Learned to Stop Worrying and Love Legacy Code - Ox:Agile 2018
How I Learned to Stop Worrying and Love Legacy Code - Ox:Agile 2018
 
The quest for global design principles - PHP Benelux 2016
The quest for global design principles - PHP Benelux 2016The quest for global design principles - PHP Benelux 2016
The quest for global design principles - PHP Benelux 2016
 
AJS UNIT-1 2021-converted.pdf
AJS UNIT-1 2021-converted.pdfAJS UNIT-1 2021-converted.pdf
AJS UNIT-1 2021-converted.pdf
 
Clean code
Clean codeClean code
Clean code
 
Building Better Applications with Data::Manager
Building Better Applications with Data::ManagerBuilding Better Applications with Data::Manager
Building Better Applications with Data::Manager
 
What You Missed in Computer Science
What You Missed in Computer ScienceWhat You Missed in Computer Science
What You Missed in Computer Science
 
The Quest for Global Design Principles
The Quest for Global Design PrinciplesThe Quest for Global Design Principles
The Quest for Global Design Principles
 
New Ideas for Old Code - Greach
New Ideas for Old Code - GreachNew Ideas for Old Code - Greach
New Ideas for Old Code - Greach
 
ER diagram slides for datanase stujdy-1.pdf
ER diagram slides for datanase stujdy-1.pdfER diagram slides for datanase stujdy-1.pdf
ER diagram slides for datanase stujdy-1.pdf
 
Data weave 2.0 language fundamentals
Data weave 2.0 language fundamentalsData weave 2.0 language fundamentals
Data weave 2.0 language fundamentals
 
Writing maintainable Oracle PL/SQL code
Writing maintainable Oracle PL/SQL codeWriting maintainable Oracle PL/SQL code
Writing maintainable Oracle PL/SQL code
 
Writing Maintainable Code
Writing Maintainable CodeWriting Maintainable Code
Writing Maintainable Code
 
Introduction to Machine Learning
Introduction to Machine LearningIntroduction to Machine Learning
Introduction to Machine Learning
 
Professional Code Reviews - Bogdan Gusiev
Professional Code Reviews - Bogdan GusievProfessional Code Reviews - Bogdan Gusiev
Professional Code Reviews - Bogdan Gusiev
 
AEM Clean Code - Miklos Csere
AEM Clean Code - Miklos Csere AEM Clean Code - Miklos Csere
AEM Clean Code - Miklos Csere
 
Roy Osherove on Unit Testing Good Practices and Horrible Mistakes
Roy Osherove on Unit Testing Good Practices and Horrible MistakesRoy Osherove on Unit Testing Good Practices and Horrible Mistakes
Roy Osherove on Unit Testing Good Practices and Horrible Mistakes
 
Why Our Code Smells
Why Our Code SmellsWhy Our Code Smells
Why Our Code Smells
 
JavaScript Fundamentals & JQuery
JavaScript Fundamentals & JQueryJavaScript Fundamentals & JQuery
JavaScript Fundamentals & JQuery
 

Dernier

How to submit a standout Adobe Champion Application
How to submit a standout Adobe Champion ApplicationHow to submit a standout Adobe Champion Application
How to submit a standout Adobe Champion ApplicationBradBedford3
 
SuccessFactors 1H 2024 Release - Sneak-Peek by Deloitte Germany
SuccessFactors 1H 2024 Release - Sneak-Peek by Deloitte GermanySuccessFactors 1H 2024 Release - Sneak-Peek by Deloitte Germany
SuccessFactors 1H 2024 Release - Sneak-Peek by Deloitte GermanyChristoph Pohl
 
A healthy diet for your Java application Devoxx France.pdf
A healthy diet for your Java application Devoxx France.pdfA healthy diet for your Java application Devoxx France.pdf
A healthy diet for your Java application Devoxx France.pdfMarharyta Nedzelska
 
Call Us🔝>༒+91-9711147426⇛Call In girls karol bagh (Delhi)
Call Us🔝>༒+91-9711147426⇛Call In girls karol bagh (Delhi)Call Us🔝>༒+91-9711147426⇛Call In girls karol bagh (Delhi)
Call Us🔝>༒+91-9711147426⇛Call In girls karol bagh (Delhi)jennyeacort
 
Xen Safety Embedded OSS Summit April 2024 v4.pdf
Xen Safety Embedded OSS Summit April 2024 v4.pdfXen Safety Embedded OSS Summit April 2024 v4.pdf
Xen Safety Embedded OSS Summit April 2024 v4.pdfStefano Stabellini
 
EY_Graph Database Powered Sustainability
EY_Graph Database Powered SustainabilityEY_Graph Database Powered Sustainability
EY_Graph Database Powered SustainabilityNeo4j
 
Folding Cheat Sheet #4 - fourth in a series
Folding Cheat Sheet #4 - fourth in a seriesFolding Cheat Sheet #4 - fourth in a series
Folding Cheat Sheet #4 - fourth in a seriesPhilip Schwarz
 
SpotFlow: Tracking Method Calls and States at Runtime
SpotFlow: Tracking Method Calls and States at RuntimeSpotFlow: Tracking Method Calls and States at Runtime
SpotFlow: Tracking Method Calls and States at Runtimeandrehoraa
 
办理学位证(UQ文凭证书)昆士兰大学毕业证成绩单原版一模一样
办理学位证(UQ文凭证书)昆士兰大学毕业证成绩单原版一模一样办理学位证(UQ文凭证书)昆士兰大学毕业证成绩单原版一模一样
办理学位证(UQ文凭证书)昆士兰大学毕业证成绩单原版一模一样umasea
 
MYjobs Presentation Django-based project
MYjobs Presentation Django-based projectMYjobs Presentation Django-based project
MYjobs Presentation Django-based projectAnoyGreter
 
Buds n Tech IT Solutions: Top-Notch Web Services in Noida
Buds n Tech IT Solutions: Top-Notch Web Services in NoidaBuds n Tech IT Solutions: Top-Notch Web Services in Noida
Buds n Tech IT Solutions: Top-Notch Web Services in Noidabntitsolutionsrishis
 
React Server Component in Next.js by Hanief Utama
React Server Component in Next.js by Hanief UtamaReact Server Component in Next.js by Hanief Utama
React Server Component in Next.js by Hanief UtamaHanief Utama
 
Building a General PDE Solving Framework with Symbolic-Numeric Scientific Mac...
Building a General PDE Solving Framework with Symbolic-Numeric Scientific Mac...Building a General PDE Solving Framework with Symbolic-Numeric Scientific Mac...
Building a General PDE Solving Framework with Symbolic-Numeric Scientific Mac...stazi3110
 
Alluxio Monthly Webinar | Cloud-Native Model Training on Distributed Data
Alluxio Monthly Webinar | Cloud-Native Model Training on Distributed DataAlluxio Monthly Webinar | Cloud-Native Model Training on Distributed Data
Alluxio Monthly Webinar | Cloud-Native Model Training on Distributed DataAlluxio, Inc.
 
Dealing with Cultural Dispersion — Stefano Lambiase — ICSE-SEIS 2024
Dealing with Cultural Dispersion — Stefano Lambiase — ICSE-SEIS 2024Dealing with Cultural Dispersion — Stefano Lambiase — ICSE-SEIS 2024
Dealing with Cultural Dispersion — Stefano Lambiase — ICSE-SEIS 2024StefanoLambiase
 
GOING AOT WITH GRAALVM – DEVOXX GREECE.pdf
GOING AOT WITH GRAALVM – DEVOXX GREECE.pdfGOING AOT WITH GRAALVM – DEVOXX GREECE.pdf
GOING AOT WITH GRAALVM – DEVOXX GREECE.pdfAlina Yurenko
 
CRM Contender Series: HubSpot vs. Salesforce
CRM Contender Series: HubSpot vs. SalesforceCRM Contender Series: HubSpot vs. Salesforce
CRM Contender Series: HubSpot vs. SalesforceBrainSell Technologies
 
Taming Distributed Systems: Key Insights from Wix's Large-Scale Experience - ...
Taming Distributed Systems: Key Insights from Wix's Large-Scale Experience - ...Taming Distributed Systems: Key Insights from Wix's Large-Scale Experience - ...
Taming Distributed Systems: Key Insights from Wix's Large-Scale Experience - ...Natan Silnitsky
 
Best Web Development Agency- Idiosys USA.pdf
Best Web Development Agency- Idiosys USA.pdfBest Web Development Agency- Idiosys USA.pdf
Best Web Development Agency- Idiosys USA.pdfIdiosysTechnologies1
 

Dernier (20)

How to submit a standout Adobe Champion Application
How to submit a standout Adobe Champion ApplicationHow to submit a standout Adobe Champion Application
How to submit a standout Adobe Champion Application
 
SuccessFactors 1H 2024 Release - Sneak-Peek by Deloitte Germany
SuccessFactors 1H 2024 Release - Sneak-Peek by Deloitte GermanySuccessFactors 1H 2024 Release - Sneak-Peek by Deloitte Germany
SuccessFactors 1H 2024 Release - Sneak-Peek by Deloitte Germany
 
A healthy diet for your Java application Devoxx France.pdf
A healthy diet for your Java application Devoxx France.pdfA healthy diet for your Java application Devoxx France.pdf
A healthy diet for your Java application Devoxx France.pdf
 
Call Us🔝>༒+91-9711147426⇛Call In girls karol bagh (Delhi)
Call Us🔝>༒+91-9711147426⇛Call In girls karol bagh (Delhi)Call Us🔝>༒+91-9711147426⇛Call In girls karol bagh (Delhi)
Call Us🔝>༒+91-9711147426⇛Call In girls karol bagh (Delhi)
 
Xen Safety Embedded OSS Summit April 2024 v4.pdf
Xen Safety Embedded OSS Summit April 2024 v4.pdfXen Safety Embedded OSS Summit April 2024 v4.pdf
Xen Safety Embedded OSS Summit April 2024 v4.pdf
 
EY_Graph Database Powered Sustainability
EY_Graph Database Powered SustainabilityEY_Graph Database Powered Sustainability
EY_Graph Database Powered Sustainability
 
Folding Cheat Sheet #4 - fourth in a series
Folding Cheat Sheet #4 - fourth in a seriesFolding Cheat Sheet #4 - fourth in a series
Folding Cheat Sheet #4 - fourth in a series
 
SpotFlow: Tracking Method Calls and States at Runtime
SpotFlow: Tracking Method Calls and States at RuntimeSpotFlow: Tracking Method Calls and States at Runtime
SpotFlow: Tracking Method Calls and States at Runtime
 
办理学位证(UQ文凭证书)昆士兰大学毕业证成绩单原版一模一样
办理学位证(UQ文凭证书)昆士兰大学毕业证成绩单原版一模一样办理学位证(UQ文凭证书)昆士兰大学毕业证成绩单原版一模一样
办理学位证(UQ文凭证书)昆士兰大学毕业证成绩单原版一模一样
 
MYjobs Presentation Django-based project
MYjobs Presentation Django-based projectMYjobs Presentation Django-based project
MYjobs Presentation Django-based project
 
2.pdf Ejercicios de programación competitiva
2.pdf Ejercicios de programación competitiva2.pdf Ejercicios de programación competitiva
2.pdf Ejercicios de programación competitiva
 
Buds n Tech IT Solutions: Top-Notch Web Services in Noida
Buds n Tech IT Solutions: Top-Notch Web Services in NoidaBuds n Tech IT Solutions: Top-Notch Web Services in Noida
Buds n Tech IT Solutions: Top-Notch Web Services in Noida
 
React Server Component in Next.js by Hanief Utama
React Server Component in Next.js by Hanief UtamaReact Server Component in Next.js by Hanief Utama
React Server Component in Next.js by Hanief Utama
 
Building a General PDE Solving Framework with Symbolic-Numeric Scientific Mac...
Building a General PDE Solving Framework with Symbolic-Numeric Scientific Mac...Building a General PDE Solving Framework with Symbolic-Numeric Scientific Mac...
Building a General PDE Solving Framework with Symbolic-Numeric Scientific Mac...
 
Alluxio Monthly Webinar | Cloud-Native Model Training on Distributed Data
Alluxio Monthly Webinar | Cloud-Native Model Training on Distributed DataAlluxio Monthly Webinar | Cloud-Native Model Training on Distributed Data
Alluxio Monthly Webinar | Cloud-Native Model Training on Distributed Data
 
Dealing with Cultural Dispersion — Stefano Lambiase — ICSE-SEIS 2024
Dealing with Cultural Dispersion — Stefano Lambiase — ICSE-SEIS 2024Dealing with Cultural Dispersion — Stefano Lambiase — ICSE-SEIS 2024
Dealing with Cultural Dispersion — Stefano Lambiase — ICSE-SEIS 2024
 
GOING AOT WITH GRAALVM – DEVOXX GREECE.pdf
GOING AOT WITH GRAALVM – DEVOXX GREECE.pdfGOING AOT WITH GRAALVM – DEVOXX GREECE.pdf
GOING AOT WITH GRAALVM – DEVOXX GREECE.pdf
 
CRM Contender Series: HubSpot vs. Salesforce
CRM Contender Series: HubSpot vs. SalesforceCRM Contender Series: HubSpot vs. Salesforce
CRM Contender Series: HubSpot vs. Salesforce
 
Taming Distributed Systems: Key Insights from Wix's Large-Scale Experience - ...
Taming Distributed Systems: Key Insights from Wix's Large-Scale Experience - ...Taming Distributed Systems: Key Insights from Wix's Large-Scale Experience - ...
Taming Distributed Systems: Key Insights from Wix's Large-Scale Experience - ...
 
Best Web Development Agency- Idiosys USA.pdf
Best Web Development Agency- Idiosys USA.pdfBest Web Development Agency- Idiosys USA.pdf
Best Web Development Agency- Idiosys USA.pdf
 

Value Objects

  • 1. Value Objects Make your code simpler
  • 2. Who am I Product Developer - Systems Architect - Freelancer - Development Manager Past experience Senior Developer for Cleverbug Lecturer at the Digital Skills Academy Director of Tercet, software development consultancy Current position Software Development Manager for OliveMedia Barry O Sullivan
  • 3. Design Patterns When developing systems, there are common patterns of problems that emerge. Design patterns are common, named solutions to these problems. The ValueObject pattern is one of these patterns. It’s simple, easy to integrate and can bring a lot of clarity to your code with minimal investment or technical overhead. So lets get to it . . .
  • 4. The Problem public function change_name($firstname, $lastname) { if (!is_string($firstname) || $firstname == “”) { throw new InvalidNameException(“Firstname is invalid”); } if (!is_string($lastname) || $lastname == “”) { throw new InvalidNameException(“Lastname is invalid”); } $this->firstname = $firstname; $this->lastname = $lastname; } Have you ever written code like this?
  • 5. Guarding This is called Guarding. You are guarding against bad input The idea is that you can’t trust the data sent by other objects/developers, it might be invalid and break your system, or worse, it might seem to work until it breaks later. Guarding protects you against inconsistent state. Guarding is as old as software development, it’s even recommended in the Mythical Man Month, which is nearly 40yrs old.
  • 6. Too much guarding The problem arises when you start adding this logic everywhere. You end up with • Duplicated code • Messy Logic • Poor legibility Which leads to a system that’s very difficult to modify and understand. This leads to more bugs, not less.
  • 7. The Solution How do we solve this problem? With encapsulation! You create a class that represents the value. On creation, it gets passed the basic types and it checks if they’re valid. • If they are not, an exception is thrown. • If they are, then the object is successfully created. That’s the basic gist of it. Everywhere you need to ensure data integrity, use one of these and you can guarantee That the data is valid.
  • 8. Example, Name as a ValueObject class Name implements ValueObject { private $firstname; private $lastname; public function __construct($firstname, $lastname) { if (!is_string($firstname) || $firstname == “”) { throw new InvalidNameException(“Firstname ‘$firstname’ is invalid”); } if (!is_string($lastname) || $lastname == “”) { throw new InvalidNameException(“Lastname ‘$lastname is invalid”); } $this->firstname = $firstname; $this->lastname = $lastname; } ………
  • 9. Using the Name ValueObject //Controller method to change name public function change_name() { $user = $this->user_repository->fetch($this->user_id); $name = new Name(Input::get(‘firstname’), Input::get(‘lastname’)); $user->change_name($name); $this->user_repository->store($user); } . . . . . . //Then in our User class public function change_name(Name $name) { $this->name = $name; }
  • 10. ValueObjects represent the value Key Concept: A value object represents the value, not the data contained within it. You shouldn’t care about the internal data when using VOs for business logic. When you want to reference a value, use a value object. The only place the internals matter is when you’re encoding/decoding them for transmission (JSON/HTML) or storage (MySQL/REDIS), nowhere else.
  • 11. ValueObjects in the wild 1. They are immutable Once set, you cannot change their values. In other words, you cannot change their state. If you need to change one, simply create a new one and replace the reference to the old one. 2. They are comparable Two value objects of the same type can be compared to check their values. This makes business rules easier to build and check. (Works a treat with the specification pattern)
  • 12. Some examples of ValueObjects • Email address • Price (Amount + Currency) • ID • Country Code • TestScore • Discount • Perspiration NB: Usually you would not use a ValueObject to represent a user, since a user can change state. User should be an entity that uses VOs internally.
  • 13. Quick Recap: ValueObjects . . . • Encapsulate a self contained value • Allow you to guard against bad input • Represent the value, not the data within • Are immutable • Make code and system design much easier, leading to more structured system that’s easier to maintain.
  • 14. More reading If you’re interested in learning more about this pattern and others like it, I’d recommend looking into “Domain Driven Design”, specifically Eric Evans book. It’s a how-to book on using this pattern and others like it to build large scale, distributed micro-services.
  • 15. Thanks for listening Any questions? Barry O Sullivan – barry@tercet.io - http://barryosullivan.me