SlideShare a Scribd company logo
Mutation and immutability
2
Mutation
 mutation: A modification to the state of an object.
 Mutation must be done with care.
 Can the object's state be damaged?
 Is the old state important? Is it okay to "lose" it?
 Do any other clients depend on this object?
 Do they expect that its state will not change?
3
Immutable classes
 immutable: Unable to be changed (mutated).
 Basic idea: A class with no "set" methods (mutators).
 In Java, Strings are immutable.
 Many methods appear to "modify" a string.
 But actually, they create and return a new string (producers).
4
"Modifying" strings
 What is the output of this code?
String name = "lil bow wow";
name.toUpperCase();
System.out.println(name);
 The code outputs lil bow wow in lowercase.
 To capitalize it, we must reassign the string:
name = name.toUpperCase();
 The toUpperCase method is a producer, not a mutator.
5
If Strings were mutable...
 What could go wrong if strings were mutable?
public Employee(String name, ...) {
this.name = name;
...
}
public String getName() {
return name;
}
 A client could accidentally damage the Employee's name.
String s = myEmployee.getName();
s.substring(0, s.indexOf(" ")); // first name
s.toUpperCase();
6
Making a class immutable
 1. Don't provide any methods that modify the object's state.
 2. Ensure that the class cannot be extended. (later)
 3. Make all fields final.
 4. Make all fields private. (ensure encapsulation)
 5. Ensure exclusive access to any mutable object fields.
 Don't let a client get a reference to a field that is a mutable
object.
(Don't allow any mutable representation exposure.)
7
Mutable Fraction class
public class Fraction {
private int numerator, denominator;
public Fraction(int n)
public Fraction(int n, int d)
public int getNumerator(), getDenominator()
public void add(Fraction other) {
numerator = numerator * other.denominator
+ other.numerator * denominator;
denominator = denominator * other.denominator;
}
}
8
Immutable methods
// mutable version
public void add(Fraction other) {
numerator = numerator * other.denominator
+ other.numerator * denominator;
denominator = denominator * other.denominator;
}
// immutable version
public Fraction add(Fraction other) {
int n = numerator * other.denominator
+ other.numerator * denominator;
int d = denominator * other.denominator;
return new Fraction(n, d);
}
 former mutators become producers
 create/return a new immutable object rather than modifying
this one
9
Pros/cons of immutability
 Immutable objects are simple.
 You know what state they're in (the state in which they were
born).
 Immutable objects can be freely shared among code.
 You can pass them, return them, etc. without fear of damage.
 Con: Immutable objects can consume more memory.
 Need a unique instance for each unique abstract value used.
10
END

More Related Content

Similar to Immutable Classes updated.ppt

Ppt on java basics1
Ppt on java basics1Ppt on java basics1
Ppt on java basics1
Mavoori Soshmitha
 
Structured Languages
Structured LanguagesStructured Languages
Structured Languages
Mufaddal Nullwala
 
CJP Unit-1 contd.pptx
CJP Unit-1 contd.pptxCJP Unit-1 contd.pptx
CJP Unit-1 contd.pptx
RAJASEKHARV10
 
Java
JavaJava
Unit 2-data types,Variables,Operators,Conitionals,loops and arrays
Unit 2-data types,Variables,Operators,Conitionals,loops and arraysUnit 2-data types,Variables,Operators,Conitionals,loops and arrays
Unit 2-data types,Variables,Operators,Conitionals,loops and arrays
DevaKumari Vijay
 
Defining classes-and-objects-1.0
Defining classes-and-objects-1.0Defining classes-and-objects-1.0
Defining classes-and-objects-1.0
BG Java EE Course
 
Unit vi(dsc++)
Unit vi(dsc++)Unit vi(dsc++)
Unit vi(dsc++)
Durga Devi
 
Core java interview questions1
Core java interview questions1Core java interview questions1
Core java interview questions1Lahari Reddy
 
Smart material - Unit 2 (1).pdf
Smart material - Unit 2 (1).pdfSmart material - Unit 2 (1).pdf
Smart material - Unit 2 (1).pdf
GayathriRHICETCSESTA
 
Smart material - Unit 2 (1).pdf
Smart material - Unit 2 (1).pdfSmart material - Unit 2 (1).pdf
Smart material - Unit 2 (1).pdf
GayathriRHICETCSESTA
 
