SlideShare a Scribd company logo
JAVA: NIE POPEŁNIAJ TYCH BŁĘDÓW!
@dpokusa
Daniel Pokusa
Not all those who wander are lost.
public String reverse(String msg) {
}
Napisz metodę, która odwróci ciąg znaków. (Jeśli na wejściu
dostaniemy “ABCD” to zwróci “DCBA” itd):
public String reverse(String msg) {
return new StringBuilder(msg)
.reverse()
.toString();
}
public static String reverse(String message) {
String ret = "";
for (int i = 0; i < message.length(); i++) {
int indexBegin = message.length() - 2 - i;
int indexEnd = indexBegin + 1;
ret += message.substring(indexBegin, indexEnd);
}
return ret;
}
public static String reverse(String message) {
String ret = "";
for (int i = 0; i < message.length(); i++) {
int indexBegin = message.length() - 2 - i;
int indexEnd = indexBegin + 1;
ret += message.substring(indexBegin, indexEnd);
}
return ret;
}
class Book {
private String name;
private String isbn;
private List<String> authors;
public Book(String name, String isbn, List<String> authors) {
this.name = name;
this.isbn = isbn;
this.authors = authors;
}
// getters
}
final class Book {
private String name;
private String isbn;
private Collection<String> authors;
public Book(String name,
String isbn,
Collection<String> authors) {
this.name = name;
this.isbn = isbn;
this.authors = authors;
}
// getters
}
final class Book {
final private String name;
final private String isbn;
final private Collection<String> authors;
public Book(String name,
String isbn,
Collection<String> authors) {
this.name = name;
this.isbn = isbn;
this.authors = authors;
}
// getters
}
List<String> author = new ArrayList<>();
author.add("J.R.R. Tolkien");
Book lotr = new Book(
"Lord of the rings",
"9780007117116",
author
);
lotr.getAuthors().add("Daniel Pokusa"); // HAHA! Hacked!
final class Book {
private final String name;
private final String isbn;
private final Collection<String> authors;
public Book(String name,
String isbn,
Collection<String> authors) {
this.name = name;
this.isbn = isbn;
this.authors = new ArrayList<>(authors);
}
public Collection<String> getAuthors() {
return Collections.unmodifiableCollection(authors);
}
// other getters
final class Book {
private final String name;
private final String isbn;
private final Collection<String> authors;
public Book(String name,
String isbn,
Collection<String> authors) {
this.name = name;
this.isbn = isbn;
this.authors = new ArrayList<>(authors);
}
public Collection<String> getAuthors() {
return Collections.unmodifiableCollection(authors);
}
// other getters
final class Book {
private final String name;
private final String isbn;
private final Collection<String> authors;
public Book(String name,
String isbn,
Collection<String> authors) {
this.name = name;
this.isbn = isbn;
this.authors = new ArrayList<>(authors);
}
public Collection<String> getAuthors() {
return unmodifiableCollection(authors);
}
// other getters
“Short cuts make delays, but inns make longer ones.”
– Frodo
public BigDecimal retrieve(String currency) {
RestTemplate restTemplate = new RestTemplate();
NBPApiResponse result = restTemplate.getForObject(
url,
NBPApiResponse.class
);
BigDecimal currentRate = result.rates[0].mid;
log.info("Current rate for {} is {}",
currency,
currentRate
);
return currentRate;
}
public BigDecimal retrieve(RestTemplate restTemplate,
String currency) {
NBPApiResponse result = restTemplate.getForObject(
url,
NBPApiResponse.class
);
BigDecimal currentRate = result.rates[0].mid;
log.debug("Current rate for {} is {}",
currency,
currentRate
);
return currentRate;
}
public BigDecimal retrieve(RestTemplate restTemplate,
String currency) {
NBPApiResponse result = restTemplate.getForObject(
url,
NBPApiResponse.class
);
BigDecimal currentRate = result.rates[0].mid;
log.debug("Current rate for {} is {}",
currency,
currentRate
);
return currentRate;
}
public BigDecimal retrieve(RestTemplate restTemplate,
String currency) {
NBPApiResponse result = restTemplate.getForObject(
url,
NBPApiResponse.class
);
BigDecimal currentRate = result.getCurrentRate();
log.debug("Current rate for {} is {}",
currency,
currentRate
);
return currentRate;
}
public BigDecimal retrieve(RestTemplate restTemplate,
String currency) {
NBPApiResponse result = restTemplate.getForObject(
url,
NBPApiResponse.class
);
return result.getCurrentRate();
}
?
Even the smallest person can change the course of the future.
– Galadriel
class Person {
private String name;
private String surname;
private String nip;
private LocalDate birthdate;
// Constructors, getters, ...
}
public int getAge(Person p);
public int getAge(LocalDate birthdate);
public int getAge(Person p);
public int getAge(LocalDate birthdate) {
return Period.between(birthdate, now()).getYears();
}
public int getAge(Person p);
public int getAge(LocalDate birthdate) {
return Period.between(birthdate, now()).getYears();
}
public int getAge(Person p);
LocalDate.now()
public int getAge(LocalDate birthdate) {
return between(birthdate, now()).getYears();
}
public int getAge(Person p);
public int getAge(LocalDate date);
public int getAge(Person p);
public int getAge();
public boolean shouldShowHappyBirthdaySignFor(Person person);
public boolean shouldShowHappyBirthdaySignFor(
LocalDate birthdayDate);
All we have to decide is what to do with the time that is given to us.
- Gandalf
public boolean isSuperhero(Person p, World w);
public boolean shouldBeSuperhero(Person p, World w);
public int calculateFriendsQuantityFor(Person person);
public boolean isPopular(Person person) {
return calculateFriendsQuantityFor(person)
> MIN_FRIENDS_QUANTITY_FOR_POPULAR_PERSONS;
}
public int calculateFriendsQuantityFor(Person person);
public boolean isPopular(Person person) {
return calculateFriendsQuantityFor(person)
> MIN_FRIENDS_QUANTITY_FOR_POPULAR_PERSONS;
}
public static final int
MIN_FRIENDS_QUANTITY_FOR_POPULAR_PERSONS = 50;
● get
● retrieve
● load
● calculate
● For
● Into
● Of
● By
I will take it! I will take the Ring to Mordor. Though… I do not know the way.
- Frodo
public class ShoppingBag {
public Collection<Item> items = new ArrayList<>();
public static final BigDecimal MULTI_DISCOUNT = new BigDecimal(0.2); // 20%
public static final BigDecimal OVERAL_DISCOUNT = new BigDecimal(0.1); // 10%
public Receipt calculate() {
Receipt r = new Receipt();
for (Item item : items) {
r.addPosition(item);
int promotions = (int) (item.getQuantity() / 2);
if (promotions > 0) {
r.addPosition(new Item("More than one promotion!", item.getPrice().multiply(MULTI_DISCOUNT).negate(),
promotions));
}
}
if (r.getFinalPrice().compareTo(new BigDecimal(100)) > 0) {
r.addPosition(new Item("Overall discount", r.getFinalPrice().multiply(OVERAL_DISCOUNT).negate(), 1));
}
saveReceipt(r);
return r;
}
// Other methods
}
public Receipt calculate() {
Receipt r = new Receipt();
for (Item item : items) {
r.addPosition(item);
int promotions = (int) (item.getQuantity() / 2);
if (promotions > 0) {
r.addPosition(new Item("More than one promotion!", item.getPrice().multiply(MULTI_DISCOUNT).negate(),
promotions));
}
}
if (r.getFinalPrice().compareTo(new BigDecimal(100)) > 0) {
r.addPosition(new Item("Overall discount", r.getFinalPrice().multiply(OVERAL_DISCOUNT).negate(), 1));
}
saveReceipt(r);
return r;
}
public Receipt calculate() {
Receipt r = new Receipt();
for (Item item : items) {
r.addPosition(item);
int promotions = (int) (item.getQuantity() / 2);
if (promotions > 0) {
r.addPosition(new Item("More than one promotion!", item.getPrice().multiply(MULTI_DISCOUNT).negate(),
promotions));
}
}
if (isOverallDiscountAwarded(r.getFinalPrice())) {
r.addPosition(new Item("Overall discount", r.getFinalPrice().multiply(OVERAL_DISCOUNT).negate(), 1));
}
saveReceipt(r);
return r;
}
public Receipt calculate() {
Receipt r = new Receipt();
for (Item item : items) {
r.addPosition(item);
int promotions = getNumberOfMultiDiscountsPromotionsFor(item.getQuantity());
if (promotions > 0) {
r.addPosition(new Item("More than one promotion!", item.getPrice().multiply(MULTI_DISCOUNT).negate(),
promotions));
}
}
if (isOverallDiscountAwarded(r.getFinalPrice())) {
r.addPosition(new Item("Overall discount", r.getFinalPrice().multiply(OVERAL_DISCOUNT).negate(), 1));
}
saveReceipt(r);
return r;
}
public Receipt calculate() {
Receipt r = new Receipt();
for (Item item : items) {
r.addPosition(item);
int promotions = getNumberOfMultiDiscountsPromotionsFor(item.getQuantity());
if (promotions > 0) {
r.addPosition(new Item("More than one promotion!", item.getPrice().multiply(MULTI_DISCOUNT).negate(),
promotions));
}
}
if (isOverallDiscountAwarded(r.getFinalPrice())) {
r.addPosition(new Item("Overall discount", r.getFinalPrice().multiply(OVERAL_DISCOUNT).negate(), 1));
}
return r;
}
public Receipt calculate() {
Receipt r = new Receipt();
for (Item item : items) {
r.addPosition(item);
int promotions = getNumberOfMultiDiscountsPromotionsFor(item.getQuantity());
if (promotions > 0) {
r.addPosition(new Item("More than one promotion!", item.getPrice().multiply(MULTI_DISCOUNT).negate(),
promotions));
}
}
if (isOverallDiscountAwarded(r.getFinalPrice())) {
r.addPosition(getOveralDiscountFor(r.getFinalPrice()));
}
return r;
}
public Receipt calculate() {
Receipt r = new Receipt();
for (Item item : items) {
r.addPosition(item);
int promotions = getNumberOfMultiDiscountsPromotionsFor(item.getQuantity());
if (promotions > 0) {
r.addPosition(getMultiDiscountFor(item.getPrice(), promotions)));
}
}
if (isOverallDiscountAwarded(r.getFinalPrice())) {
r.addPosition(getOverallDiscountFor(r.getFinalPrice()));
}
return r;
}
public Receipt calculate() {
Receipt r = new Receipt();
for (Item item : items) {
r.addPosition(item);
int promotions = getNumberOfMultiDiscountsPromotionsFor(item.getQuantity());
if (promotions > 0) {
r.addPosition(getMultiDiscountFor(item.getPrice(), promotions)));
}
}
if (isOverallDiscountAwarded(r.getFinalPrice())) {
r.addPosition(getOverallDiscountFor(r.getFinalPrice()));
}
return r;
}
public Receipt calculate() {
return ReceiptBuilder.for(items)
.addItemDiscount(priceItemDiscount)
.addOverallDiscount(priceOverallDiscount)
.build();
}
public Receipt calculate() {
return ReceiptBuilder.for(items)
.addItemDiscount(priceItemDiscount)
.addOverallDiscount(priceOverallDiscount)
.build();
}
private void calculateItems() {
for (Item item : items) {
receipt.addPosition(item);
for (ItemDiscount discount : itemDiscounts) {
Optional<Item> itemDiscount = discount.calculateFor(item);
if (itemDiscount.isPresent()) {
receipt.addPosition(itemDiscount.get());
}
}
}
}
public Receipt calculate() {
return ReceiptBuilder.for(items)
.addItemDiscount(priceItemDiscount)
.addOverallDiscount(priceOverallDiscount)
.build();
}
private void applyOverallDiscounts() {
for (OverallDiscount discount : overallDiscounts) {
Optional<Item> discountItem = discount.calculateFor(receipt);
if (discountItem.isPresent()) {
receipt.addPosition(discountItem.get());
}
}
}
public Receipt calculate() {
return ReceiptBuilder.for(items)
.addItemDiscount(priceItemDiscount)
.addOverallDiscount(priceOverallDiscount)
.build();
}
public Receipt build() {
calculateItemsWithDiscounts();
applyOverallDiscounts();
return receipt;
}
public Receipt calculate(List<ItemDiscount> itemDiscounts, List<OveralDiscount> overallDiscounts) {
return ReceiptBuilder.for(items)
.addItemDiscounts(itemDiscounts)
.addOverallDiscounts(overallDiscount)
.build();
}
public class ShoppingBag {
public Collection<Item> items = new ArrayList<>();
public static final BigDecimal MULTI_DISCOUNT = new BigDecimal(0.2); // 20%
public static final BigDecimal OVERAL_DISCOUNT = new BigDecimal(0.1); // 10%
public Receipt calculate() {
Receipt r = new Receipt();
for (Item item : items) {
r.addPosition(item);
int promotions = (int) (item.getQuantity() / 2);
if (promotions > 0) {
r.addPosition(new Item("More than one promotion!", item.getPrice().multiply(MULTI_DISCOUNT).negate(),
promotions));
}
}
if (r.getFinalPrice().compareTo(new BigDecimal(100)) > 0) {
r.addPosition(new Item("Overall discount", r.getFinalPrice().multiply(OVERAL_DISCOUNT).negate(), 1));
}
saveReceipt(r);
return r;
}
// Other methods
}
public Receipt calculate(List<ItemDiscount> itemDiscounts, List<OveralDiscount> overallDiscounts) {
return ReceiptBuilder.for(items)
.addItemDiscounts(itemDiscounts)
.addOverallDiscounts(overallDiscount)
.build();
}
Courage is found in unlikely places
- Gildor
● NIE ignoruj podstaw języka
● NIE ignoruj podstaw języka
● Zrozum istotę klas niemodyfikowalnych i klas wartości
● NIE ignoruj podstaw języka
● Zrozum istotę klas niemodyfikowalnych i klas wartości
● Znaj przynajmniej podstawy GC
● NIE ignoruj podstaw języka
● Zrozum istotę klas niemodyfikowalnych i klas wartości
● Znaj przynajmniej podstawy GC
● Pamiętaj o regule Demeter
● NIE ignoruj podstaw języka
● Zrozum istotę klas niemodyfikowalnych i klas wartości
● Znaj przynajmniej podstawy GC
● Pamiętaj o regule Demeter
● Nazewnictwo jest bardzo ważne
● NIE ignoruj podstaw języka
● Zrozum istotę klas niemodyfikowalnych i klas wartości
● Znaj przynajmniej podstawy GC
●Pamiętaj o regule Demeter
● Nazewnictwo jest bardzo ważne
● SOLID, ale zacznij od porządnego zrozumienia SRP :)
● NIE ignoruj podstaw języka
● Zrozum istotę klas niemodyfikowalnych i klas wartości
● Znaj przynajmniej podstawy GC
●Pamiętaj o regule Demeter
● Nazewnictwo jest bardzo ważne
● SOLID, ale zacznij od porządnego zrozumienia SRP :)
● Jeśli korzystasz z jakiegoś frameworka- spróbuj zrozumieć jego
podstawowe mechanizmy
● Pisz testy.
● Programuj tak jakby Code Review mał zrobić Ci socjopata, który zna
Twój adres domowy :)
● NIE ignoruj podstaw języka
● Zrozum istotę klas niemodyfikowalnych i klas wartości
● Znaj przynajmniej podstawy GC
●Pamiętaj o regule Demeter
● Nazewnictwo jest bardzo ważne
● SOLID, ale zacznij od porządnego zrozumienia SRP :)
● Jeśli korzystasz z jakiegoś frameworka- spróbuj zrozumieć jego
podstawowe mechanizmy
● NIE ignoruj podstaw języka
● Zrozum istotę klas niemodyfikowalnych i klas wartości
● Znaj przynajmniej podstawy GC
●Pamiętaj o regule Demeter
● Nazewnictwo jest bardzo ważne
● SOLID, ale zacznij od porządnego zrozumienia SRP :)
● Jeśli korzystasz z jakiegoś frameworka- spróbuj zrozumieć jego
podstawowe mechanizmy
● Pisz testy.
● NIE ignoruj podstaw języka
● Zrozum istotę klas niemodyfikowalnych i klas wartości
● Znaj przynajmniej podstawy GC
●Pamiętaj o regule Demeter
● Nazewnictwo jest bardzo ważne
● SOLID, ale zacznij od porządnego zrozumienia SRP :)
● Jeśli korzystasz z jakiegoś frameworka- spróbuj zrozumieć jego
podstawowe mechanizmy
● Pisz testy.
● Programuj tak jakby Code Review mał zrobić Ci socjopata, który zna
Twój adres domowy :)
software-empathy.pl
@dpokusa
Danielpokusa.pl
SPREADIT.PL
@dpokusa
18.11.2017, Gliwice
Q&A
DZIĘKI!

