SlideShare a Scribd company logo
1 of 41
Download to read offline
Miroslav Wengner
Boost delivery stream
with code discipline engineering
Safe Harbour Statement
All what you will hear can be di
ff
erent, this presentation is for
motivational purposes …
Miroslav Wengner
• Husband, Father, Software Engineer, Author, Blogger, Technology Enthusiast
• Book Author: Practical Design Patterns for Java Developers [Packt]
• JCP: Executive Committee Board Member, OpenJDK Committer
• Java Mission Control Project, Open-Source projects
• Co-Author of Robo4J Project (Duke Award)
• Java Champion, JavaOne RockStar
• Principal Engineer at OpenValue
• Group Of Talented and Motivated Individuals
• Netherlands, Germany, Switzerland, Austria…
• Fun, Development, Trainings, Migration and
more…
Agenda
• [study] cost of the bad code
• [engineering] pyramid of project healthiness
• [power features] gang of 21
• [anti-patterns] let’s get serious
• [anti-patterns, platform] squeezing resources and proper tools
• [design-patterns] 2 cents make di
ff
• [design-patterns] creational, structural, behavioral and concurrency
• Conclusion
• Q/A
[study] cost of the bad code
• CNBC Global CFO Council about [2018, Stripe and Harris Poll]
• Company lose upward $300 billion/year
• technical debts
• maintaining legacy
• impacts of bad code
• 57% of the week productive time ?
?
Average Working Week
10%
34%
57%
Work time
Tech debt
Bad code
[engineering] pyramid of focus healthiness
information span
consequence
of
poor-solution
innovations
requirements stream
tooling awareness
domain knowledge
< DISCIPLINE >
pyramid of project healthiness
FOCUS
ARCHITECTURE
CODE
PLATFORM
[power features] gang of 21
• innovation through stability and compatibility “guarantees”
• Language syntax
• Local-Variable type inference (323)
• Record Patterns (440), Sealed classes (409)
• Switch expression and pattern matching (441)
• Text Blocks (378)
• Internal APIs
• Sequenced Collection (431)
• Virtual Threads and Executors(444) ?
<= Module system (200, 261)
[power features] gang of 21
sealed interface Val permits Ch {};
record Ch(Integer v) implements Val {
String toText() {
var number = v;
return switch (number) {
case Integer i
when i > 74 -> {yield new String("".getBytes(), Charset.defaultCharset());}
case null -> “”;
default -> Character.toString(number);
};}}
Executors.newVirtualThreadPerTaskExecutor().submit(() -> System.out.println("""
%sON%d""".formatted(IntStream.of(74, 67, 80)
.mapToObj(Ch::new).map(Ch::toText).collect(Collectors.joining()),
ThreadLocalRandom.current().nextInt(2023, 2024))));
?
[anti-patterns] let’s get serious
keep it simple
• works … for me, now
• FITYMI
• innovation through bottlenecks?
• we
fi
x it later … so when … ?
• test free …
?
• limits an ability to e
ff
ectively address the issue: bottleneck
[anti-patterns, requirements] originated by code
Cut and paste programming
Spaghetti code
Blob
Lava
fl
ow
Functional decomposition
Boat anchor
expecting next challenge from outdated
God Class
PoC to Production
past is knocking
keep it single
[anti-patterns, domain]: originated by architecture
?
Golden hammer
Continuous obsolescence
Input kludge
Working in mine
fi
eld
Ambiguous viewpoint
Poltergeists
Dead end
believe and not verify
Test? appears like magic …
don’t remove
old good approach
onion
don't touch
[anti-patterns, platform] squeezing resources
MODEL:
record Sensor(int value) {}
LOGIC:
Collection<Sensor> set = provider.values();
for (Sensor e : set) {
SensorAlarmSystemUtil.evaluateAlarm(provider, e.value(), measurementCount);
}
UTILS:
void evaluateAlarm(Map<Integer, Sensor> storage, Integer criticalValue, long measurementNumber) {
if (!storage.containsKey(criticalValue)) {…}
“Der liebe Gott steckt im Detail”
Aby Warburg
[anti-patterns, platform] squeezing resources
• What about AutoBoxing ?
• Platform optimalisation
• internal caches: Integers, …
?
[anti-patterns, platform] squeezing resources
?
record Sensor(Integer value) {}
Collection<Sensor> set = provider.values();
for (Sensor e : set) {
SensorAlarmSystemUtil.evaluateAlarm(provider, e.value(), measurementCount);
}
void evaluateAlarm(Map<Integer, Sensor> storage, Integer criticalValue, long measurementNumber) {
if (!storage.containsKey(criticalValue)) {
System.out.println(“SHOULD NOT HAPPEN!”);
}
FEEL DIFFERENCE ?
[anti-patterns, platform] proper tools
?
MODEL:
for (int i = 0; i < THREADS_NUMBER; i++) {
builder.addRunnable(
new VehicleAnalyticalWorker(i,ELEMENTS_NUMBER, new ArrayList<>(), new ArrayList<>())
);
}
LOGIC:
public int countIntersections(VehicleDataContainer c) {
int count = 0;
for (int n : collection) {
if (c.getCollection().contains(n)) {
count++;
}
}
return count;
}
[anti-patterns, platform] proper tools
Internal JDK APIs, java.base
• Impact:
• produce less code
• e
ff
ective behaviour
• optimisation under the hood
• selecting the right tool
?
[anti-patterns, platform] proper tools
?
MODEL:
for (int i = 0; i < THREADS_NUMBER; i++) {
builder.addRunnable(
new VehicleAnalyticalWorker(i, ELEMENTS_NUMBER, new HashSet<>(), new HashSet<>())
);
}
FEEL DIFFERENCE ?
Anti-pattern known as a CODE SMELL
LOAD DISTRIBUTION
[design-patterns]: 2 cents make diff
CREATE MAINTAINABLE NAMING PATTERN
Encapsulation
Inheritance
Polymorphism
Abstraction
Expose what is required
Inevitable evolution
Behaviour on demand
Generalisation
[pillars] follow EIPA
towards evolution: Do NOT Repeat Yourself
Single Responsibility
Open-Close
Liskov-Sustitution
Interface Segregation
Expose what is required
Inevitable evolution
Behaviour on demand
Generalisation
[principles] stay SOLID
towards evolution: Do NOT Repeat Yourself
Dependency Inversion
[design-patterns]: coding standards are inevitable
• readable, maintainable code, performance is not the
“target”
• Pareto Principle (80/20) : depends on perspective
• Maintainable naming, CleanCode, Best Practices
• Start small to build something useful!
• Design Patterns
Creational
Structural
Behavioral
Concurrency
[design-patterns] creational
?
Factory Method
Abstract Factory
Builder
Prototype
Singleton Object pool
Lazy initialization
Dependency
injection
[design-patterns] creational - java
?
Builder
class Car implements Vehicle {
final static class Builder {
private Part cabin = Part.PART_EMPTY;
private Part engine = Part.PART_EMPTY;
public Builder addCabin(String name) {
this.cabin = new Part(name);
return this;
}
separate the composition from the representation
record Part(String name) {
static final Part PART_EMPTY = new Part("");
}
[design-patterns] creational - scala
?
Builder
class Car(val name: String = "no_name",
val cabin: Part = EMPTY_PART,
val engine: Part = EMPTY_PART) extends Vehicle {
override def showParts(): Seq[Part] = Seq(cabin, engine)
}
object Car {
case class Builder private(cabin: Part = EMPTY_PART, engine: Part = EMPTY_PART) {
def withEngine(name: String): Builder = {
val part = Part(name)
copy(engine = part)
}
separate the composition from the representation
object Part {
val EMPTY_PART = new Part("")
}
case class Part(name: String = ""){ }
[design-patterns] creational - kotlin
?
Builder
class Car(
private val name: String,
private val cabin: Part = Part.PART_EMPTY,
private val engine: Part = Part.PART_EMPTY
) : Vehicle {
data class Builder(
var name: String = "no_name",
var cabin: Part = Part.PART_EMPTY,
var engine: Part = Part.PART_EMPTY
) {
fun withName(name: String) = apply {
this.name = name
}
separate the composition from the representation
class Part constructor(val name: String){
companion object {
val PART_EMPTY = Part("")
}
override fun toString(): String {
return "Part(${name})"
}
}
[design-patterns] creational - java 21
?
Factory Method
static Vehicle produce(Specs specs) {
return switch (specs) {
case CarSpecs s when s.specType().startsWith("sport") -> {
var car = new Car("sport_car");
System.out.println("factory, car, more action");
yield car;
}
case TruckSpecs ts -> new Truck("magic_truck");
default -> throw new IllegalArgumentException("""
not supported specs:'%s'""".formatted(specs));
};
}
centralise the class instantiation
[design-patterns] creational - kotlin
?
Factory Method
fun produce(specs: Specs): Vehicle {
return when (specs) {
is CarSpecs -> {
if (specs.specType.startsWith(“sport")) {
val car = Car("sport_car")
println("car:${car}")
return car
} else {
throw IllegalArgumentException("not supported car:’${specs.specType}'")
}
}
is TruckSpecs -> Truck("magic_truck")
else -> throw IllegalArgumentException("not supported specs:'$specs'")
}
}
centralise the class instantiation
[design-patterns] creational - scala
?
Factory Method
def produce(specs: Specs): Vehicle = specs match {
case carSpec: CarSpecs if carSpec.specType.startsWith("sport") => {
val car = new Car(name = "sport_car")
print("factory, car, more action")
car
}
case truckSpec: TruckSpecs => new Truck("magic_truck")
case _ => throw new IllegalArgumentException(s"not supported specs:'$specs'")
}
centralise the class instantiation
[design-patterns] structural
?
Adapter Bridge
Composite Decorator
Facade Filter
Flyweight Front controller
Marker Module
Proxy Twin
[design-patterns] structural
?
Adapter
sealed interface VehicleCommand permits StartCommand, StopCommand {..}
record StartCommand(…) implements VehicleCommand {
…
@Override
public void process(String command) {
if(command.contains("start")){
switch (vehicle){
case StandardVehicle v when v.getLoadWeight() > 1 ->
System.out.printf("""
%s with description:’%s’… v, v.getDescription(), v.getLoadWeight());
case StandardVehicle v -> System.out.printf("""
%s with description:'%s'%n""", v, v.getDescription());
case SportVehicle v -> System.out.println(v);
default -> System.out.println("NOTHING");
}
executed.set(true);
allows to work classes together
[design-patterns] structural
?
Facade
sealed interface VehicleCommand permits StartCommand, StopCommand {..}
uni
fi
ed interfaces to underlaying subsystems
public interface VehicleFactory<T> {
Vehicle produce(T type);
}
[design-patterns] behavioral
?
Caching Chain of responsibility
Command Interpreter Iterator
Mediator
Null Object
Observer
Pipeline
State
Strategy
Template
Visitor
[design-patterns] behavioral
?
Command like action, event on what client act
public record StartCommand(…) implements VehicleCommand {…
public final class StopCommand implements VehicleCommand {
private final Vehicle vehicle;
private boolean executed;
public StopCommand(Vehicle vehicle){
this.vehicle = vehicle;
}
@Override
public void process(String command) {
…
[design-patterns] behavioral
?
Caching
Observer
public class Driver {
private final List<VehicleCommand> commands = new ArrayList<>();
public Driver addCommand(VehicleCommand command){…}
public void executeCommands(final String command){
commands.forEach(c -> {
// Records decomposition
if(c instanceof StartCommand(Vehicle v, AtomicBoolean state)){
….
}
public void printCommands() {
System.out.printf("""
Considered COMMANDS:%n%s""", commands.stream()
.map(VehicleCommand::status)
.collect(Collectors.joining("")));
react on demand reuse knowledge
[design-patterns] concurrency is inevitable
?
Active Object Asynchronous Method
Balking Double Checked Locking
Read Write Lock Producer consumer
Scheduler Thread Pool
CONCURRENCY IS HARD <3
[design-patterns] concurrency
?
Balking
var vehicle = new Vehicle();
var numberOfDrivers = 5;
var executors = Executors.newFixedThreadPool(2);
for (int i = 0; i < numberOfDrivers; i++) {
executors.submit(vehicle::drive);
}
an access to critical section
enum VehicleState {
MOVING,
STOPPED,
}
[design-patterns] concurrency
?
ReentrantReadWriteLock readWriteLock = new ReentrantReadWriteLock();
var sensor = new Sensor(readWriteLock.readLock(), readWriteLock.writeLock());
var sensorWriter = new SensorWriter("writer-1", sensor);
var writerThread = getWriterThread(sensorWriter);
ExecutorService executor = Executors.newFixedThreadPool(NUMBER_READERS);
var readers = IntStream.range(0, NUMBER_READERS)
.boxed().map(i -> new SensorReader("reader-" + i, sensor, CYCLES_READER)).toList();
readers.forEach(executor::submit);
Read Write Lock natural exclusivity for lock acquisition
Conclusion
• Code Discipline Engineering:
• pyramid of focus healthiness
• enforce iterative process by following EIPA and staying SOLID
• Design-Patterns: improve maintainability and reduce verbosity
• Don’t Repeat Yourself
• Maintainable naming standards
• Costs “reduction”
?
Q / A
twitter: @miragemiko
github:@mirage22
email: miro@openvalue.de
Thank YOU !
References:
• Project Amber: https://openjdk.org/projects/amber/
• Project Valhalla: https://openjdk.org/projects/valhalla/
• Project Panama: https://openjdk.org/projects/panama/
• JFR Project: https://github.com/openjdk/jmc
• OpenJDK: https://openjdk.org/
• foojay.io: https://foojay.io/today/author/miro-wengner/
• OpenValue Blog: https://openvalue.blog/
• GitHub Examples: https://github.com/mirage22/mastering_java_enhancements
Title : Practical Design Patterns for Java Developers [PACKT]
Amazon: https://a.co/d/eizSkr2
GitHub: https://github.com/PacktPublishing/Practical-Design-Patterns-for-Java-Developers

More Related Content

Similar to Boost delivery stream with code discipline engineering

Introduction to web programming for java and c# programmers by @drpicox
Introduction to web programming for java and c# programmers by @drpicoxIntroduction to web programming for java and c# programmers by @drpicox
Introduction to web programming for java and c# programmers by @drpicoxDavid Rodenas
 
Heroku pop-behind-the-sense
Heroku pop-behind-the-senseHeroku pop-behind-the-sense
Heroku pop-behind-the-senseBen Lin
 
Headache from using mathematical software
Headache from using mathematical softwareHeadache from using mathematical software
Headache from using mathematical softwarePVS-Studio
 
Microservices Chaos Testing at Jet
Microservices Chaos Testing at JetMicroservices Chaos Testing at Jet
Microservices Chaos Testing at JetC4Media
 
Event-driven IO server-side JavaScript environment based on V8 Engine
Event-driven IO server-side JavaScript environment based on V8 EngineEvent-driven IO server-side JavaScript environment based on V8 Engine
Event-driven IO server-side JavaScript environment based on V8 EngineRicardo Silva
 
Designing REST API automation tests in Kotlin
Designing REST API automation tests in KotlinDesigning REST API automation tests in Kotlin
Designing REST API automation tests in KotlinDmitriy Sobko
 
The First C# Project Analyzed
The First C# Project AnalyzedThe First C# Project Analyzed
The First C# Project AnalyzedPVS-Studio
 
Spring Day | Spring and Scala | Eberhard Wolff
Spring Day | Spring and Scala | Eberhard WolffSpring Day | Spring and Scala | Eberhard Wolff
Spring Day | Spring and Scala | Eberhard WolffJAX London
 
Andrea Lattuada, Gabriele Petronella - Building startups on Scala
Andrea Lattuada, Gabriele Petronella - Building startups on ScalaAndrea Lattuada, Gabriele Petronella - Building startups on Scala
Andrea Lattuada, Gabriele Petronella - Building startups on ScalaScala Italy
 
SproutCore and the Future of Web Apps
SproutCore and the Future of Web AppsSproutCore and the Future of Web Apps
SproutCore and the Future of Web AppsMike Subelsky
 
React Native - Workshop
React Native - WorkshopReact Native - Workshop
React Native - WorkshopFellipe Chagas
 
Scalable web application architecture
Scalable web application architectureScalable web application architecture
Scalable web application architecturepostrational
 
Unit testing PHP apps with PHPUnit
Unit testing PHP apps with PHPUnitUnit testing PHP apps with PHPUnit
Unit testing PHP apps with PHPUnitMichelangelo van Dam
 
.NET Foundation, Future of .NET and C#
.NET Foundation, Future of .NET and C#.NET Foundation, Future of .NET and C#
.NET Foundation, Future of .NET and C#Bertrand Le Roy
 
The operation principles of PVS-Studio static code analyzer
The operation principles of PVS-Studio static code analyzerThe operation principles of PVS-Studio static code analyzer
The operation principles of PVS-Studio static code analyzerAndrey Karpov
 
Developer Joy - How great teams get s%*t done
Developer Joy - How great teams get s%*t doneDeveloper Joy - How great teams get s%*t done
Developer Joy - How great teams get s%*t doneSven Peters
 

Similar to Boost delivery stream with code discipline engineering (20)

DIWE - Advanced PHP Concepts
DIWE - Advanced PHP ConceptsDIWE - Advanced PHP Concepts
DIWE - Advanced PHP Concepts
 
Introduction to web programming for java and c# programmers by @drpicox
Introduction to web programming for java and c# programmers by @drpicoxIntroduction to web programming for java and c# programmers by @drpicox
Introduction to web programming for java and c# programmers by @drpicox
 
Heroku pop-behind-the-sense
Heroku pop-behind-the-senseHeroku pop-behind-the-sense
Heroku pop-behind-the-sense
 
C#2
C#2C#2
C#2
 
Headache from using mathematical software
Headache from using mathematical softwareHeadache from using mathematical software
Headache from using mathematical software
 
L04 Software Design Examples
L04 Software Design ExamplesL04 Software Design Examples
L04 Software Design Examples
 
Microservices Chaos Testing at Jet
Microservices Chaos Testing at JetMicroservices Chaos Testing at Jet
Microservices Chaos Testing at Jet
 
Event-driven IO server-side JavaScript environment based on V8 Engine
Event-driven IO server-side JavaScript environment based on V8 EngineEvent-driven IO server-side JavaScript environment based on V8 Engine
Event-driven IO server-side JavaScript environment based on V8 Engine
 
Designing REST API automation tests in Kotlin
Designing REST API automation tests in KotlinDesigning REST API automation tests in Kotlin
Designing REST API automation tests in Kotlin
 
Java Lab Manual
Java Lab ManualJava Lab Manual
Java Lab Manual
 
The First C# Project Analyzed
The First C# Project AnalyzedThe First C# Project Analyzed
The First C# Project Analyzed
 
Spring Day | Spring and Scala | Eberhard Wolff
Spring Day | Spring and Scala | Eberhard WolffSpring Day | Spring and Scala | Eberhard Wolff
Spring Day | Spring and Scala | Eberhard Wolff
 
Andrea Lattuada, Gabriele Petronella - Building startups on Scala
Andrea Lattuada, Gabriele Petronella - Building startups on ScalaAndrea Lattuada, Gabriele Petronella - Building startups on Scala
Andrea Lattuada, Gabriele Petronella - Building startups on Scala
 
SproutCore and the Future of Web Apps
SproutCore and the Future of Web AppsSproutCore and the Future of Web Apps
SproutCore and the Future of Web Apps
 
React Native - Workshop
React Native - WorkshopReact Native - Workshop
React Native - Workshop
 
Scalable web application architecture
Scalable web application architectureScalable web application architecture
Scalable web application architecture
 
Unit testing PHP apps with PHPUnit
Unit testing PHP apps with PHPUnitUnit testing PHP apps with PHPUnit
Unit testing PHP apps with PHPUnit
 
.NET Foundation, Future of .NET and C#
.NET Foundation, Future of .NET and C#.NET Foundation, Future of .NET and C#
.NET Foundation, Future of .NET and C#
 
The operation principles of PVS-Studio static code analyzer
The operation principles of PVS-Studio static code analyzerThe operation principles of PVS-Studio static code analyzer
The operation principles of PVS-Studio static code analyzer
 
Developer Joy - How great teams get s%*t done
Developer Joy - How great teams get s%*t doneDeveloper Joy - How great teams get s%*t done
Developer Joy - How great teams get s%*t done
 

More from Miro Wengner

New Java features: Simplified Design Patterns[LIT3826]
New Java features: Simplified Design Patterns[LIT3826]New Java features: Simplified Design Patterns[LIT3826]
New Java features: Simplified Design Patterns[LIT3826]Miro Wengner
 
ASML_FlightRecorderMeetsJava.pdf
ASML_FlightRecorderMeetsJava.pdfASML_FlightRecorderMeetsJava.pdf
ASML_FlightRecorderMeetsJava.pdfMiro Wengner
 
DevDays: Profiling With Java Flight Recorder
DevDays: Profiling With Java Flight RecorderDevDays: Profiling With Java Flight Recorder
DevDays: Profiling With Java Flight RecorderMiro Wengner
 
JMC/JFR: Kotlin spezial
JMC/JFR: Kotlin spezialJMC/JFR: Kotlin spezial
JMC/JFR: Kotlin spezialMiro Wengner
 
Plug Hardware and Play Java
Plug Hardware and Play JavaPlug Hardware and Play Java
Plug Hardware and Play JavaMiro Wengner
 
From Concept to Robotic Overlord with Robo4J
From Concept to Robotic Overlord with Robo4J From Concept to Robotic Overlord with Robo4J
From Concept to Robotic Overlord with Robo4J Miro Wengner
 
JavaOne 2016 :: Bringing Robot online with Robo4j Framework
JavaOne 2016 :: Bringing Robot online with Robo4j FrameworkJavaOne 2016 :: Bringing Robot online with Robo4j Framework
JavaOne 2016 :: Bringing Robot online with Robo4j FrameworkMiro Wengner
 
JavaOne presentation - building steps :: Number42 is alive
JavaOne presentation - building steps :: Number42 is alive JavaOne presentation - building steps :: Number42 is alive
JavaOne presentation - building steps :: Number42 is alive Miro Wengner
 
The Robot under dictate of the LegoMindStorm Java Concurrency API
The Robot under dictate of the LegoMindStorm Java Concurrency APIThe Robot under dictate of the LegoMindStorm Java Concurrency API
The Robot under dictate of the LegoMindStorm Java Concurrency APIMiro Wengner
 
How RaspberryPi workers building GraphDatabase
How RaspberryPi workers building GraphDatabaseHow RaspberryPi workers building GraphDatabase
How RaspberryPi workers building GraphDatabaseMiro Wengner
 

More from Miro Wengner (10)

New Java features: Simplified Design Patterns[LIT3826]
New Java features: Simplified Design Patterns[LIT3826]New Java features: Simplified Design Patterns[LIT3826]
New Java features: Simplified Design Patterns[LIT3826]
 
ASML_FlightRecorderMeetsJava.pdf
ASML_FlightRecorderMeetsJava.pdfASML_FlightRecorderMeetsJava.pdf
ASML_FlightRecorderMeetsJava.pdf
 
DevDays: Profiling With Java Flight Recorder
DevDays: Profiling With Java Flight RecorderDevDays: Profiling With Java Flight Recorder
DevDays: Profiling With Java Flight Recorder
 
JMC/JFR: Kotlin spezial
JMC/JFR: Kotlin spezialJMC/JFR: Kotlin spezial
JMC/JFR: Kotlin spezial
 
Plug Hardware and Play Java
Plug Hardware and Play JavaPlug Hardware and Play Java
Plug Hardware and Play Java
 
From Concept to Robotic Overlord with Robo4J
From Concept to Robotic Overlord with Robo4J From Concept to Robotic Overlord with Robo4J
From Concept to Robotic Overlord with Robo4J
 
JavaOne 2016 :: Bringing Robot online with Robo4j Framework
JavaOne 2016 :: Bringing Robot online with Robo4j FrameworkJavaOne 2016 :: Bringing Robot online with Robo4j Framework
JavaOne 2016 :: Bringing Robot online with Robo4j Framework
 
JavaOne presentation - building steps :: Number42 is alive
JavaOne presentation - building steps :: Number42 is alive JavaOne presentation - building steps :: Number42 is alive
JavaOne presentation - building steps :: Number42 is alive
 
The Robot under dictate of the LegoMindStorm Java Concurrency API
The Robot under dictate of the LegoMindStorm Java Concurrency APIThe Robot under dictate of the LegoMindStorm Java Concurrency API
The Robot under dictate of the LegoMindStorm Java Concurrency API
 
How RaspberryPi workers building GraphDatabase
How RaspberryPi workers building GraphDatabaseHow RaspberryPi workers building GraphDatabase
How RaspberryPi workers building GraphDatabase
 

Recently uploaded

Bun (KitWorks Team Study 노별마루 발표 2024.4.22)
Bun (KitWorks Team Study 노별마루 발표 2024.4.22)Bun (KitWorks Team Study 노별마루 발표 2024.4.22)
Bun (KitWorks Team Study 노별마루 발표 2024.4.22)Wonjun Hwang
 
Kotlin Multiplatform & Compose Multiplatform - Starter kit for pragmatics
Kotlin Multiplatform & Compose Multiplatform - Starter kit for pragmaticsKotlin Multiplatform & Compose Multiplatform - Starter kit for pragmatics
Kotlin Multiplatform & Compose Multiplatform - Starter kit for pragmaticscarlostorres15106
 
"Subclassing and Composition – A Pythonic Tour of Trade-Offs", Hynek Schlawack
"Subclassing and Composition – A Pythonic Tour of Trade-Offs", Hynek Schlawack"Subclassing and Composition – A Pythonic Tour of Trade-Offs", Hynek Schlawack
"Subclassing and Composition – A Pythonic Tour of Trade-Offs", Hynek SchlawackFwdays
 
Understanding the Laravel MVC Architecture
Understanding the Laravel MVC ArchitectureUnderstanding the Laravel MVC Architecture
Understanding the Laravel MVC ArchitecturePixlogix Infotech
 
Install Stable Diffusion in windows machine
Install Stable Diffusion in windows machineInstall Stable Diffusion in windows machine
Install Stable Diffusion in windows machinePadma Pradeep
 
Vertex AI Gemini Prompt Engineering Tips
Vertex AI Gemini Prompt Engineering TipsVertex AI Gemini Prompt Engineering Tips
Vertex AI Gemini Prompt Engineering TipsMiki Katsuragi
 
SQL Database Design For Developers at php[tek] 2024
SQL Database Design For Developers at php[tek] 2024SQL Database Design For Developers at php[tek] 2024
SQL Database Design For Developers at php[tek] 2024Scott Keck-Warren
 
costume and set research powerpoint presentation
costume and set research powerpoint presentationcostume and set research powerpoint presentation
costume and set research powerpoint presentationphoebematthew05
 
Unleash Your Potential - Namagunga Girls Coding Club
Unleash Your Potential - Namagunga Girls Coding ClubUnleash Your Potential - Namagunga Girls Coding Club
Unleash Your Potential - Namagunga Girls Coding ClubKalema Edgar
 
"Federated learning: out of reach no matter how close",Oleksandr Lapshyn
"Federated learning: out of reach no matter how close",Oleksandr Lapshyn"Federated learning: out of reach no matter how close",Oleksandr Lapshyn
"Federated learning: out of reach no matter how close",Oleksandr LapshynFwdays
 
Advanced Test Driven-Development @ php[tek] 2024
Advanced Test Driven-Development @ php[tek] 2024Advanced Test Driven-Development @ php[tek] 2024
Advanced Test Driven-Development @ php[tek] 2024Scott Keck-Warren
 
SIP trunking in Janus @ Kamailio World 2024
SIP trunking in Janus @ Kamailio World 2024SIP trunking in Janus @ Kamailio World 2024
SIP trunking in Janus @ Kamailio World 2024Lorenzo Miniero
 
My INSURER PTE LTD - Insurtech Innovation Award 2024
My INSURER PTE LTD - Insurtech Innovation Award 2024My INSURER PTE LTD - Insurtech Innovation Award 2024
My INSURER PTE LTD - Insurtech Innovation Award 2024The Digital Insurer
 
Automating Business Process via MuleSoft Composer | Bangalore MuleSoft Meetup...
Automating Business Process via MuleSoft Composer | Bangalore MuleSoft Meetup...Automating Business Process via MuleSoft Composer | Bangalore MuleSoft Meetup...
Automating Business Process via MuleSoft Composer | Bangalore MuleSoft Meetup...shyamraj55
 
Nell’iperspazio con Rocket: il Framework Web di Rust!
Nell’iperspazio con Rocket: il Framework Web di Rust!Nell’iperspazio con Rocket: il Framework Web di Rust!
Nell’iperspazio con Rocket: il Framework Web di Rust!Commit University
 
Unraveling Multimodality with Large Language Models.pdf
Unraveling Multimodality with Large Language Models.pdfUnraveling Multimodality with Large Language Models.pdf
Unraveling Multimodality with Large Language Models.pdfAlex Barbosa Coqueiro
 
Are Multi-Cloud and Serverless Good or Bad?
Are Multi-Cloud and Serverless Good or Bad?Are Multi-Cloud and Serverless Good or Bad?
Are Multi-Cloud and Serverless Good or Bad?Mattias Andersson
 
Commit 2024 - Secret Management made easy
Commit 2024 - Secret Management made easyCommit 2024 - Secret Management made easy
Commit 2024 - Secret Management made easyAlfredo García Lavilla
 
Story boards and shot lists for my a level piece
Story boards and shot lists for my a level pieceStory boards and shot lists for my a level piece
Story boards and shot lists for my a level piececharlottematthew16
 

Recently uploaded (20)

Bun (KitWorks Team Study 노별마루 발표 2024.4.22)
Bun (KitWorks Team Study 노별마루 발표 2024.4.22)Bun (KitWorks Team Study 노별마루 발표 2024.4.22)
Bun (KitWorks Team Study 노별마루 발표 2024.4.22)
 
Kotlin Multiplatform & Compose Multiplatform - Starter kit for pragmatics
Kotlin Multiplatform & Compose Multiplatform - Starter kit for pragmaticsKotlin Multiplatform & Compose Multiplatform - Starter kit for pragmatics
Kotlin Multiplatform & Compose Multiplatform - Starter kit for pragmatics
 
"Subclassing and Composition – A Pythonic Tour of Trade-Offs", Hynek Schlawack
"Subclassing and Composition – A Pythonic Tour of Trade-Offs", Hynek Schlawack"Subclassing and Composition – A Pythonic Tour of Trade-Offs", Hynek Schlawack
"Subclassing and Composition – A Pythonic Tour of Trade-Offs", Hynek Schlawack
 
Understanding the Laravel MVC Architecture
Understanding the Laravel MVC ArchitectureUnderstanding the Laravel MVC Architecture
Understanding the Laravel MVC Architecture
 
Install Stable Diffusion in windows machine
Install Stable Diffusion in windows machineInstall Stable Diffusion in windows machine
Install Stable Diffusion in windows machine
 
Vertex AI Gemini Prompt Engineering Tips
Vertex AI Gemini Prompt Engineering TipsVertex AI Gemini Prompt Engineering Tips
Vertex AI Gemini Prompt Engineering Tips
 
SQL Database Design For Developers at php[tek] 2024
SQL Database Design For Developers at php[tek] 2024SQL Database Design For Developers at php[tek] 2024
SQL Database Design For Developers at php[tek] 2024
 
costume and set research powerpoint presentation
costume and set research powerpoint presentationcostume and set research powerpoint presentation
costume and set research powerpoint presentation
 
Unleash Your Potential - Namagunga Girls Coding Club
Unleash Your Potential - Namagunga Girls Coding ClubUnleash Your Potential - Namagunga Girls Coding Club
Unleash Your Potential - Namagunga Girls Coding Club
 
"Federated learning: out of reach no matter how close",Oleksandr Lapshyn
"Federated learning: out of reach no matter how close",Oleksandr Lapshyn"Federated learning: out of reach no matter how close",Oleksandr Lapshyn
"Federated learning: out of reach no matter how close",Oleksandr Lapshyn
 
Advanced Test Driven-Development @ php[tek] 2024
Advanced Test Driven-Development @ php[tek] 2024Advanced Test Driven-Development @ php[tek] 2024
Advanced Test Driven-Development @ php[tek] 2024
 
SIP trunking in Janus @ Kamailio World 2024
SIP trunking in Janus @ Kamailio World 2024SIP trunking in Janus @ Kamailio World 2024
SIP trunking in Janus @ Kamailio World 2024
 
My INSURER PTE LTD - Insurtech Innovation Award 2024
My INSURER PTE LTD - Insurtech Innovation Award 2024My INSURER PTE LTD - Insurtech Innovation Award 2024
My INSURER PTE LTD - Insurtech Innovation Award 2024
 
Automating Business Process via MuleSoft Composer | Bangalore MuleSoft Meetup...
Automating Business Process via MuleSoft Composer | Bangalore MuleSoft Meetup...Automating Business Process via MuleSoft Composer | Bangalore MuleSoft Meetup...
Automating Business Process via MuleSoft Composer | Bangalore MuleSoft Meetup...
 
Nell’iperspazio con Rocket: il Framework Web di Rust!
Nell’iperspazio con Rocket: il Framework Web di Rust!Nell’iperspazio con Rocket: il Framework Web di Rust!
Nell’iperspazio con Rocket: il Framework Web di Rust!
 
E-Vehicle_Hacking_by_Parul Sharma_null_owasp.pptx
E-Vehicle_Hacking_by_Parul Sharma_null_owasp.pptxE-Vehicle_Hacking_by_Parul Sharma_null_owasp.pptx
E-Vehicle_Hacking_by_Parul Sharma_null_owasp.pptx
 
Unraveling Multimodality with Large Language Models.pdf
Unraveling Multimodality with Large Language Models.pdfUnraveling Multimodality with Large Language Models.pdf
Unraveling Multimodality with Large Language Models.pdf
 
Are Multi-Cloud and Serverless Good or Bad?
Are Multi-Cloud and Serverless Good or Bad?Are Multi-Cloud and Serverless Good or Bad?
Are Multi-Cloud and Serverless Good or Bad?
 
Commit 2024 - Secret Management made easy
Commit 2024 - Secret Management made easyCommit 2024 - Secret Management made easy
Commit 2024 - Secret Management made easy
 
Story boards and shot lists for my a level piece
Story boards and shot lists for my a level pieceStory boards and shot lists for my a level piece
Story boards and shot lists for my a level piece
 

Boost delivery stream with code discipline engineering

  • 1. Miroslav Wengner Boost delivery stream with code discipline engineering
  • 2. Safe Harbour Statement All what you will hear can be di ff erent, this presentation is for motivational purposes …
  • 3. Miroslav Wengner • Husband, Father, Software Engineer, Author, Blogger, Technology Enthusiast • Book Author: Practical Design Patterns for Java Developers [Packt] • JCP: Executive Committee Board Member, OpenJDK Committer • Java Mission Control Project, Open-Source projects • Co-Author of Robo4J Project (Duke Award) • Java Champion, JavaOne RockStar • Principal Engineer at OpenValue
  • 4. • Group Of Talented and Motivated Individuals • Netherlands, Germany, Switzerland, Austria… • Fun, Development, Trainings, Migration and more…
  • 5. Agenda • [study] cost of the bad code • [engineering] pyramid of project healthiness • [power features] gang of 21 • [anti-patterns] let’s get serious • [anti-patterns, platform] squeezing resources and proper tools • [design-patterns] 2 cents make di ff • [design-patterns] creational, structural, behavioral and concurrency • Conclusion • Q/A
  • 6. [study] cost of the bad code • CNBC Global CFO Council about [2018, Stripe and Harris Poll] • Company lose upward $300 billion/year • technical debts • maintaining legacy • impacts of bad code • 57% of the week productive time ? ? Average Working Week 10% 34% 57% Work time Tech debt Bad code
  • 7. [engineering] pyramid of focus healthiness information span consequence of poor-solution innovations requirements stream tooling awareness domain knowledge < DISCIPLINE > pyramid of project healthiness FOCUS ARCHITECTURE CODE PLATFORM
  • 8. [power features] gang of 21 • innovation through stability and compatibility “guarantees” • Language syntax • Local-Variable type inference (323) • Record Patterns (440), Sealed classes (409) • Switch expression and pattern matching (441) • Text Blocks (378) • Internal APIs • Sequenced Collection (431) • Virtual Threads and Executors(444) ? <= Module system (200, 261)
  • 9. [power features] gang of 21 sealed interface Val permits Ch {}; record Ch(Integer v) implements Val { String toText() { var number = v; return switch (number) { case Integer i when i > 74 -> {yield new String("".getBytes(), Charset.defaultCharset());} case null -> “”; default -> Character.toString(number); };}} Executors.newVirtualThreadPerTaskExecutor().submit(() -> System.out.println(""" %sON%d""".formatted(IntStream.of(74, 67, 80) .mapToObj(Ch::new).map(Ch::toText).collect(Collectors.joining()), ThreadLocalRandom.current().nextInt(2023, 2024)))); ?
  • 10. [anti-patterns] let’s get serious keep it simple • works … for me, now • FITYMI • innovation through bottlenecks? • we fi x it later … so when … ? • test free … ? • limits an ability to e ff ectively address the issue: bottleneck
  • 11. [anti-patterns, requirements] originated by code Cut and paste programming Spaghetti code Blob Lava fl ow Functional decomposition Boat anchor expecting next challenge from outdated God Class PoC to Production past is knocking keep it single
  • 12. [anti-patterns, domain]: originated by architecture ? Golden hammer Continuous obsolescence Input kludge Working in mine fi eld Ambiguous viewpoint Poltergeists Dead end believe and not verify Test? appears like magic … don’t remove old good approach onion don't touch
  • 13. [anti-patterns, platform] squeezing resources MODEL: record Sensor(int value) {} LOGIC: Collection<Sensor> set = provider.values(); for (Sensor e : set) { SensorAlarmSystemUtil.evaluateAlarm(provider, e.value(), measurementCount); } UTILS: void evaluateAlarm(Map<Integer, Sensor> storage, Integer criticalValue, long measurementNumber) { if (!storage.containsKey(criticalValue)) {…} “Der liebe Gott steckt im Detail” Aby Warburg
  • 14. [anti-patterns, platform] squeezing resources • What about AutoBoxing ? • Platform optimalisation • internal caches: Integers, … ?
  • 15. [anti-patterns, platform] squeezing resources ? record Sensor(Integer value) {} Collection<Sensor> set = provider.values(); for (Sensor e : set) { SensorAlarmSystemUtil.evaluateAlarm(provider, e.value(), measurementCount); } void evaluateAlarm(Map<Integer, Sensor> storage, Integer criticalValue, long measurementNumber) { if (!storage.containsKey(criticalValue)) { System.out.println(“SHOULD NOT HAPPEN!”); } FEEL DIFFERENCE ?
  • 16. [anti-patterns, platform] proper tools ? MODEL: for (int i = 0; i < THREADS_NUMBER; i++) { builder.addRunnable( new VehicleAnalyticalWorker(i,ELEMENTS_NUMBER, new ArrayList<>(), new ArrayList<>()) ); } LOGIC: public int countIntersections(VehicleDataContainer c) { int count = 0; for (int n : collection) { if (c.getCollection().contains(n)) { count++; } } return count; }
  • 17. [anti-patterns, platform] proper tools Internal JDK APIs, java.base • Impact: • produce less code • e ff ective behaviour • optimisation under the hood • selecting the right tool ?
  • 18. [anti-patterns, platform] proper tools ? MODEL: for (int i = 0; i < THREADS_NUMBER; i++) { builder.addRunnable( new VehicleAnalyticalWorker(i, ELEMENTS_NUMBER, new HashSet<>(), new HashSet<>()) ); } FEEL DIFFERENCE ? Anti-pattern known as a CODE SMELL LOAD DISTRIBUTION
  • 19. [design-patterns]: 2 cents make diff CREATE MAINTAINABLE NAMING PATTERN
  • 20. Encapsulation Inheritance Polymorphism Abstraction Expose what is required Inevitable evolution Behaviour on demand Generalisation [pillars] follow EIPA towards evolution: Do NOT Repeat Yourself
  • 21. Single Responsibility Open-Close Liskov-Sustitution Interface Segregation Expose what is required Inevitable evolution Behaviour on demand Generalisation [principles] stay SOLID towards evolution: Do NOT Repeat Yourself Dependency Inversion
  • 22. [design-patterns]: coding standards are inevitable • readable, maintainable code, performance is not the “target” • Pareto Principle (80/20) : depends on perspective • Maintainable naming, CleanCode, Best Practices • Start small to build something useful! • Design Patterns Creational Structural Behavioral Concurrency
  • 23. [design-patterns] creational ? Factory Method Abstract Factory Builder Prototype Singleton Object pool Lazy initialization Dependency injection
  • 24. [design-patterns] creational - java ? Builder class Car implements Vehicle { final static class Builder { private Part cabin = Part.PART_EMPTY; private Part engine = Part.PART_EMPTY; public Builder addCabin(String name) { this.cabin = new Part(name); return this; } separate the composition from the representation record Part(String name) { static final Part PART_EMPTY = new Part(""); }
  • 25. [design-patterns] creational - scala ? Builder class Car(val name: String = "no_name", val cabin: Part = EMPTY_PART, val engine: Part = EMPTY_PART) extends Vehicle { override def showParts(): Seq[Part] = Seq(cabin, engine) } object Car { case class Builder private(cabin: Part = EMPTY_PART, engine: Part = EMPTY_PART) { def withEngine(name: String): Builder = { val part = Part(name) copy(engine = part) } separate the composition from the representation object Part { val EMPTY_PART = new Part("") } case class Part(name: String = ""){ }
  • 26. [design-patterns] creational - kotlin ? Builder class Car( private val name: String, private val cabin: Part = Part.PART_EMPTY, private val engine: Part = Part.PART_EMPTY ) : Vehicle { data class Builder( var name: String = "no_name", var cabin: Part = Part.PART_EMPTY, var engine: Part = Part.PART_EMPTY ) { fun withName(name: String) = apply { this.name = name } separate the composition from the representation class Part constructor(val name: String){ companion object { val PART_EMPTY = Part("") } override fun toString(): String { return "Part(${name})" } }
  • 27. [design-patterns] creational - java 21 ? Factory Method static Vehicle produce(Specs specs) { return switch (specs) { case CarSpecs s when s.specType().startsWith("sport") -> { var car = new Car("sport_car"); System.out.println("factory, car, more action"); yield car; } case TruckSpecs ts -> new Truck("magic_truck"); default -> throw new IllegalArgumentException(""" not supported specs:'%s'""".formatted(specs)); }; } centralise the class instantiation
  • 28. [design-patterns] creational - kotlin ? Factory Method fun produce(specs: Specs): Vehicle { return when (specs) { is CarSpecs -> { if (specs.specType.startsWith(“sport")) { val car = Car("sport_car") println("car:${car}") return car } else { throw IllegalArgumentException("not supported car:’${specs.specType}'") } } is TruckSpecs -> Truck("magic_truck") else -> throw IllegalArgumentException("not supported specs:'$specs'") } } centralise the class instantiation
  • 29. [design-patterns] creational - scala ? Factory Method def produce(specs: Specs): Vehicle = specs match { case carSpec: CarSpecs if carSpec.specType.startsWith("sport") => { val car = new Car(name = "sport_car") print("factory, car, more action") car } case truckSpec: TruckSpecs => new Truck("magic_truck") case _ => throw new IllegalArgumentException(s"not supported specs:'$specs'") } centralise the class instantiation
  • 30. [design-patterns] structural ? Adapter Bridge Composite Decorator Facade Filter Flyweight Front controller Marker Module Proxy Twin
  • 31. [design-patterns] structural ? Adapter sealed interface VehicleCommand permits StartCommand, StopCommand {..} record StartCommand(…) implements VehicleCommand { … @Override public void process(String command) { if(command.contains("start")){ switch (vehicle){ case StandardVehicle v when v.getLoadWeight() > 1 -> System.out.printf(""" %s with description:’%s’… v, v.getDescription(), v.getLoadWeight()); case StandardVehicle v -> System.out.printf(""" %s with description:'%s'%n""", v, v.getDescription()); case SportVehicle v -> System.out.println(v); default -> System.out.println("NOTHING"); } executed.set(true); allows to work classes together
  • 32. [design-patterns] structural ? Facade sealed interface VehicleCommand permits StartCommand, StopCommand {..} uni fi ed interfaces to underlaying subsystems public interface VehicleFactory<T> { Vehicle produce(T type); }
  • 33. [design-patterns] behavioral ? Caching Chain of responsibility Command Interpreter Iterator Mediator Null Object Observer Pipeline State Strategy Template Visitor
  • 34. [design-patterns] behavioral ? Command like action, event on what client act public record StartCommand(…) implements VehicleCommand {… public final class StopCommand implements VehicleCommand { private final Vehicle vehicle; private boolean executed; public StopCommand(Vehicle vehicle){ this.vehicle = vehicle; } @Override public void process(String command) { …
  • 35. [design-patterns] behavioral ? Caching Observer public class Driver { private final List<VehicleCommand> commands = new ArrayList<>(); public Driver addCommand(VehicleCommand command){…} public void executeCommands(final String command){ commands.forEach(c -> { // Records decomposition if(c instanceof StartCommand(Vehicle v, AtomicBoolean state)){ …. } public void printCommands() { System.out.printf(""" Considered COMMANDS:%n%s""", commands.stream() .map(VehicleCommand::status) .collect(Collectors.joining(""))); react on demand reuse knowledge
  • 36. [design-patterns] concurrency is inevitable ? Active Object Asynchronous Method Balking Double Checked Locking Read Write Lock Producer consumer Scheduler Thread Pool CONCURRENCY IS HARD <3
  • 37. [design-patterns] concurrency ? Balking var vehicle = new Vehicle(); var numberOfDrivers = 5; var executors = Executors.newFixedThreadPool(2); for (int i = 0; i < numberOfDrivers; i++) { executors.submit(vehicle::drive); } an access to critical section enum VehicleState { MOVING, STOPPED, }
  • 38. [design-patterns] concurrency ? ReentrantReadWriteLock readWriteLock = new ReentrantReadWriteLock(); var sensor = new Sensor(readWriteLock.readLock(), readWriteLock.writeLock()); var sensorWriter = new SensorWriter("writer-1", sensor); var writerThread = getWriterThread(sensorWriter); ExecutorService executor = Executors.newFixedThreadPool(NUMBER_READERS); var readers = IntStream.range(0, NUMBER_READERS) .boxed().map(i -> new SensorReader("reader-" + i, sensor, CYCLES_READER)).toList(); readers.forEach(executor::submit); Read Write Lock natural exclusivity for lock acquisition
  • 39. Conclusion • Code Discipline Engineering: • pyramid of focus healthiness • enforce iterative process by following EIPA and staying SOLID • Design-Patterns: improve maintainability and reduce verbosity • Don’t Repeat Yourself • Maintainable naming standards • Costs “reduction” ?
  • 40. Q / A twitter: @miragemiko github:@mirage22 email: miro@openvalue.de Thank YOU !
  • 41. References: • Project Amber: https://openjdk.org/projects/amber/ • Project Valhalla: https://openjdk.org/projects/valhalla/ • Project Panama: https://openjdk.org/projects/panama/ • JFR Project: https://github.com/openjdk/jmc • OpenJDK: https://openjdk.org/ • foojay.io: https://foojay.io/today/author/miro-wengner/ • OpenValue Blog: https://openvalue.blog/ • GitHub Examples: https://github.com/mirage22/mastering_java_enhancements Title : Practical Design Patterns for Java Developers [PACKT] Amazon: https://a.co/d/eizSkr2 GitHub: https://github.com/PacktPublishing/Practical-Design-Patterns-for-Java-Developers