SlideShare a Scribd company logo
1 of 19
Download to read offline
(software) design pattern
Builder Pattern
Contoh penerapan software design pattern
pada pemrograman aplikasi Android
Arif Akbarul Huda
●
Android Developer di qiscus
●
Penulis buku “Livecoding! 9 Aplikasi
Android Buatan Sendiri”
●
omayib@gmail.com (email) | @omayib
(Twitter)
Isu...
Bagaimana teknik menangani objek personal
yang dibuat berdasarkan formulir seperti
gambar ini?
public class Person {
private final String firstName; //required
private final String lastName; //required
private final int age; //optional
private final String phone; //optional
private final String address; //optional
//and many more optional variable…….
}
● Bayangkan seandainya, class yang kamu buat memiliki banyak atribut/variabel
● Beberapa variabel diantaranya wajib diisi dan sisanya optional
Studi kasus….
Bagaimana cara menginisiasi objek
Person?
public Person(String firstName, String lastName) {
this(firstName, lastName, 0);
}
public Person(String firstName, String lastName, int age) {
this(firstName, lastName, age, '');
}
public Person(String firstName, String lastName, int age, String phone)
{
this(firstName, lastName, age, phone, '');
}
public Person(String firstName, String lastName, int age, String phone,
String address) {
this.firstName = firstName;
this.lastName = lastName;
this.age = age;
this.phone = phone;
this.address = address;
}
Membuat beberapa constructor….
Its work!, namun (nampak) membingungkan jika dilihat dari sisi client….
● Constructor yang mana yang harus dipilih?
● Cunstructor dengan 2 parameter atau 3 parameter?
● Apa isi default-value dari variabel yang tidak di-pass nilainya?
● Bagaimana jika ingin memberikan nilai pada variabel address, tapi tidak menganggu
variabel age dan phone?
● Kadang Bingung urutannya. Parameter String pertama merupakan phone atau
address?
● Apabila software berkembang, variabel bertambah banyak, maka constructor juga
Semakin bertambah. Lalu…. Bingung!?!!!
Arrrgggghhhh….. pucing pala berbi
Solution...
Aha… gunakan saja JavaBeans convention…
● No argument didalam constructor
● Setiap atribut/variabel punya setter & getter
public class Person {
private String firstName; // required
private String lastName; // required
private int age; // optional
private String phone; // optional
private String address; //optional
public String getFirstName() {
return firstName;
}
public void setFirstName(String firstName) {
this.firstName = firstName;
}
public String getLastName() {
return lastName;
}
public void setLastName(String lastName) {
this.lastName = lastName;
}
public int getAge() {
return age;
}
public void setAge(int age) {
this.age = age;
}
public String getPhone() {
return phone;
}
public void setPhone(String phone) {
this.phone = phone;
}
public String getAddress() {
return address;
}
public void setAddress(String address) {
this.address = address;
}
}
● Pendekatan ini paling mudah dilakukan , mudah
dibaca dan mudah di kelola.
● Client cukup menginisiasi sebuah object tanpa
melwatkan argument apapun kedalam
consturctor.
● Masing-masing variabel, nilainya diberikan
melalui setter.
Coba perhatikan dgn seksama,
apakah kamu menemukan
ke-aneh-an?
Setter-getter issue
● Status objek menjadi tidak konsisten
● Person Class menjadi mutable. Bisa diubah
sewaktu-waktu.
● Kita akan kehilangan kelebihan-kelebihan dari
immutable objek
Classes should be immutable unless there's a very good reason to
make them mutable....If a class cannot be made immutable, limit its
mutability as much as possible. by Joshua Bloch (taken from the book
Effective Java)
Classes should be immutable unless there's a very good reason to
make them mutable....If a class cannot be made immutable, limit its
mutability as much as possible. by Joshua Bloch (taken from the book
Effective Java)
Next solution
using builder pattern
Tujuan builder pattern
Mengurangi kompleksitas berkaitan dengan hal berikut
● Constructor berlebihan (lebih dari 1)
● Banyak variabel
● Meminimalkan penggunaan setter
public class Person {
private String firstName;//required
private String address;//required
private String phone;//required
private String salary; //optional
// .... others optional variable
private String job;//optional
private Person(Builder b){
this.firstName=b.firstName;
this.address=b.address;
this.phone=b.phone;
this.salary=b.salary;
this.job=b.job;
}
public String getFirstName() {return firstName;}
public String getAddress() {return address;}
public String getPhone() {return phone;}
public String getJob() {return job;}
public String getSalary() {return salary;}
public static class Builder{}
}
public static class Builder{
private String firstName;//required
private String address;//required
private String phone;//required
private String salary; //optional
// .... others optional variable
private String job;//optional
public Builder firstName(String firstNamePerson){
this.firstName=firstNamePerson;
return this;
}
public Builder address(String addressPerson){
this.address=addressPerson;
return this;
}
public Builder phone(String phonePerson){
this.phone=phonePerson;
return this;
}
public Builder salary(String salaryPerson){
this.salary=salaryPerson;
return this;
}
public Builder job(String jobPerson){
this.job=jobPerson;
return this;
}
public Person build(){
Person person= new Person(this);
if(person.firstName==null){
throw new IllegalStateException("first name can not be empty");
}
if(person.address==null){
throw new IllegalStateException("address can not be empty");
}
if(person.phone==null){
throw new IllegalStateException("phone can not be empty");
}
return person;
}
}
Bagaimana cara menginisiasi objek Person?
Person person=new Person.Builder().address("alamat")
.birthDay("12/2/1990")
.birthPlace("solo")
.bodyHeight(120)
.bodyWedight(70)
.job("pekerjaan")
.lastName("huda")
.middleName("midle name")
.phone("2232323")
.firstName("ariff")
.salary("23000000000").build();
menggunakan builder pattern :
●
Tipe constructor adalah private, sehingga class tidak bisa di inisiasi secara langsung dari
sisi client
●
Class bersifat immutable, kita hanya perlu menyediakan getter.
● Builder menggunakan style Fluent interface, sehingga mudah dibaca
● Mudah dilakukan validasi utnuk membedakan atribut wajib dan optional.
Keunggulannya….
sourcode
Tersedia di Github
(https://github.com/omayib/BuilderPatterOnAndroid)

More Related Content

Viewers also liked

introduction to programmer career path
introduction to programmer career pathintroduction to programmer career path
introduction to programmer career pathArif Huda
 
android design pattern
android design patternandroid design pattern
android design patternLucas Xu
 
Design pattern
Design patternDesign pattern
Design patternOmar Isaid
 
Application Of Software Design Pattern
Application Of Software Design PatternApplication Of Software Design Pattern
Application Of Software Design Patternguest46da5428
 
Design Pattern in Software Engineering
Design Pattern in Software EngineeringDesign Pattern in Software Engineering
Design Pattern in Software EngineeringManish Kumar
 
Acrhitecture deisign pattern_MVC_MVP_MVVM
Acrhitecture deisign pattern_MVC_MVP_MVVMAcrhitecture deisign pattern_MVC_MVP_MVVM
Acrhitecture deisign pattern_MVC_MVP_MVVMDong-Ho Lee
 
Observer Software Design Pattern
Observer Software Design Pattern Observer Software Design Pattern
Observer Software Design Pattern Nirthika Rajendran
 
Design pattern - Software Engineering
Design pattern - Software EngineeringDesign pattern - Software Engineering
Design pattern - Software EngineeringNadimozzaman Pappo
 
Design Pattern Explained CH1
Design Pattern Explained CH1Design Pattern Explained CH1
Design Pattern Explained CH1Jamie (Taka) Wang
 
Reactive Design Patterns: a talk by Typesafe's Dr. Roland Kuhn
Reactive Design Patterns: a talk by Typesafe's Dr. Roland KuhnReactive Design Patterns: a talk by Typesafe's Dr. Roland Kuhn
Reactive Design Patterns: a talk by Typesafe's Dr. Roland KuhnZalando Technology
 
Design pattern in android
Design pattern in androidDesign pattern in android
Design pattern in androidJay Kumarr
 

Viewers also liked (12)

introduction to programmer career path
introduction to programmer career pathintroduction to programmer career path
introduction to programmer career path
 
android design pattern
android design patternandroid design pattern
android design pattern
 
Design pattern
Design patternDesign pattern
Design pattern
 
Application Of Software Design Pattern
Application Of Software Design PatternApplication Of Software Design Pattern
Application Of Software Design Pattern
 
Design Pattern in Software Engineering
Design Pattern in Software EngineeringDesign Pattern in Software Engineering
Design Pattern in Software Engineering
 
Acrhitecture deisign pattern_MVC_MVP_MVVM
Acrhitecture deisign pattern_MVC_MVP_MVVMAcrhitecture deisign pattern_MVC_MVP_MVVM
Acrhitecture deisign pattern_MVC_MVP_MVVM
 
Observer Software Design Pattern
Observer Software Design Pattern Observer Software Design Pattern
Observer Software Design Pattern
 
Creational Design Patterns
Creational Design PatternsCreational Design Patterns
Creational Design Patterns
 
Design pattern - Software Engineering
Design pattern - Software EngineeringDesign pattern - Software Engineering
Design pattern - Software Engineering
 
Design Pattern Explained CH1
Design Pattern Explained CH1Design Pattern Explained CH1
Design Pattern Explained CH1
 
Reactive Design Patterns: a talk by Typesafe's Dr. Roland Kuhn
Reactive Design Patterns: a talk by Typesafe's Dr. Roland KuhnReactive Design Patterns: a talk by Typesafe's Dr. Roland Kuhn
Reactive Design Patterns: a talk by Typesafe's Dr. Roland Kuhn
 
Design pattern in android
Design pattern in androidDesign pattern in android
Design pattern in android
 

Similar to Android (software) Design Pattern

pbo 5 ervan
pbo 5 ervanpbo 5 ervan
pbo 5 ervanaris
 
AST Transformations at JFokus
AST Transformations at JFokusAST Transformations at JFokus
AST Transformations at JFokusHamletDRC
 
Having Fun with Kotlin Android - DILo Surabaya
Having Fun with Kotlin Android - DILo SurabayaHaving Fun with Kotlin Android - DILo Surabaya
Having Fun with Kotlin Android - DILo SurabayaDILo Surabaya
 
Kotlin mufix 31 10-2019 by Ahmed Nabil(AhmedNMahran)
Kotlin mufix 31 10-2019 by Ahmed Nabil(AhmedNMahran)Kotlin mufix 31 10-2019 by Ahmed Nabil(AhmedNMahran)
Kotlin mufix 31 10-2019 by Ahmed Nabil(AhmedNMahran)Ahmed Nabil
 
Missing objects: ?. and ?? in JavaScript (BrazilJS 2018)
Missing objects: ?. and ?? in JavaScript (BrazilJS 2018)Missing objects: ?. and ?? in JavaScript (BrazilJS 2018)
Missing objects: ?. and ?? in JavaScript (BrazilJS 2018)Igalia
 
Design patterns
Design patternsDesign patterns
Design patternsBa Tran
 
Lombokの紹介
Lombokの紹介Lombokの紹介
Lombokの紹介onozaty
 
Glancing essential features of Dart, before stepping into Flutter
Glancing essential features of Dart, before stepping into FlutterGlancing essential features of Dart, before stepping into Flutter
Glancing essential features of Dart, before stepping into FlutterToru Wonyoung Choi
 
Speed up the mobile development process
Speed up the mobile development processSpeed up the mobile development process
Speed up the mobile development processLeonardoSarra
 
Refactoring - Mejorando el diseño del código existente
Refactoring - Mejorando el diseño del código existenteRefactoring - Mejorando el diseño del código existente
Refactoring - Mejorando el diseño del código existenteMariano Sánchez
 
Laporan Final Project - Aplikasi Sistem Informasi Rental CD - Netbeans
Laporan Final Project - Aplikasi Sistem Informasi Rental CD - NetbeansLaporan Final Project - Aplikasi Sistem Informasi Rental CD - Netbeans
Laporan Final Project - Aplikasi Sistem Informasi Rental CD - NetbeansMelina Krisnawati
 
Laporan pembuatan Final Project (Java - Netbeans) "Rental CD"
Laporan pembuatan Final Project (Java - Netbeans) "Rental CD"Laporan pembuatan Final Project (Java - Netbeans) "Rental CD"
Laporan pembuatan Final Project (Java - Netbeans) "Rental CD"Melina Krisnawati
 
運用Closure Compiler 打造高品質的JavaScript
運用Closure Compiler 打造高品質的JavaScript運用Closure Compiler 打造高品質的JavaScript
運用Closure Compiler 打造高品質的JavaScripttaobao.com
 
Advanced JavaScript
Advanced JavaScriptAdvanced JavaScript
Advanced JavaScriptNascenia IT
 
Code Smells y Refactoring o haciendo que nuestro codigo huela (y se vea) mejo...
Code Smells y Refactoring o haciendo que nuestro codigo huela (y se vea) mejo...Code Smells y Refactoring o haciendo que nuestro codigo huela (y se vea) mejo...
Code Smells y Refactoring o haciendo que nuestro codigo huela (y se vea) mejo....NET Conf UY
 

Similar to Android (software) Design Pattern (20)

Code generating beans in Java
Code generating beans in JavaCode generating beans in Java
Code generating beans in Java
 
F# for C# Programmers
F# for C# ProgrammersF# for C# Programmers
F# for C# Programmers
 
pbo 5 ervan
pbo 5 ervanpbo 5 ervan
pbo 5 ervan
 
OOP Lab Report.docx
OOP Lab Report.docxOOP Lab Report.docx
OOP Lab Report.docx
 
AST Transformations at JFokus
AST Transformations at JFokusAST Transformations at JFokus
AST Transformations at JFokus
 
Having Fun with Kotlin Android - DILo Surabaya
Having Fun with Kotlin Android - DILo SurabayaHaving Fun with Kotlin Android - DILo Surabaya
Having Fun with Kotlin Android - DILo Surabaya
 
Kotlin mufix 31 10-2019 by Ahmed Nabil(AhmedNMahran)
Kotlin mufix 31 10-2019 by Ahmed Nabil(AhmedNMahran)Kotlin mufix 31 10-2019 by Ahmed Nabil(AhmedNMahran)
Kotlin mufix 31 10-2019 by Ahmed Nabil(AhmedNMahran)
 
Missing objects: ?. and ?? in JavaScript (BrazilJS 2018)
Missing objects: ?. and ?? in JavaScript (BrazilJS 2018)Missing objects: ?. and ?? in JavaScript (BrazilJS 2018)
Missing objects: ?. and ?? in JavaScript (BrazilJS 2018)
 
Design patterns
Design patternsDesign patterns
Design patterns
 
Lombokの紹介
Lombokの紹介Lombokの紹介
Lombokの紹介
 
Classes and Inheritance
Classes and InheritanceClasses and Inheritance
Classes and Inheritance
 
Glancing essential features of Dart, before stepping into Flutter
Glancing essential features of Dart, before stepping into FlutterGlancing essential features of Dart, before stepping into Flutter
Glancing essential features of Dart, before stepping into Flutter
 
Speed up the mobile development process
Speed up the mobile development processSpeed up the mobile development process
Speed up the mobile development process
 
Refactoring - Mejorando el diseño del código existente
Refactoring - Mejorando el diseño del código existenteRefactoring - Mejorando el diseño del código existente
Refactoring - Mejorando el diseño del código existente
 
Laporan Final Project - Aplikasi Sistem Informasi Rental CD - Netbeans
Laporan Final Project - Aplikasi Sistem Informasi Rental CD - NetbeansLaporan Final Project - Aplikasi Sistem Informasi Rental CD - Netbeans
Laporan Final Project - Aplikasi Sistem Informasi Rental CD - Netbeans
 
Laporan pembuatan Final Project (Java - Netbeans) "Rental CD"
Laporan pembuatan Final Project (Java - Netbeans) "Rental CD"Laporan pembuatan Final Project (Java - Netbeans) "Rental CD"
Laporan pembuatan Final Project (Java - Netbeans) "Rental CD"
 
運用Closure Compiler 打造高品質的JavaScript
運用Closure Compiler 打造高品質的JavaScript運用Closure Compiler 打造高品質的JavaScript
運用Closure Compiler 打造高品質的JavaScript
 
Advanced JavaScript
Advanced JavaScriptAdvanced JavaScript
Advanced JavaScript
 
Javascript tid-bits
Javascript tid-bitsJavascript tid-bits
Javascript tid-bits
 
Code Smells y Refactoring o haciendo que nuestro codigo huela (y se vea) mejo...
Code Smells y Refactoring o haciendo que nuestro codigo huela (y se vea) mejo...Code Smells y Refactoring o haciendo que nuestro codigo huela (y se vea) mejo...
Code Smells y Refactoring o haciendo que nuestro codigo huela (y se vea) mejo...
 

More from Arif Huda

Spotify Recommender System
Spotify Recommender SystemSpotify Recommender System
Spotify Recommender SystemArif Huda
 
Startup Tanpa Mentor, Bisa?
Startup Tanpa Mentor, Bisa?Startup Tanpa Mentor, Bisa?
Startup Tanpa Mentor, Bisa?Arif Huda
 
Introducing Startup 101
Introducing Startup 101Introducing Startup 101
Introducing Startup 101Arif Huda
 
Solusi Mencegah Coding Ruwet
Solusi Mencegah Coding RuwetSolusi Mencegah Coding Ruwet
Solusi Mencegah Coding RuwetArif Huda
 
Bedah Teknologi Semacam Gojek
Bedah Teknologi Semacam GojekBedah Teknologi Semacam Gojek
Bedah Teknologi Semacam GojekArif Huda
 
Rahasia Mendapatkan Investasi Milyaran Rupiah Sebelum Usia 30 Tahun
Rahasia Mendapatkan Investasi Milyaran Rupiah Sebelum Usia 30 TahunRahasia Mendapatkan Investasi Milyaran Rupiah Sebelum Usia 30 Tahun
Rahasia Mendapatkan Investasi Milyaran Rupiah Sebelum Usia 30 TahunArif Huda
 
Membuat Media Edukasi Daring
Membuat Media Edukasi DaringMembuat Media Edukasi Daring
Membuat Media Edukasi DaringArif Huda
 
Single responsibility pattern
Single responsibility patternSingle responsibility pattern
Single responsibility patternArif Huda
 
5 jalan rahasia mewujudkan ide startup
5 jalan rahasia mewujudkan ide startup5 jalan rahasia mewujudkan ide startup
5 jalan rahasia mewujudkan ide startupArif Huda
 
programmersworld
programmersworldprogrammersworld
programmersworldArif Huda
 
5 Langkah Jitu Melejitkan Ide Bisnis Startup
5 Langkah Jitu Melejitkan Ide Bisnis Startup5 Langkah Jitu Melejitkan Ide Bisnis Startup
5 Langkah Jitu Melejitkan Ide Bisnis StartupArif Huda
 
getting started startup in millenial era
getting started startup in millenial eragetting started startup in millenial era
getting started startup in millenial eraArif Huda
 
Fingertip Detection
Fingertip DetectionFingertip Detection
Fingertip DetectionArif Huda
 
Protocol oriented programming
Protocol oriented programmingProtocol oriented programming
Protocol oriented programmingArif Huda
 
an implementation of repository pattern for mobile application
an implementation of repository pattern for mobile applicationan implementation of repository pattern for mobile application
an implementation of repository pattern for mobile applicationArif Huda
 
Inovasi Teknologi Berkemajuan
Inovasi Teknologi BerkemajuanInovasi Teknologi Berkemajuan
Inovasi Teknologi BerkemajuanArif Huda
 
Git workflow
Git workflowGit workflow
Git workflowArif Huda
 
Media pembelajaran audio untuk tunanetra
Media pembelajaran audio untuk tunanetraMedia pembelajaran audio untuk tunanetra
Media pembelajaran audio untuk tunanetraArif Huda
 
Tobe a superstar programmer
Tobe a superstar programmerTobe a superstar programmer
Tobe a superstar programmerArif Huda
 
clean code for high quality software
clean code for high quality softwareclean code for high quality software
clean code for high quality softwareArif Huda
 

More from Arif Huda (20)

Spotify Recommender System
Spotify Recommender SystemSpotify Recommender System
Spotify Recommender System
 
Startup Tanpa Mentor, Bisa?
Startup Tanpa Mentor, Bisa?Startup Tanpa Mentor, Bisa?
Startup Tanpa Mentor, Bisa?
 
Introducing Startup 101
Introducing Startup 101Introducing Startup 101
Introducing Startup 101
 
Solusi Mencegah Coding Ruwet
Solusi Mencegah Coding RuwetSolusi Mencegah Coding Ruwet
Solusi Mencegah Coding Ruwet
 
Bedah Teknologi Semacam Gojek
Bedah Teknologi Semacam GojekBedah Teknologi Semacam Gojek
Bedah Teknologi Semacam Gojek
 
Rahasia Mendapatkan Investasi Milyaran Rupiah Sebelum Usia 30 Tahun
Rahasia Mendapatkan Investasi Milyaran Rupiah Sebelum Usia 30 TahunRahasia Mendapatkan Investasi Milyaran Rupiah Sebelum Usia 30 Tahun
Rahasia Mendapatkan Investasi Milyaran Rupiah Sebelum Usia 30 Tahun
 
Membuat Media Edukasi Daring
Membuat Media Edukasi DaringMembuat Media Edukasi Daring
Membuat Media Edukasi Daring
 
Single responsibility pattern
Single responsibility patternSingle responsibility pattern
Single responsibility pattern
 
5 jalan rahasia mewujudkan ide startup
5 jalan rahasia mewujudkan ide startup5 jalan rahasia mewujudkan ide startup
5 jalan rahasia mewujudkan ide startup
 
programmersworld
programmersworldprogrammersworld
programmersworld
 
5 Langkah Jitu Melejitkan Ide Bisnis Startup
5 Langkah Jitu Melejitkan Ide Bisnis Startup5 Langkah Jitu Melejitkan Ide Bisnis Startup
5 Langkah Jitu Melejitkan Ide Bisnis Startup
 
getting started startup in millenial era
getting started startup in millenial eragetting started startup in millenial era
getting started startup in millenial era
 
Fingertip Detection
Fingertip DetectionFingertip Detection
Fingertip Detection
 
Protocol oriented programming
Protocol oriented programmingProtocol oriented programming
Protocol oriented programming
 
an implementation of repository pattern for mobile application
an implementation of repository pattern for mobile applicationan implementation of repository pattern for mobile application
an implementation of repository pattern for mobile application
 
Inovasi Teknologi Berkemajuan
Inovasi Teknologi BerkemajuanInovasi Teknologi Berkemajuan
Inovasi Teknologi Berkemajuan
 
Git workflow
Git workflowGit workflow
Git workflow
 
Media pembelajaran audio untuk tunanetra
Media pembelajaran audio untuk tunanetraMedia pembelajaran audio untuk tunanetra
Media pembelajaran audio untuk tunanetra
 
Tobe a superstar programmer
Tobe a superstar programmerTobe a superstar programmer
Tobe a superstar programmer
 
clean code for high quality software
clean code for high quality softwareclean code for high quality software
clean code for high quality software
 

Recently uploaded

Tech Tuesday-Harness the Power of Effective Resource Planning with OnePlan’s ...
Tech Tuesday-Harness the Power of Effective Resource Planning with OnePlan’s ...Tech Tuesday-Harness the Power of Effective Resource Planning with OnePlan’s ...
Tech Tuesday-Harness the Power of Effective Resource Planning with OnePlan’s ...OnePlan Solutions
 
Advancing Engineering with AI through the Next Generation of Strategic Projec...
Advancing Engineering with AI through the Next Generation of Strategic Projec...Advancing Engineering with AI through the Next Generation of Strategic Projec...
Advancing Engineering with AI through the Next Generation of Strategic Projec...OnePlan Solutions
 
Russian Call Girls in Karol Bagh Aasnvi ➡️ 8264348440 💋📞 Independent Escort S...
Russian Call Girls in Karol Bagh Aasnvi ➡️ 8264348440 💋📞 Independent Escort S...Russian Call Girls in Karol Bagh Aasnvi ➡️ 8264348440 💋📞 Independent Escort S...
Russian Call Girls in Karol Bagh Aasnvi ➡️ 8264348440 💋📞 Independent Escort S...soniya singh
 
5 Signs You Need a Fashion PLM Software.pdf
5 Signs You Need a Fashion PLM Software.pdf5 Signs You Need a Fashion PLM Software.pdf
5 Signs You Need a Fashion PLM Software.pdfWave PLM
 
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
 
The Essentials of Digital Experience Monitoring_ A Comprehensive Guide.pdf
The Essentials of Digital Experience Monitoring_ A Comprehensive Guide.pdfThe Essentials of Digital Experience Monitoring_ A Comprehensive Guide.pdf
The Essentials of Digital Experience Monitoring_ A Comprehensive Guide.pdfkalichargn70th171
 
(Genuine) Escort Service Lucknow | Starting ₹,5K To @25k with A/C 🧑🏽‍❤️‍🧑🏻 89...
(Genuine) Escort Service Lucknow | Starting ₹,5K To @25k with A/C 🧑🏽‍❤️‍🧑🏻 89...(Genuine) Escort Service Lucknow | Starting ₹,5K To @25k with A/C 🧑🏽‍❤️‍🧑🏻 89...
(Genuine) Escort Service Lucknow | Starting ₹,5K To @25k with A/C 🧑🏽‍❤️‍🧑🏻 89...gurkirankumar98700
 
Learn the Fundamentals of XCUITest Framework_ A Beginner's Guide.pdf
Learn the Fundamentals of XCUITest Framework_ A Beginner's Guide.pdfLearn the Fundamentals of XCUITest Framework_ A Beginner's Guide.pdf
Learn the Fundamentals of XCUITest Framework_ A Beginner's Guide.pdfkalichargn70th171
 
How To Use Server-Side Rendering with Nuxt.js
How To Use Server-Side Rendering with Nuxt.jsHow To Use Server-Side Rendering with Nuxt.js
How To Use Server-Side Rendering with Nuxt.jsAndolasoft Inc
 
SyndBuddy AI 2k Review 2024: Revolutionizing Content Syndication with AI
SyndBuddy AI 2k Review 2024: Revolutionizing Content Syndication with AISyndBuddy AI 2k Review 2024: Revolutionizing Content Syndication with AI
SyndBuddy AI 2k Review 2024: Revolutionizing Content Syndication with AIABDERRAOUF MEHENNI
 
Active Directory Penetration Testing, cionsystems.com.pdf
Active Directory Penetration Testing, cionsystems.com.pdfActive Directory Penetration Testing, cionsystems.com.pdf
Active Directory Penetration Testing, cionsystems.com.pdfCionsystems
 
Test Automation Strategy for Frontend and Backend
Test Automation Strategy for Frontend and BackendTest Automation Strategy for Frontend and Backend
Test Automation Strategy for Frontend and BackendArshad QA
 
Der Spagat zwischen BIAS und FAIRNESS (2024)
Der Spagat zwischen BIAS und FAIRNESS (2024)Der Spagat zwischen BIAS und FAIRNESS (2024)
Der Spagat zwischen BIAS und FAIRNESS (2024)OPEN KNOWLEDGE GmbH
 
Building Real-Time Data Pipelines: Stream & Batch Processing workshop Slide
Building Real-Time Data Pipelines: Stream & Batch Processing workshop SlideBuilding Real-Time Data Pipelines: Stream & Batch Processing workshop Slide
Building Real-Time Data Pipelines: Stream & Batch Processing workshop SlideChristina Lin
 
Try MyIntelliAccount Cloud Accounting Software As A Service Solution Risk Fre...
Try MyIntelliAccount Cloud Accounting Software As A Service Solution Risk Fre...Try MyIntelliAccount Cloud Accounting Software As A Service Solution Risk Fre...
Try MyIntelliAccount Cloud Accounting Software As A Service Solution Risk Fre...MyIntelliSource, Inc.
 
Right Money Management App For Your Financial Goals
Right Money Management App For Your Financial GoalsRight Money Management App For Your Financial Goals
Right Money Management App For Your Financial GoalsJhone kinadey
 
The Ultimate Test Automation Guide_ Best Practices and Tips.pdf
The Ultimate Test Automation Guide_ Best Practices and Tips.pdfThe Ultimate Test Automation Guide_ Best Practices and Tips.pdf
The Ultimate Test Automation Guide_ Best Practices and Tips.pdfkalichargn70th171
 

Recently uploaded (20)

Tech Tuesday-Harness the Power of Effective Resource Planning with OnePlan’s ...
Tech Tuesday-Harness the Power of Effective Resource Planning with OnePlan’s ...Tech Tuesday-Harness the Power of Effective Resource Planning with OnePlan’s ...
Tech Tuesday-Harness the Power of Effective Resource Planning with OnePlan’s ...
 
Advancing Engineering with AI through the Next Generation of Strategic Projec...
Advancing Engineering with AI through the Next Generation of Strategic Projec...Advancing Engineering with AI through the Next Generation of Strategic Projec...
Advancing Engineering with AI through the Next Generation of Strategic Projec...
 
Russian Call Girls in Karol Bagh Aasnvi ➡️ 8264348440 💋📞 Independent Escort S...
Russian Call Girls in Karol Bagh Aasnvi ➡️ 8264348440 💋📞 Independent Escort S...Russian Call Girls in Karol Bagh Aasnvi ➡️ 8264348440 💋📞 Independent Escort S...
Russian Call Girls in Karol Bagh Aasnvi ➡️ 8264348440 💋📞 Independent Escort S...
 
Call Girls In Mukherjee Nagar 📱 9999965857 🤩 Delhi 🫦 HOT AND SEXY VVIP 🍎 SE...
Call Girls In Mukherjee Nagar 📱  9999965857  🤩 Delhi 🫦 HOT AND SEXY VVIP 🍎 SE...Call Girls In Mukherjee Nagar 📱  9999965857  🤩 Delhi 🫦 HOT AND SEXY VVIP 🍎 SE...
Call Girls In Mukherjee Nagar 📱 9999965857 🤩 Delhi 🫦 HOT AND SEXY VVIP 🍎 SE...
 
5 Signs You Need a Fashion PLM Software.pdf
5 Signs You Need a Fashion PLM Software.pdf5 Signs You Need a Fashion PLM Software.pdf
5 Signs You Need a Fashion PLM Software.pdf
 
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...
 
The Essentials of Digital Experience Monitoring_ A Comprehensive Guide.pdf
The Essentials of Digital Experience Monitoring_ A Comprehensive Guide.pdfThe Essentials of Digital Experience Monitoring_ A Comprehensive Guide.pdf
The Essentials of Digital Experience Monitoring_ A Comprehensive Guide.pdf
 
(Genuine) Escort Service Lucknow | Starting ₹,5K To @25k with A/C 🧑🏽‍❤️‍🧑🏻 89...
(Genuine) Escort Service Lucknow | Starting ₹,5K To @25k with A/C 🧑🏽‍❤️‍🧑🏻 89...(Genuine) Escort Service Lucknow | Starting ₹,5K To @25k with A/C 🧑🏽‍❤️‍🧑🏻 89...
(Genuine) Escort Service Lucknow | Starting ₹,5K To @25k with A/C 🧑🏽‍❤️‍🧑🏻 89...
 
Learn the Fundamentals of XCUITest Framework_ A Beginner's Guide.pdf
Learn the Fundamentals of XCUITest Framework_ A Beginner's Guide.pdfLearn the Fundamentals of XCUITest Framework_ A Beginner's Guide.pdf
Learn the Fundamentals of XCUITest Framework_ A Beginner's Guide.pdf
 
How To Use Server-Side Rendering with Nuxt.js
How To Use Server-Side Rendering with Nuxt.jsHow To Use Server-Side Rendering with Nuxt.js
How To Use Server-Side Rendering with Nuxt.js
 
SyndBuddy AI 2k Review 2024: Revolutionizing Content Syndication with AI
SyndBuddy AI 2k Review 2024: Revolutionizing Content Syndication with AISyndBuddy AI 2k Review 2024: Revolutionizing Content Syndication with AI
SyndBuddy AI 2k Review 2024: Revolutionizing Content Syndication with AI
 
Exploring iOS App Development: Simplifying the Process
Exploring iOS App Development: Simplifying the ProcessExploring iOS App Development: Simplifying the Process
Exploring iOS App Development: Simplifying the Process
 
Active Directory Penetration Testing, cionsystems.com.pdf
Active Directory Penetration Testing, cionsystems.com.pdfActive Directory Penetration Testing, cionsystems.com.pdf
Active Directory Penetration Testing, cionsystems.com.pdf
 
Test Automation Strategy for Frontend and Backend
Test Automation Strategy for Frontend and BackendTest Automation Strategy for Frontend and Backend
Test Automation Strategy for Frontend and Backend
 
Der Spagat zwischen BIAS und FAIRNESS (2024)
Der Spagat zwischen BIAS und FAIRNESS (2024)Der Spagat zwischen BIAS und FAIRNESS (2024)
Der Spagat zwischen BIAS und FAIRNESS (2024)
 
Vip Call Girls Noida ➡️ Delhi ➡️ 9999965857 No Advance 24HRS Live
Vip Call Girls Noida ➡️ Delhi ➡️ 9999965857 No Advance 24HRS LiveVip Call Girls Noida ➡️ Delhi ➡️ 9999965857 No Advance 24HRS Live
Vip Call Girls Noida ➡️ Delhi ➡️ 9999965857 No Advance 24HRS Live
 
Building Real-Time Data Pipelines: Stream & Batch Processing workshop Slide
Building Real-Time Data Pipelines: Stream & Batch Processing workshop SlideBuilding Real-Time Data Pipelines: Stream & Batch Processing workshop Slide
Building Real-Time Data Pipelines: Stream & Batch Processing workshop Slide
 
Try MyIntelliAccount Cloud Accounting Software As A Service Solution Risk Fre...
Try MyIntelliAccount Cloud Accounting Software As A Service Solution Risk Fre...Try MyIntelliAccount Cloud Accounting Software As A Service Solution Risk Fre...
Try MyIntelliAccount Cloud Accounting Software As A Service Solution Risk Fre...
 
Right Money Management App For Your Financial Goals
Right Money Management App For Your Financial GoalsRight Money Management App For Your Financial Goals
Right Money Management App For Your Financial Goals
 
The Ultimate Test Automation Guide_ Best Practices and Tips.pdf
The Ultimate Test Automation Guide_ Best Practices and Tips.pdfThe Ultimate Test Automation Guide_ Best Practices and Tips.pdf
The Ultimate Test Automation Guide_ Best Practices and Tips.pdf
 

Android (software) Design Pattern

  • 1. (software) design pattern Builder Pattern Contoh penerapan software design pattern pada pemrograman aplikasi Android
  • 2. Arif Akbarul Huda ● Android Developer di qiscus ● Penulis buku “Livecoding! 9 Aplikasi Android Buatan Sendiri” ● omayib@gmail.com (email) | @omayib (Twitter)
  • 4. Bagaimana teknik menangani objek personal yang dibuat berdasarkan formulir seperti gambar ini?
  • 5. public class Person { private final String firstName; //required private final String lastName; //required private final int age; //optional private final String phone; //optional private final String address; //optional //and many more optional variable……. } ● Bayangkan seandainya, class yang kamu buat memiliki banyak atribut/variabel ● Beberapa variabel diantaranya wajib diisi dan sisanya optional Studi kasus….
  • 7. public Person(String firstName, String lastName) { this(firstName, lastName, 0); } public Person(String firstName, String lastName, int age) { this(firstName, lastName, age, ''); } public Person(String firstName, String lastName, int age, String phone) { this(firstName, lastName, age, phone, ''); } public Person(String firstName, String lastName, int age, String phone, String address) { this.firstName = firstName; this.lastName = lastName; this.age = age; this.phone = phone; this.address = address; } Membuat beberapa constructor….
  • 8. Its work!, namun (nampak) membingungkan jika dilihat dari sisi client…. ● Constructor yang mana yang harus dipilih? ● Cunstructor dengan 2 parameter atau 3 parameter? ● Apa isi default-value dari variabel yang tidak di-pass nilainya? ● Bagaimana jika ingin memberikan nilai pada variabel address, tapi tidak menganggu variabel age dan phone? ● Kadang Bingung urutannya. Parameter String pertama merupakan phone atau address? ● Apabila software berkembang, variabel bertambah banyak, maka constructor juga Semakin bertambah. Lalu…. Bingung!?!!!
  • 10. Solution... Aha… gunakan saja JavaBeans convention… ● No argument didalam constructor ● Setiap atribut/variabel punya setter & getter
  • 11. public class Person { private String firstName; // required private String lastName; // required private int age; // optional private String phone; // optional private String address; //optional public String getFirstName() { return firstName; } public void setFirstName(String firstName) { this.firstName = firstName; } public String getLastName() { return lastName; } public void setLastName(String lastName) { this.lastName = lastName; } public int getAge() { return age; } public void setAge(int age) { this.age = age; } public String getPhone() { return phone; } public void setPhone(String phone) { this.phone = phone; } public String getAddress() { return address; } public void setAddress(String address) { this.address = address; } } ● Pendekatan ini paling mudah dilakukan , mudah dibaca dan mudah di kelola. ● Client cukup menginisiasi sebuah object tanpa melwatkan argument apapun kedalam consturctor. ● Masing-masing variabel, nilainya diberikan melalui setter. Coba perhatikan dgn seksama, apakah kamu menemukan ke-aneh-an?
  • 12. Setter-getter issue ● Status objek menjadi tidak konsisten ● Person Class menjadi mutable. Bisa diubah sewaktu-waktu. ● Kita akan kehilangan kelebihan-kelebihan dari immutable objek Classes should be immutable unless there's a very good reason to make them mutable....If a class cannot be made immutable, limit its mutability as much as possible. by Joshua Bloch (taken from the book Effective Java) Classes should be immutable unless there's a very good reason to make them mutable....If a class cannot be made immutable, limit its mutability as much as possible. by Joshua Bloch (taken from the book Effective Java)
  • 14. Tujuan builder pattern Mengurangi kompleksitas berkaitan dengan hal berikut ● Constructor berlebihan (lebih dari 1) ● Banyak variabel ● Meminimalkan penggunaan setter
  • 15. public class Person { private String firstName;//required private String address;//required private String phone;//required private String salary; //optional // .... others optional variable private String job;//optional private Person(Builder b){ this.firstName=b.firstName; this.address=b.address; this.phone=b.phone; this.salary=b.salary; this.job=b.job; } public String getFirstName() {return firstName;} public String getAddress() {return address;} public String getPhone() {return phone;} public String getJob() {return job;} public String getSalary() {return salary;} public static class Builder{} } public static class Builder{ private String firstName;//required private String address;//required private String phone;//required private String salary; //optional // .... others optional variable private String job;//optional public Builder firstName(String firstNamePerson){ this.firstName=firstNamePerson; return this; } public Builder address(String addressPerson){ this.address=addressPerson; return this; } public Builder phone(String phonePerson){ this.phone=phonePerson; return this; } public Builder salary(String salaryPerson){ this.salary=salaryPerson; return this; } public Builder job(String jobPerson){ this.job=jobPerson; return this; } public Person build(){ Person person= new Person(this); if(person.firstName==null){ throw new IllegalStateException("first name can not be empty"); } if(person.address==null){ throw new IllegalStateException("address can not be empty"); } if(person.phone==null){ throw new IllegalStateException("phone can not be empty"); } return person; } }
  • 18. menggunakan builder pattern : ● Tipe constructor adalah private, sehingga class tidak bisa di inisiasi secara langsung dari sisi client ● Class bersifat immutable, kita hanya perlu menyediakan getter. ● Builder menggunakan style Fluent interface, sehingga mudah dibaca ● Mudah dilakukan validasi utnuk membedakan atribut wajib dan optional. Keunggulannya….