More Related Content

What's hot

Map/reduce, geospatial indexing, and other cool features (Kristina Chodorow)
Map/reduce, geospatial indexing, and other cool features (Kristina Chodorow)Map/reduce, geospatial indexing, and other cool features (Kristina Chodorow)
Map/reduce, geospatial indexing, and other cool features (Kristina Chodorow)
MongoSF
 
computer notes - Data Structures - 21
computer notes - Data Structures - 21computer notes - Data Structures - 21
computer notes - Data Structures - 21
ecomputernotes
 
Ipc: aidl sexy, not a curse
Ipc: aidl sexy, not a curseIpc: aidl sexy, not a curse
Ipc: aidl sexy, not a curse
Yonatan Levin
 
Computer notes - singleRightRotation
Computer notes   - singleRightRotationComputer notes   - singleRightRotation
Computer notes - singleRightRotation
ecomputernotes
 

What's hot (19)

Palestra collection google
Palestra collection googlePalestra collection google
Palestra collection google
 
mobl
moblmobl
mobl
 
Swipe 2011 - iOS Gems
Swipe 2011 - iOS GemsSwipe 2011 - iOS Gems
Swipe 2011 - iOS Gems
 
Into Clojure
Into ClojureInto Clojure
Into Clojure
 
Map/reduce, geospatial indexing, and other cool features (Kristina Chodorow)
Map/reduce, geospatial indexing, and other cool features (Kristina Chodorow)Map/reduce, geospatial indexing, and other cool features (Kristina Chodorow)
Map/reduce, geospatial indexing, and other cool features (Kristina Chodorow)
 