Classes & Interfaces
Classes & InterfacesClasses & Interfaces
Classes & Interfaces
Sandeep Chawla
 
Chapter 02: Classes Objects and Methods Java by Tushar B Kute
Chapter 02: Classes Objects and Methods Java by Tushar B KuteChapter 02: Classes Objects and Methods Java by Tushar B Kute
Chapter 02: Classes Objects and Methods Java by Tushar B Kute
Tushar B Kute
 
Lesson10 behavioral patterns
Lesson10 behavioral patternsLesson10 behavioral patterns
Lesson10 behavioral patterns
OktJona
 
Java data types, variables and jvm
Java data types, variables and jvm Java data types, variables and jvm
Java data types, variables and jvm
Madishetty Prathibha
 
Dotnet programming concepts difference faqs- 2
Dotnet programming concepts difference faqs- 2Dotnet programming concepts difference faqs- 2
Dotnet programming concepts difference faqs- 2Umar Ali
 
Python day2
Python day2Python day2
Python day2
Mantavya Gajjar
 
python interview prep question , 52 questions
python interview prep question , 52 questionspython interview prep question , 52 questions
python interview prep question , 52 questions
gokul174578
 

Similar to Immutable Classes updated.ppt (20)

Ppt on java basics1
Ppt on java basics1Ppt on java basics1
Ppt on java basics1
 
Structured Languages
Structured LanguagesStructured Languages
Structured Languages
 
Clean code
Clean codeClean code
Clean code
 
CJP Unit-1 contd.pptx
CJP Unit-1 contd.pptxCJP Unit-1 contd.pptx
CJP Unit-1 contd.pptx
 
Java
JavaJava
Java
 
Unit 2-data types,Variables,Operators,Conitionals,loops and arrays
Unit 2-data types,Variables,Operators,Conitionals,loops and arraysUnit 2-data types,Variables,Operators,Conitionals,loops and arrays
Unit 2-data types,Variables,Operators,Conitionals,loops and arrays
 
Defining classes-and-objects-1.0
Defining classes-and-objects-1.0Defining classes-and-objects-1.0
Defining classes-and-objects-1.0
 
Unit vi(dsc++)
Unit vi(dsc++)Unit vi(dsc++)
Unit vi(dsc++)
 
Core java interview questions1
Core java interview questions1Core java interview questions1
Core java interview questions1
 
Smart material - Unit 2 (1).pdf
Smart material - Unit 2 (1).pdfSmart material - Unit 2 (1).pdf
Smart material - Unit 2 (1).pdf
 
Smart material - Unit 2 (1).pdf
Smart material - Unit 2 (1).pdfSmart material - Unit 2 (1).pdf
Smart material - Unit 2 (1).pdf
 
Classes & Interfaces
Classes & InterfacesClasses & Interfaces
Classes & Interfaces
 
Chapter 02: Classes Objects and Methods Java by Tushar B Kute
Chapter 02: Classes Objects and Methods Java by Tushar B KuteChapter 02: Classes Objects and Methods Java by Tushar B Kute
Chapter 02: Classes Objects and Methods Java by Tushar B Kute
 
Lesson10 behavioral patterns
Lesson10 behavioral patternsLesson10 behavioral patterns
Lesson10 behavioral patterns
 
Md03 - part3
Md03 - part3Md03 - part3
Md03 - part3
 
Java data types, variables and jvm
Java data types, variables and jvm Java data types, variables and jvm
Java data types, variables and jvm
 
Dotnet programming concepts difference faqs- 2
Dotnet programming concepts difference faqs- 2Dotnet programming concepts difference faqs- 2
Dotnet programming concepts difference faqs- 2
 
Python day2
Python day2Python day2
Python day2
 
Hemajava
HemajavaHemajava
Hemajava
 
python interview prep question , 52 questions
python interview prep question , 52 questionspython interview prep question , 52 questions
python interview prep question , 52 questions
 

Recently uploaded

Digital Artifact 2 - Investigating Pavilion Designs
Digital Artifact 2 - Investigating Pavilion DesignsDigital Artifact 2 - Investigating Pavilion Designs
Digital Artifact 2 - Investigating Pavilion Designs
chanes7
 
