Why should we use TDD to develop in Elixir? When we are applying it correctly? What are the differences that we can find in a code developed with TDD and in code not developed with it? Is it TDD about testing? Really? In this talk, I'll show what is TDD and how can be used it in functional programming like Elixir to design the small and the big parts of your system, showing what are the difference and the similarities between an OOP and FP environment. Showing what is the values of applying a technique like TDD in Elixir and what we should obtain applying it.
We want code that is easy to understand, re-usable, and flexible. But we are always up against deadlines, so we rush, and end up with code that is messy, buggy, hard to maintain, and makes us go slower even though we’re trying to go faster.
What is clean code? In this talk I’ll provide some answers to this question, and introduce you to 10 good habits that will help keep your code clean, such as the use of meaningful names for your variables and functions, and following the “Boy Scout Rule” (leave the code cleaner than you found it). I will even try to persuade you that using a lot of code comments is a sign that there are problems with your code.
Practical tips for dealing with projects involving legacy code. Covers investigating past projects, static analysis of existing code, and methods for changing legacy code.
Presented at PHP Benelux '10
In this whitepaper, LearnItFirst founder Scott Whigham talks about how you can become a good (or better) C# programmer. This whitepaper is long - 15 pages - but it includes both a step-by-step system to follow as well as an in-depth discussion of each step.
If you follow this 13-step system (with a bonus 14th step), you can’t help but become a good C# developer!
Building unit tests correctly with visual studio 2013Dror Helper
Unit testing is now considered a mainstream practice, but that does not mean it is as common, pervasive or as well understood as it could or should be. Many programmers struggle with the quality of their tests and with the focus of their code. In this session we’ll learn how to write good unit testing code.
Clean Code with Java 8 - Functional Patterns and Best PracticesVictor Rentea
My talk about how the Clean Code principles and techniques apply/change when you start using functional programming with Java 8. Presented in Paris at Devoxx FR 2018
The Art of Unit Testing - Towards a Testable DesignVictor Rentea
Slides of the Talk I gave at Devoxx Belgium 2019.
=== Abstract ===
Focusing on the creative work without being terrified of breaking the existing behavior can make software development very addictive! Good automated tests can buy you that!
However, if your tests are not maintainable they may end up slowing you down and causing you painful headaches, compilation errors and spurious failures. To avoid that, your unit tests should be significant; expressive; clean; DRY; non-overlapping; and blazing fast. Writing good tests becomes the toughest challenge for any developer, no matter how battle-hardened: you need to balance risk with test maintenance costs, while looking out for test design smells that call for [risky] refactoring to drive your design towards a set of key principles (included:).
Principles that will end up shaping the way you craft the Production code itself. Because in the end, a good, clean design is more important than coverage%.
But testing gives you the best feedback to get there.
Grab a black coffee and join this snippet from Victor’s Pro Unit Testing #training, to learn about testing priorities, buggy tests, the shared @Before, Mocks vs Stubs and how to reduce them by "purifying" your logic, testing Legacy Code and refactoring @Spy-es out.
All of that in an entertaining, dynamic and memorable session.
Exception handling is always an important topic. This presentation will provide couple of good practices to deal with Errors & Exceptions happing in Node.js.
Keep those in mind, you will write a better code for a more stable software.
Happy Coding!
The following slides summarize and curate most of the knowledge and patterns gathered to date on Node error handling.
Without clear understanding and strategy, Node error handling might be the Achilles heel of your app – its unique single-threaded execution model and loose types raise challenges that don’t exist in any other frameworks. Node by itself doesn’t provide patterns for critical paths like where to put error handling code, even worst it suggest patterns that were rejected by the community like passing errors in callbacks.
It covers topics like promises, generators, callbacks, unhandled exceptions, APM products, testing errors, operational errors vs development errors and much more
We want code that is easy to understand, re-usable, and flexible. But we are always up against deadlines, so we rush, and end up with code that is messy, buggy, hard to maintain, and makes us go slower even though we’re trying to go faster.
What is clean code? In this talk I’ll provide some answers to this question, and introduce you to 10 good habits that will help keep your code clean, such as the use of meaningful names for your variables and functions, and following the “Boy Scout Rule” (leave the code cleaner than you found it). I will even try to persuade you that using a lot of code comments is a sign that there are problems with your code.
Practical tips for dealing with projects involving legacy code. Covers investigating past projects, static analysis of existing code, and methods for changing legacy code.
Presented at PHP Benelux '10
In this whitepaper, LearnItFirst founder Scott Whigham talks about how you can become a good (or better) C# programmer. This whitepaper is long - 15 pages - but it includes both a step-by-step system to follow as well as an in-depth discussion of each step.
If you follow this 13-step system (with a bonus 14th step), you can’t help but become a good C# developer!
Building unit tests correctly with visual studio 2013Dror Helper
Unit testing is now considered a mainstream practice, but that does not mean it is as common, pervasive or as well understood as it could or should be. Many programmers struggle with the quality of their tests and with the focus of their code. In this session we’ll learn how to write good unit testing code.
Clean Code with Java 8 - Functional Patterns and Best PracticesVictor Rentea
My talk about how the Clean Code principles and techniques apply/change when you start using functional programming with Java 8. Presented in Paris at Devoxx FR 2018
The Art of Unit Testing - Towards a Testable DesignVictor Rentea
Slides of the Talk I gave at Devoxx Belgium 2019.
=== Abstract ===
Focusing on the creative work without being terrified of breaking the existing behavior can make software development very addictive! Good automated tests can buy you that!
However, if your tests are not maintainable they may end up slowing you down and causing you painful headaches, compilation errors and spurious failures. To avoid that, your unit tests should be significant; expressive; clean; DRY; non-overlapping; and blazing fast. Writing good tests becomes the toughest challenge for any developer, no matter how battle-hardened: you need to balance risk with test maintenance costs, while looking out for test design smells that call for [risky] refactoring to drive your design towards a set of key principles (included:).
Principles that will end up shaping the way you craft the Production code itself. Because in the end, a good, clean design is more important than coverage%.
But testing gives you the best feedback to get there.
Grab a black coffee and join this snippet from Victor’s Pro Unit Testing #training, to learn about testing priorities, buggy tests, the shared @Before, Mocks vs Stubs and how to reduce them by "purifying" your logic, testing Legacy Code and refactoring @Spy-es out.
All of that in an entertaining, dynamic and memorable session.
Exception handling is always an important topic. This presentation will provide couple of good practices to deal with Errors & Exceptions happing in Node.js.
Keep those in mind, you will write a better code for a more stable software.
Happy Coding!
The following slides summarize and curate most of the knowledge and patterns gathered to date on Node error handling.
Without clear understanding and strategy, Node error handling might be the Achilles heel of your app – its unique single-threaded execution model and loose types raise challenges that don’t exist in any other frameworks. Node by itself doesn’t provide patterns for critical paths like where to put error handling code, even worst it suggest patterns that were rejected by the community like passing errors in callbacks.
It covers topics like promises, generators, callbacks, unhandled exceptions, APM products, testing errors, operational errors vs development errors and much more
Functional Patterns with Java8 at Devoxx UK - SlidesVictor Rentea
The backing slides for my live coding session at Devoxx UK London 2018. Summarizing all the conclusions. A summary of how to apply clean code principles in Java8 code.
Clean Pragmatic Architecture - Avoiding a MonolithVictor Rentea
Talk built based on several of my trainings: http://www.victorrentea.ro/#training
Covers: Clean/Onion/Hexagonal Architecture, Domain Entities, Value Objects, Repository, Extract When it Grows Principle, Dependency Inversion Principle, Clean Code and Design Patterns.
These are the backing slides of the talks given at JPoint 2017 and Devoxx PL 2017: https://www.youtube.com/embed/4-4ahz7zDiQ
All 3 Clean Code presentations provide great value by themselves, but taken together are designed to offer a holistic approach to successful software creation. This first session creates the foundation for the 2nd and 3rd Clean Code presentation on Dependency Injection, as it explains expected base knowledge. Why writing Clean Code makes us more efficient Over the lifetime of a product, maintaining the product is actually one - if not the most - expensive area(s) of the overall product costs.
We will dive into the basics of Inversion of Control (IOC) and Dependency Injection (DI) to review different ways of achieving decoupling, using and exploring both: Best Practices, Design and Anti Patterns. This presentation requires knowledge and understanding of basics like DRY, SoC, SRP, SOLID etc. which are building the base for decoupled architecture. However, we will start at the basics of DI and will work towards intermediate and advanced scenarios depending on the participating group.
This presentation is based on C# and Visual Studio 2013. However, the demonstrated patterns and practice can be applied to every other programming language too.
Note: Moving forwards this presentation will be updated with the latest version of the slides for the last event I did the presentation instead of creating new separate slide decks here on SlideShare.
Presentation dates and locations:
2015-10-03 Silicon Valley Code Camp, San Jose, CA
2015-06-27 SoCal Code Camp - San Diego, CA
2015-06-25 Bay.NET South Bay, Mountain View, CA
2014-11-14 SoCal Code Camp - Los Angeles, CA
2014-10-11 Silicon Valley Code Camp, Los Altos Hills, CA
Don't Be Mocked by your Mocks - Best Practices using MocksVictor Rentea
Do you ❤️ Mocks? When you write your first unit tests, especially on older codebases, mocking foreign code is key to survival. But as you grow older in the craft, you start piling up hours and days wasted to refactor fragile tests or to fix bugs that those heavy mock-based tests didn't catch. And so you start looking at Mocks differently.
Let's go through the key factors to consider to strike the optimal balance between what needs to be mocked away and what code should be tested in integration. There's sometimes a fine line there, often interwoven with strong emotions:
"Why am I testing this?"
"Argh… these tests take too long"
"Can this ever really break?"
etc...
Among the points that we'll touch on:
- Mocks vs Refactoring
- Mocks vs Reliability
- Fine vs Coarse Mocks
- Reproducibility
- Partial Mocks
- Mocking Statics
- Alternatives to Mocks
Speakers: Victor Rentea
Victor is a Java Champion and Independent Trainer with an impressive experience: thousands of developers in dozens of companies trained in dedicated company sessions. He is the founder of one of the largest developer communities in Romania, Bucharest Software Craftsmanship Community and a top international conference speaker.
To find more about him, join a live masterclass or call him in for a company dedicated training: victorrentea.ro
Are you using Java8 Lambdas & Streams in your core business logic? Then you might be having this strange feeling that it’s not Java anymore: at times it’s cryptic, barely readable.. This was the topic of the workshop with the same name that I held at VoxxedDays Bucharest 2017. These are the slides backing the that workshop.
As a summary, the materials walk through the functional features of Java8, adding details along the way about how we can keep the code clean as we embrace the Java 8 features.
The entire desktop screencast + voice it's on youtube, here: https://youtu.be/uH9A37k2QkU
How should a professional software developer behave in code? What guidelines should one follow? How should we name our constructs? What about OOP principles? What's their real use?
This classic training module in my training curricula is the cornerstone of my professionalism. These are my conduit guidelines at work. I've held this training > 10 times, including at Voxxed Days Bucharest 2016 and at a Bucharest Java User Group meetup.
Evolving a Clean, Pragmatic Architecture - A Craftsman's GuideVictor Rentea
Talk given at Devoxx Belgium 2019.
===== Abstract =====
Are you in a mood for a brainstorm? Join this critical review of the major decisions taken in a typical enterprise application architecture and learn to balance pragmatism with your design goals. Find out how to do just-in-time design to keep as many use-cases as simple as possible.
The core purpose of this presentation is to learn to strike a **balance between pragmatism and maintainability** in your design. Without continuous refactoring, a simple design will inevitably degenerate into a Big Ball of Mud, under the assault of the new features and bugfixes.
On the other hand, the very highly-factored code can burden the take-off of the development and end up freezing the mindset in some rigid upfront design.
The end goal of this talk is to challenge you to rethink critically the architecture of your systems and seek ways to simplify it to match your actual needs, with a pragmatic mindset. "Architecture is the art of postponing decisions", said Uncle Bob.
This talk takes this idea further and explains an optimal mindset about designing enterprise applications: Evolving (Continuously Refactoring) a Pragmatic (Simple), Clean (aka Onion) Architecture, aiming to provide Developer Safety™️ and Comfort™️.
It’s the philosophy that Victor distilled over the past 5 years, designing and implementing 9 applications as IBM Lead Architect, and delivering training and advises to many other companies.
You’ll learn how to break data into pieces (Fit Entities, Value Objects, Data Transfer Objects), how to keep the logic simple (Facades, Domain Services, logic extraction patterns, Mappers, AOP), layering to enforce boundaries (keeping DTOs out of your logic, Dependency Inversion Principle), and many more, all in a dynamic, interactive and extremely entertaining session.
Unit testing and test-driven development are practices that makes it easy and efficient to create well-structured and well-working code. However, many software projects didn't create unit tests from the beginning.
In this presentation I will show a test automation strategy that works well for legacy code, and how to implement such a strategy on a project. The strategy focuses on characterization tests and refactoring, and the slides contain a detailed example of how to carry through a major refactoring in many tiny steps
You will learn why naming is really difficult if done right, why coding and style guidelines are crucial, code structuring, exception handling and why other elements of coding often define the tipping point between success and failure of projects. Following the principles of software craftsmanship will allow you to end up with better maintainability and extensibility of your software and the success of the project in the end. All 3 Clean Code presentations provide great value by themselves, but taken together are designed to offer a holistic approach to successful software creation.
Why writing Clean Code makes us more efficient Over the lifetime of a product, maintaining the product is actually one - if not the most - expensive area(s) of the overall product costs. Writing clean code can significantly lower these costs. However, writing clean code also makes you more efficient during the initial development time and results in more stable code. You will be presented design patterns and best practices which will make you write better and more easily maintainable code, seeing code in a holistic way. You will learn how to apply them by using an existing implementation as the starting point of the presentation. Finally, patterns & practices benefits are explained.
This presentation is based on C# and Visual Studio 2013. However, the demonstrated patterns and practice can be applied to every other programming language too.
Note: Moving forwards this presentation will be updated with the latest version of the slides for the last event I did the presentation instead of creating new separate slide decks here on SlideShare.
Presentation dates and locations:
2015-06-27 SoCal Code Camp - San Diego, CA
2014-11-14 SoCal Code Camp - Los Angeles, CA
2014-10-18 Desert Code Camp - Chandler, AZ
Session from NDC London 2013
Writing unit tests is hard, isn't it? you need an entire set of tools just to start. One of the crucial decisions when building this set is picking up a mocking framework.
But BEWARE! what you choose has the ability to make you or break you!
Come to the session and see Dror Helper, once a mocking framework developer, show the good and the bad of different mocking frameworks (free and commercial) and make them battle to the death!
Clean Code - Design Patterns and Best Practices at Silicon Valley Code CampTheo Jungeblut
Why writing Clean Code makes us more efficient Over the lifetime of a product, maintaining the product is actually one - if not the most - expensive area(s) of the overall product costs.
Writing clean code can significantly lower these costs. However, writing clean code also makes you more efficient during the initial development time and results in more stable code.
You will be presented design patterns and best practices which will make you write better and more easily maintainable code, seeing code in a holistic way. You will learn how to apply them by using an existing implementation as the starting point of the presentation. Finally, patterns & practices benefits are explained. This presentation is based on C# and Visual Studio 2012.
However, the demonstrated patterns and practice can be applied to almost every other programming language too.
In this talk I'm going to focus on the technical aspects of 'test automation', using examples of approaches from a variety of Agile projects where we automated APIs, and GUIs. You'll learn about the use of abstractions and how to think about modeling the system in code to support automating it. Also how to use these abstractions to support stress testing, exploratory testing, ongoing CI assertions and the testing process in general. I'll also discuss the different styles of coding used to support automating tactically vs automating strategically.
Refactoring legacy code driven by tests - ENGLuca Minudel
re you working on code poorly designed or on legacy code that’s hard to test? And you cannot refactor it because there are no tests?
During this Coding Dojo you’ll be assigned a coding challenge in Java, C#, Ruby, JavaScript or Python. You will face the challenge of improving the design and refactoring existing code in order to make it testable and to write unit tests.
We will discuss SOLID principles, the relation between design and TDD, and how this applies to your solution.
Reading list:
Growing Object-Oriented Software, Guided by Tests; Steve Freeman, Nat Pryce
Test Driven Development: By Example; Kent Beck
Working Effectively with Legacy; Michael Feathers
Agile Software Development, Principles, Patterns, and Practices; Robert C. Martin (C++, Java)
Agile Principles, Patterns, and Practices in C#; Robert C. Martin (C#)
First, what are they? And why they are important? What do they allow us to do, and what problems do they shield us from?
After this talk, you'll inevitably fall in love with pure functions and immutable objects. We'll see how to implement them in Java, in the most geek ways possible, concerned about long-term maintainability of the code. Oh, and we'll also have Lombok and records along the way, plus lots of fun while tasting a bit of "a senior developer's night-life".
Given at jLove Dec 2020
Coder sans peur du changement avec la meme pas mal hexagonal architectureThomas Pierrain
Découvrez en pratique l'architecture hexagonale, indispensable pour vos applications complexes !
Ce style d'architecture permet d'adapter votre code à tout changement de technologie sans souffrir. Si vous aimez changer de frameworks ou de librairies, tester correctement ou appliquer le Domain-Driven Design, alors vous avez besoin d'architecture hexagonale !
Avec des exemples en code Java, et au travers d’un kata d’architecture auquel vous pourrez participer, nous vous montrerons les pièges à éviter et comment mettre en œuvre ce pattern sans trop galérer, et ce dès votre retour au bureau !
Book review: Working Effectively with Legacy Code, by Michael C. Feathers
Agenda
- The mechanics of change
- Changing software
- Dependency breaking techniques
This session is for developers who need to work on code projects that where written without good unit-testing.
TDD is now mainstream but a lot people don't know or don't remember what is its purpose. TDD is about software design not testing or catching bug. TDD helps developers to shape and create software with "good" design, what is a "good" design is something that we will discuss in the topic.
TDD is now mainstream but a lot people don't know or don't remember what is its purpose. TDD is about software design not testing or catching bug. TDD helps developers to shape and create software with "good" design, what is a "good" design is something that we will discuss in the topic.
Functional Patterns with Java8 at Devoxx UK - SlidesVictor Rentea
The backing slides for my live coding session at Devoxx UK London 2018. Summarizing all the conclusions. A summary of how to apply clean code principles in Java8 code.
Clean Pragmatic Architecture - Avoiding a MonolithVictor Rentea
Talk built based on several of my trainings: http://www.victorrentea.ro/#training
Covers: Clean/Onion/Hexagonal Architecture, Domain Entities, Value Objects, Repository, Extract When it Grows Principle, Dependency Inversion Principle, Clean Code and Design Patterns.
These are the backing slides of the talks given at JPoint 2017 and Devoxx PL 2017: https://www.youtube.com/embed/4-4ahz7zDiQ
All 3 Clean Code presentations provide great value by themselves, but taken together are designed to offer a holistic approach to successful software creation. This first session creates the foundation for the 2nd and 3rd Clean Code presentation on Dependency Injection, as it explains expected base knowledge. Why writing Clean Code makes us more efficient Over the lifetime of a product, maintaining the product is actually one - if not the most - expensive area(s) of the overall product costs.
We will dive into the basics of Inversion of Control (IOC) and Dependency Injection (DI) to review different ways of achieving decoupling, using and exploring both: Best Practices, Design and Anti Patterns. This presentation requires knowledge and understanding of basics like DRY, SoC, SRP, SOLID etc. which are building the base for decoupled architecture. However, we will start at the basics of DI and will work towards intermediate and advanced scenarios depending on the participating group.
This presentation is based on C# and Visual Studio 2013. However, the demonstrated patterns and practice can be applied to every other programming language too.
Note: Moving forwards this presentation will be updated with the latest version of the slides for the last event I did the presentation instead of creating new separate slide decks here on SlideShare.
Presentation dates and locations:
2015-10-03 Silicon Valley Code Camp, San Jose, CA
2015-06-27 SoCal Code Camp - San Diego, CA
2015-06-25 Bay.NET South Bay, Mountain View, CA
2014-11-14 SoCal Code Camp - Los Angeles, CA
2014-10-11 Silicon Valley Code Camp, Los Altos Hills, CA
Don't Be Mocked by your Mocks - Best Practices using MocksVictor Rentea
Do you ❤️ Mocks? When you write your first unit tests, especially on older codebases, mocking foreign code is key to survival. But as you grow older in the craft, you start piling up hours and days wasted to refactor fragile tests or to fix bugs that those heavy mock-based tests didn't catch. And so you start looking at Mocks differently.
Let's go through the key factors to consider to strike the optimal balance between what needs to be mocked away and what code should be tested in integration. There's sometimes a fine line there, often interwoven with strong emotions:
"Why am I testing this?"
"Argh… these tests take too long"
"Can this ever really break?"
etc...
Among the points that we'll touch on:
- Mocks vs Refactoring
- Mocks vs Reliability
- Fine vs Coarse Mocks
- Reproducibility
- Partial Mocks
- Mocking Statics
- Alternatives to Mocks
Speakers: Victor Rentea
Victor is a Java Champion and Independent Trainer with an impressive experience: thousands of developers in dozens of companies trained in dedicated company sessions. He is the founder of one of the largest developer communities in Romania, Bucharest Software Craftsmanship Community and a top international conference speaker.
To find more about him, join a live masterclass or call him in for a company dedicated training: victorrentea.ro
Are you using Java8 Lambdas & Streams in your core business logic? Then you might be having this strange feeling that it’s not Java anymore: at times it’s cryptic, barely readable.. This was the topic of the workshop with the same name that I held at VoxxedDays Bucharest 2017. These are the slides backing the that workshop.
As a summary, the materials walk through the functional features of Java8, adding details along the way about how we can keep the code clean as we embrace the Java 8 features.
The entire desktop screencast + voice it's on youtube, here: https://youtu.be/uH9A37k2QkU
How should a professional software developer behave in code? What guidelines should one follow? How should we name our constructs? What about OOP principles? What's their real use?
This classic training module in my training curricula is the cornerstone of my professionalism. These are my conduit guidelines at work. I've held this training > 10 times, including at Voxxed Days Bucharest 2016 and at a Bucharest Java User Group meetup.
Evolving a Clean, Pragmatic Architecture - A Craftsman's GuideVictor Rentea
Talk given at Devoxx Belgium 2019.
===== Abstract =====
Are you in a mood for a brainstorm? Join this critical review of the major decisions taken in a typical enterprise application architecture and learn to balance pragmatism with your design goals. Find out how to do just-in-time design to keep as many use-cases as simple as possible.
The core purpose of this presentation is to learn to strike a **balance between pragmatism and maintainability** in your design. Without continuous refactoring, a simple design will inevitably degenerate into a Big Ball of Mud, under the assault of the new features and bugfixes.
On the other hand, the very highly-factored code can burden the take-off of the development and end up freezing the mindset in some rigid upfront design.
The end goal of this talk is to challenge you to rethink critically the architecture of your systems and seek ways to simplify it to match your actual needs, with a pragmatic mindset. "Architecture is the art of postponing decisions", said Uncle Bob.
This talk takes this idea further and explains an optimal mindset about designing enterprise applications: Evolving (Continuously Refactoring) a Pragmatic (Simple), Clean (aka Onion) Architecture, aiming to provide Developer Safety™️ and Comfort™️.
It’s the philosophy that Victor distilled over the past 5 years, designing and implementing 9 applications as IBM Lead Architect, and delivering training and advises to many other companies.
You’ll learn how to break data into pieces (Fit Entities, Value Objects, Data Transfer Objects), how to keep the logic simple (Facades, Domain Services, logic extraction patterns, Mappers, AOP), layering to enforce boundaries (keeping DTOs out of your logic, Dependency Inversion Principle), and many more, all in a dynamic, interactive and extremely entertaining session.
Unit testing and test-driven development are practices that makes it easy and efficient to create well-structured and well-working code. However, many software projects didn't create unit tests from the beginning.
In this presentation I will show a test automation strategy that works well for legacy code, and how to implement such a strategy on a project. The strategy focuses on characterization tests and refactoring, and the slides contain a detailed example of how to carry through a major refactoring in many tiny steps
You will learn why naming is really difficult if done right, why coding and style guidelines are crucial, code structuring, exception handling and why other elements of coding often define the tipping point between success and failure of projects. Following the principles of software craftsmanship will allow you to end up with better maintainability and extensibility of your software and the success of the project in the end. All 3 Clean Code presentations provide great value by themselves, but taken together are designed to offer a holistic approach to successful software creation.
Why writing Clean Code makes us more efficient Over the lifetime of a product, maintaining the product is actually one - if not the most - expensive area(s) of the overall product costs. Writing clean code can significantly lower these costs. However, writing clean code also makes you more efficient during the initial development time and results in more stable code. You will be presented design patterns and best practices which will make you write better and more easily maintainable code, seeing code in a holistic way. You will learn how to apply them by using an existing implementation as the starting point of the presentation. Finally, patterns & practices benefits are explained.
This presentation is based on C# and Visual Studio 2013. However, the demonstrated patterns and practice can be applied to every other programming language too.
Note: Moving forwards this presentation will be updated with the latest version of the slides for the last event I did the presentation instead of creating new separate slide decks here on SlideShare.
Presentation dates and locations:
2015-06-27 SoCal Code Camp - San Diego, CA
2014-11-14 SoCal Code Camp - Los Angeles, CA
2014-10-18 Desert Code Camp - Chandler, AZ
Session from NDC London 2013
Writing unit tests is hard, isn't it? you need an entire set of tools just to start. One of the crucial decisions when building this set is picking up a mocking framework.
But BEWARE! what you choose has the ability to make you or break you!
Come to the session and see Dror Helper, once a mocking framework developer, show the good and the bad of different mocking frameworks (free and commercial) and make them battle to the death!
Clean Code - Design Patterns and Best Practices at Silicon Valley Code CampTheo Jungeblut
Why writing Clean Code makes us more efficient Over the lifetime of a product, maintaining the product is actually one - if not the most - expensive area(s) of the overall product costs.
Writing clean code can significantly lower these costs. However, writing clean code also makes you more efficient during the initial development time and results in more stable code.
You will be presented design patterns and best practices which will make you write better and more easily maintainable code, seeing code in a holistic way. You will learn how to apply them by using an existing implementation as the starting point of the presentation. Finally, patterns & practices benefits are explained. This presentation is based on C# and Visual Studio 2012.
However, the demonstrated patterns and practice can be applied to almost every other programming language too.
In this talk I'm going to focus on the technical aspects of 'test automation', using examples of approaches from a variety of Agile projects where we automated APIs, and GUIs. You'll learn about the use of abstractions and how to think about modeling the system in code to support automating it. Also how to use these abstractions to support stress testing, exploratory testing, ongoing CI assertions and the testing process in general. I'll also discuss the different styles of coding used to support automating tactically vs automating strategically.
Refactoring legacy code driven by tests - ENGLuca Minudel
re you working on code poorly designed or on legacy code that’s hard to test? And you cannot refactor it because there are no tests?
During this Coding Dojo you’ll be assigned a coding challenge in Java, C#, Ruby, JavaScript or Python. You will face the challenge of improving the design and refactoring existing code in order to make it testable and to write unit tests.
We will discuss SOLID principles, the relation between design and TDD, and how this applies to your solution.
Reading list:
Growing Object-Oriented Software, Guided by Tests; Steve Freeman, Nat Pryce
Test Driven Development: By Example; Kent Beck
Working Effectively with Legacy; Michael Feathers
Agile Software Development, Principles, Patterns, and Practices; Robert C. Martin (C++, Java)
Agile Principles, Patterns, and Practices in C#; Robert C. Martin (C#)
First, what are they? And why they are important? What do they allow us to do, and what problems do they shield us from?
After this talk, you'll inevitably fall in love with pure functions and immutable objects. We'll see how to implement them in Java, in the most geek ways possible, concerned about long-term maintainability of the code. Oh, and we'll also have Lombok and records along the way, plus lots of fun while tasting a bit of "a senior developer's night-life".
Given at jLove Dec 2020
Coder sans peur du changement avec la meme pas mal hexagonal architectureThomas Pierrain
Découvrez en pratique l'architecture hexagonale, indispensable pour vos applications complexes !
Ce style d'architecture permet d'adapter votre code à tout changement de technologie sans souffrir. Si vous aimez changer de frameworks ou de librairies, tester correctement ou appliquer le Domain-Driven Design, alors vous avez besoin d'architecture hexagonale !
Avec des exemples en code Java, et au travers d’un kata d’architecture auquel vous pourrez participer, nous vous montrerons les pièges à éviter et comment mettre en œuvre ce pattern sans trop galérer, et ce dès votre retour au bureau !
Book review: Working Effectively with Legacy Code, by Michael C. Feathers
Agenda
- The mechanics of change
- Changing software
- Dependency breaking techniques
This session is for developers who need to work on code projects that where written without good unit-testing.
TDD is now mainstream but a lot people don't know or don't remember what is its purpose. TDD is about software design not testing or catching bug. TDD helps developers to shape and create software with "good" design, what is a "good" design is something that we will discuss in the topic.
TDD is now mainstream but a lot people don't know or don't remember what is its purpose. TDD is about software design not testing or catching bug. TDD helps developers to shape and create software with "good" design, what is a "good" design is something that we will discuss in the topic.
Testing is fundamental in software development. Quality gates demand high coverage levels, pull requests need sufficient tests, leading to teams spending considerable time writing and maintaining them. But are we using our tests to their full potential?
'If code is hard to test, the design can be improved'. Starting from this mantra, this deep-dive session unveils hints to simplify code, break-down complexity, and effectively use functional programming. We'll delve into topics like fixture creep, partial mocks, onion architecture, and pure functions, providing numerous best practices and practical tips for your testing.
Be warned: This session may significantly disrupt your work routine and will likely change how you see testing. Attend at your own risk.
Lightening Talk I gave at Inaka in April 2014.
I was in charge of investigating test-driven development for our iOS mobile team. Since I realized it was such a big concept, after having gathered enough information and having played with it enough, I decided to introduce my fellows on the topic by presenting it in a formal talk with slides. The aim was teaching them a different way of developing, which, for us, at that moment, was completely new and controversial.
The PVS-Studio team is now actively developing a static analyzer for C# code. The first version is expected by the end of 2015. And for now my task is to write a few articles to attract C# programmers' attention to our tool in advance. I've got an updated installer today, so we can now install PVS-Studio with C#-support enabled and even analyze some source code. Without further hesitation, I decided to scan whichever program I had at hand. This happened to be the Umbraco project. Of course we can't expect too much of the current version of the analyzer, but its functionality has been enough to allow me to write this small article.
Learn how to get small teams to embrace both using and contributing to open source in a healthy way. See case studies of open source projects and how they have contributed to the growth of a small team.
Test-Driven Developments are Inefficient; Behavior-Driven Developments are a ...Abdelkrim Boujraf
In summary, we have presented here a method for efficiently testing large parts of web-based software by using elements of code generation to generate automatable tests, and by using BDD concepts to model tests for non-generated screens and non-generated business actions. Further, we have described a method for context-based unit
testing that, when combined with generated code and tests, yields an acceptable trade-off between development efficiency and time spent on testing
Unit tests are the first barrier that protects our code from bugs. We'll talk about main principles, metrics and best practices, which are important for unit tests. And how to build this barier strong and maintainable.
This was a workshop given on the UTN University, for the Software Engineering students. The idea is to give a brief explanation about TDD, and how to use it.
Ever tried doing Test First Test Driven Development? Ever failed? TDD is not easy to get right. Here's some practical advice on doing BDD and TDD correctly. This presentation attempts to explain to you why, what, and how you should test, tell you about the FIRST principles of tests, the connections of unit testing and the SOLID principles, writing testable code, test doubles, the AAA of unit testing, and some practical ideas about structuring tests.
How to complement TDD with static analysisPVS-Studio
TDD is one of the most popular software development techniques. I like this technology in general, and we employ it to some extent. The main thing is not to run to extremes when using it. One shouldn't fully rely on it alone forgetting other methods of software quality enhancement. In this article, I will show you how the static code analysis methodology can be used by programmers using TDD to additionally secure themselves against errors.
Cosa sono i microservizi? Perché li devo usare? Sono una moda? In alcuni dicono che siano una soluzione "standard", altri dicono che non si dovrebbero usare, altri ne negano l'esistenza... Ma chi sviluppa software e deve portare a casa un po' di software che funziona... cosa deve fare?
Proviamo a vedere e a capire da dove arrivano, cosa sono e quali caratteristiche hanno, in modo da fare in ogni contesto una scelta una consapevole.
Elixir and Erlang share the same VM called BEAM. In this very practical demo, we discover some secrets of BEAM and OTP. This a refreshed version of an old presentations.
These are slides of talk made at https://www.agilemovement.it/workingsoftware/schedule.html. In this talks I'll show how the concepts of DDD like aggregate, domains events, read model, command, CQRS and so on love the idea of Actor Model and how a languages like Elixir that is built on a real Actor Model VM like the BEAM, is very powerful to build software that take care of DDD/CQRS/ES.
In this talk, I'll explain how the current web applications are no more simple DB projections but more complex and distributed applications that require technologies and architectures different from the past. We start with a simple & classic application to move to a more complex and feature-rich application that need a more advanced architecture.
Workshop on how, using RabbitMQ and Elixir, we can integrate a lot of different application written in different languages (Java, .NET, js, ruby, python and C++) with different protocols AMQP and MQTT.
Docker & GitLab as a Continuous Integration platform. In this talk we describe how we use gitlab and docker as a platform to implement Continuous Integration in a simple and effective weay.
In questo talk farò vedere il primo approccio ad Elixir in un semplice caso reale. Vedremo cosa significa sviluppare un piccolo servizio in Elixir e quanto l'ecosistema sia pronto per andare in produzione.
Can we move beyond threads and locks to manage concurrency? Are there more advanced models than threads and locks? How do other languages manage the concurrency?
We see some examples in others languages and a possible solution in C++.
Example code: https://github.com/italiancpp/meetup-milano-2014/tree/master/cpp_actor_model
Climate Science Flows: Enabling Petabyte-Scale Climate Analysis with the Eart...Globus
The Earth System Grid Federation (ESGF) is a global network of data servers that archives and distributes the planet’s largest collection of Earth system model output for thousands of climate and environmental scientists worldwide. Many of these petabyte-scale data archives are located in proximity to large high-performance computing (HPC) or cloud computing resources, but the primary workflow for data users consists of transferring data, and applying computations on a different system. As a part of the ESGF 2.0 US project (funded by the United States Department of Energy Office of Science), we developed pre-defined data workflows, which can be run on-demand, capable of applying many data reduction and data analysis to the large ESGF data archives, transferring only the resultant analysis (ex. visualizations, smaller data files). In this talk, we will showcase a few of these workflows, highlighting how Globus Flows can be used for petabyte-scale climate analysis.
AI Pilot Review: The World’s First Virtual Assistant Marketing SuiteGoogle
AI Pilot Review: The World’s First Virtual Assistant Marketing Suite
👉👉 Click Here To Get More Info 👇👇
https://sumonreview.com/ai-pilot-review/
AI Pilot Review: Key Features
✅Deploy AI expert bots in Any Niche With Just A Click
✅With one keyword, generate complete funnels, websites, landing pages, and more.
✅More than 85 AI features are included in the AI pilot.
✅No setup or configuration; use your voice (like Siri) to do whatever you want.
✅You Can Use AI Pilot To Create your version of AI Pilot And Charge People For It…
✅ZERO Manual Work With AI Pilot. Never write, Design, Or Code Again.
✅ZERO Limits On Features Or Usages
✅Use Our AI-powered Traffic To Get Hundreds Of Customers
✅No Complicated Setup: Get Up And Running In 2 Minutes
✅99.99% Up-Time Guaranteed
✅30 Days Money-Back Guarantee
✅ZERO Upfront Cost
See My Other Reviews Article:
(1) TubeTrivia AI Review: https://sumonreview.com/tubetrivia-ai-review
(2) SocioWave Review: https://sumonreview.com/sociowave-review
(3) AI Partner & Profit Review: https://sumonreview.com/ai-partner-profit-review
(4) AI Ebook Suite Review: https://sumonreview.com/ai-ebook-suite-review
How to Position Your Globus Data Portal for Success Ten Good PracticesGlobus
Science gateways allow science and engineering communities to access shared data, software, computing services, and instruments. Science gateways have gained a lot of traction in the last twenty years, as evidenced by projects such as the Science Gateways Community Institute (SGCI) and the Center of Excellence on Science Gateways (SGX3) in the US, The Australian Research Data Commons (ARDC) and its platforms in Australia, and the projects around Virtual Research Environments in Europe. A few mature frameworks have evolved with their different strengths and foci and have been taken up by a larger community such as the Globus Data Portal, Hubzero, Tapis, and Galaxy. However, even when gateways are built on successful frameworks, they continue to face the challenges of ongoing maintenance costs and how to meet the ever-expanding needs of the community they serve with enhanced features. It is not uncommon that gateways with compelling use cases are nonetheless unable to get past the prototype phase and become a full production service, or if they do, they don't survive more than a couple of years. While there is no guaranteed pathway to success, it seems likely that for any gateway there is a need for a strong community and/or solid funding streams to create and sustain its success. With over twenty years of examples to draw from, this presentation goes into detail for ten factors common to successful and enduring gateways that effectively serve as best practices for any new or developing gateway.
Into the Box Keynote Day 2: Unveiling amazing updates and announcements for modern CFML developers! Get ready for exciting releases and updates on Ortus tools and products. Stay tuned for cutting-edge innovations designed to boost your productivity.
Enterprise Resource Planning System includes various modules that reduce any business's workload. Additionally, it organizes the workflows, which drives towards enhancing productivity. Here are a detailed explanation of the ERP modules. Going through the points will help you understand how the software is changing the work dynamics.
To know more details here: https://blogs.nyggs.com/nyggs/enterprise-resource-planning-erp-system-modules/
We describe the deployment and use of Globus Compute for remote computation. This content is aimed at researchers who wish to compute on remote resources using a unified programming interface, as well as system administrators who will deploy and operate Globus Compute services on their research computing infrastructure.
How Recreation Management Software Can Streamline Your Operations.pptxwottaspaceseo
Recreation management software streamlines operations by automating key tasks such as scheduling, registration, and payment processing, reducing manual workload and errors. It provides centralized management of facilities, classes, and events, ensuring efficient resource allocation and facility usage. The software offers user-friendly online portals for easy access to bookings and program information, enhancing customer experience. Real-time reporting and data analytics deliver insights into attendance and preferences, aiding in strategic decision-making. Additionally, effective communication tools keep participants and staff informed with timely updates. Overall, recreation management software enhances efficiency, improves service delivery, and boosts customer satisfaction.
First Steps with Globus Compute Multi-User EndpointsGlobus
In this presentation we will share our experiences around getting started with the Globus Compute multi-user endpoint. Working with the Pharmacology group at the University of Auckland, we have previously written an application using Globus Compute that can offload computationally expensive steps in the researcher's workflows, which they wish to manage from their familiar Windows environments, onto the NeSI (New Zealand eScience Infrastructure) cluster. Some of the challenges we have encountered were that each researcher had to set up and manage their own single-user globus compute endpoint and that the workloads had varying resource requirements (CPUs, memory and wall time) between different runs. We hope that the multi-user endpoint will help to address these challenges and share an update on our progress here.
Unleash Unlimited Potential with One-Time Purchase
BoxLang is more than just a language; it's a community. By choosing a Visionary License, you're not just investing in your success, you're actively contributing to the ongoing development and support of BoxLang.
Accelerate Enterprise Software Engineering with PlatformlessWSO2
Key takeaways:
Challenges of building platforms and the benefits of platformless.
Key principles of platformless, including API-first, cloud-native middleware, platform engineering, and developer experience.
How Choreo enables the platformless experience.
How key concepts like application architecture, domain-driven design, zero trust, and cell-based architecture are inherently a part of Choreo.
Demo of an end-to-end app built and deployed on Choreo.
Globus Compute wth IRI Workflows - GlobusWorld 2024Globus
As part of the DOE Integrated Research Infrastructure (IRI) program, NERSC at Lawrence Berkeley National Lab and ALCF at Argonne National Lab are working closely with General Atomics on accelerating the computing requirements of the DIII-D experiment. As part of the work the team is investigating ways to speedup the time to solution for many different parts of the DIII-D workflow including how they run jobs on HPC systems. One of these routes is looking at Globus Compute as a way to replace the current method for managing tasks and we describe a brief proof of concept showing how Globus Compute could help to schedule jobs and be a tool to connect compute at different facilities.
Gamify Your Mind; The Secret Sauce to Delivering Success, Continuously Improv...Shahin Sheidaei
Games are powerful teaching tools, fostering hands-on engagement and fun. But they require careful consideration to succeed. Join me to explore factors in running and selecting games, ensuring they serve as effective teaching tools. Learn to maintain focus on learning objectives while playing, and how to measure the ROI of gaming in education. Discover strategies for pitching gaming to leadership. This session offers insights, tips, and examples for coaches, team leads, and enterprise leaders seeking to teach from simple to complex concepts.
In 2015, I used to write extensions for Joomla, WordPress, phpBB3, etc and I ...Juraj Vysvader
In 2015, I used to write extensions for Joomla, WordPress, phpBB3, etc and I didn't get rich from it but it did have 63K downloads (powered possible tens of thousands of websites).
Globus Connect Server Deep Dive - GlobusWorld 2024Globus
We explore the Globus Connect Server (GCS) architecture and experiment with advanced configuration options and use cases. This content is targeted at system administrators who are familiar with GCS and currently operate—or are planning to operate—broader deployments at their institution.
Code reviews are vital for ensuring good code quality. They serve as one of our last lines of defense against bugs and subpar code reaching production.
Yet, they often turn into annoying tasks riddled with frustration, hostility, unclear feedback and lack of standards. How can we improve this crucial process?
In this session we will cover:
- The Art of Effective Code Reviews
- Streamlining the Review Process
- Elevating Reviews with Automated Tools
By the end of this presentation, you'll have the knowledge on how to organize and improve your code review proces
Paketo Buildpacks : la meilleure façon de construire des images OCI? DevopsDa...Anthony Dahanne
Les Buildpacks existent depuis plus de 10 ans ! D’abord, ils étaient utilisés pour détecter et construire une application avant de la déployer sur certains PaaS. Ensuite, nous avons pu créer des images Docker (OCI) avec leur dernière génération, les Cloud Native Buildpacks (CNCF en incubation). Sont-ils une bonne alternative au Dockerfile ? Que sont les buildpacks Paketo ? Quelles communautés les soutiennent et comment ?
Venez le découvrir lors de cette session ignite
top nidhi software solution freedownloadvrstrong314
This presentation emphasizes the importance of data security and legal compliance for Nidhi companies in India. It highlights how online Nidhi software solutions, like Vector Nidhi Software, offer advanced features tailored to these needs. Key aspects include encryption, access controls, and audit trails to ensure data security. The software complies with regulatory guidelines from the MCA and RBI and adheres to Nidhi Rules, 2014. With customizable, user-friendly interfaces and real-time features, these Nidhi software solutions enhance efficiency, support growth, and provide exceptional member services. The presentation concludes with contact information for further inquiries.
1. TDD is not about
testing
Bad name for good technique ...
2. #CodeBEAMSTO
GPad
Born to be a developer with an interest in distributed system.
I have developed with many languages like C++, C#, js and ruby. I had fallen in
love with functional programming, especially with elixir, erlang.
● Twitter: https://twitter.com/gpad619
● Github: https://github.com/gpad/
● Medium: https://medium.com/@gpad
CTO & founder of coders51
4. #CodeBEAMSTO
What is TDD - History
Wikipedia - TDD
Wikipedia - Extreme Programming
Quora - Why does Kent Beck rediscover TDD
http://wiki.c2.com/?TestingFramework
Wikipedia - C2 System
5. #CodeBEAMSTO
What is TDD - History
The C3 project started in 1993 [...]. Smalltalk development was initiated in 1994.
[...] In 1996 Kent Beck was hired [...]; at this point the system had not printed a
single paycheck.
In March 1996 the development team estimated the system would be ready to go
into production around one year later.
In 1997 the development team adopted a way of working which is now formalized
as Extreme Programming.
The one-year delivery target was nearly achieved, with actual delivery being a
couple of months late;
6. #CodeBEAMSTO
What is TDD - History
It was developed by Grady Booch, Ivar Jacobson
and James Rumbaugh at Rational Software in
1994–1995, with further development led by them
through 1996.
In 1997 UML was adopted as a standard by the
Object Management Group (OMG) [...].
In 2005 UML was also published by the International Organization for
Standardization (ISO) as an approved ISO standard. Since then the standard
has been periodically revised to cover the latest revision of UML.
8. #CodeBEAMSTO
What is TDD - History
Form Wikipedia:
Test-driven development (TDD) is a software development process that relies on the
repetition of a very short development cycle: requirements are turned into very
specific test cases, then the software is improved to pass the new tests, only.
This is opposed to software development that allows software to be added that is
not proven to meet requirements.
American software engineer Kent Beck, who is credited with having developed or
"rediscovered" the technique, stated in 2003 that TDD encourages simple designs
and inspires confidence.
10. #CodeBEAMSTO
What is TDD
1. Add a test
2. Run all tests and see if the new test
fails (RED)
3. Write the code (Only to make the
test pass!!!)
4. Run tests
5. Refactor code
6. Repeat
13. #CodeBEAMSTO
Why TDD
TDD changes the point of view.
Forces the developer to think about the “behaviour” of the code.
Talks to the developer showing what are the “difficult points” of the code.
If the tests talk, we should listen them … (often we ignore them).
14. #CodeBEAMSTO
Listen the test
defmodule MyModule do
def postpone(dest, msg) do
msg = encapsulate(msg)
time = get_delay()
Process.send_after(dest, msg, time)
end
defp encapsulate(msg) do
{:postone, msg}
end
def get_delay() do
Application.get_env(:postone, :time, 10000)
end
end
15. #CodeBEAMSTO
Listen the test
defmodule MyModuleTest do
use ExUnit.Case
test "postone right" do
MyModule.postpone(self(), "ciao")
assert_receive {:postone, "ciao"}, 20_000
end
end
The name doesn’t mean anything
Our test is sloooow ...
16. #CodeBEAMSTO
Listen the test - other smells ...
defmodule MyModuleTest do
use ExUnit.Case
test "postpone right" do
Application.put_env(:postone, :time, 1)
MyModule.postpone(self(), "ciao")
assert_receive {:postone, "ciao"}
end
test "postpone for right time ..." do
MyModule.postpone(self(), "ciao")
refute_receive {:postone, "ciao"}, 5000
end
end
Change GLOBAL value!!!!
No More isolated !!!
17. #CodeBEAMSTO
Listen the test
defmodule MyModuleTest do
use ExUnit.Case, async: false
import Mock
test "postone right with mock" do
with_mock(Process, [:passthrough], send_after: fn dst, msg, _ -> send(dst, msg) end) do
MyModule.postpone(self(), "ciao")
assert_receive {:postone, msg}
end
end
end
No more concurrency
Why this ?!?!
Still doesn’t work ...
This is not our module
19. #CodeBEAMSTO
Listen the test
defmodule MyModuleTest do
use ExUnit.Case
test "postone right" do
MyModule.postpone(self(), "ciao")
assert_receive {:postone, "ciao"}, 20_000
end
end
The name doesn’t mean anything
Our test is sloooow ...
20. #CodeBEAMSTO
Listen the test
defmodule MyModuleTest do
use ExUnit.Case
test "postone/1 send delayed message" do
MyModule.postpone(self(), "ciao", 0)
assert_receive {:postone, "ciao"}
end
end
Describe the behaviour of method
We can manage the behaviour of our function ...
21. #CodeBEAMSTO
Listen the test
defmodule MyModule do
@postpone_time Application.get_env(:postone, :time, 10000)
def postpone(dest, msg, time @postpone_time) do
msg = encapsulate(msg)
Process.send_after(dest, msg, time)
end
defp encapsulate(msg) do
{:postone, msg}
end
end
24. #CodeBEAMSTO
Type of tests
End to End tests - Tests that work on the entire stack.
Integration Test - Tests that work on some parts of the application.
Unit Test - Tests that work on a single “module/function”.
Why is it important to know which type of test we are writing?
Because we get different feedbacks from different types of test.
26. #CodeBEAMSTO
Cycle of TDD ...
1. Add a test
2. Run all tests and see if the new
test fails (RED)
3. Write the code
4. Run tests
5. Refactor code
6. Repeat
28. #CodeBEAMSTO
End To End Test or Acceptance Test
This type of test exercises the entire stack of the application.
It remains RED until the feature is completed.
Don’t write too much E2E.
They are slow and fragile.
Where is the design?
30. #CodeBEAMSTO
How application is done (or should be)
Try to create a E2E test that interacts
with system from the external.
If it’s “impossible” try to move a little
inside skipping the adapter.
32. #CodeBEAMSTO
OOP vs FP
OOP - We pass object reference to Object under test!
FP - We have immutability!
Elixir - We have almost always immutability!
Immutability means purity.
Purity means no side effects.
33. #CodeBEAMSTO
OOP vs FP
What are the instructions that make the code impure?
Everytime we make an I/O operation we aren’t pure.
Everytime we send a message.
Everytime we use the time.
34. #CodeBEAMSTO
OOP vs FP
What’s happen when we lost our purity?
We depend to something “external”.
We are doing at least integration test.
So ...
35. #CodeBEAMSTO
OOP vs FP
In OOP is quite common use mock to mock dependencies of objects and to
define the relationship between them.
In FP (IMHO) mock should be used to manage the impurity of our language.
37. #CodeBEAMSTO
When to use Mock?
When we want to isolate one part from another.
Classic example HTTP connections.
We have to make some HTTP calls and manipulate the results in some ways.
How can we do it?
38. #CodeBEAMSTO
When to use Mock?
DON’T TRY THIS AT HOME!!
test "create data via https", %{id: id} do
response = create_response(201, %{key: "value"})
with_mock HTTPoison, [:passthrough], post: fn @url, _, _, _ -> {:ok, response} end do
{:ok, %{res: value}} = MyModule.execute(id)
assert value == "value"
assert called(HTTPoison.post(@url, %{id: id}, :_, :_))
end
end
39. #CodeBEAMSTO
When to use Mock?
Better solution
test "create data via https", %{id: id} do
with_mock RemoteData, create: fn %{id: id} -> {:ok, %{key: "value"}} end do
{:ok, %{res: "value"}} = MyModule.execute(id)
assert called(RemoteData.create(%{id: id}))
end
end”
Our module
More domain related function ...
40. #CodeBEAMSTO
When to use Mock?
We are at the boundaries of our
system and we can use the mock to
shape the behavior between the
CORE and the adapter that talks with
the external system.
It’s the CORE that choose the shape
of the data and how the functions
should be done.
41. #CodeBEAMSTO
When to use Mock? - I/0
defmodule MyCoreModule do
def store_valid_data(data, limit, delta) do
content = data
|> Enum.filter(fn %{value: value} -> around(value, limit, delta) end)
|> Enum.map(fn %{value: v, comment: c} -> "value: #{v} - comment: #{c}" end)
|> Enum.join("n")
:ok = File.write(@path, content)
end
end
42. #CodeBEAMSTO
When to use Mock? - I/0
defmodule MyCoreModule do
def store_valid_data(data, limit, delta, storage FileStorage) do
content = data
|> Enum.filter(fn %{value: value} -> around(value, limit, delta) end)
|> Enum.map(fn %{value: v, comment: c} -> "value: #{v} - comment: #{c}" end)
|> Enum.join("n")
:ok = storage.store(content)
end
end
43. #CodeBEAMSTO
When to use Mock? - I/O
defmodule MyCoreModuleTest do
use ExUnit.Case
defmodule MockStorage do
def store(content) do
send(self(), {:store, content})
:ok
end
end
test "store only valid data", %{limit: limit, delta: delta} do
valid = valid_data(limit, delta)
invalid = invalid_data(limit, delta)
content = "value: #{valid.value} - comment: #{valid.comment}"
MyCoreModule.store_valid_data(
[valid, invalid], limit, delta, MockStorage)
assert_received {:store, ^content}
end
44. #CodeBEAMSTO
When to use Mock? - Time
defmodule MyCoreModule do
def create_question(opts) do
%{
question: Keyword.get(opts, :q, "Sense of life?"),
response: Keyword.get(opts, :a, 42),
created_at: DateTime.utc_now()
}
end
end
45. #CodeBEAMSTO
When to use Mock? - Time
defmodule MyCoreModuleTest do
use ExUnit.Case
test "create questions" do
assert MyCoreModule.create_question([]) == %{
question: "Sense of life?",
response: 42,
created_at: DateTime.utc_now()
}
end
end
47. #CodeBEAMSTO
When to use Mock? - Time
defmodule MyCoreModule do
def create_question(opts, clock Clock) do
%{
question: Keyword.get(opts, :q, "Sense of life?"),
response: Keyword.get(opts, :a, 42),
created_at: clock.utc_now()
}
end
end
48. #CodeBEAMSTO
When to use Mock? - Time
test "create default questions" do
assert MyCoreModule.create_question([], MockClock) == %{
question: "Sense of life?",
response: 42,
created_at: MockClock.utc_now()
}
end
51. #CodeBEAMSTO
When to use Mock? - Time
defmodule MyCoreModuleTest do
use ExUnit.Case
test "change state at every tick" do
prev = MyCoreModule.new()
next = MyCoreModule.tick(prev)
assert next.value == prev.value + 1
end
end
52. #CodeBEAMSTO
When to use Mock? - Time
defmodule MyCoreModuleServerTest do
use ExUnit.Case
test "call tick when receive tick" do
with_mock(MyCoreModule, tick: fn s -> s end) do
pid = MyCoreModuleServer.start_link()
send(pid, :tick)
eventually_assert(fn -> assert_called(MyCoreModule.tick(:_)) end)
end
end
end
53. #CodeBEAMSTO
When to use Mock? - Time
defmodule MyCoreModuleServer do
use GenServer
def init([other_args, duration]) do
state = calc_state(other_args, duration)
Process.send_after(self(), :tick, duration)
{:ok, state}
end
def handle_info(:tick, state) do
new_core = MyCoreModule.tick(state.core)
Process.send_after(self(), :tick, state.duration)
{:noreply, %{state | core: new_core}}
end
54. #CodeBEAMSTO
WHERE to use Mock?
Use the mock at the external of
CORE/Domain (adapter).
Try to keep the CORE pure so we
don’t have “side-effect” inside it.
55. #CodeBEAMSTO
When not to use Mock?
Don’t use mock on Module that don’t own.
test "create data via https", %{id: id} do
response = create_response(201, %{key: "value"})
with_mock HTTPoison, [:passthrough], post: fn @url, _, _, _ -> {:ok, response} end do
{:ok, %{res: value}} = MyModule.execute(id)
assert value == "value"
assert called(HTTPoison.post(@url, %{id: id}, :_, :_))
end
end
56. #CodeBEAMSTO
When not to use Mock?
Don’t use mock because otherwise “you aren’t doing unit test”
defmodule MyCoreModule1 do
def execute(data) do
data
|> Enum.map(fn -> {data.id, data.value, data} end)
|> MyCoreModule2.filter(data.filter)
|> MyCoreModule3.map(data.type)
end
end
57. #CodeBEAMSTO
When not to use Mock?
defmodule MyCoreModule1Test do
use ExUnit.Case
test "execute filter and map data" do
with_mocks [
{MyCoreModule2, [], filter: fn data, _level -> data end},
{MyCoreModule3, [], map: fn data, _type -> data end}
] do
MyCoreModule1.execute([%{id: 12, value: 1, filter: 10, type: OtherModule}])
assert called(MyCoreModule2.filter(:_, :_))
assert called(MyCoreModule3.map(:_, :_))
end
end
end
58. #CodeBEAMSTO
TDD - Mix Everything together
What is the first test to do?
We could start from an E2E test to enter inside our application.
Create at least one E2E for every User Story.
Don’t create too much E2E they are slow and fragile.
59. #CodeBEAMSTO
TDD - Mix Everything together
defmodule MayApp.EndToEnd.GamesTest do
use MayApp.ConnCase, async: false
describe "As Logged User" do
test "I would see my active games", %{conn: conn} do
{:ok, game} = create_active_game()
conn = get(conn, "/api/games")
assert json_response(conn, 200) == expected_response_for(game)
end
...
60. #CodeBEAMSTO
TDD - Mix Everything together
defmodule MayApp.EndToEnd.GamesTest do
use MayApp.ConnCase, async: false
describe "As Logged User" do
...
test "I would create a new games", %{conn: conn} do
conn = post(conn, "/api/games")
res = json_response(conn, 200)
assert %{"id" => _, "status" => "active"} = res
end
end
end
61. #CodeBEAMSTO
TDD - Mix Everything together
The E2E remains RED until all the cycle is completed.
After that we have written the E2E we go inside the CORE and start to create
some unit tests.
The Unit Test should be PURE.
62. #CodeBEAMSTO
TDD - Mix Everything together
defmodule MayApp.MyCoreModuleTest do
use ExUnit.Case
test "at every tick the count is incremented" do
state = MyCoreModule.new(MockClock)
new_state = MyCoreModule.tick(state)
assert new_state.count == state.count + 1
assert new_state.last_updated_at == MockClock.utc_now()
end
...
end
63. #CodeBEAMSTO
TDD - Mix Everything together
defmodule MayApp.MyCoreModuleTest do
use ExUnit.Case
test "at every tick the count is incremented" do
state = MyCoreModule.new()
new_state = MyCoreModule.tick(state, now)
assert new_state.count == state.count + 1
assert new_state.last_updated_at == now
end
...
end
64. #CodeBEAMSTO
TDD - Mix Everything together
After we have written the unit tests for the CORE we could move to the
boundaries where we should write tests for the adapter parts.
The test for storage part should be written using the DB. IMHO they are more
integration than unit.
65. #CodeBEAMSTO
TDD - Mix Everything together
defmodule MayApp.GameServerTest do
use ExUnit.Case, async: false
test "at every tick the state is changed" do
id = 123
game = %{id: id, state: :ready}
with_mocks [{GameStorage, load: fn ^id -> game end},
{MyCoreModule, tick: fn ^game, _ -> game end}] do
{:ok, pid} = GameServer.start_link(id, tick: :manual)
GameServer.tick(pid)
assert_called(MyCoreModule.tick(game, :_))
end
end
66. #CodeBEAMSTO
TDD - Mix Everything together
defmodule MayApp.GameServerTest do
use ExUnit.Case, async: false
test "at every tick the new game is stored" do
game = Game.new()
GameStorage.save_game(game)
{:ok, pid} = GameServer.start_link(game.id, tick: :manual)
GameServer.tick(pid)
eventually_assert(fn ->
new_game = GameStorage.load(game.id)
assert new_game.count == game.count + 1
end)
end
end
67. #CodeBEAMSTO
TDD - Mix Everything together
Writing these tests BEFORE the implementation we are doing DESIGN.
We are shaping the production code.
The code became more “composable”.
It’s more clear where are side effects (I/O, Time).
It’s more clear what are the different parts of our applications.
68. #CodeBEAMSTO
Recap
TDD is not a Silver Bullet.
TDD doesn’t give us a “good” design if we are not able to do it.
TDD can help us to find some issues in our design.
Listen the test, often they are screaming in pain ...