10b. Graph Databases Lab
10b. Graph Databases Lab10b. Graph Databases Lab
10b. Graph Databases Lab
 
concurrency with GPars
concurrency with GParsconcurrency with GPars
concurrency with GPars
 
TDC2016SP - Código funcional em Java: superando o hype
TDC2016SP - Código funcional em Java: superando o hypeTDC2016SP - Código funcional em Java: superando o hype
TDC2016SP - Código funcional em Java: superando o hype
 
computer notes - Data Structures - 21
computer notes - Data Structures - 21computer notes - Data Structures - 21
computer notes - Data Structures - 21
 
Mattbrenner
MattbrennerMattbrenner
Mattbrenner
 
Scala in practice
Scala in practiceScala in practice
Scala in practice
 
Should I Use Scalding or Scoobi or Scrunch?
Should I Use Scalding or Scoobi or Scrunch? Should I Use Scalding or Scoobi or Scrunch?
Should I Use Scalding or Scoobi or Scrunch?
 
Secuencias Recursivas, Sucesiones Recursivas & Progresiones con Geogebra
Secuencias Recursivas, Sucesiones Recursivas & Progresiones con GeogebraSecuencias Recursivas, Sucesiones Recursivas & Progresiones con Geogebra
Secuencias Recursivas, Sucesiones Recursivas & Progresiones con Geogebra
 