A Survey of Techniques for Maximizing LLM Performance.pptx
A Survey of Techniques for Maximizing LLM Performance.pptxA Survey of Techniques for Maximizing LLM Performance.pptx
A Survey of Techniques for Maximizing LLM Performance.pptx
thanhdowork
 
MATATAG CURRICULUM: ASSESSING THE READINESS OF ELEM. PUBLIC SCHOOL TEACHERS I...
MATATAG CURRICULUM: ASSESSING THE READINESS OF ELEM. PUBLIC SCHOOL TEACHERS I...MATATAG CURRICULUM: ASSESSING THE READINESS OF ELEM. PUBLIC SCHOOL TEACHERS I...
MATATAG CURRICULUM: ASSESSING THE READINESS OF ELEM. PUBLIC SCHOOL TEACHERS I...
NelTorrente
 
Thesis Statement for students diagnonsed withADHD.ppt
Thesis Statement for students diagnonsed withADHD.pptThesis Statement for students diagnonsed withADHD.ppt
Thesis Statement for students diagnonsed withADHD.ppt
EverAndrsGuerraGuerr
 
PCOS corelations and management through Ayurveda.
PCOS corelations and management through Ayurveda.PCOS corelations and management through Ayurveda.
PCOS corelations and management through Ayurveda.
Dr. Shivangi Singh Parihar
 
Mule 4.6 & Java 17 Upgrade | MuleSoft Mysore Meetup #46
Mule 4.6 & Java 17 Upgrade | MuleSoft Mysore Meetup #46Mule 4.6 & Java 17 Upgrade | MuleSoft Mysore Meetup #46
Mule 4.6 & Java 17 Upgrade | MuleSoft Mysore Meetup #46
MysoreMuleSoftMeetup
 
A Strategic Approach: GenAI in Education
A Strategic Approach: GenAI in EducationA Strategic Approach: GenAI in Education
A Strategic Approach: GenAI in Education
Peter Windle
 
World environment day ppt For 5 June 2024
World environment day ppt For 5 June 2024World environment day ppt For 5 June 2024
World environment day ppt For 5 June 2024
ak6969907
 
The basics of sentences session 5pptx.pptx
The basics of sentences session 5pptx.pptxThe basics of sentences session 5pptx.pptx
The basics of sentences session 5pptx.pptx
heathfieldcps1
 
South African Journal of Science: Writing with integrity workshop (2024)
South African Journal of Science: Writing with integrity workshop (2024)South African Journal of Science: Writing with integrity workshop (2024)
South African Journal of Science: Writing with integrity workshop (2024)
Academy of Science of South Africa
 
2024.06.01 Introducing a competency framework for languag learning materials ...
2024.06.01 Introducing a competency framework for languag learning materials ...2024.06.01 Introducing a competency framework for languag learning materials ...
2024.06.01 Introducing a competency framework for languag learning materials ...
Sandy Millin
 
The simplified electron and muon model, Oscillating Spacetime: The Foundation...
The simplified electron and muon model, Oscillating Spacetime: The Foundation...The simplified electron and muon model, Oscillating Spacetime: The Foundation...
The simplified electron and muon model, Oscillating Spacetime: The Foundation...
RitikBhardwaj56
 
Acetabularia Information For Class 9 .docx
Acetabularia Information For Class 9  .docxAcetabularia Information For Class 9  .docx
Acetabularia Information For Class 9 .docx
vaibhavrinwa19
 
Assignment_4_ArianaBusciglio Marvel(1).docx
Assignment_4_ArianaBusciglio Marvel(1).docxAssignment_4_ArianaBusciglio Marvel(1).docx
Assignment_4_ArianaBusciglio Marvel(1).docx
ArianaBusciglio
 
S1-Introduction-Biopesticides in ICM.pptx
S1-Introduction-Biopesticides in ICM.pptxS1-Introduction-Biopesticides in ICM.pptx
S1-Introduction-Biopesticides in ICM.pptx
tarandeep35
 
Best Digital Marketing Institute In NOIDA
Best Digital Marketing Institute In NOIDABest Digital Marketing Institute In NOIDA
Best Digital Marketing Institute In NOIDA
deeptiverma2406
 
