The document discusses clean coding practices for Java developers. It covers topics such as choosing meaningful names for variables, methods, and classes; writing code that is easy for others to understand; breaking methods down into single logical steps; and using fluent APIs to make code more readable. The presentation provides examples of clean code and ways to refactor code to follow best practices.
Vladimir Romanov - How to write code that is easy to read and change? What should you do when you see a piece of code written years ago which is hard to understand? In my experience, this boils down to 4 principles that I would like to share along with some examples in Apex
The document discusses principles of clean code, beginning with definitions of clean code from various authors. It outlines key principles like the single responsibility principle and open/closed principle. It then covers sections on meaningful naming, functions, and classes. For functions, it recommends they be small, do one thing, avoid flag arguments, and have no side effects. For classes, it advocates for small size, encapsulation, high cohesion and low coupling following the single responsibility principle.
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.
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 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
2014-11-14 SoCal Code Camp - Los Angeles, CA
2014-10-18 Desert Code Camp - Chandler, AZ
2014-10-11 Silicon Valley Code Camp, Los Altos Hills, CA
The document discusses clean code versus bad code. Clean code is easy to understand, maintain, and extend, while bad code is mysterious, fragile, and dangerous. The author provides tips for writing clean code such as using meaningful names, consistent formatting, small and focused functions, and comments that explain intent rather than state the obvious. The goal is to write code that is readable and maintainable over time.
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
This document provides an overview of writing clean code, focusing on readability, code style, naming conventions, code comments, control structures, functions/methods, classes, and modules. Key points include formatting code for readability, using explicit and descriptive naming, minimizing comments by ensuring code is self-explanatory, limiting nested control structures and side effects, following single responsibility and encapsulation principles, and leveraging software patterns.
The document discusses the principles of clean code as outlined in the book "Clean Code" by Robert C. Martin. It covers topics like meaningful names, comments, functions, objects and data structures, error handling, and unit tests. The goal of clean code is to produce readable, maintainable code through practices like breaking code into small, single-purpose functions and hiding implementation details in objects.
Evolving a Clean, Pragmatic Architecture - A Craftsman's GuideVictor Rentea
This document outlines an agenda and presentation on clean code architecture. It discusses modeling data with entities and value objects, organizing logic by extracting services and applying the onion architecture. It emphasizes testing to reduce fear, and protecting developers through simplicity and avoiding overengineering. The presentation emphasizes keeping data transfer objects lightweight and external to the domain.
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.
This document discusses principles for writing clean code in functions. It recommends that functions should be small, do one thing, have descriptive names, and avoid side effects. Functions with many arguments or switch statements are harder to understand. Exceptions should be used instead of return codes to indicate errors. Overall, following best practices for functions helps produce code that is easy to read and maintain.
Clean code is code that is elegant, efficient, focused, and readable. It should do one thing well. Bad code lacks these traits. Some heuristics for writing clean code include using descriptive naming, short methods that do one thing, avoiding comments when possible, consistent formatting, following object-oriented design principles like the Law of Demeter, and properly handling errors through exceptions.
Slides of the talk held at JEEConf, Kiev and jPrime, Sofia. A personal view on the classic topics from the Uncle Bob's Clean Code bible, with some personal additions and tips&tricks. This topic actually represents the core of the training sessions that I provide as an independent trainer (www.victorrentea.ro)
The tests are trying to tell you something@VoxxedBucharest.pptxVictor Rentea
If tests are hard to write, the production design is crappy - goes an old saying. Indeed, writing unit tests gives you one of the most comprehensive, yet brutal, feedback about the design of your production code, but if it comes too late, many developers can’t stand it anymore and they will either stop testing or test more superficially. At the other extreme, others struggle to write contrived, fragile tests full of mocks that end up frustrating more than helping them. This talk reviews the main hints that unit tests provide you, from the most obvious improvements to some of the most subtle design principles.
The document introduces the Kotlin programming language developed by JetBrains. It provides an overview of Kotlin's motivation, features, syntax and tooling. Key points include Kotlin being a statically typed JVM language intended for industrial use, its focus on common sense features from other languages, and full interoperability with Java.
From object oriented to functional domain modelingMario Fusco
This document discusses moving from an object-oriented approach to a functional approach for domain modeling. It provides examples of modeling a bank account and salary calculator in both OOP and FP styles. Some key benefits of the functional approach highlighted include immutability, avoiding side effects, handling errors through monads instead of exceptions, and composing functions together through currying and composition. Overall the document advocates that while OOP and FP both have merits, modeling as functions can provide advantages in terms of understandability, testability, and extensibility of the code.
Clean architecture - Protecting the DomainVictor Rentea
The goal of architecture is to simplify the most complex parts of your logic. Any other goal should be secondary to this. The problem is that you can’t always anticipate where the complexity of your application will accumulate, especially when confronted with ever-changing requirements. The only way to keep your code simple is to gradually evolve the architecture without adding useless complexity up front, but always looking out for opportunities to break-down and refactor towards the most simple design that solves the problem. Drawing concepts from the Domain-Driven Development mindset, this talk summarizes the most important lessons learned designing and consulting many real-world projects. Along the way, you’ll hear about Value Objects and Entities, DTOs, Dependency Inversion Principle, Facades, the Onion Architecture and many pragmatic tips and tricks immediately applicable to your day-to-day work.
Whitebox testing of Spring Boot applicationsYura Nosenko
This document discusses whitebox testing of Spring Boot applications. It begins with introductions and backgrounds, then discusses issues with existing testing frameworks like TestNG and JUnit 4. It proposes alternatives like Spock and JUnit 5, highlighting advantages of each. It also provides an overview of Spring Boot testing capabilities, focusing on integration testing support, transaction handling, main components, and reactive support. It concludes with examples of setting up Spring Boot testing with Spock and JUnit 5.
"Even bad code can function. But if code isn't clean, it can bring a development organization to its knees. Every year, countless hours and significant resources are lost because of poorly written code. But it doesn't have to be that way." In this knolx session, a few important topics for having clean code are covered. Basically the following topics - Meaningful name, Functions, Comments and Classes.
The document discusses code refactoring and code smells. It provides an overview of code refactoring techniques such as extract class, extract method, rename method, substitute algorithm, decompose conditional, consolidate conditional expression, consolidate duplicate conditional fragments, introduce parameter object, inline temporary variable, and replace magic number with symbolic constant. It also describes common code smells like duplicated code, large class, long method, long parameter list, lazy class, switch statements, undescriptive names, temporary fields, message chains, and comments. The document emphasizes that refactoring is important to improve code quality and reduce complexity, and that developers should refactor frequently to avoid code smells.
This document discusses techniques for working with legacy code, including sprout method, wrap method, and wrap class. Sprout method involves extracting part of an existing method into a new method. Wrap method surrounds an existing method with new code. Wrap class creates a new class that delegates to the original class, allowing new behavior to be added. The techniques allow new functionality to be added to legacy code in a way that does not disrupt existing behavior and allows the new code to be tested independently.
1. The document discusses good and bad practices for writing unit tests. It emphasizes that tests should verify the expected behavior, fail clearly when something goes wrong, and use mocks and isolation to focus on the code being tested.
2. Some examples of bad tests shown include tests that don't make assertions or assertions that don't provide useful information on failure. Real objects are also used instead of mocks, obscuring the test.
3. Good practices include using mocks to isolate the code being tested, making sure tests fail clearly when something goes wrong, and focusing tests on expected behavior through clear assertions. Automated testing, fixing broken tests, and mastering testing tools are also emphasized.
A GWT Application with MVP Pattern Deploying to CloudFoundry using Spring Roo Ali Parmaksiz
This document summarizes a presentation about developing a MVP application using GWT, Spring Roo, and deploying it to CloudFoundry. The presentation covers MVP pattern in GWT, using activities and places for navigation, using Spring Roo for rapid development, and deploying the application to CloudFoundry. It provides code examples for implementing MVP using views, presenters, activities and places. It also outlines the steps to deploy an application to CloudFoundry including installing the vmc CLI and pushing the application.
This document summarizes a test for an ExchangeRateUploader class that uploads exchange rates to a database. The test mocks several dependencies, sets up test data including currencies and exchange rates, and verifies the uploader saves the rates and finalizes the thread.
1. The document discusses the evolution of the C# programming language from versions 1.0 through 4.0, highlighting new features introduced in each version such as generics, LINQ, dynamic programming, and covariance/contravariance.
2. It provides code examples to illustrate key concepts like generics, LINQ queries, dynamic binding, and how covariance/contravariance enables safer usage of generics.
3. The last section summarizes some of the main features introduced in each C# version from managed code to generics to dynamic programming.
Workshop slides from the Alt.Net Seattle 2011 workshop. Presented by Wes Dyer and Ryan Riley. Get the slides and the workshop code at http://rxworkshop.codeplex.com/
The document provides templates and examples for creating Swing-based GUI applications, servlets, Java Server Pages (JSP), Java Database Connectivity (JDBC), Java Server Faces (JSF), Enterprise Java Beans (EJB), Hibernate, Struts, and web services in Java. It includes templates for common GUI components, servlets, JSP tags, database queries, managed beans, navigation rules, entity beans, Hibernate mappings, actions, and web service providers/consumers.
REX about JavaFX8 used in SlideshowFX. This presentation covers concept from JavaFX as well as technologies like OSGi, Vert.x, LeapMotion, nashorn and friends in order to make them communicate inside one application developed in JavaFX.
This presentation was made at the ElsassJUG
Here are some suggestions to improve the test method name:
- shouldReturnNullWhenQueryReturnsNull
- shouldPassNullFromDaoWhenQueryReturnsNull
Using "should" makes the intent clearer - we expect the method to return null under certain conditions. Describing those conditions ("when query returns null") in the name provides more context than a generic "testQuery".
Overall, test method names should clearly communicate what is being tested and under what conditions we expect the test to pass or fail. This helps readers understand the purpose and focus of each test.
Paco de la Cruz gave a presentation on Durable Functions 2.0 and stateful serverless functions. The presentation covered an overview of serverless computing on Azure, a recap of Azure Functions and an introduction to Durable Functions. It discussed new features in Durable Functions 2.0 including Durable Entities, additional function types and patterns. The presentation also provided demonstrations of common Durable Functions patterns and a stateful serverless request bin application. It concluded with a Q&A section.
This document provides an overview of key Android development concepts and techniques. It discusses fragments, the support library, dependency injection, image caching, threading and AsyncTask, notifications, supporting multiple screens, and optimizing ListView performance. The document also recommends several popular Android libraries and open source apps that demonstrate best practices.
Poche chiacchiere e tanto codice per cercare rendere la nostra vita di
sviluppatori più divertente.
Parleremo di JAX-RS, le annotazioni, l'MVC che mette a disposizione e
l'integrazione di Jersey con Guice.
Useremo AOP per gestire log, transazioni e con l'aiuto di Infinispan
limiteremo le chamate concorrenti sul nostro cluster.
This document provides instructions for setting up and running a bot project using the Bot Builder SDK v4. It discusses downloading necessary software, creating a project in Visual Studio, implementing a welcome message, and managing state using user profiles and state accessors. The document contains code samples for creating a SampleBot class that inherits from IBot and uses state accessors and user profiles to save and retrieve a user's handle name.
Learn how to write scripted load tests in PHP to run against your system without breaking the bank. Jason will cover not only the importance of load testing, but share stories of how load tests uncovered problems that would otherwise not have been discovered until production. Also, learn how to use load testing to learn how to deal with large traffic sites without needing to be employed by a large scale site first. We’ll be using RedLine13, an almost free load testing tool that is at the same time inexpensive, easy, and effective.
Binary patching for fun and profit @ JUG.ru, 25.02.2012Anton Arhipov
This document discusses binary patching techniques using bytecode manipulation libraries like Javassist. It explains how to use the java.lang.instrument API to add a Java agent that will hook into the class loading process using a ClassFileTransformer. The transformer can then manipulate class bytecodes to add aspects or intercept method calls using libraries like Javassist that provide an easy way to modify bytecode through source-like APIs and on-the-fly compilation of injected code. Examples demonstrate how to add interfaces and methods, implement simple AOP through proxies, and intercept statements. The document also briefly mentions the JRebel SDK for dynamic class reloading in development.
This document provides an overview of the Griffon framework for building desktop applications in Groovy and Java. It discusses key Griffon concepts like conventions over configuration, MVC patterns, built-in testing support, and automation of repetitive tasks. The document also covers Griffon features such as lifecycle scripts, binding, threading, and popular plugins. Resources for learning more about Griffon and its community are provided at the end.
Лаконічні та елегантні автоматизовані тести? Безболісний (майже) тестовий стек для UI веб-додатків? Більше часу, щоб випити кави/пограти у Cuphead/ подивитись у порожнечу?
Ми поговоримо про Lombok, Vavr, Owner, чому вам варто використовувати готові рішення та як зробити тести більш лаконічними та читабельними. Вам знадобиться Vaper та/або гіроборд.
This document discusses optimizing C# code for speed, maintainability, and flexibility. It provides tips for using profilers to optimize for speed, establishing coding standards to improve maintainability, and refactoring code. Exceptions, allocation in loops, string concatenation, and validating enum values are discussed as examples of code that could be optimized. Guidelines are provided around using exceptions, GC.Collect, and designing enums.
Net/http and the http.handler interfaceJoakim Gustin
1. The document discusses building web servers in Go using the net/http package and the http.Handler interface. It covers the basics of routing, middleware, accessing dependencies, and testing HTTP handlers.
2. Various techniques for routing requests, using middleware, injecting dependencies, and testing HTTP handlers are demonstrated. Key concepts like the http.Handler interface and middleware signatures are explained.
3. Tips and tricks for Go HTTP development are provided, such as using anonymous structs, returning errors from handlers, and setting HTTP status codes on errors.
Written specs are easy to read but hard to write. Even with an understanding of the principles and tips for writing good Gherkin, it can be very hard to keep scenarios clean, informative and readable.
These slides are from a workshop given by John Ferguson Smart and Tom Roden, where they take a practical look at some real-world Gherkin scenarios, investigate what makes them smell and practise how to improve them. Discover some powerful refactoring patterns to help make your own specs a joy to read.
It was the time of Da Vinci and Michelangelo. It was also the time of Machiavelli and the Medici. Artists working on timeless masterpieces crossed paths with mercenary captains, contracted to do a very specific job.
In this keynote talk, John Smart will address important questions with deep implications for any IT team, or any organisation trying to make a difference, or simply to get the most value out of their IT projects.
Who is your real customer? Is there a cost to quality? Are you building an artwork that will last, or simply fulfilling a contract?
An inspiring and entertaining talk that will take attendees on journey from the Italian Renaissance to Silicon Valley and the City of London, and see what lessons can be learned about cultures, attitudes and work ethics today.
Discover how you can multiply your team’s productivity and innovation by engaging the creativity of your whole team from the outset. Drawing from his long experience helping teams deliver better software faster and more effectively, John will discuss the latest practical techniques leveraged from Behaviour Driven Development, Lean Enterprise, DevOps, and Test Automation, combined with research in Psychology and Team Performance, to show you how to get the best out of your teams.
Learn about the new roles of business analysts, developers and testers in the future of software development, where testers can play a vital role in not only detecting defects but preventing them. Discover how you can make test automation happen during, not after, the sprint, and how to engage the creativity of the whole team right from the word "go".
his talk will present the core concepts of Exponential Business Agility, or XBA. XBA is a set of patterns for organising value streams around self-organising, autonomous teams, and is part of the XSCALE approach to scaling agile. XBA combines the Spotify model with practice patterns drawn from the Iroquois Confederacy, the most successful and longest-lived holarchy in history.
Learn how Throughput Accounting optimises the contribution of each business function to top line throughput rather than blindly attempting to minimise operating expense.
And discover how Self-Propagating Transformation avoids pushing change into pre-existing teams, programs or silos, but generates agile capability by grafting the kernel of a new culture onto the trunk of the old.
Be a pod of dolphins, not a dancing elephant. Don’t try to scale agile. De-scale your organisation instead.
As projects get faster and teams get leaner, the need to write high quality automated acceptance criteria quickly and efficiently has never been greater. Engineers in Test simply cannot afford to spend time maintaining brittle tests. And yet, without solid test automation strategies, this is what many teams find themselves doing. In this workshop, you will learn a better way. You will learn how to write clean, clear and maintainable tests using the Screenplay Pattern, an innovative new approach to writing BDD-style automated acceptance tests that are easier to understand, easier to extend and easier to maintain. The workshop will be a practical demonstration of the principles of good automated test design. There will be live coding of real-world BDD automated acceptance tests in abundance, using Java, Serenity BDD and Cucumber. We will go from requirements and BDD-style Acceptance Criteria in Cucumber right through to automated acceptance tests and living documentation.
Writing good acceptance criteria is one of the keys to effective software delivery. But it’s hard. In this workshop, you will learn about Feature Mapping, a new technique and easy that can help teams write higher quality acceptance criteria more easily. Feature Mapping is an excellent way to build a deep shared understanding of a story's requirements and clear a path to a smooth implementation of automated acceptance tests.
International speaker and author of “BDD in Action” John Ferguson Smart shows how you can multiply your team’s productivity and innovation by engaging the creativity of your whole team from the outset. Drawing from his long experience helping teams deliver better software faster and more effectively, John will discuss the latest practical techniques leveraged from Behaviour Driven Development, Lean Enterprise, DevOps, and Test Automation, combined with research in Psychology and Team Performance, to show you how to get the best out of your teams. Learn about the new roles of business analysts, developers and testers in a DevOps world, and how testers can play a vital role in not only detecting defects but preventing them. Discover how you can make test automation happen during, not after, the sprint, and how to engage the creativity of the whole team right from the word "go".
IT teams today are under constant pressure to deliver more value sooner, and Behaviour Driven Development (BDD) is one of the more effective ways to help teams deliver the high quality software that their business needs. When they adopt BDD, many teams look to tools like Cucumber to help them. But BDD isn’t simply about picking up a new tool.
In fact, there is a lot more to BDD than Given/When/Then and tools like Cucumber, and both can be misused. In this talk, we will take a step back and look at the bigger picture, and learn why using Gherkin at the wrong time, or for the wrong purpose, may be holding you back.
IT teams today are under constant pressure to deliver more value sooner, and Behaviour Driven Development (BDD) is one of the more effective ways to help teams deliver the high quality software that their business needs. When they adopt BDD, many teams look to tools like Cucumber to help them. But BDD isn’t simply about picking up a new tool.
In fact, there is a lot more to BDD than Given/When/Then and tools like Cucumber, and both can be misused. In this talk, we will take a step back and look at the bigger picture, and learn why using Gherkin at the wrong time, or for the wrong purpose, may be holding you back.
The changing role of testing and test automation in the increasingly fast-paced world of continuous delivery and automated acceptance testing. Learn how, in a DevOps environment, testing activities start with requirements discovery and definition, playing a vital role in not only detecting defects, but preventing them, and ensuring not only that the features are built right, but the right features are built. And learn how test automation needs to happen during, not after, the sprint, and how you can achieve this.
Despite rumors to the contrary, the role of the tester is not diminished with the arrival of automated DevOps, with its ultra-rapid deployment cycles and its emphasis on automation. On the contrary, testers play a vital role in ensuring that the code that gets deployed ten times a day is worth deploying.
Learn how to write robust and articulate tests using the Screenplay Pattern, an innovative approach to writing BDD-style automated acceptance tests that are easier to understand, easier to extend and easier to maintain.
The essentials of Cucumber-JVM and Spock - a handbook written for the BDD/TDD Masterclass (https://johnfergusonsmart.com/programs-courses/bdd-tdd-clean-coding/)
Every test tells a story, but some tell a better story than others. Every test illustrates a specific path through the system to achieve a specific goal, but some paths are clearer than others. Valuable tests are the ones that both tell a compelling story, and can stand the test of time, providing value not only as acceptance tests but also as living documentation and easily maintainable regression tests.
In this session, John will invite you to come on a journey of discovery to learn how to write clean, clear and maintainable tests using the Journey Pattern, an innovative new approach to writing automated acceptance tests that are easier to understand, easier to extend and easier to maintain. You will also witness a demonstration of these principles in action, with live coding of Serenity BDD automated tests.
Learn how to plan, prioritise and deliver higher value features by thinking of deliverable features not in terms of what they cost, but of what they can deliver.
XScale is a set of practices based on BDD that enables a product team to efficiently define, budget and prioritise a roadmap or backlog.
It’s also a way to answer some questions Agile has traditionally avoided:
- How much will a set of features cost?
- How do we trade off different feature sets?
- How do we know a feature is ready to ship?
In this workshop, we outline several key practices and practice using a few of them. The main practices we cover include:
- Feature Points, a way to reconcile budgets with story points
- Backlog Bingo determines the dollar investment and relative return for a set of products and services
- Royal Cod applies Backlog Bingo to prioritize a Breadth-First Roadmap
- Release Refactoring enables product owners to make rational trade-offs between feature-sets.
Behaviour Driven Development is a powerful collaboration technique that can empower teams to deliver higher value features to the business faster and more effectively. But although Behaviour Driven Development is based on a number of simple principles, it can go dramatically wrong in a myriad of different ways.
In this talk we discuss twelve BDD anti-patterns we frequently encounter in real-world BDD projects, anti-patterns that can dramatically reduce the effectiveness of BDD as a practice, and that can even cause BDD adoption to fail entirely. Looking at everything from insufficient collaboration practices to poor use of test automation tooling, from teams that test too much to teams that forget the most important scenarios, we will look at the many different ways that BDD can go wrong, and how it should be done.
We will use real-world examples to illustrate each of these anti-patterns. You will learn how to spot these issues in your own projects, and more importantly how to avoid them in the first place.
Every test tells a story, but some tell a better story than others. Every test illustrates a specific path through the system to achieve a specific goal, but some paths are clearer than others. Valuable tests are the ones that tell a compelling story.
Come on a journey of discovery to learn how to write such tests, and witness a demonstration of these principles in action, with live coding of Serenity BDD automated tests.
Behaviour-Driven Development (BDD) is a game changer for the whole team! Behaviour Driven Development is a powerful collaboration technique that can empower teams to deliver higher value features to the business faster and more effectively. More than just a testing technique, BDD is both a collaboration and a verification tool, and a vital step on the road to Continuous Delivery.
The document discusses testing approaches for microservices, including unit tests, integration tests, and end-to-end tests. It advocates for an outside-in development approach using behavior-driven development (BDD) with automated tests written at multiple levels to ensure software delivers expected functionality. BDD involves collaboratively defining requirements as structured scenarios to guide development and act as executable tests.
Behaviour Driven Development is a powerful collaboration technique that can empower teams to deliver higher value features to the business faster and more effectively. But although Behaviour Driven Development is based on a number of simple principles, it can go dramatically wrong in a myriad of different ways.
In this talk we discuss twelve BDD anti-patterns we frequently encounter in real-world BDD projects, anti-patterns that can dramatically reduce the effectiveness of BDD as a practice, and that can even cause BDD adoption to fail entirely. Looking at everything from insufficient collaboration practices to poor use of test automation tooling, from teams that test too much to teams that forget the most important scenarios, we will look at the many different ways that BDD can go wrong, and how it should be done.
We will use real-world examples to illustrate each of these anti-patterns. You will learn how to spot these issues in your own projects, and more importantly how to avoid them in the first place.
Behaviour Driven Development is an increasingly popular Agile practice that turns testing on its head, and involves a major shift in the role testers play in a project. Although popularly associated with automated acceptance testing and tools like Cucumber, BDD actually has much broader applications. In this talk, we will look at how Behaviour Driven Development radically changes the traditional tester role in Agile projects, and empowers them to tangibly contribute much more to the successful outcomes of the project. We will see how collaboratively discussing and defining acceptance criteria help reduce assumptions and errors in the early phases of the project, and help ensure that the features being built are well understood, testable, and valuable to the business. We will look at ways to write more effective, easier to maintain automated acceptance criteria, that free testers to do more productive testing tasks such as exploratory testing. And we will see how automated and manual acceptance test reporting can be combined to provide valuable progress, product documentation and release preparation reporting.
An invited talk given by Mark Billinghurst on Research Directions for Cross Reality Interfaces. This was given on July 2nd 2024 as part of the 2024 Summer School on Cross Reality in Hagenberg, Austria (July 1st - 7th)
The DealBook is our annual overview of the Ukrainian tech investment industry. This edition comprehensively covers the full year 2023 and the first deals of 2024.
Are you interested in learning about creating an attractive website? Here it is! Take part in the challenge that will broaden your knowledge about creating cool websites! Don't miss this opportunity, only in "Redesign Challenge"!
GDG Cloud Southlake #34: Neatsun Ziv: Automating AppsecJames Anderson
The lecture titled "Automating AppSec" delves into the critical challenges associated with manual application security (AppSec) processes and outlines strategic approaches for incorporating automation to enhance efficiency, accuracy, and scalability. The lecture is structured to highlight the inherent difficulties in traditional AppSec practices, emphasizing the labor-intensive triage of issues, the complexity of identifying responsible owners for security flaws, and the challenges of implementing security checks within CI/CD pipelines. Furthermore, it provides actionable insights on automating these processes to not only mitigate these pains but also to enable a more proactive and scalable security posture within development cycles.
The Pains of Manual AppSec:
This section will explore the time-consuming and error-prone nature of manually triaging security issues, including the difficulty of prioritizing vulnerabilities based on their actual risk to the organization. It will also discuss the challenges in determining ownership for remediation tasks, a process often complicated by cross-functional teams and microservices architectures. Additionally, the inefficiencies of manual checks within CI/CD gates will be examined, highlighting how they can delay deployments and introduce security risks.
Automating CI/CD Gates:
Here, the focus shifts to the automation of security within the CI/CD pipelines. The lecture will cover methods to seamlessly integrate security tools that automatically scan for vulnerabilities as part of the build process, thereby ensuring that security is a core component of the development lifecycle. Strategies for configuring automated gates that can block or flag builds based on the severity of detected issues will be discussed, ensuring that only secure code progresses through the pipeline.
Triaging Issues with Automation:
This segment addresses how automation can be leveraged to intelligently triage and prioritize security issues. It will cover technologies and methodologies for automatically assessing the context and potential impact of vulnerabilities, facilitating quicker and more accurate decision-making. The use of automated alerting and reporting mechanisms to ensure the right stakeholders are informed in a timely manner will also be discussed.
Identifying Ownership Automatically:
Automating the process of identifying who owns the responsibility for fixing specific security issues is critical for efficient remediation. This part of the lecture will explore tools and practices for mapping vulnerabilities to code owners, leveraging version control and project management tools.
Three Tips to Scale the Shift Left Program:
Finally, the lecture will offer three practical tips for organizations looking to scale their Shift Left security programs. These will include recommendations on fostering a security culture within development teams, employing DevSecOps principles to integrate security throughout the development
For the full video of this presentation, please visit: https://www.edge-ai-vision.com/2024/07/intels-approach-to-operationalizing-ai-in-the-manufacturing-sector-a-presentation-from-intel/
Tara Thimmanaik, AI Systems and Solutions Architect at Intel, presents the “Intel’s Approach to Operationalizing AI in the Manufacturing Sector,” tutorial at the May 2024 Embedded Vision Summit.
AI at the edge is powering a revolution in industrial IoT, from real-time processing and analytics that drive greater efficiency and learning to predictive maintenance. Intel is focused on developing tools and assets to help domain experts operationalize AI-based solutions in their fields of expertise.
In this talk, Thimmanaik explains how Intel’s software platforms simplify labor-intensive data upload, labeling, training, model optimization and retraining tasks. She shows how domain experts can quickly build vision models for a wide range of processes—detecting defective parts on a production line, reducing downtime on the factory floor, automating inventory management and other digitization and automation projects. And she introduces Intel-provided edge computing assets that empower faster localized insights and decisions, improving labor productivity through easy-to-use AI tools that democratize AI.
Implementations of Fused Deposition Modeling in real worldEmerging Tech
The presentation showcases the diverse real-world applications of Fused Deposition Modeling (FDM) across multiple industries:
1. **Manufacturing**: FDM is utilized in manufacturing for rapid prototyping, creating custom tools and fixtures, and producing functional end-use parts. Companies leverage its cost-effectiveness and flexibility to streamline production processes.
2. **Medical**: In the medical field, FDM is used to create patient-specific anatomical models, surgical guides, and prosthetics. Its ability to produce precise and biocompatible parts supports advancements in personalized healthcare solutions.
3. **Education**: FDM plays a crucial role in education by enabling students to learn about design and engineering through hands-on 3D printing projects. It promotes innovation and practical skill development in STEM disciplines.
4. **Science**: Researchers use FDM to prototype equipment for scientific experiments, build custom laboratory tools, and create models for visualization and testing purposes. It facilitates rapid iteration and customization in scientific endeavors.
5. **Automotive**: Automotive manufacturers employ FDM for prototyping vehicle components, tooling for assembly lines, and customized parts. It speeds up the design validation process and enhances efficiency in automotive engineering.
6. **Consumer Electronics**: FDM is utilized in consumer electronics for designing and prototyping product enclosures, casings, and internal components. It enables rapid iteration and customization to meet evolving consumer demands.
7. **Robotics**: Robotics engineers leverage FDM to prototype robot parts, create lightweight and durable components, and customize robot designs for specific applications. It supports innovation and optimization in robotic systems.
8. **Aerospace**: In aerospace, FDM is used to manufacture lightweight parts, complex geometries, and prototypes of aircraft components. It contributes to cost reduction, faster production cycles, and weight savings in aerospace engineering.
9. **Architecture**: Architects utilize FDM for creating detailed architectural models, prototypes of building components, and intricate designs. It aids in visualizing concepts, testing structural integrity, and communicating design ideas effectively.
Each industry example demonstrates how FDM enhances innovation, accelerates product development, and addresses specific challenges through advanced manufacturing capabilities.
Sustainability requires ingenuity and stewardship. Did you know Pigging Solutions pigging systems help you achieve your sustainable manufacturing goals AND provide rapid return on investment.
How? Our systems recover over 99% of product in transfer piping. Recovering trapped product from transfer lines that would otherwise become flush-waste, means you can increase batch yields and eliminate flush waste. From raw materials to finished product, if you can pump it, we can pig it.
Quality Patents: Patents That Stand the Test of TimeAurora Consulting
Is your patent a vanity piece of paper for your office wall? Or is it a reliable, defendable, assertable, property right? The difference is often quality.
Is your patent simply a transactional cost and a large pile of legal bills for your startup? Or is it a leverageable asset worthy of attracting precious investment dollars, worth its cost in multiples of valuation? The difference is often quality.
Is your patent application only good enough to get through the examination process? Or has it been crafted to stand the tests of time and varied audiences if you later need to assert that document against an infringer, find yourself litigating with it in an Article 3 Court at the hands of a judge and jury, God forbid, end up having to defend its validity at the PTAB, or even needing to use it to block pirated imports at the International Trade Commission? The difference is often quality.
Quality will be our focus for a good chunk of the remainder of this season. What goes into a quality patent, and where possible, how do you get it without breaking the bank?
** Episode Overview **
In this first episode of our quality series, Kristen Hansen and the panel discuss:
⦿ What do we mean when we say patent quality?
⦿ Why is patent quality important?
⦿ How to balance quality and budget
⦿ The importance of searching, continuations, and draftsperson domain expertise
⦿ Very practical tips, tricks, examples, and Kristen’s Musts for drafting quality applications
https://www.aurorapatents.com/patently-strategic-podcast.html
Video traffic on the Internet is constantly growing; networked multimedia applications consume a predominant share of the available Internet bandwidth. A major technical breakthrough and enabler in multimedia systems research and of industrial networked multimedia services certainly was the HTTP Adaptive Streaming (HAS) technique. This resulted in the standardization of MPEG Dynamic Adaptive Streaming over HTTP (MPEG-DASH) which, together with HTTP Live Streaming (HLS), is widely used for multimedia delivery in today’s networks. Existing challenges in multimedia systems research deal with the trade-off between (i) the ever-increasing content complexity, (ii) various requirements with respect to time (most importantly, latency), and (iii) quality of experience (QoE). Optimizing towards one aspect usually negatively impacts at least one of the other two aspects if not both. This situation sets the stage for our research work in the ATHENA Christian Doppler (CD) Laboratory (Adaptive Streaming over HTTP and Emerging Networked Multimedia Services; https://athena.itec.aau.at/), jointly funded by public sources and industry. In this talk, we will present selected novel approaches and research results of the first year of the ATHENA CD Lab’s operation. We will highlight HAS-related research on (i) multimedia content provisioning (machine learning for video encoding); (ii) multimedia content delivery (support of edge processing and virtualized network functions for video networking); (iii) multimedia content consumption and end-to-end aspects (player-triggered segment retransmissions to improve video playout quality); and (iv) novel QoE investigations (adaptive point cloud streaming). We will also put the work into the context of international multimedia systems research.
Are you interested in dipping your toes in the cloud native observability waters, but as an engineer you are not sure where to get started with tracing problems through your microservices and application landscapes on Kubernetes? Then this is the session for you, where we take you on your first steps in an active open-source project that offers a buffet of languages, challenges, and opportunities for getting started with telemetry data.
The project is called openTelemetry, but before diving into the specifics, we’ll start with de-mystifying key concepts and terms such as observability, telemetry, instrumentation, cardinality, percentile to lay a foundation. After understanding the nuts and bolts of observability and distributed traces, we’ll explore the openTelemetry community; its Special Interest Groups (SIGs), repositories, and how to become not only an end-user, but possibly a contributor.We will wrap up with an overview of the components in this project, such as the Collector, the OpenTelemetry protocol (OTLP), its APIs, and its SDKs.
Attendees will leave with an understanding of key observability concepts, become grounded in distributed tracing terminology, be aware of the components of openTelemetry, and know how to take their first steps to an open-source contribution!
Key Takeaways: Open source, vendor neutral instrumentation is an exciting new reality as the industry standardizes on openTelemetry for observability. OpenTelemetry is on a mission to enable effective observability by making high-quality, portable telemetry ubiquitous. The world of observability and monitoring today has a steep learning curve and in order to achieve ubiquity, the project would benefit from growing our contributor community.
How to Avoid Learning the Linux-Kernel Memory ModelScyllaDB
The Linux-kernel memory model (LKMM) is a powerful tool for developing highly concurrent Linux-kernel code, but it also has a steep learning curve. Wouldn't it be great to get most of LKMM's benefits without the learning curve?
This talk will describe how to do exactly that by using the standard Linux-kernel APIs (locking, reference counting, RCU) along with a simple rules of thumb, thus gaining most of LKMM's power with less learning. And the full LKMM is always there when you need it!
Kief Morris rethinks the infrastructure code delivery lifecycle, advocating for a shift towards composable infrastructure systems. We should shift to designing around deployable components rather than code modules, use more useful levels of abstraction, and drive design and deployment from applications rather than bottom-up, monolithic architecture and delivery.
9. Choose
your
names
well
"What's in a name? That which we call a rose
By any other name would smell as sweet."
Romeo and Juliet (II, ii, 1-2)
Really?
10. Use
a
common
vocabulary
getCustomerInfo()
getClientDetails()
getCustomerRecord()
...
Which one do I use? Are they the same?
getCustomer()
Choose one and stick to it
11. Use
meaningful
names
int days;
What does this represent?
int daysSinceCreation;
int daysSinceLastModification;
int durationInDays;
These are all more meaningful choices
12. Don’t
talk
in
code
class DtaRcrd102 {
private Date genymdhms;
private Date modymdhms;
private final String pszqint = “102”;
...
} Huh?
class Customer {
private Date generationTimestamp;
private Date modificationTimestamp;
private final String recordId = “102”
...
}
13. But
don’t
state
the
obvious
List<Client> clientList;
Is ‘List’ significant or just noise?
List<Client> clients;
List<Client> regularClients;
List<Client> newClients;
14. In
short:
Don’t
make
me
think!
What does this do?
Clearer parameter name
More explicit method name
What are we counting?
Method call rather than
boolean expression
16. High-Level
Methods
should
be
small Refactoring
public void generateAggregateReportFor(final List<StoryTestResults> storyResults,
final List<FeatureResults> featureResults) throws IOException {
LOGGER.info("Generating summary report for user stories to "+ getOutputDirectory());
copyResourcesToOutputDirectory();
Map<String, Object> storyContext = new HashMap<String, Object>();
storyContext.put("stories", storyResults);
storyContext.put("storyContext", "All stories");
addFormattersToContext(storyContext);
writeReportToOutputDirectory("stories.html",
mergeTemplate(STORIES_TEMPLATE_PATH).usingContext(storyContext));
Map<String, Object> featureContext = new HashMap<String, Object>();
addFormattersToContext(featureContext);
featureContext.put("features", featureResults);
writeReportToOutputDirectory("features.html",
mergeTemplate(FEATURES_TEMPLATE_PATH).usingContext(featureContext));
for(FeatureResults feature : featureResults) {
generateStoryReportForFeature(feature);
}
generateReportHomePage(storyResults, featureResults);
Code hard to understand
getTestHistory().updateData(featureResults);
generateHistoryReport();
}
17. High-Level
Methods
should
be
small Refactoring
public void generateAggregateReportFor(final List<StoryTestResults> storyResults,
final List<FeatureResults> featureResults) throws IOException {
LOGGER.info("Generating summary report for user stories to "+ getOutputDirectory());
copyResourcesToOutputDirectory();
private void Object> storyContext = new HashMap<String, Object>(); storyResults) throws IOException {
Map<String, generateStoriesReport(final List<StoryTestResults>
storyContext.put("stories", storyResults);
Map<String, Object> context = new HashMap<String, Object>();
storyContext.put("storyContext", "All stories");
context.put("stories", storyResults);
addFormattersToContext(storyContext); stories");
context.put("storyContext", "All
writeReportToOutputDirectory("stories.html",
addFormattersToContext(context);
mergeTemplate(STORIES_TEMPLATE_PATH).usingContext(storyContext));
String htmlContents = mergeTemplate(STORIES_TEMPLATE_PATH).usingContext(context);
writeReportToOutputDirectory("stories.html", htmlContents);
Map<String, Object> featureContext = new HashMap<String, Object>();
}
addFormattersToContext(featureContext);
featureContext.put("features", featureResults); Refactor into clear steps
writeReportToOutputDirectory("features.html",
mergeTemplate(FEATURES_TEMPLATE_PATH).usingContext(featureContext));
for(FeatureResults feature : featureResults) {
generateStoryReportForFeature(feature);
}
generateReportHomePage(storyResults, featureResults);
getTestHistory().updateData(featureResults);
generateHistoryReport();
}
18. High-Level
Methods
should
be
small Refactoring
public void generateAggregateReportFor(final List<StoryTestResults> storyResults,
final List<FeatureResults> featureResults) throws IOException {
LOGGER.info("Generating summary report for user stories to "+ getOutputDirectory());
copyResourcesToOutputDirectory();
generateStoriesReportFor(storyResults);
Map<String, Object> featureContext = new HashMap<String, Object>();
addFormattersToContext(featureContext);
featureContext.put("features", featureResults);
writeReportToOutputDirectory("features.html",
mergeTemplate(FEATURES_TEMPLATE_PATH).usingContext(featureContext));
for(FeatureResults feature : featureResults) {
generateStoryReportForFeature(feature);
}
generateReportHomePage(storyResults, featureResults);
getTestHistory().updateData(featureResults);
private void updateHistoryFor(final List<FeatureResults> featureResults) {
generateHistoryReport();
} getTestHistory().updateData(featureResults);
}
19. High-Level
Methods
should
be
small Refactoring
private void generateAggregateReportFor(final List<StoryTestResults> storyResults,
final List<FeatureResults> featureResults)
throws IOException {
copyResourcesToOutputDirectory();
generateStoriesReportFor(storyResults);
generateFeatureReportFor(featureResults);
generateReportHomePage(storyResults, featureResults);
updateHistoryFor(featureResults);
generateHistoryReport();
}
20. High-Level Refactoring
Methods
should
only
do
one
thing
Too much going on here...
public String getReportName(String reportType, final String qualifier) {
if (qualifier == null) {
String testName = "";
if (getUserStory() != null) {
testName = NameConverter.underscore(getUserStory().getName());
}
String scenarioName = NameConverter.underscore(getMethodName());
testName = withNoIssueNumbers(withNoArguments(appendToIfNotNull(testName, scenarioName)));
return testName + "." + reportType;
} else {
String userStory = "";
if (getUserStory() != null) {
userStory = NameConverter.underscore(getUserStory().getName()) + "_";
}
String normalizedQualifier = qualifier.replaceAll(" ", "_");
return userStory + withNoArguments(getMethodName()) + "_" + normalizedQualifier + "." + reportType;
}
}
Mixing what and how
21. High-Level Refactoring
Methods
should
only
do
one
thing
Chose what to do here
public String getReportName(final ReportType type, final String qualifier) {
ReportNamer reportNamer = ReportNamer.forReportType(type);
if (shouldAddQualifier(qualifier)) {
return reportNamer.getQualifiedTestNameFor(this, qualifier);
} else {
return reportNamer.getNormalizedTestNameFor(this);
}
}
The how is the responsibility of another class
22. Encapsulate
boolean
expressions
for (TestStep currentStep : testSteps) {
if (!currentStep.isAGroup() && currentStep.getScreenshots() != null) {
for (RecordedScreenshot screenshot : currentStep.getScreenshots()) {
screenshots.add(new Screenshot(screenshot.getScreenshot().getName(),
currentStep.getDescription(),
widthOf(screenshot.getScreenshot()),
currentStep.getException()));
}
}
}
What does this boolean mean?
for (TestStep currentStep : testSteps) {
if (currentStep.needsScreenshots()) {
...
public boolean needsScreenshots() {
return (!isAGroup() && getScreenshotsAndHtmlSources() != null);
}
Expresses the intent better
23. Avoid
unclear/ambiguous
class
name
for (TestStep currentStep : testSteps) {
if (currentStep.needsScreenshots()) {
for (RecordedScreenshot screenshot : currentStep.getScreenshots()) {
screenshots.add(new Screenshot(screenshot.getScreenshot().getName(),
currentStep.getDescription(),
widthOf(screenshot.getScreenshot()),
currentStep.getException()));
}
}
}
Is this class name really accurate?
public List<Screenshot> getScreenshots() { Too many screenshots!
List<Screenshot> screenshots = new ArrayList<Screenshot>();
List<TestStep> testSteps = getFlattenedTestSteps();
for (TestStep currentStep : testSteps) {
if (weNeedAScreenshotFor(currentStep)) {
for (ScreenshotAndHtmlSource screenshotAndHtml : currentStep.getScreenshotsAndHtmlSources()) {
screenshots.add(new Screenshot(screenshotAndHtml.getScreenshotFile().getName(),
currentStep.getDescription(),
widthOf(screenshotAndHtml.getScreenshot()),
currentStep.getException()));
}
}
}
return ImmutableList.copyOf(screenshots);
Using a more revealing class name
}
And a clearer method name
24. Encapsulate
overly-‐complex
code
public List<Screenshot> getScreenshots() {
List<Screenshot> screenshots = new ArrayList<Screenshot>();
List<TestStep> testSteps = getFlattenedTestSteps();
for (TestStep currentStep : testSteps) {
if (currentStep.needsScreenshots()) {
for (ScreenshotAndHtmlSource screenshotAndHtml : currentStep.getScreenshotsAndHtmlSources()) {
screenshots.add(new Screenshot(screenshotAndHtml.getScreenshot().getName(),
currentStep.getDescription(),
widthOf(screenshotAndHtml.getScreenshot()),
currentStep.getException()));
}
}
}
return ImmutableList.copyOf(screenshots);
What does all this do?
}
public List<Screenshot> getScreenshots() {
List<Screenshot> screenshots = new ArrayList<Screenshot>();
List<TestStep> testSteps = getFlattenedTestSteps();
for (TestStep currentStep : testSteps) {
if (weNeedAScreenshotFor(currentStep)) {
screenshots.addAll(
convert(currentStep.getScreenshotsAndHtmlSources(), toScreenshotsFor(currentStep)));
}
}
}
return ImmutableList.copyOf(screenshots); Clearer intention
25. Encapsulate
overly-‐complex
code
public List<Screenshot> getScreenshots() {
List<Screenshot> screenshots = new ArrayList<Screenshot>();
List<TestStep> testSteps = getFlattenedTestSteps();
for (TestStep currentStep : testSteps) {
if (currentStep.needsScreenshots()) {
screenshots.addAll(
convert(currentStep.getScreenshotsAndHtmlSources(), toScreenshotsFor(currentStep)));
}
}
return ImmutableList.copyOf(screenshots); What we are doing
}
private Converter<ScreenshotAndHtmlSource, Screenshot> toScreenshotsFor(final TestStep currentStep) {
return new Converter<ScreenshotAndHtmlSource, Screenshot>() {
@Override
public Screenshot convert(ScreenshotAndHtmlSource from) {
return new Screenshot(from.getScreenshotFile().getName(),
currentStep.getDescription(),
widthOf(from.getScreenshotFile()),
currentStep.getException());
}
};
}
How we do it
26. Avoid
deep
nes;ng
public List<Screenshot> getScreenshots() {
List<Screenshot> screenshots = new ArrayList<Screenshot>();
List<TestStep> testSteps = getFlattenedTestSteps();
for (TestStep currentStep : testSteps) {
if (currentStep.needsScreenshots()) {
Code doing too many things
screenshots.addAll(
convert(currentStep.getScreenshotsAndHtmlSources(), toScreenshotsFor(currentStep)));
}
}
return ImmutableList.copyOf(screenshots);
} Break the code down into
public List<Screenshot> getScreenshots() { logical steps
List<Screenshot> screenshots = new ArrayList<Screenshot>();
List<TestStep> testStepsWithScreenshots = select(getFlattenedTestSteps(),
having(on(TestStep.class).needsScreenshots()));
for (TestStep currentStep : testStepsWithScreenshots) {
screenshots.addAll(convert(currentStep.getScreenshotsAndHtmlSources(),
toScreenshotsFor(currentStep)));
}
return ImmutableList.copyOf(screenshots);
} Remove the nested condition
27. Keep
each
step
simple!
public List<Screenshot> getScreenshots() {
List<Screenshot> screenshots = new ArrayList<Screenshot>();
List<TestStep> testStepsWithScreenshots = select(getFlattenedTestSteps(),
having(on(TestStep.class).needsScreenshots()));
for (TestStep currentStep : testStepsWithScreenshots) {
screenshots.addAll(convert(currentStep.getScreenshotsAndHtmlSources(),
toScreenshotsFor(currentStep)));
}
return ImmutableList.copyOf(screenshots); Too much happening here?
}
public List<Screenshot> getScreenshots() {
List<Screenshot> screenshots = new ArrayList<Screenshot>();
List<TestStep> testStepsWithScreenshots = select(getFlattenedTestSteps(),
having(on(TestStep.class).needsScreenshots()));
for (TestStep currentStep : testStepsWithScreenshots) {
screenshots.addAll(screenshotsIn(currentStep));
}
return ImmutableList.copyOf(screenshots); This reads more smoothly
}
private List<Screenshot> screenshotsIn(TestStep currentStep) {
return convert(currentStep.getScreenshotsAndHtmlSources(), toScreenshotsFor(currentStep));
}
29. Use
Fluent
APIs
Complex domain object
Lots of variants
Object tree
FundsTransferOrder order = new FundsTransferOrder();
order.setType("SWIFT");
Party originatorParty = organizationServer.findPartyByCode("WPAC");
order.setOriginatorParty(originatorParty);
Party counterParty = organizationServer.findPartyByCode("CBAA");
order.setCounterParty(counterParty);
order.setDate(DateTime.parse("22/11/2011"));
Currency currency = currencyTable.findCurrency("USD");
Amount amount = new Amount(500, currency);
order.setAmount(amount);
Complex code
...
Need to know how to create the child objects
30. Use
Fluent
APIs
More readable
No object creation
Easier to maintain
FundsTransferOrder.createNewSWIFTOrder()
.fromOriginatorParty("WPAC")
.toCounterParty("CBAA")
.forDebitor("WPAC")
.and().forCreditor("CBAA")
.settledOnThe("22/11/2011")
.forAnAmountOf(500, US_DOLLARS)
.asXML();
34. Replace
Constructors
with
Crea7on
Methods
Too many constructors
Business knowledge
hidden in the constructors
Which one should I use?
35. Replace
Constructors
with
Crea7on
Methods
Private constructor
Static creator methods
One implementing class
36. Replace
Constructors
with
Crea7on
Methods
Communicates
the
intended
use
be5er
Overcomes
technical
limits
with
constructors
Inconsistent
object
crea<on
pa5erns
37. Encapsulate
Classes
with
a
Factory
High-Level Refactoring
Only this interface should
be visible
Many different
implementations
Which implementation
should I use?
38. Encapsulate
Classes
with
a
Factory
High-Level Refactoring
Helpful factory methods
Easier
to
create
the
right
instances
Hides
classes
that
don’t
need
to
be
exposed
Encourages
“programming
to
an
interface”
Need
a
new
method
when
new
classes
are
added
Need
access
to
factory
class
to
customize/extend
39. Plenty
of
other
refactoring
pa2erns...
But
know
why
you
are
applying
them
48. lambdaj
– DSL for manipulating collections in a functional style
– Replace loops with more concise and readable code
Functional constructs in Java
49. LambdaJ support many high level
collection-related functions
filter aggregate
sort
convert
extract index group
50. Find all adult ages filter
List<Integer> adultAges = new ArrayList<Integer>();
for(int age : ages) {
if (age >= 18) {
adults.add(age);
}
}
List<Integer> adultAges = filter(greaterThanOrEqualTo(18), ages);
51. Find all adults filter
List<Person> adults = new ArrayList<Person>();
for(int person : people) {
if (person.getAge() >= 18) {
adults.add(person);
}
}
List<Person> adults = filter(having(on(Person.class).getAge(), greaterThanOrEqualTo(18)),
people);
52. Find all the sales of Ferraris filter
List<Sale> salesOfAFerrari = new ArrayList<Sale>();
for (Sale sale : sales) {
if (sale.getCar().getBrand().equals("Ferrari"))
salesOfAFerrari.add(sale);
}
List<Sale> salesOfAFerrari = select(sales,
having(on(Sale.class).getCar().getBrand(),equalTo("Ferrari")));
53. Sort sales by cost sort
List<Sale> sortedSales = new ArrayList<Sale>(sales);
Collections.sort(sortedSales, new Comparator<Sale>() {
public int compare(Sale s1, Sale s2) {
return Double.valueOf(s1.getCost()).compareTo(s2.getCost());
}
});
List<Sale> sortedSales = sort(sales, on(Sale.class).getCost());
54. Index cars by brand index
Map<String, Car> carsByBrand = new HashMap<String, Car>();
for (Car car : db.getCars()) {
carsByBrand.put(car.getBrand(), car);
}
Map<String, Car> carsByBrand = index(cars, on(Car.class).getBrand());
55. Find the total sales
aggregate
double totalSales = 0.0;
for (Sale sale : sales) {
totalSales = totalSales + sale.getCost();
}
double totalSales = sumFrom(sales).getCost();
56. Find most costly sale
aggregate
double maxCost = 0.0;
for (Sale sale : sales) {
double cost = sale.getCost();
if (cost > maxCost) maxCost = cost;
}
double maxCost = maxFrom(sales).getCost();
57. extract
Extract the costs of the cars as a list
List<Double> costs = new ArrayList<Double>();
for (Car car : cars) costs.add(car.getCost());
List<Double> costs = extract(cars, on(Car.class).getCost());