groovy databases
groovy databasesgroovy databases
groovy databases
 
IPC: AIDL is sexy, not a curse
IPC: AIDL is sexy, not a curseIPC: AIDL is sexy, not a curse
IPC: AIDL is sexy, not a curse
 
Ipc: aidl sexy, not a curse
Ipc: aidl sexy, not a curseIpc: aidl sexy, not a curse
Ipc: aidl sexy, not a curse
 
Marimba - Ein MapReduce-basiertes Programmiermodell für selbstwartbare Aggreg...
Marimba - Ein MapReduce-basiertes Programmiermodell für selbstwartbare Aggreg...Marimba - Ein MapReduce-basiertes Programmiermodell für selbstwartbare Aggreg...
Marimba - Ein MapReduce-basiertes Programmiermodell für selbstwartbare Aggreg...
 
Computer notes - singleRightRotation
Computer notes   - singleRightRotationComputer notes   - singleRightRotation
Computer notes - singleRightRotation
 
اسلاید اول جلسه چهارم کلاس پایتون برای هکرهای قانونی
اسلاید اول جلسه چهارم کلاس پایتون برای هکرهای قانونیاسلاید اول جلسه چهارم کلاس پایتون برای هکرهای قانونی
اسلاید اول جلسه چهارم کلاس پایتون برای هکرهای قانونی
 

Similar to Java: Nie popełniaj tych błędów!

VISUALIZAR REGISTROS EN UN JTABLE
VISUALIZAR REGISTROS EN UN JTABLEVISUALIZAR REGISTROS EN UN JTABLE
VISUALIZAR REGISTROS EN UN JTABLE
Darwin Durand
 
can do this in java please thanks in advance The code that y.pdf
can do this in java please thanks in advance The code that y.pdfcan do this in java please thanks in advance The code that y.pdf
can do this in java please thanks in advance The code that y.pdf
akshpatil4
 
CodeCamp Iasi 10 march 2012 - Practical Groovy
CodeCamp Iasi 10 march 2012 - Practical GroovyCodeCamp Iasi 10 march 2012 - Practical Groovy
CodeCamp Iasi 10 march 2012 - Practical Groovy
Codecamp Romania
 
AST Transformations at JFokus
AST Transformations at JFokusAST Transformations at JFokus
AST Transformations at JFokus
HamletDRC
 

Similar to Java: Nie popełniaj tych błędów! (20)

Madrid gug - sacando partido a las transformaciones ast de groovy
Madrid gug - sacando partido a las transformaciones ast de groovyMadrid gug - sacando partido a las transformaciones ast de groovy
Madrid gug - sacando partido a las transformaciones ast de groovy
 
G3 Summit 2016 - Taking Advantage of Groovy Annotations
G3 Summit 2016 - Taking Advantage of Groovy AnnotationsG3 Summit 2016 - Taking Advantage of Groovy Annotations
G3 Summit 2016 - Taking Advantage of Groovy Annotations
 
Ian 20150116 java script oop
Ian 20150116 java script oopIan 20150116 java script oop
Ian 20150116 java script oop
 
Kotlin for Android Developers - Victor Kropp - Codemotion Rome 2018
Kotlin for Android Developers - Victor Kropp - Codemotion Rome 2018Kotlin for Android Developers - Victor Kropp - Codemotion Rome 2018
Kotlin for Android Developers - Victor Kropp - Codemotion Rome 2018
 
Greach 2015 AST – Groovy Transformers: More than meets the eye!
Greach 2015   AST – Groovy Transformers: More than meets the eye!Greach 2015   AST – Groovy Transformers: More than meets the eye!
Greach 2015 AST – Groovy Transformers: More than meets the eye!
 
Wykorzystanie języka Kotlin do aplikacji na platformie Android
Wykorzystanie języka Kotlin do aplikacji na platformie AndroidWykorzystanie języka Kotlin do aplikacji na platformie Android
Wykorzystanie języka Kotlin do aplikacji na platformie Android
 
Pure kotlin
Pure kotlinPure kotlin
Pure kotlin
 
VISUALIZAR REGISTROS EN UN JTABLE
VISUALIZAR REGISTROS EN UN JTABLEVISUALIZAR REGISTROS EN UN JTABLE
VISUALIZAR REGISTROS EN UN JTABLE
 
ES6 patterns in the wild
ES6 patterns in the wildES6 patterns in the wild
ES6 patterns in the wild
 
6. Generics. Collections. Streams
6. Generics. Collections. Streams6. Generics. Collections. Streams
6. Generics. Collections. Streams
 
Tuga IT 2017 - What's new in C# 7
Tuga IT 2017 - What's new in C# 7Tuga IT 2017 - What's new in C# 7
Tuga IT 2017 - What's new in C# 7
 