Group Presentation 2 Economics.Ariana Buscigliopptx
Group Presentation 2 Economics.Ariana BuscigliopptxGroup Presentation 2 Economics.Ariana Buscigliopptx
Group Presentation 2 Economics.Ariana Buscigliopptx
ArianaBusciglio
 
How to Add Chatter in the odoo 17 ERP Module
How to Add Chatter in the odoo 17 ERP ModuleHow to Add Chatter in the odoo 17 ERP Module
How to Add Chatter in the odoo 17 ERP Module
Celine George
 
The Challenger.pdf DNHS Official Publication
The Challenger.pdf DNHS Official PublicationThe Challenger.pdf DNHS Official Publication
The Challenger.pdf DNHS Official Publication
Delapenabediema
 
The Diamonds of 2023-2024 in the IGRA collection
The Diamonds of 2023-2024 in the IGRA collectionThe Diamonds of 2023-2024 in the IGRA collection
The Diamonds of 2023-2024 in the IGRA collection
Israel Genealogy Research Association
 

Recently uploaded (20)

Digital Artifact 2 - Investigating Pavilion Designs
Digital Artifact 2 - Investigating Pavilion DesignsDigital Artifact 2 - Investigating Pavilion Designs
Digital Artifact 2 - Investigating Pavilion Designs
 
A Survey of Techniques for Maximizing LLM Performance.pptx
A Survey of Techniques for Maximizing LLM Performance.pptxA Survey of Techniques for Maximizing LLM Performance.pptx
A Survey of Techniques for Maximizing LLM Performance.pptx
 
MATATAG CURRICULUM: ASSESSING THE READINESS OF ELEM. PUBLIC SCHOOL TEACHERS I...
MATATAG CURRICULUM: ASSESSING THE READINESS OF ELEM. PUBLIC SCHOOL TEACHERS I...MATATAG CURRICULUM: ASSESSING THE READINESS OF ELEM. PUBLIC SCHOOL TEACHERS I...
MATATAG CURRICULUM: ASSESSING THE READINESS OF ELEM. PUBLIC SCHOOL TEACHERS I...
 
Thesis Statement for students diagnonsed withADHD.ppt
Thesis Statement for students diagnonsed withADHD.pptThesis Statement for students diagnonsed withADHD.ppt
Thesis Statement for students diagnonsed withADHD.ppt
 
PCOS corelations and management through Ayurveda.
PCOS corelations and management through Ayurveda.PCOS corelations and management through Ayurveda.
PCOS corelations and management through Ayurveda.
 
Mule 4.6 & Java 17 Upgrade | MuleSoft Mysore Meetup #46
Mule 4.6 & Java 17 Upgrade | MuleSoft Mysore Meetup #46Mule 4.6 & Java 17 Upgrade | MuleSoft Mysore Meetup #46
Mule 4.6 & Java 17 Upgrade | MuleSoft Mysore Meetup #46
 
A Strategic Approach: GenAI in Education
A Strategic Approach: GenAI in EducationA Strategic Approach: GenAI in Education
A Strategic Approach: GenAI in Education
 
World environment day ppt For 5 June 2024
World environment day ppt For 5 June 2024World environment day ppt For 5 June 2024
World environment day ppt For 5 June 2024
 
The basics of sentences session 5pptx.pptx
The basics of sentences session 5pptx.pptxThe basics of sentences session 5pptx.pptx
The basics of sentences session 5pptx.pptx
 
South African Journal of Science: Writing with integrity workshop (2024)
South African Journal of Science: Writing with integrity workshop (2024)South African Journal of Science: Writing with integrity workshop (2024)
South African Journal of Science: Writing with integrity workshop (2024)
 
2024.06.01 Introducing a competency framework for languag learning materials ...
2024.06.01 Introducing a competency framework for languag learning materials ...2024.06.01 Introducing a competency framework for languag learning materials ...
2024.06.01 Introducing a competency framework for languag learning materials ...
 
The simplified electron and muon model, Oscillating Spacetime: The Foundation...
The simplified electron and muon model, Oscillating Spacetime: The Foundation...The simplified electron and muon model, Oscillating Spacetime: The Foundation...
The simplified electron and muon model, Oscillating Spacetime: The Foundation...
 
