SlideShare uma empresa Scribd logo
1 de 64
—
Trisha Gee (@trisha_gee)
Developer & Technical Advocate, JetBrains
Is Boilerplate Code
Really So Bad?
Most of the time
TL;DR
Yes
Code is Read More Than Written
“Indeed, the ratio of time spent reading
versus writing is well over 10 to 1. We are
constantly reading old code as part of the
effort to write new code. ...[Therefore,]
making it easy to read makes it easier to
write.”
Robert C. Martin, Clean Code: A Handbook of Agile
Software Craftsmanship
Hello World
Writing: Java & Kotlin
Writing: REPL
package com.mechanitis.demo.boilerplate.demo;
public class Main {
public static void main(String[] args) {
System.out.println("Hello World!");
}
}
println("Hello World!")
Reading: Java
package com.mechanitis.demo.boilerplate.demo
fun main(args: Array<String>) {
println("Hello")
}
println("Hello")
Reading: Kotlin
System.out.println("Hello World!")println("Hello World!")
Reading: JShell
Declaring Variables
Map<Integer, Customer> customers = new HashMap<Integer, Customer>();
Java 5
Map<Integer, Customer> customers = new HashMap<~>();
Java 7
Map<Integer, Customer> customers = new HashMap<>();
Java 10
var customers = new HashMap<Integer, Customer>();
Kotlin
val customers = HashMap<Int, Customer>()
var customers = new HashMap<Integer, Customer>();
Reading: Java
var customers = HashMap<Integer, Customer>()
val customers = HashMap<Int, Customer>()
Reading: Kotlin
Data Classes
Writing: Java
Writing: Kotlin
public class Customer {
private final String name;
private final int age;
@Override
public boolean equals(final Object o) {
if (this == o) {
return true;
}
if (o == null || getClass() != o.getClass()) {
return false;
}
final Customer customer = (Customer) o;
if (age != customer.age) {
return false;
}
return name != null ? name.equals(customer.name) : customer.name == null;
}
@Override
public int hashCode() {
int result = name != null ? name.hashCode() : 0;
result = 31 * result + age;
return result;
}
@Override
public String toString() {
return "Customer{" +
"name='" + name + ''' +
", age=" + age +
'}';
}
private String getName() {
return name;
}
private int getAge() {
return age;
}
public Customer(final String name, final int age) {
this.name = name;
this.age = age;
}
}
Reading: Java
Reading: Kotlin
data class CustomerKotlin (val name: String, val age: Int)
Writing Code Is Not The Hard Bit
http://cr.openjdk.java.net/~briangoetz/
amber/datum.html
Casting
Java
Kotlin
JEP 305: Pattern Matching for
instanceof (Preview)
Nulls
Java
Kotlin
Java 8
Switch
var port = Integer.valueOf(portInputValue);
return switch (port) {
case 20 -> PortType.FTP;
case 80,8080 -> PortType.HTTP;
case 27017 -> PortType.DATABASE;
default -> {
if (port >= 20_001 && port <= 30_000) {
break PortType.SAFE;
} else if (port >= 9080 && port <= 9092) {
break PortType.BUSY;
} else {
break PortType.UNKNOWN;
}
}
};
Default parameter values
Java
Kotlin
Collections
Java
Kotlin
Groovy
Java
Kotlin
Groovy
Lambda Expressions
Java
Kotlin
Functional Parameters
Java 8
Java 8
Kotlin
Navigating Collections
Java 8
Kotlin
Kotlin
Can we go too far?
Dangers of var/val
Customer c = CustomerFactory.create("Sam");Customer c = create("Sam");var c = create("Sam");
Implicits in Scala
When Is Boilerplate Code Good?
Kotlin
Kotlin
Groovy
def 'emits an event for new projects'() {
@Subject
def service = new EventService()
given:
def subscriber = Mock(Subscriber)
subscriber.onSubscribe(_) >> { Subscription sub -> sub.request(MAX_VALUE) }
Flux<Schedule.Project> projects = service.getProjects();
projects.subscribe(subscriber)
when:
service.recordNewActivity(schedule)
then:
1 * subscriber.onNext(schedule.projects[0])
}
In Summary
Elimination of Boilerplate Can
Improve Readability
You can focus on the business logic
data class CustomerKotlin (val name: String, val age: Int)
Not All “Boilerplate” is Boilerplate
…and removing it can change the meaning
val emails = customers.asSequence()
.filter { it.name.startsWith("A") }
.map { it.email }
.toList()
val emails = customers
.filter { it.name.startsWith("A") }
.map { it.email }
Less Code Is Not Always Better
Additional code can improve readability
def 'emits an event for new projects'() {
@Subject
def service = new EventService()
given:
def subscriber = Mock(Subscriber)
subscriber.onSubscribe(_) >> { Subscription sub -> sub.request(MAX_VALUE) }
Flux<Schedule.Project> projects = service.getProjects();
projects.subscribe(subscriber)
when:
service.recordNewActivity(schedule)
then:
1 * subscriber.onNext(schedule.projects[0])
}
Readability is subjective
…and is often related to familiarity
List<String> emails = customers.stream()
.filter(customer -> customer.getName().startsWith("A"))
.map(CustomerJava::getEmail)
.collect(toList());
List<String> emails = new ArrayList<>();
for (CustomerJava customer : customers) {
if (customer.getName().startsWith("A")) {
String email = customer.getEmail();
emails.add(email);
}
}
Modern languages offer the option to
reduce code
Will this make it more readable?
http://bit.ly/BoilJVM

Mais conteúdo relacionado

Mais procurados

parenscript-tutorial
parenscript-tutorialparenscript-tutorial
parenscript-tutorial
tutorialsruby
 
Switch case and looping kim
Switch case and looping kimSwitch case and looping kim
Switch case and looping kim
kimberly_Bm10203
 

Mais procurados (20)

Karate - Web-Service API Testing Made Simple
Karate - Web-Service API Testing Made SimpleKarate - Web-Service API Testing Made Simple
Karate - Web-Service API Testing Made Simple
 
parenscript-tutorial
parenscript-tutorialparenscript-tutorial
parenscript-tutorial
 
Switch case and looping kim
Switch case and looping kimSwitch case and looping kim
Switch case and looping kim
 
The Ongoing Democratization of Robotics Development
The Ongoing Democratization of Robotics DevelopmentThe Ongoing Democratization of Robotics Development
The Ongoing Democratization of Robotics Development
 
Switch case and looping jam
Switch case and looping jamSwitch case and looping jam
Switch case and looping jam
 
From V8 to Modern Compilers
From V8 to Modern CompilersFrom V8 to Modern Compilers
From V8 to Modern Compilers
 
Advanced VCL Workshop - Rogier Mulhuijzen and Stephen Basile at Fastly Altitu...
Advanced VCL Workshop - Rogier Mulhuijzen and Stephen Basile at Fastly Altitu...Advanced VCL Workshop - Rogier Mulhuijzen and Stephen Basile at Fastly Altitu...
Advanced VCL Workshop - Rogier Mulhuijzen and Stephen Basile at Fastly Altitu...
 
What do you mean it needs to be Java based? How jython saved the day.
What do you mean it needs to be Java based? How jython saved the day.What do you mean it needs to be Java based? How jython saved the day.
What do you mean it needs to be Java based? How jython saved the day.
 
Communication between Java and Python
Communication between Java and PythonCommunication between Java and Python
Communication between Java and Python
 
Community Tech Days C# 4.0
Community Tech Days C# 4.0Community Tech Days C# 4.0
Community Tech Days C# 4.0
 
FregeFX - JavaFX with Frege, a Haskell for the JVM
FregeFX - JavaFX with Frege, a Haskell for the JVMFregeFX - JavaFX with Frege, a Haskell for the JVM
FregeFX - JavaFX with Frege, a Haskell for the JVM
 
Loom and concurrency latest
Loom and concurrency latestLoom and concurrency latest
Loom and concurrency latest
 
Information security programming in ruby
Information security programming in rubyInformation security programming in ruby
Information security programming in ruby
 
WebCamp 2016: PHP.Алексей Петров.PHP at Scale: System Architect Toolbox
WebCamp 2016: PHP.Алексей Петров.PHP at Scale: System Architect ToolboxWebCamp 2016: PHP.Алексей Петров.PHP at Scale: System Architect Toolbox
WebCamp 2016: PHP.Алексей Петров.PHP at Scale: System Architect Toolbox
 
Introduction to Khronos SYCL
Introduction to Khronos SYCLIntroduction to Khronos SYCL
Introduction to Khronos SYCL
 
Kotlin
KotlinKotlin
Kotlin
 
Python master class 2
Python master class 2Python master class 2
Python master class 2
 
Frege Tutorial at JavaOne 2015
Frege Tutorial at JavaOne 2015Frege Tutorial at JavaOne 2015
Frege Tutorial at JavaOne 2015
 
OpenAPI and gRPC Side by-Side
OpenAPI and gRPC Side by-SideOpenAPI and gRPC Side by-Side
OpenAPI and gRPC Side by-Side
 
PHP, Under The Hood - DPC
PHP, Under The Hood - DPCPHP, Under The Hood - DPC
PHP, Under The Hood - DPC
 

Semelhante a Is boilerplate code really so bad?

Os Worthington
Os WorthingtonOs Worthington
Os Worthington
oscon2007
 
Polyglot Programming in the JVM
Polyglot Programming in the JVMPolyglot Programming in the JVM
Polyglot Programming in the JVM
Andres Almiray
 
Getting Started with WebSockets and Server-Sent Events
Getting Started with WebSockets and Server-Sent EventsGetting Started with WebSockets and Server-Sent Events
Getting Started with WebSockets and Server-Sent Events
Arun Gupta
 

Semelhante a Is boilerplate code really so bad? (20)

Rapid Web API development with Kotlin and Ktor
Rapid Web API development with Kotlin and KtorRapid Web API development with Kotlin and Ktor
Rapid Web API development with Kotlin and Ktor
 
Automatically Documenting Program Changes
Automatically Documenting Program ChangesAutomatically Documenting Program Changes
Automatically Documenting Program Changes
 
Davide Cerbo - Kotlin loves React - Codemotion Milan 2018
Davide Cerbo - Kotlin loves React - Codemotion Milan 2018Davide Cerbo - Kotlin loves React - Codemotion Milan 2018
Davide Cerbo - Kotlin loves React - Codemotion Milan 2018
 
Compose Code Camp (1).pptx
Compose Code Camp (1).pptxCompose Code Camp (1).pptx
Compose Code Camp (1).pptx
 
GWT Extreme!
GWT Extreme!GWT Extreme!
GWT Extreme!
 
Karate for Complex Web-Service API Testing by Peter Thomas
Karate for Complex Web-Service API Testing by Peter ThomasKarate for Complex Web-Service API Testing by Peter Thomas
Karate for Complex Web-Service API Testing by Peter Thomas
 
Switch case and looping
Switch case and loopingSwitch case and looping
Switch case and looping
 
A quick and fast intro to Kotlin
A quick and fast intro to Kotlin A quick and fast intro to Kotlin
A quick and fast intro to Kotlin
 
10 Groovy Little JavaScript Tips
10 Groovy Little JavaScript Tips10 Groovy Little JavaScript Tips
10 Groovy Little JavaScript Tips
 
Os Worthington
Os WorthingtonOs Worthington
Os Worthington
 
Polyglot Programming in the JVM
Polyglot Programming in the JVMPolyglot Programming in the JVM
Polyglot Programming in the JVM
 
Crushing Latency with Vert.x
Crushing Latency with Vert.xCrushing Latency with Vert.x
Crushing Latency with Vert.x
 
Scaling application with RabbitMQ
Scaling application with RabbitMQScaling application with RabbitMQ
Scaling application with RabbitMQ
 
Getting Started with WebSocket and Server-Sent Events using Java - Arun Gupta...
Getting Started with WebSocket and Server-Sent Events using Java - Arun Gupta...Getting Started with WebSocket and Server-Sent Events using Java - Arun Gupta...
Getting Started with WebSocket and Server-Sent Events using Java - Arun Gupta...
 
Getting Started with WebSockets and Server-Sent Events
Getting Started with WebSockets and Server-Sent EventsGetting Started with WebSockets and Server-Sent Events
Getting Started with WebSockets and Server-Sent Events
 
Intro dotnet
Intro dotnetIntro dotnet
Intro dotnet
 
Java one 2010
Java one 2010Java one 2010
Java one 2010
 
gRPC & Kubernetes
gRPC & KubernetesgRPC & Kubernetes
gRPC & Kubernetes
 
TechDays - IronRuby
TechDays - IronRubyTechDays - IronRuby
TechDays - IronRuby
 
Node.js
Node.jsNode.js
Node.js
 

Mais de Trisha Gee

Mais de Trisha Gee (20)

Career Advice for Architects
Career Advice for Architects Career Advice for Architects
Career Advice for Architects
 
Code Review Best Practices
Code Review Best PracticesCode Review Best Practices
Code Review Best Practices
 
Career Advice for Programmers - ProgNET London
Career Advice for Programmers - ProgNET LondonCareer Advice for Programmers - ProgNET London
Career Advice for Programmers - ProgNET London
 
Is Boilerplate Code Really So Bad?
Is Boilerplate Code Really So Bad?Is Boilerplate Code Really So Bad?
Is Boilerplate Code Really So Bad?
 
Real World Java 9 - JetBrains Webinar
Real World Java 9 - JetBrains WebinarReal World Java 9 - JetBrains Webinar
Real World Java 9 - JetBrains Webinar
 
Real World Java 9
Real World Java 9Real World Java 9
Real World Java 9
 
Real World Java 9
Real World Java 9Real World Java 9
Real World Java 9
 
Career Advice for Programmers
Career Advice for Programmers Career Advice for Programmers
Career Advice for Programmers
 
Real World Java 9
Real World Java 9Real World Java 9
Real World Java 9
 
Becoming fully buzzword compliant
Becoming fully buzzword compliantBecoming fully buzzword compliant
Becoming fully buzzword compliant
 
Real World Java 9 (QCon London)
Real World Java 9 (QCon London)Real World Java 9 (QCon London)
Real World Java 9 (QCon London)
 
Java 9 Functionality and Tooling
Java 9 Functionality and ToolingJava 9 Functionality and Tooling
Java 9 Functionality and Tooling
 
Java 8 and 9 in Anger
Java 8 and 9 in AngerJava 8 and 9 in Anger
Java 8 and 9 in Anger
 
Refactoring to Java 8 (Devoxx BE)
Refactoring to Java 8 (Devoxx BE)Refactoring to Java 8 (Devoxx BE)
Refactoring to Java 8 (Devoxx BE)
 
Migrating to IntelliJ IDEA from Eclipse
Migrating to IntelliJ IDEA from EclipseMigrating to IntelliJ IDEA from Eclipse
Migrating to IntelliJ IDEA from Eclipse
 
Code Review Matters and Manners
Code Review Matters and MannersCode Review Matters and Manners
Code Review Matters and Manners
 
Refactoring to Java 8 (QCon New York)
Refactoring to Java 8 (QCon New York)Refactoring to Java 8 (QCon New York)
Refactoring to Java 8 (QCon New York)
 
Refactoring to Java 8 (Devoxx UK)
Refactoring to Java 8 (Devoxx UK)Refactoring to Java 8 (Devoxx UK)
Refactoring to Java 8 (Devoxx UK)
 
Staying Ahead of the Curve
Staying Ahead of the CurveStaying Ahead of the Curve
Staying Ahead of the Curve
 
Level Up Your Automated Tests
Level Up Your Automated TestsLevel Up Your Automated Tests
Level Up Your Automated Tests
 

Último

Architecting Cloud Native Applications
Architecting Cloud Native ApplicationsArchitecting Cloud Native Applications
Architecting Cloud Native Applications
WSO2
 
Finding Java's Hidden Performance Traps @ DevoxxUK 2024
Finding Java's Hidden Performance Traps @ DevoxxUK 2024Finding Java's Hidden Performance Traps @ DevoxxUK 2024
Finding Java's Hidden Performance Traps @ DevoxxUK 2024
Victor Rentea
 
Modular Monolith - a Practical Alternative to Microservices @ Devoxx UK 2024
Modular Monolith - a Practical Alternative to Microservices @ Devoxx UK 2024Modular Monolith - a Practical Alternative to Microservices @ Devoxx UK 2024
Modular Monolith - a Practical Alternative to Microservices @ Devoxx UK 2024
Victor Rentea
 

Último (20)

Apidays New York 2024 - Scaling API-first by Ian Reasor and Radu Cotescu, Adobe
Apidays New York 2024 - Scaling API-first by Ian Reasor and Radu Cotescu, AdobeApidays New York 2024 - Scaling API-first by Ian Reasor and Radu Cotescu, Adobe
Apidays New York 2024 - Scaling API-first by Ian Reasor and Radu Cotescu, Adobe
 
Exploring the Future Potential of AI-Enabled Smartphone Processors
Exploring the Future Potential of AI-Enabled Smartphone ProcessorsExploring the Future Potential of AI-Enabled Smartphone Processors
Exploring the Future Potential of AI-Enabled Smartphone Processors
 
Architecting Cloud Native Applications
Architecting Cloud Native ApplicationsArchitecting Cloud Native Applications
Architecting Cloud Native Applications
 
Biography Of Angeliki Cooney | Senior Vice President Life Sciences | Albany, ...
Biography Of Angeliki Cooney | Senior Vice President Life Sciences | Albany, ...Biography Of Angeliki Cooney | Senior Vice President Life Sciences | Albany, ...
Biography Of Angeliki Cooney | Senior Vice President Life Sciences | Albany, ...
 
Connector Corner: Accelerate revenue generation using UiPath API-centric busi...
Connector Corner: Accelerate revenue generation using UiPath API-centric busi...Connector Corner: Accelerate revenue generation using UiPath API-centric busi...
Connector Corner: Accelerate revenue generation using UiPath API-centric busi...
 
Manulife - Insurer Transformation Award 2024
Manulife - Insurer Transformation Award 2024Manulife - Insurer Transformation Award 2024
Manulife - Insurer Transformation Award 2024
 
EMPOWERMENT TECHNOLOGY GRADE 11 QUARTER 2 REVIEWER
EMPOWERMENT TECHNOLOGY GRADE 11 QUARTER 2 REVIEWEREMPOWERMENT TECHNOLOGY GRADE 11 QUARTER 2 REVIEWER
EMPOWERMENT TECHNOLOGY GRADE 11 QUARTER 2 REVIEWER
 
Rising Above_ Dubai Floods and the Fortitude of Dubai International Airport.pdf
Rising Above_ Dubai Floods and the Fortitude of Dubai International Airport.pdfRising Above_ Dubai Floods and the Fortitude of Dubai International Airport.pdf
Rising Above_ Dubai Floods and the Fortitude of Dubai International Airport.pdf
 
2024: Domino Containers - The Next Step. News from the Domino Container commu...
2024: Domino Containers - The Next Step. News from the Domino Container commu...2024: Domino Containers - The Next Step. News from the Domino Container commu...
2024: Domino Containers - The Next Step. News from the Domino Container commu...
 
Finding Java's Hidden Performance Traps @ DevoxxUK 2024
Finding Java's Hidden Performance Traps @ DevoxxUK 2024Finding Java's Hidden Performance Traps @ DevoxxUK 2024
Finding Java's Hidden Performance Traps @ DevoxxUK 2024
 
ProductAnonymous-April2024-WinProductDiscovery-MelissaKlemke
ProductAnonymous-April2024-WinProductDiscovery-MelissaKlemkeProductAnonymous-April2024-WinProductDiscovery-MelissaKlemke
ProductAnonymous-April2024-WinProductDiscovery-MelissaKlemke
 
Emergent Methods: Multi-lingual narrative tracking in the news - real-time ex...
Emergent Methods: Multi-lingual narrative tracking in the news - real-time ex...Emergent Methods: Multi-lingual narrative tracking in the news - real-time ex...
Emergent Methods: Multi-lingual narrative tracking in the news - real-time ex...
 
Exploring Multimodal Embeddings with Milvus
Exploring Multimodal Embeddings with MilvusExploring Multimodal Embeddings with Milvus
Exploring Multimodal Embeddings with Milvus
 
[BuildWithAI] Introduction to Gemini.pdf
[BuildWithAI] Introduction to Gemini.pdf[BuildWithAI] Introduction to Gemini.pdf
[BuildWithAI] Introduction to Gemini.pdf
 
Modular Monolith - a Practical Alternative to Microservices @ Devoxx UK 2024
Modular Monolith - a Practical Alternative to Microservices @ Devoxx UK 2024Modular Monolith - a Practical Alternative to Microservices @ Devoxx UK 2024
Modular Monolith - a Practical Alternative to Microservices @ Devoxx UK 2024
 
Polkadot JAM Slides - Token2049 - By Dr. Gavin Wood
Polkadot JAM Slides - Token2049 - By Dr. Gavin WoodPolkadot JAM Slides - Token2049 - By Dr. Gavin Wood
Polkadot JAM Slides - Token2049 - By Dr. Gavin Wood
 
Apidays New York 2024 - APIs in 2030: The Risk of Technological Sleepwalk by ...
Apidays New York 2024 - APIs in 2030: The Risk of Technological Sleepwalk by ...Apidays New York 2024 - APIs in 2030: The Risk of Technological Sleepwalk by ...
Apidays New York 2024 - APIs in 2030: The Risk of Technological Sleepwalk by ...
 
CNIC Information System with Pakdata Cf In Pakistan
CNIC Information System with Pakdata Cf In PakistanCNIC Information System with Pakdata Cf In Pakistan
CNIC Information System with Pakdata Cf In Pakistan
 
How to Troubleshoot Apps for the Modern Connected Worker
How to Troubleshoot Apps for the Modern Connected WorkerHow to Troubleshoot Apps for the Modern Connected Worker
How to Troubleshoot Apps for the Modern Connected Worker
 
"I see eyes in my soup": How Delivery Hero implemented the safety system for ...
"I see eyes in my soup": How Delivery Hero implemented the safety system for ..."I see eyes in my soup": How Delivery Hero implemented the safety system for ...
"I see eyes in my soup": How Delivery Hero implemented the safety system for ...
 

Is boilerplate code really so bad?

Notas do Editor

  1. Intro you Intro your experience as a Java developer Talk about how you were never bothered by boilerplace
  2. Managers can leave now
  3. Duplication; convention (get); not needed (new, ;); messy (final)
  4. Java has crap loads of boilerplate Kotlin less The REPL less (not even semi colons!) Code generation is fine for <9 REPL optimises for writability
  5. Java 5: Generics Java 7: Diamond operator Java 10: Local-variable type inference Kotlin: var & val
  6. Java 5: Generics Java 7: Diamond operator Java 10: Local-variable type inference Kotlin: var & val
  7. Java 5: Generics Java 7: Diamond operator Java 10: Local-variable type inference Kotlin: var & val
  8. Java 5: Generics Java 7: Diamond operator Java 10: Local-variable type inference Kotlin: var & val
  9. Modern Java is much improved
  10. Kotlin tries to remove everything you don’t need
  11. Live demo of generating the code? Kotlin version Turn on code folding (properties, then methods) Writing is fine, reading is terrible
  12. Kotlin’s List is automatically read only, has mutable list otherwise. Easier to tell when reading Java’s list gives a runtime error if you try to add anything to it
  13. Kotlin’s List is automatically read only, has mutable list otherwise. Easier to tell when reading Java’s list gives a runtime error if you try to add anything to it
  14. Can be slideware On the other hand, IntelliJ does a good job of generating and hiding the code here Slideware for the summary?
  15. Can be slideware On the other hand, IntelliJ does a good job of generating and hiding the code here Slideware for the summary?
  16. Java 5: Generics Java 7: Diamond operator Java 10: Local-variable type inference Kotlin: var & val
  17. Java 5: Generics Java 7: Diamond operator Java 10: Local-variable type inference Kotlin: var & val
  18. Kotlin and modern Java both do this
  19. Kotlin and modern Java both do this
  20. Kotlin and modern Java both do this
  21. Kotlin and modern Java both do this
  22. Kotlin and modern Java both do this
  23. Kotlin and modern Java both do this