can do this in java please thanks in advance The code that y.pdf
can do this in java please thanks in advance The code that y.pdfcan do this in java please thanks in advance The code that y.pdf
can do this in java please thanks in advance The code that y.pdf
 
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...
 
TypeScript Introduction
TypeScript IntroductionTypeScript Introduction
TypeScript Introduction
 
From java to kotlin beyond alt+shift+cmd+k - Droidcon italy
From java to kotlin beyond alt+shift+cmd+k - Droidcon italyFrom java to kotlin beyond alt+shift+cmd+k - Droidcon italy
From java to kotlin beyond alt+shift+cmd+k - Droidcon italy
 
3. Объекты, классы и пакеты в Java
3. Объекты, классы и пакеты в Java3. Объекты, классы и пакеты в Java
3. Объекты, классы и пакеты в Java
 
From java to kotlin beyond alt+shift+cmd+k
From java to kotlin beyond alt+shift+cmd+kFrom java to kotlin beyond alt+shift+cmd+k
From java to kotlin beyond alt+shift+cmd+k
 
CodeCamp Iasi 10 march 2012 - Practical Groovy
CodeCamp Iasi 10 march 2012 - Practical GroovyCodeCamp Iasi 10 march 2012 - Practical Groovy
CodeCamp Iasi 10 march 2012 - Practical Groovy
 
AST Transformations at JFokus
AST Transformations at JFokusAST Transformations at JFokus
AST Transformations at JFokus
 
はじめてのGroovy
はじめてのGroovyはじめてのGroovy
はじめてのGroovy
 

More from Daniel Pokusa

More from Daniel Pokusa (11)

Errors errors, everywhere! - JSession
Errors errors, everywhere! - JSessionErrors errors, everywhere! - JSession
Errors errors, everywhere! - JSession
 
Errors errors, everywhere! - 4Developers 2018
Errors errors, everywhere! - 4Developers 2018Errors errors, everywhere! - 4Developers 2018
Errors errors, everywhere! - 4Developers 2018
 
Errors errors everywhere! - BoilingFrogs 2018
Errors errors everywhere! - BoilingFrogs 2018Errors errors everywhere! - BoilingFrogs 2018
Errors errors everywhere! - BoilingFrogs 2018
 
Orchestrate Your Choreography
Orchestrate Your ChoreographyOrchestrate Your Choreography
Orchestrate Your Choreography
 
Evolving architecture 4 Confitura 2017
Evolving architecture 4 Confitura 2017Evolving architecture 4 Confitura 2017
Evolving architecture 4 Confitura 2017
 
Evolving architecture 4 QualityExcites 2017
Evolving architecture 4 QualityExcites 2017Evolving architecture 4 QualityExcites 2017
Evolving architecture 4 QualityExcites 2017
 
How to become a DevOps
How to become a DevOpsHow to become a DevOps
How to become a DevOps
 
Evolving architecture @ 4Developers 2017
Evolving architecture @ 4Developers 2017Evolving architecture @ 4Developers 2017
Evolving architecture @ 4Developers 2017
 
Work in agile distributed teams. Cookbook
Work in agile distributed teams. CookbookWork in agile distributed teams. Cookbook
Work in agile distributed teams. Cookbook
 
Jak wdrożyć Continuous Delivery do Twojego (starego) projektu?
Jak wdrożyć Continuous Delivery do Twojego (starego) projektu?Jak wdrożyć Continuous Delivery do Twojego (starego) projektu?
Jak wdrożyć Continuous Delivery do Twojego (starego) projektu?
 
IDE to za mało! Jak stworzyć efektywne środowisko pracy?
IDE to za mało! Jak stworzyć efektywne środowisko pracy?IDE to za mało! Jak stworzyć efektywne środowisko pracy?
IDE to za mało! Jak stworzyć efektywne środowisko pracy?
 

Recently uploaded

527598851-ppc-due-to-various-govt-policies.pdf
527598851-ppc-due-to-various-govt-policies.pdf527598851-ppc-due-to-various-govt-policies.pdf
527598851-ppc-due-to-various-govt-policies.pdf
rajpreetkaur75080
 
Introduction of Biology in living organisms
Introduction of Biology in living organismsIntroduction of Biology in living organisms
Introduction of Biology in living organisms
soumyapottola
 

Recently uploaded (14)

Sharpen existing tools or get a new toolbox? Contemporary cluster initiatives...
Sharpen existing tools or get a new toolbox? Contemporary cluster initiatives...Sharpen existing tools or get a new toolbox? Contemporary cluster initiatives...
Sharpen existing tools or get a new toolbox? Contemporary cluster initiatives...
 
Hi-Tech Industry 2024-25 Prospective.pptx
Hi-Tech Industry 2024-25 Prospective.pptxHi-Tech Industry 2024-25 Prospective.pptx
Hi-Tech Industry 2024-25 Prospective.pptx
 
The Canoga Gardens Development Project. PDF
The Canoga Gardens Development Project. PDFThe Canoga Gardens Development Project. PDF
The Canoga Gardens Development Project. PDF
 
Acorn Recovery: Restore IT infra within minutes
Acorn Recovery: Restore IT infra within minutesAcorn Recovery: Restore IT infra within minutes
Acorn Recovery: Restore IT infra within minutes
 
123445566544333222333444dxcvbcvcvharsh.pptx
123445566544333222333444dxcvbcvcvharsh.pptx123445566544333222333444dxcvbcvcvharsh.pptx
123445566544333222333444dxcvbcvcvharsh.pptx
 
527598851-ppc-due-to-various-govt-policies.pdf
527598851-ppc-due-to-various-govt-policies.pdf527598851-ppc-due-to-various-govt-policies.pdf
527598851-ppc-due-to-various-govt-policies.pdf
 
Oracle Database Administration I (1Z0-082) Exam Dumps 2024.pdf
Oracle Database Administration I (1Z0-082) Exam Dumps 2024.pdfOracle Database Administration I (1Z0-082) Exam Dumps 2024.pdf
Oracle Database Administration I (1Z0-082) Exam Dumps 2024.pdf
 
Getting started with Amazon Bedrock Studio and Control Tower
Getting started with Amazon Bedrock Studio and Control TowerGetting started with Amazon Bedrock Studio and Control Tower
Getting started with Amazon Bedrock Studio and Control Tower
 