Acetabularia Information For Class 9 .docx
Acetabularia Information For Class 9  .docxAcetabularia Information For Class 9  .docx
Acetabularia Information For Class 9 .docx
 
Assignment_4_ArianaBusciglio Marvel(1).docx
Assignment_4_ArianaBusciglio Marvel(1).docxAssignment_4_ArianaBusciglio Marvel(1).docx
Assignment_4_ArianaBusciglio Marvel(1).docx
 
S1-Introduction-Biopesticides in ICM.pptx
S1-Introduction-Biopesticides in ICM.pptxS1-Introduction-Biopesticides in ICM.pptx
S1-Introduction-Biopesticides in ICM.pptx
 
Best Digital Marketing Institute In NOIDA
Best Digital Marketing Institute In NOIDABest Digital Marketing Institute In NOIDA
Best Digital Marketing Institute In NOIDA
 
Group Presentation 2 Economics.Ariana Buscigliopptx
Group Presentation 2 Economics.Ariana BuscigliopptxGroup Presentation 2 Economics.Ariana Buscigliopptx
Group Presentation 2 Economics.Ariana Buscigliopptx
 
How to Add Chatter in the odoo 17 ERP Module
How to Add Chatter in the odoo 17 ERP ModuleHow to Add Chatter in the odoo 17 ERP Module
How to Add Chatter in the odoo 17 ERP Module
 
The Challenger.pdf DNHS Official Publication
The Challenger.pdf DNHS Official PublicationThe Challenger.pdf DNHS Official Publication
The Challenger.pdf DNHS Official Publication
 
The Diamonds of 2023-2024 in the IGRA collection
The Diamonds of 2023-2024 in the IGRA collectionThe Diamonds of 2023-2024 in the IGRA collection
The Diamonds of 2023-2024 in the IGRA collection
 

Immutable Classes updated.ppt

  • 2. 2 Mutation  mutation: A modification to the state of an object.  Mutation must be done with care.  Can the object's state be damaged?  Is the old state important? Is it okay to "lose" it?  Do any other clients depend on this object?  Do they expect that its state will not change?
  • 3. 3 Immutable classes  immutable: Unable to be changed (mutated).  Basic idea: A class with no "set" methods (mutators).  In Java, Strings are immutable.  Many methods appear to "modify" a string.  But actually, they create and return a new string (producers).
  • 4. 4 "Modifying" strings  What is the output of this code? String name = "lil bow wow"; name.toUpperCase(); System.out.println(name);  The code outputs lil bow wow in lowercase.  To capitalize it, we must reassign the string: name = name.toUpperCase();  The toUpperCase method is a producer, not a mutator.
  • 5. 5 If Strings were mutable...  What could go wrong if strings were mutable? public Employee(String name, ...) { this.name = name; ... } public String getName() { return name; }  A client could accidentally damage the Employee's name. String s = myEmployee.getName(); s.substring(0, s.indexOf(" ")); // first name s.toUpperCase();
  • 6. 6 Making a class immutable  1. Don't provide any methods that modify the object's state.  2. Ensure that the class cannot be extended. (later)  3. Make all fields final.  4. Make all fields private. (ensure encapsulation)  5. Ensure exclusive access to any mutable object fields.  Don't let a client get a reference to a field that is a mutable object. (Don't allow any mutable representation exposure.)
  • 7. 7 Mutable Fraction class public class Fraction { private int numerator, denominator; public Fraction(int n) public Fraction(int n, int d) public int getNumerator(), getDenominator() public void add(Fraction other) { numerator = numerator * other.denominator + other.numerator * denominator; denominator = denominator * other.denominator; } }
  • 8. 8 Immutable methods // mutable version public void add(Fraction other) { numerator = numerator * other.denominator + other.numerator * denominator; denominator = denominator * other.denominator; } // immutable version public Fraction add(Fraction other) { int n = numerator * other.denominator + other.numerator * denominator; int d = denominator * other.denominator; return new Fraction(n, d); }  former mutators become producers  create/return a new immutable object rather than modifying this one
  • 9. 9 Pros/cons of immutability  Immutable objects are simple.  You know what state they're in (the state in which they were born).  Immutable objects can be freely shared among code.  You can pass them, return them, etc. without fear of damage.  Con: Immutable objects can consume more memory.  Need a unique instance for each unique abstract value used.