Introduction of Biology in living organisms
Introduction of Biology in living organismsIntroduction of Biology in living organisms
Introduction of Biology in living organisms
 
0x01 - Newton's Third Law: Static vs. Dynamic Abusers
0x01 - Newton's Third Law:  Static vs. Dynamic Abusers0x01 - Newton's Third Law:  Static vs. Dynamic Abusers
0x01 - Newton's Third Law: Static vs. Dynamic Abusers
 
Writing Sample 2 -Bridging the Divide: Enhancing Public Engagement in Urban D...
Writing Sample 2 -Bridging the Divide: Enhancing Public Engagement in Urban D...Writing Sample 2 -Bridging the Divide: Enhancing Public Engagement in Urban D...
Writing Sample 2 -Bridging the Divide: Enhancing Public Engagement in Urban D...
 
Eureka, I found it! - Special Libraries Association 2021 Presentation
Eureka, I found it! - Special Libraries Association 2021 PresentationEureka, I found it! - Special Libraries Association 2021 Presentation
Eureka, I found it! - Special Libraries Association 2021 Presentation
 
Pollinator Ambassador Earth Steward Day Presentation 2024-05-22
Pollinator Ambassador Earth Steward Day Presentation 2024-05-22Pollinator Ambassador Earth Steward Day Presentation 2024-05-22
Pollinator Ambassador Earth Steward Day Presentation 2024-05-22
 
05232024 Joint Meeting - Community Networking
05232024 Joint Meeting - Community Networking05232024 Joint Meeting - Community Networking
05232024 Joint Meeting - Community Networking
 

Java: Nie popełniaj tych błędów!

  • 1. JAVA: NIE POPEŁNIAJ TYCH BŁĘDÓW! @dpokusa Daniel Pokusa
  • 2. Not all those who wander are lost.
  • 3. public String reverse(String msg) { } Napisz metodę, która odwróci ciąg znaków. (Jeśli na wejściu dostaniemy “ABCD” to zwróci “DCBA” itd):
  • 4. public String reverse(String msg) { return new StringBuilder(msg) .reverse() .toString(); }
  • 5. public static String reverse(String message) { String ret = ""; for (int i = 0; i < message.length(); i++) { int indexBegin = message.length() - 2 - i; int indexEnd = indexBegin + 1; ret += message.substring(indexBegin, indexEnd); } return ret; }
  • 6. public static String reverse(String message) { String ret = ""; for (int i = 0; i < message.length(); i++) { int indexBegin = message.length() - 2 - i; int indexEnd = indexBegin + 1; ret += message.substring(indexBegin, indexEnd); } return ret; }
  • 7.
  • 8. class Book { private String name; private String isbn; private List<String> authors; public Book(String name, String isbn, List<String> authors) { this.name = name; this.isbn = isbn; this.authors = authors; } // getters }
  • 9. final class Book { private String name; private String isbn; private Collection<String> authors; public Book(String name, String isbn, Collection<String> authors) { this.name = name; this.isbn = isbn; this.authors = authors; } // getters }
  • 10. final class Book { final private String name; final private String isbn; final private Collection<String> authors; public Book(String name, String isbn, Collection<String> authors) { this.name = name; this.isbn = isbn; this.authors = authors; } // getters }
  • 11. List<String> author = new ArrayList<>(); author.add("J.R.R. Tolkien"); Book lotr = new Book( "Lord of the rings", "9780007117116", author ); lotr.getAuthors().add("Daniel Pokusa"); // HAHA! Hacked!
  • 12. final class Book { private final String name; private final String isbn; private final Collection<String> authors; public Book(String name, String isbn, Collection<String> authors) { this.name = name; this.isbn = isbn; this.authors = new ArrayList<>(authors); } public Collection<String> getAuthors() { return Collections.unmodifiableCollection(authors); } // other getters
  • 13. final class Book { private final String name; private final String isbn; private final Collection<String> authors; public Book(String name, String isbn, Collection<String> authors) { this.name = name; this.isbn = isbn; this.authors = new ArrayList<>(authors); } public Collection<String> getAuthors() { return Collections.unmodifiableCollection(authors); } // other getters
  • 14. final class Book { private final String name; private final String isbn; private final Collection<String> authors; public Book(String name, String isbn, Collection<String> authors) { this.name = name; this.isbn = isbn; this.authors = new ArrayList<>(authors); } public Collection<String> getAuthors() { return unmodifiableCollection(authors); } // other getters
  • 15. “Short cuts make delays, but inns make longer ones.” – Frodo
  • 16. public BigDecimal retrieve(String currency) { RestTemplate restTemplate = new RestTemplate(); NBPApiResponse result = restTemplate.getForObject( url, NBPApiResponse.class ); BigDecimal currentRate = result.rates[0].mid; log.info("Current rate for {} is {}", currency, currentRate ); return currentRate; }
  • 17.
  • 18.
  • 19. public BigDecimal retrieve(RestTemplate restTemplate, String currency) { NBPApiResponse result = restTemplate.getForObject( url, NBPApiResponse.class ); BigDecimal currentRate = result.rates[0].mid; log.debug("Current rate for {} is {}", currency, currentRate ); return currentRate; }
  • 20. public BigDecimal retrieve(RestTemplate restTemplate, String currency) { NBPApiResponse result = restTemplate.getForObject( url, NBPApiResponse.class ); BigDecimal currentRate = result.rates[0].mid; log.debug("Current rate for {} is {}", currency, currentRate ); return currentRate; }
  • 21. public BigDecimal retrieve(RestTemplate restTemplate, String currency) { NBPApiResponse result = restTemplate.getForObject( url, NBPApiResponse.class ); BigDecimal currentRate = result.getCurrentRate(); log.debug("Current rate for {} is {}", currency, currentRate ); return currentRate; }
  • 22. public BigDecimal retrieve(RestTemplate restTemplate, String currency) { NBPApiResponse result = restTemplate.getForObject( url, NBPApiResponse.class ); return result.getCurrentRate(); } ?
  • 23. Even the smallest person can change the course of the future. – Galadriel
  • 24. class Person { private String name; private String surname; private String nip; private LocalDate birthdate; // Constructors, getters, ... }
  • 26. public int getAge(LocalDate birthdate); public int getAge(Person p);
  • 27. public int getAge(LocalDate birthdate) { return Period.between(birthdate, now()).getYears(); } public int getAge(Person p);
  • 28. public int getAge(LocalDate birthdate) { return Period.between(birthdate, now()).getYears(); } public int getAge(Person p); LocalDate.now()
  • 29. public int getAge(LocalDate birthdate) { return between(birthdate, now()).getYears(); } public int getAge(Person p);
  • 30. public int getAge(LocalDate date); public int getAge(Person p); public int getAge();
  • 31. public boolean shouldShowHappyBirthdaySignFor(Person person); public boolean shouldShowHappyBirthdaySignFor( LocalDate birthdayDate);
  • 32. All we have to decide is what to do with the time that is given to us. - Gandalf
  • 33. public boolean isSuperhero(Person p, World w); public boolean shouldBeSuperhero(Person p, World w);
  • 34. public int calculateFriendsQuantityFor(Person person); public boolean isPopular(Person person) { return calculateFriendsQuantityFor(person) > MIN_FRIENDS_QUANTITY_FOR_POPULAR_PERSONS; }
  • 35. public int calculateFriendsQuantityFor(Person person); public boolean isPopular(Person person) { return calculateFriendsQuantityFor(person) > MIN_FRIENDS_QUANTITY_FOR_POPULAR_PERSONS; } public static final int MIN_FRIENDS_QUANTITY_FOR_POPULAR_PERSONS = 50;
  • 36. ● get ● retrieve ● load ● calculate ● For ● Into ● Of ● By
  • 37. I will take it! I will take the Ring to Mordor. Though… I do not know the way. - Frodo
  • 38. public class ShoppingBag { public Collection<Item> items = new ArrayList<>(); public static final BigDecimal MULTI_DISCOUNT = new BigDecimal(0.2); // 20% public static final BigDecimal OVERAL_DISCOUNT = new BigDecimal(0.1); // 10% public Receipt calculate() { Receipt r = new Receipt(); for (Item item : items) { r.addPosition(item); int promotions = (int) (item.getQuantity() / 2); if (promotions > 0) { r.addPosition(new Item("More than one promotion!", item.getPrice().multiply(MULTI_DISCOUNT).negate(), promotions)); } } if (r.getFinalPrice().compareTo(new BigDecimal(100)) > 0) { r.addPosition(new Item("Overall discount", r.getFinalPrice().multiply(OVERAL_DISCOUNT).negate(), 1)); } saveReceipt(r); return r; } // Other methods }
  • 39. public Receipt calculate() { Receipt r = new Receipt(); for (Item item : items) { r.addPosition(item); int promotions = (int) (item.getQuantity() / 2); if (promotions > 0) { r.addPosition(new Item("More than one promotion!", item.getPrice().multiply(MULTI_DISCOUNT).negate(), promotions)); } } if (r.getFinalPrice().compareTo(new BigDecimal(100)) > 0) { r.addPosition(new Item("Overall discount", r.getFinalPrice().multiply(OVERAL_DISCOUNT).negate(), 1)); } saveReceipt(r); return r; }
  • 40. public Receipt calculate() { Receipt r = new Receipt(); for (Item item : items) { r.addPosition(item); int promotions = (int) (item.getQuantity() / 2); if (promotions > 0) { r.addPosition(new Item("More than one promotion!", item.getPrice().multiply(MULTI_DISCOUNT).negate(), promotions)); } } if (isOverallDiscountAwarded(r.getFinalPrice())) { r.addPosition(new Item("Overall discount", r.getFinalPrice().multiply(OVERAL_DISCOUNT).negate(), 1)); } saveReceipt(r); return r; }
  • 41. public Receipt calculate() { Receipt r = new Receipt(); for (Item item : items) { r.addPosition(item); int promotions = getNumberOfMultiDiscountsPromotionsFor(item.getQuantity()); if (promotions > 0) { r.addPosition(new Item("More than one promotion!", item.getPrice().multiply(MULTI_DISCOUNT).negate(), promotions)); } } if (isOverallDiscountAwarded(r.getFinalPrice())) { r.addPosition(new Item("Overall discount", r.getFinalPrice().multiply(OVERAL_DISCOUNT).negate(), 1)); } saveReceipt(r); return r; }
  • 42. public Receipt calculate() { Receipt r = new Receipt(); for (Item item : items) { r.addPosition(item); int promotions = getNumberOfMultiDiscountsPromotionsFor(item.getQuantity()); if (promotions > 0) { r.addPosition(new Item("More than one promotion!", item.getPrice().multiply(MULTI_DISCOUNT).negate(), promotions)); } } if (isOverallDiscountAwarded(r.getFinalPrice())) { r.addPosition(new Item("Overall discount", r.getFinalPrice().multiply(OVERAL_DISCOUNT).negate(), 1)); } return r; }
  • 43. public Receipt calculate() { Receipt r = new Receipt(); for (Item item : items) { r.addPosition(item); int promotions = getNumberOfMultiDiscountsPromotionsFor(item.getQuantity()); if (promotions > 0) { r.addPosition(new Item("More than one promotion!", item.getPrice().multiply(MULTI_DISCOUNT).negate(), promotions)); } } if (isOverallDiscountAwarded(r.getFinalPrice())) { r.addPosition(getOveralDiscountFor(r.getFinalPrice())); } return r; }
  • 44. public Receipt calculate() { Receipt r = new Receipt(); for (Item item : items) { r.addPosition(item); int promotions = getNumberOfMultiDiscountsPromotionsFor(item.getQuantity()); if (promotions > 0) { r.addPosition(getMultiDiscountFor(item.getPrice(), promotions))); } } if (isOverallDiscountAwarded(r.getFinalPrice())) { r.addPosition(getOverallDiscountFor(r.getFinalPrice())); } return r; }
  • 45. public Receipt calculate() { Receipt r = new Receipt(); for (Item item : items) { r.addPosition(item); int promotions = getNumberOfMultiDiscountsPromotionsFor(item.getQuantity()); if (promotions > 0) { r.addPosition(getMultiDiscountFor(item.getPrice(), promotions))); } } if (isOverallDiscountAwarded(r.getFinalPrice())) { r.addPosition(getOverallDiscountFor(r.getFinalPrice())); } return r; }
  • 46. public Receipt calculate() { return ReceiptBuilder.for(items) .addItemDiscount(priceItemDiscount) .addOverallDiscount(priceOverallDiscount) .build(); }
  • 47. public Receipt calculate() { return ReceiptBuilder.for(items) .addItemDiscount(priceItemDiscount) .addOverallDiscount(priceOverallDiscount) .build(); } private void calculateItems() { for (Item item : items) { receipt.addPosition(item); for (ItemDiscount discount : itemDiscounts) { Optional<Item> itemDiscount = discount.calculateFor(item); if (itemDiscount.isPresent()) { receipt.addPosition(itemDiscount.get()); } } } }
  • 48. public Receipt calculate() { return ReceiptBuilder.for(items) .addItemDiscount(priceItemDiscount) .addOverallDiscount(priceOverallDiscount) .build(); } private void applyOverallDiscounts() { for (OverallDiscount discount : overallDiscounts) { Optional<Item> discountItem = discount.calculateFor(receipt); if (discountItem.isPresent()) { receipt.addPosition(discountItem.get()); } } }
  • 49. public Receipt calculate() { return ReceiptBuilder.for(items) .addItemDiscount(priceItemDiscount) .addOverallDiscount(priceOverallDiscount) .build(); } public Receipt build() { calculateItemsWithDiscounts(); applyOverallDiscounts(); return receipt; }
  • 50. public Receipt calculate(List<ItemDiscount> itemDiscounts, List<OveralDiscount> overallDiscounts) { return ReceiptBuilder.for(items) .addItemDiscounts(itemDiscounts) .addOverallDiscounts(overallDiscount) .build(); }
  • 51. public class ShoppingBag { public Collection<Item> items = new ArrayList<>(); public static final BigDecimal MULTI_DISCOUNT = new BigDecimal(0.2); // 20% public static final BigDecimal OVERAL_DISCOUNT = new BigDecimal(0.1); // 10% public Receipt calculate() { Receipt r = new Receipt(); for (Item item : items) { r.addPosition(item); int promotions = (int) (item.getQuantity() / 2); if (promotions > 0) { r.addPosition(new Item("More than one promotion!", item.getPrice().multiply(MULTI_DISCOUNT).negate(), promotions)); } } if (r.getFinalPrice().compareTo(new BigDecimal(100)) > 0) { r.addPosition(new Item("Overall discount", r.getFinalPrice().multiply(OVERAL_DISCOUNT).negate(), 1)); } saveReceipt(r); return r; } // Other methods }
  • 52. public Receipt calculate(List<ItemDiscount> itemDiscounts, List<OveralDiscount> overallDiscounts) { return ReceiptBuilder.for(items) .addItemDiscounts(itemDiscounts) .addOverallDiscounts(overallDiscount) .build(); }
  • 53. Courage is found in unlikely places - Gildor
  • 54. ● NIE ignoruj podstaw języka
  • 55. ● NIE ignoruj podstaw języka ● Zrozum istotę klas niemodyfikowalnych i klas wartości
  • 56. ● NIE ignoruj podstaw języka ● Zrozum istotę klas niemodyfikowalnych i klas wartości ● Znaj przynajmniej podstawy GC
  • 57. ● NIE ignoruj podstaw języka ● Zrozum istotę klas niemodyfikowalnych i klas wartości ● Znaj przynajmniej podstawy GC ● Pamiętaj o regule Demeter
  • 58. ● NIE ignoruj podstaw języka ● Zrozum istotę klas niemodyfikowalnych i klas wartości ● Znaj przynajmniej podstawy GC ● Pamiętaj o regule Demeter ● Nazewnictwo jest bardzo ważne
  • 59. ● NIE ignoruj podstaw języka ● Zrozum istotę klas niemodyfikowalnych i klas wartości ● Znaj przynajmniej podstawy GC ●Pamiętaj o regule Demeter ● Nazewnictwo jest bardzo ważne ● SOLID, ale zacznij od porządnego zrozumienia SRP :)
  • 60. ● NIE ignoruj podstaw języka ● Zrozum istotę klas niemodyfikowalnych i klas wartości ● Znaj przynajmniej podstawy GC ●Pamiętaj o regule Demeter ● Nazewnictwo jest bardzo ważne ● SOLID, ale zacznij od porządnego zrozumienia SRP :) ● Jeśli korzystasz z jakiegoś frameworka- spróbuj zrozumieć jego podstawowe mechanizmy ● Pisz testy. ● Programuj tak jakby Code Review mał zrobić Ci socjopata, który zna Twój adres domowy :)
  • 61. ● NIE ignoruj podstaw języka ● Zrozum istotę klas niemodyfikowalnych i klas wartości ● Znaj przynajmniej podstawy GC ●Pamiętaj o regule Demeter ● Nazewnictwo jest bardzo ważne ● SOLID, ale zacznij od porządnego zrozumienia SRP :) ● Jeśli korzystasz z jakiegoś frameworka- spróbuj zrozumieć jego podstawowe mechanizmy
  • 62. ● NIE ignoruj podstaw języka ● Zrozum istotę klas niemodyfikowalnych i klas wartości ● Znaj przynajmniej podstawy GC ●Pamiętaj o regule Demeter ● Nazewnictwo jest bardzo ważne ● SOLID, ale zacznij od porządnego zrozumienia SRP :) ● Jeśli korzystasz z jakiegoś frameworka- spróbuj zrozumieć jego podstawowe mechanizmy ● Pisz testy.
  • 63. ● NIE ignoruj podstaw języka ● Zrozum istotę klas niemodyfikowalnych i klas wartości ● Znaj przynajmniej podstawy GC ●Pamiętaj o regule Demeter ● Nazewnictwo jest bardzo ważne ● SOLID, ale zacznij od porządnego zrozumienia SRP :) ● Jeśli korzystasz z jakiegoś frameworka- spróbuj zrozumieć jego podstawowe mechanizmy ● Pisz testy. ● Programuj tak jakby Code Review mał zrobić Ci socjopata, który zna Twój adres domowy :)
  • 66. Q&A