The document discusses design by contract (DbC), which involves specifying function contracts that define pre-conditions, post-conditions, and error conditions. It provides an example of specifying contracts for a square root function in Racket. It then addresses common questions about DbC, such as what to do if contracts are specified incorrectly, performance impacts, and how DbC relates to testing and static type checking. The document advocates for hybrid approaches that combine contracts with testing and/or static typing.
A fair analysis of the Agile Methodology. A quick comparison of Agile and Waterfall to clear up misconceptions about the two. Scalability is a major issue with Agile and is worth considering if you're not a large software company.
The Figma prototyping hacks will be covering best practices and tips needed to get the best out of prototyping. Some of these can be simple prototyping hacks that when combined with other hacks will create a complex transition or interaction. The hacks can be random and do not have to be sequentially related.
A fair analysis of the Agile Methodology. A quick comparison of Agile and Waterfall to clear up misconceptions about the two. Scalability is a major issue with Agile and is worth considering if you're not a large software company.
The Figma prototyping hacks will be covering best practices and tips needed to get the best out of prototyping. Some of these can be simple prototyping hacks that when combined with other hacks will create a complex transition or interaction. The hacks can be random and do not have to be sequentially related.
In this episode, I showed & discussed one of the most anticipated topics! "Prototypes in Figma". Here I talked in detail about the concepts and applications for both beginners & advanced learners. Enjoy!
Kanban is the simplest approach which is currently used in software development. Since Kanban prescribes close to nothing there are often a lot of basic questions about the method.
The presentation depicts what Kanban is generally using Scrum as a reference point. Then it presents a series of situations to answer basic questions about working with Kanban
Teams often struggle with meeting sprint commitments, properly prioritizing stories, having to manage dependencies across teams, and creating stories that deliver value to the customer. Vertical story slicing is a useful technique to help teams create stories that fulfill the INVEST criteria.
This slide share:
• Discusses the characteristics of a well-formed story
• Introduces nine common patterns for effective story slicing
• Identifies clues for when/how to slice stories
Automation for JIRA - The Simplest Way to Automate Your Team and ProjectBosnia Agile
Automation for JIRA allows project administrators to capture even more on their process directly in JIRA. With simple rule builder, admins can configure powerful automation rules with ease, combining triggers, conditions and actions to handle even the most complex scenarios.
Prototyping: what is it, why should you care, common mistakes, and how to choose the right tools.
Presented at IxDA Sydney Meetup: The Prototype Edition - 28 May 2015
Waterfall vs Agile : A Beginner's Guide in Project ManagementJonathan Donado
A beginner's guide to learn about Waterfall and Agile methodologies and frameworks in project management.
This is done in plain English for the non-tech savvy reader.
Presentation by Jonathan Donado
Connect with me on Twitter @donadosays
Linkedin: https://www.linkedin.com/in/jonathandonado/
PMI / PMP / Agile / Business / Project Management / Project Manager / Waterfall
Presentation I held before my colleagues about the book Clean Code (http://www.amazon.com/Clean-Code-Handbook-Software-Craftsmanship/dp/0132350882).
It contains the highlights of several chapters and hint/guidelines a developer should know.
In this episode, I showed & discussed one of the most anticipated topics! "Prototypes in Figma". Here I talked in detail about the concepts and applications for both beginners & advanced learners. Enjoy!
Kanban is the simplest approach which is currently used in software development. Since Kanban prescribes close to nothing there are often a lot of basic questions about the method.
The presentation depicts what Kanban is generally using Scrum as a reference point. Then it presents a series of situations to answer basic questions about working with Kanban
Teams often struggle with meeting sprint commitments, properly prioritizing stories, having to manage dependencies across teams, and creating stories that deliver value to the customer. Vertical story slicing is a useful technique to help teams create stories that fulfill the INVEST criteria.
This slide share:
• Discusses the characteristics of a well-formed story
• Introduces nine common patterns for effective story slicing
• Identifies clues for when/how to slice stories
Automation for JIRA - The Simplest Way to Automate Your Team and ProjectBosnia Agile
Automation for JIRA allows project administrators to capture even more on their process directly in JIRA. With simple rule builder, admins can configure powerful automation rules with ease, combining triggers, conditions and actions to handle even the most complex scenarios.
Prototyping: what is it, why should you care, common mistakes, and how to choose the right tools.
Presented at IxDA Sydney Meetup: The Prototype Edition - 28 May 2015
Waterfall vs Agile : A Beginner's Guide in Project ManagementJonathan Donado
A beginner's guide to learn about Waterfall and Agile methodologies and frameworks in project management.
This is done in plain English for the non-tech savvy reader.
Presentation by Jonathan Donado
Connect with me on Twitter @donadosays
Linkedin: https://www.linkedin.com/in/jonathandonado/
PMI / PMP / Agile / Business / Project Management / Project Manager / Waterfall
Presentation I held before my colleagues about the book Clean Code (http://www.amazon.com/Clean-Code-Handbook-Software-Craftsmanship/dp/0132350882).
It contains the highlights of several chapters and hint/guidelines a developer should know.
When to Code / Config / Config + Code in Salesforce - Nikunj DoshiSakthivel Madesh
When to Code / Config / Config + Code in Salesforce - Nikunj Doshi
In this session discussed about,
- Key Criteria in deciding right solution.
- Pragmatic takeaways from Salesforce's decision guide https://link.medium.com/SNjI4Rs6Udb
- Sample solutions displaying power of Configurable Code!
- - Any Object to Big Objects archiving utility
- - Metadata Driven declarative rollup
- Q&A & Share our horror/memorable stories on this topic
The working architecture of node js applications open tech week javascript ...Viktor Turskyi
We launched more than 60 projects, developed a web application architecture that is suitable for projects of completely different sizes. In the talk, I'll analyze this architecture, will consider the question what to choose “monolith or microservices”, will show the main architectural mistakes that developers make.
One of the main hindrances to teams being able to respond rapidly to new features are technical problems resulting from bad coding practices, also known as technical debt. Melissa and Brett will cover Agile tools and practices that help development teams write better code and increase maintainability. Topics that will be covered include:
Pair programming
Automated Unit Testing
Refactoring
Test-Driven Development
Agile Architecture
Taming the Legacy Beast: Turning wild old code into a sleak new thoroughbread.Chris Laning
Got a legacy application? Trying to turn into a modern one? This presentation, given by Chris Laning, takes you through a methodical process that helps you attack that seemingly insurmountable task and tame it like a pro! The presentation is ColdFusion focused, but many of the methods employed could be used by programmers in other languages. This presentation was given at NCDevCon on September 13, 2014 in Raleigh, NC.
Chris is a Senior WebDeveloper and has been doing web development since 1996.
Viktor Turskyi "Effective NodeJS Application Development"Fwdays
For 15 years in development, I managed to take part in the creation of a large number of various projects. I have already made a number of talks on the working architecture of Web applications, but this is only part of the efficient development puzzle. We will consider the whole process from the start of the project to its launch in production. I’ll tell you how we approach the ideas of the “12 Factor App”, how we use the docker, discuss environment deployment issues, security issues, testing issues, discuss the nuances of SDLC and much more.
CHAPTER 1 Creating a ProgramOBJECTIVES· Analyze some of the i.docxwalterl4
CHAPTER 1: Creating a Program
OBJECTIVES
· Analyze some of the issues involved in producing a simple program:
· Requirements (functional, nonfunctional)
· Design constraints and design decisions
· Testing
· Effort estimation
· Implementation details
· Understand the activities involved in writing even a simple program.
· Preview many additional software engineering topics found in the later chapters.
1.1 A Simple Problem
In this chapter we will analyze the tasks involved in writing a relatively simple program. This will serve as a contrast to what is involved in developing a large system, which is described in Chapter 2.
Assume that you have been given the following simple problem: “Given a collection of lines of text (strings) stored in a file, sort them in alphabetical order, and write them to another file.” This is probably one of the simplest problems you will be involved with. You have probably done similar assignments for some of your introduction to programming classes.
1.1.1 Decisions, Decisions
A problem statement such as the one mentioned in the above simple problem does not completely specify the problem. You need to clarify the requirements in order to produce a program that better satisfies the real problem. You need to understand all the program requirements and the design constraints imposed by the client on the design, and you need to make important technical decisions. A complete problem statement would include the requirements, which state and qualify what the program does, and the design constraints, which depict the ways in which you can design and implement it.
Program requirements Statements that define and qualify what the program needs to do.
Design constraints Statements that constrain the ways in which the software can be designed and implemented.
The most important thing to realize is that the word requirements is not used as it is in colloquial English. In many business transactions, a requirement is something that absolutely must happen. However, in software engineering many items are negotiable. Given that every requirement will have a cost, the clients may decide that they do not really need it after they understand the related cost. Requirements are often grouped into those that are “needed” and those that are “nice to have.”
It is also useful to distinguish between functional requirements—what the program does—and nonfunctional requirements—the manner in which the program must behave. In a way, a function is similar to that of a direct and indirect object in grammar. Thus the functional requirements for our problem will describe what it does: sort a file (with all the detail required); the nonfunctional requirements will describe items such as performance, usability, and maintainability. Functional requirements tend to have a Boolean measurement where the requirement is either satisfied or not satisfied, but nonfunctional requirements tend to apply to things measured on a linear scale where the measurements ca.
Removing Uninteresting Bytes in Software FuzzingAftab Hussain
Imagine a world where software fuzzing, the process of mutating bytes in test seeds to uncover hidden and erroneous program behaviors, becomes faster and more effective. A lot depends on the initial seeds, which can significantly dictate the trajectory of a fuzzing campaign, particularly in terms of how long it takes to uncover interesting behaviour in your code. We introduce DIAR, a technique designed to speedup fuzzing campaigns by pinpointing and eliminating those uninteresting bytes in the seeds. Picture this: instead of wasting valuable resources on meaningless mutations in large, bloated seeds, DIAR removes the unnecessary bytes, streamlining the entire process.
In this work, we equipped AFL, a popular fuzzer, with DIAR and examined two critical Linux libraries -- Libxml's xmllint, a tool for parsing xml documents, and Binutil's readelf, an essential debugging and security analysis command-line tool used to display detailed information about ELF (Executable and Linkable Format). Our preliminary results show that AFL+DIAR does not only discover new paths more quickly but also achieves higher coverage overall. This work thus showcases how starting with lean and optimized seeds can lead to faster, more comprehensive fuzzing campaigns -- and DIAR helps you find such seeds.
- These are slides of the talk given at IEEE International Conference on Software Testing Verification and Validation Workshop, ICSTW 2022.
Essentials of Automations: The Art of Triggers and Actions in FMESafe Software
In this second installment of our Essentials of Automations webinar series, we’ll explore the landscape of triggers and actions, guiding you through the nuances of authoring and adapting workspaces for seamless automations. Gain an understanding of the full spectrum of triggers and actions available in FME, empowering you to enhance your workspaces for efficient automation.
We’ll kick things off by showcasing the most commonly used event-based triggers, introducing you to various automation workflows like manual triggers, schedules, directory watchers, and more. Plus, see how these elements play out in real scenarios.
Whether you’re tweaking your current setup or building from the ground up, this session will arm you with the tools and insights needed to transform your FME usage into a powerhouse of productivity. Join us to discover effective strategies that simplify complex processes, enhancing your productivity and transforming your data management practices with FME. Let’s turn complexity into clarity and make your workspaces work wonders!
Goodbye Windows 11: Make Way for Nitrux Linux 3.5.0!SOFTTECHHUB
As the digital landscape continually evolves, operating systems play a critical role in shaping user experiences and productivity. The launch of Nitrux Linux 3.5.0 marks a significant milestone, offering a robust alternative to traditional systems such as Windows 11. This article delves into the essence of Nitrux Linux 3.5.0, exploring its unique features, advantages, and how it stands as a compelling choice for both casual users and tech enthusiasts.
Threats to mobile devices are more prevalent and increasing in scope and complexity. Users of mobile devices desire to take full advantage of the features
available on those devices, but many of the features provide convenience and capability but sacrifice security. This best practices guide outlines steps the users can take to better protect personal devices and information.
UiPath Test Automation using UiPath Test Suite series, part 5DianaGray10
Welcome to UiPath Test Automation using UiPath Test Suite series part 5. In this session, we will cover CI/CD with devops.
Topics covered:
CI/CD with in UiPath
End-to-end overview of CI/CD pipeline with Azure devops
Speaker:
Lyndsey Byblow, Test Suite Sales Engineer @ UiPath, Inc.
Observability Concepts EVERY Developer Should Know -- DeveloperWeek Europe.pdfPaige Cruz
Monitoring and observability aren’t traditionally found in software curriculums and many of us cobble this knowledge together from whatever vendor or ecosystem we were first introduced to and whatever is a part of your current company’s observability stack.
While the dev and ops silo continues to crumble….many organizations still relegate monitoring & observability as the purview of ops, infra and SRE teams. This is a mistake - achieving a highly observable system requires collaboration up and down the stack.
I, a former op, would like to extend an invitation to all application developers to join the observability party will share these foundational concepts to build on:
Generative AI Deep Dive: Advancing from Proof of Concept to ProductionAggregage
Join Maher Hanafi, VP of Engineering at Betterworks, in this new session where he'll share a practical framework to transform Gen AI prototypes into impactful products! He'll delve into the complexities of data collection and management, model selection and optimization, and ensuring security, scalability, and responsible use.
GraphSummit Singapore | The Future of Agility: Supercharging Digital Transfor...Neo4j
Leonard Jayamohan, Partner & Generative AI Lead, Deloitte
This keynote will reveal how Deloitte leverages Neo4j’s graph power for groundbreaking digital twin solutions, achieving a staggering 100x performance boost. Discover the essential role knowledge graphs play in successful generative AI implementations. Plus, get an exclusive look at an innovative Neo4j + Generative AI solution Deloitte is developing in-house.
LF Energy Webinar: Electrical Grid Modelling and Simulation Through PowSyBl -...DanBrown980551
Do you want to learn how to model and simulate an electrical network from scratch in under an hour?
Then welcome to this PowSyBl workshop, hosted by Rte, the French Transmission System Operator (TSO)!
During the webinar, you will discover the PowSyBl ecosystem as well as handle and study an electrical network through an interactive Python notebook.
PowSyBl is an open source project hosted by LF Energy, which offers a comprehensive set of features for electrical grid modelling and simulation. Among other advanced features, PowSyBl provides:
- A fully editable and extendable library for grid component modelling;
- Visualization tools to display your network;
- Grid simulation tools, such as power flows, security analyses (with or without remedial actions) and sensitivity analyses;
The framework is mostly written in Java, with a Python binding so that Python developers can access PowSyBl functionalities as well.
What you will learn during the webinar:
- For beginners: discover PowSyBl's functionalities through a quick general presentation and the notebook, without needing any expert coding skills;
- For advanced developers: master the skills to efficiently apply PowSyBl functionalities to your real-world scenarios.
Full-RAG: A modern architecture for hyper-personalizationZilliz
Mike Del Balso, CEO & Co-Founder at Tecton, presents "Full RAG," a novel approach to AI recommendation systems, aiming to push beyond the limitations of traditional models through a deep integration of contextual insights and real-time data, leveraging the Retrieval-Augmented Generation architecture. This talk will outline Full RAG's potential to significantly enhance personalization, address engineering challenges such as data management and model training, and introduce data enrichment with reranking as a key solution. Attendees will gain crucial insights into the importance of hyperpersonalization in AI, the capabilities of Full RAG for advanced personalization, and strategies for managing complex data integrations for deploying cutting-edge AI solutions.
GDG Cloud Southlake #33: Boule & Rebala: Effective AppSec in SDLC using Deplo...James Anderson
Effective Application Security in Software Delivery lifecycle using Deployment Firewall and DBOM
The modern software delivery process (or the CI/CD process) includes many tools, distributed teams, open-source code, and cloud platforms. Constant focus on speed to release software to market, along with the traditional slow and manual security checks has caused gaps in continuous security as an important piece in the software supply chain. Today organizations feel more susceptible to external and internal cyber threats due to the vast attack surface in their applications supply chain and the lack of end-to-end governance and risk management.
The software team must secure its software delivery process to avoid vulnerability and security breaches. This needs to be achieved with existing tool chains and without extensive rework of the delivery processes. This talk will present strategies and techniques for providing visibility into the true risk of the existing vulnerabilities, preventing the introduction of security issues in the software, resolving vulnerabilities in production environments quickly, and capturing the deployment bill of materials (DBOM).
Speakers:
Bob Boule
Robert Boule is a technology enthusiast with PASSION for technology and making things work along with a knack for helping others understand how things work. He comes with around 20 years of solution engineering experience in application security, software continuous delivery, and SaaS platforms. He is known for his dynamic presentations in CI/CD and application security integrated in software delivery lifecycle.
Gopinath Rebala
Gopinath Rebala is the CTO of OpsMx, where he has overall responsibility for the machine learning and data processing architectures for Secure Software Delivery. Gopi also has a strong connection with our customers, leading design and architecture for strategic implementations. Gopi is a frequent speaker and well-known leader in continuous delivery and integrating security into software delivery.
Building RAG with self-deployed Milvus vector database and Snowpark Container...Zilliz
This talk will give hands-on advice on building RAG applications with an open-source Milvus database deployed as a docker container. We will also introduce the integration of Milvus with Snowpark Container Services.
How to Get CNIC Information System with Paksim Ga.pptxdanishmna97
Pakdata Cf is a groundbreaking system designed to streamline and facilitate access to CNIC information. This innovative platform leverages advanced technology to provide users with efficient and secure access to their CNIC details.
Why You Should Replace Windows 11 with Nitrux Linux 3.5.0 for enhanced perfor...SOFTTECHHUB
The choice of an operating system plays a pivotal role in shaping our computing experience. For decades, Microsoft's Windows has dominated the market, offering a familiar and widely adopted platform for personal and professional use. However, as technological advancements continue to push the boundaries of innovation, alternative operating systems have emerged, challenging the status quo and offering users a fresh perspective on computing.
One such alternative that has garnered significant attention and acclaim is Nitrux Linux 3.5.0, a sleek, powerful, and user-friendly Linux distribution that promises to redefine the way we interact with our devices. With its focus on performance, security, and customization, Nitrux Linux presents a compelling case for those seeking to break free from the constraints of proprietary software and embrace the freedom and flexibility of open-source computing.
Unlock the Future of Search with MongoDB Atlas_ Vector Search Unleashed.pdfMalak Abu Hammad
Discover how MongoDB Atlas and vector search technology can revolutionize your application's search capabilities. This comprehensive presentation covers:
* What is Vector Search?
* Importance and benefits of vector search
* Practical use cases across various industries
* Step-by-step implementation guide
* Live demos with code snippets
* Enhancing LLM capabilities with vector search
* Best practices and optimization strategies
Perfect for developers, AI enthusiasts, and tech leaders. Learn how to leverage MongoDB Atlas to deliver highly relevant, context-aware search results, transforming your data retrieval process. Stay ahead in tech innovation and maximize the potential of your applications.
#MongoDB #VectorSearch #AI #SemanticSearch #TechInnovation #DataScience #LLM #MachineLearning #SearchTechnology
In the rapidly evolving landscape of technologies, XML continues to play a vital role in structuring, storing, and transporting data across diverse systems. The recent advancements in artificial intelligence (AI) present new methodologies for enhancing XML development workflows, introducing efficiency, automation, and intelligent capabilities. This presentation will outline the scope and perspective of utilizing AI in XML development. The potential benefits and the possible pitfalls will be highlighted, providing a balanced view of the subject.
We will explore the capabilities of AI in understanding XML markup languages and autonomously creating structured XML content. Additionally, we will examine the capacity of AI to enrich plain text with appropriate XML markup. Practical examples and methodological guidelines will be provided to elucidate how AI can be effectively prompted to interpret and generate accurate XML markup.
Further emphasis will be placed on the role of AI in developing XSLT, or schemas such as XSD and Schematron. We will address the techniques and strategies adopted to create prompts for generating code, explaining code, or refactoring the code, and the results achieved.
The discussion will extend to how AI can be used to transform XML content. In particular, the focus will be on the use of AI XPath extension functions in XSLT, Schematron, Schematron Quick Fixes, or for XML content refactoring.
The presentation aims to deliver a comprehensive overview of AI usage in XML development, providing attendees with the necessary knowledge to make informed decisions. Whether you’re at the early stages of adopting AI or considering integrating it in advanced XML development, this presentation will cover all levels of expertise.
By highlighting the potential advantages and challenges of integrating AI with XML development tools and languages, the presentation seeks to inspire thoughtful conversation around the future of XML development. We’ll not only delve into the technical aspects of AI-powered XML development but also discuss practical implications and possible future directions.
Introduction to Contracts and Functional Contracts
1. Daniel Prager @agilejitsu agilejitsu.blogspot.com
Melbourne Functional User Group, September 6, 2013
There are two ways of constructing a software design: One way is to make it
so simple that there are obviously no deficiencies, and the other way is to
make it so complicated that there are no obvious deficiencies.
The first method is far more difficult. It demands the same skill, devotion,
insight, and even inspiration as the discovery of the simple physical laws
which underlie the complex phenomena of nature.
– Tony Hoare, in his 1980 Turing Award lecture
Introduction to Contracts and
Functional Contracts
2. A personal Preamble
● 1998: I discover Design by Contract and start using it
– Time spent debugging: ↓ 90%
– Joy ↑
● I've used variants ever since
– Technical pay-off:
– Hit rate in persuading colleagues to join in: variable
● In this talk I
– Introduce the basics of Design by Contract
– Show how it can work in combination with functional programming
– Share some hard-won advice
– Ideally chat with you about where DbC sits today in relation to automated testing and static
type-checking
3. Overview
● The Problem of Software Quality
● Contracts: The basic idea
● Design By Contract (DbC)
● Questions and Concerns
● Functional Contracts
● Comparison with Tests and with Static Type-checking
● Some Hybrid Approaches
● Conclusion
4. The Problem of Software Quality
● Problem: How to design and program correct,
robust, maintainable, etc., etc. software?
● Assumption: BUGS happen!
● Prevention: Simplicity and clarity of design;
modularity; concision
● Treatment: Rapid isolation and diagnosis of
problems
5. Contracts: a metaphor
● Commercial Contract
– The client pays a supplier
to provide a good or service
– The contract
●
makes explicit the
expectations on both parties
● specifies who is to blame –
client or supplier – if
something goes wrong.
● Programming Contract
– The calling code (the client) calls a function
(the supplier)
– The contract
● defines explicit pre-conditions on
arguments passed by the calling code (and
on the initial state)
● defines explicit post-conditions on the
result of the function (and the final state)
● specifies which code is to blame – calling
code or function – if something goes wrong.
6. The standard example in Eiffel
square_root (x: REAL): REAL is
-- Returns the positive square root of x
require
-- Pre-condition section
positive_argument: x >= 0.0
do
-- Implementation section
...
ensure
-- Post-condition section
correct_root: abs(Result * Result – x) <= 0.000001
positive_root: Result >= 0
end
7. Same example in Racket
with hand-rolled contract
(define (square-root x)
(require (non-negative-real? x) "real, non-negative argument")
(let ([result ...])
(ensure (non-negative-real? result) "real, non-negative result")
(ensure (approx-equal? (* result result) x) "correct root")
result))
(define (require test [message “”])
(unless test (error 'pre-condition-violation message)))
(define (ensure test [message “”])
(unless test (error 'post-condition-violation message)))
(define (non-negative-real? x) (and (real? x) (>= x 0)))
(define (approx-equal? x y [tol 0.000001]) (<= (abs (- x y)) tol))
8. Quiz: Test your understanding
(define (square-root x)
(require (non-negative-real? x) "real, non-negative argument")
(let ([result (/ x 2)])
(ensure (non-negative-real? result) "real, non-negative result")
(ensure (approx-equal? (* result result) x) "correct root")
result))
● Which errors would the following calls induce?
– (square-root “five”)
– (square-root -8.0)
– (square-root 9)
10. Square root with hand-rolled
contract and static types
#lang typed/racket
(define: (square-root [x : Nonnegative-Real]) : Nonnegative-Real
(let ([result ...])
(ensure (approx-equal? (* result result) x) "correct root")
result))
(define: (require [test : Boolean] [message : String]) : Symbol
(if test 'ok (error 'pre-condition-violation message)))
(define: (ensure [test : Boolean] [message : String]) : Symbol
(if test 'ok (error 'post-condition-violation message)))
(define: (approx-equal? [x : Real] [y : Real]) : Boolean
(<= (abs (- x y)) 0.000001))
11. Design by Contract
● Design By Contract (DbC) is the discipline of writing out the contracts before
implementation.
– Steps of Design By Contract:
1)Declare a function and write-down its contract
2)Write an implementation
3)Manually test and fix any breakages
4)Refactor the contract and the code for concision and precision
5)Rinse, repeat.
– The mechanics are similar to Test-Driven Design/Development (TDD):
1)Write a failing test
2)Make it pass
3)Refactor to remove duplication, etc.
4)Rinse, repeat.
●
12. Let's DbC together!
● Scenario: Insert a string into another string
– Signature: (define (string-insert str other-str pos) …)
– Usage:
● (string-insert "stuff" "FOO" 0) → "FOOstuff"
● (string-insert "stuff" "FOO" 3) → "stuFOOff"
● (string-insert "stuff" "FOO" 5) → “stuffFOO”
● Challenge:
– Write down as many pre-conditions as you can
– Write down some post-conditions [usually harder]
13. Design by Contract: a solution
(define (string-insert str other-str pos)
(require (string? str) "str is a string")
(require (string? other-str) "other-str is a string")
(require (integer? pos) "pos is an integer")
(require (<= 0 pos (string-length str)) "0 <= pos <= length(str)")
(let ([result ...]
[other-len (string-length other-str)])
(ensure (string? result))
(ensure (= (string-length result) (+ (string-length str) other-len))
"len(result) = len(str) + len(other-str)")
(ensure (string=? (substring result pos (+ pos other-len)) other-str)
"other-str is spliced into the correct spot")
result))
15. How are we doing so far?
● Questions and Concerns?
16. How are we doing so far?
● Questions and Concerns
– What if I make a mistake in specifying the contract?
– Do contracts slow down execution speed?
– Do I need to fully specify every contract?
– Can I use contracts with language X?
– Do contracts replace documentation?
– What about state?
– What about object-oriented programming?
– What about functional programming?
17. Questions and Concerns
● What if I make a mistake in specifying the contract?
● This happens, occasionally.
● Running the program with contracts in place checks
consistency between contracts and code, not absolute
correctness.
● Usually the contracts are simpler than the code, so most of the
time the problem is in the client or supplier code.
● Advice:
– Try to keep your contracts clear and concise
– If the problem is unclear, review the contract
18. Questions and Concerns
● Do contracts slow down execution speed?
– Yes, but …
● Pre-conditions are usually very cheap to test
● Complex post-conditions (and especially invariants) can be expensive
● Advice:
– Make the level of checking configurable.
– Turn everything on in testing; turn painfully slow checks off selectively
– Leave pre-condition checking on in production, augmented by recovery strategies
● Do I need to fully specify every contract?
– No, but …
● High contract coverage helps with design, defect-detection, and overall effectiveness
● Advice:
– Specify pre-conditions fully
– Keep post-conditions simple initially; jot down complex ones as comments and implement as needed
19. Questions and Concerns
● Can I use contracts with language X?
– Almost certainly, Yes
– You can usually roll your own support using asserts,
exceptions, or even pop-ups.
– Many languages have built-in support or libraries:
● Eiffel, Racket, Clojure, D, .NET languages (via Code
Contracts add-on), etc.
20. Questions and Concerns
● Do contracts replace documentation?
– Partly. Contracts can help reduce the documentation
burden and help keep technical documentation up-to-
dated.
– Ideally, language support should include a tool for
summarizing source code, by
● omitting implementation details
● retaining signatures, doc-strings and contracts
● formatting the output appropriately, and adding hyperlinks
21. Questions and Concerns
● What about state?
– State adds a bit of complexity, but Contracts can cope.
– Pre-conditions can check initial state (as well as arguments):
● E.g. A pre-condition on a routine that reads a token from a file should
check that the file is open and that the end hasn't been reached.
– Post-conditions can check final state (as well as the result)
● E.g. A setter can check that the desired effect has occurred.
– Advice:
● Favour pure functions over ones with side-effects
● Favour immutable data structures
22. Questions and Concerns
● What about object-oriented programming?
– OO design and programming with contracts is a major
focus of the Eiffel language, but not the focus of this talk.
– Besides object state, OO-progamming with contracts
involves invariant checking, and support for inheritance
when methods are redefined in sub-types.
– Advice:
● Read up on it elsewhere, e.g.
– Bertrand Meyer's Object-oriented Software Construction, 2nd ed.
23. Questions and Concerns
● What about functional programming?
– That's the focus of the next part of this presentation!
– The material so far applied equally to both the imperative
and functional paradigms.
– Now we switch to some more functional aspects
● Out-of-the-box support in Racket for contracts
● Higher-order functions and contracts
● Checking contracts at module boundaries
24. Square root reprised, using
Racket's contract combinators
; The simple (-> domain range) contract combinator is concise,
; but limited:
;
(define/contract (real-sqrt-1 x)
(-> non-negative-real? non-negative-real?)
...)
; The “indy” (->i ...) contract combinator gives names to the
; argument(s) and to the result: greater richness, less concision
;
(define/contract (real-sqrt x)
(->i ([x non-negative-real?])
(r non-negative-real?)
#:post (r x) (approx-equal? (* r r) x))
...)
25. Contract combinators provide richer
error messages
● Hand-rolled:
– (square-root 'foo)
● Combinator:
– (real-sqrt 'foo)
pre-condition-violation: real,
non-negative argument
real-sqrt: contract violation
expected: non-negative-real?
given: 'foo
in: the x argument of
(->i
((x non-negative-real?))
(r non-negative-real?)
#:post
(r x)
...)
contract from: .../contracts.rkt
Blaming: .../contracts.rkt
At: .../contracts.rkt: [line/col of the contract]
26. Higher-order functions and
Contracts
● Higher-order functions can't be checked
immediately for conformance to a predicate. E.g.
(define/contract (make-indenter n)
(->i ([n natural-number/c])
[r (n) (->i ([s string?])
[result string?]
#:post (s result) (= (string-length result)
(+ n (string-length s))))])
(λ (s) (string-append (make-string n #space) s)))
Usage: ((make-indenter 4) “foo”) → “ foo”
27. Higher order functions and Contracts
● Racket wraps the higher-order functions in a guard and
checks what's passed in and returned at the time of
function application.
● Failures are deciphered in the error message. E.g.
((make-indenter 4) 'foo) → make-indenter: contract violation
expected: string?
given: 'foo
in: the s argument of
the r result of
(->i ((n natural-number/c)) (r (n) ...))
28. Attaching contracts at module
boundaries
● Traditionally, contracts are enforced at function
boundaries, but other choices are possible.
● In Racket, contracts are commonly wrapped around
existing functions (and data) when they are
exported from modules.
● Contract checking only occurs across module
boundaries, useful e.g. in highly recursive
scenarios.
30. Additional facilities in Racket
● Racket includes many more features for working
with contracts, including:
– Support for variable-arity and keyword arguments
– Contracts on structures
– Additional contract combinators
● See the Racket docs for details
31. Interlude: What do you do now?
● Questions for fans of automated tests:
– TDD? BDD? CI?
– What do you like about automated tests?
– Pains?
● Questions for fans of static typing:
– How sophisticated is your type-system?
– Is anyone using dependent types?
– Is anyone automatically generating tests from types?
– Likes? Pains?
● Any other approaches?
32. Automated Tests smackdown
● Positives of tests
– Popular
– Concrete and relatively
easy to understand
– Automated tests exercise
the code
– No performance impact on
production code
– TDD encourages good
design
● Negatives of tests:
– Requires discipline
– Tests don't apportion precise
blame (although TDD / rolling
back can help isolate issues)
– Not helpful in production
– A big test suite can be time-
consuming to run and take a
lot of work to maintain
33. Static Type-Checking smackdown
● Positives
– Type checks are at compile
time: early feedback
– Faster execution
– Simplifies contracts
– Enforces discipline
● Limitation
– You can't check everything
statically: Rice's theorem
● Negatives
– Demands discipline
– Can break programmer flow
– Can result in lots of boilerplate (Java,
C#, etc.)
– Large systems can be slow to compile
– Simpler type systems can be unduly
restrictive and inflexible
– Languages with superior type systems
are fairly challenging to learn (Haskell
is hard)
– Language / tool support is essential
34. Contracts smackdown
● Positives
– Assigns blame accurately
– Crushes debugging time
– Simplifies code and tests
– Can express elaborate checks
– Simplifies documentation
– Helps clarify design and
improve modularity
– Most of the benefit can be
achieved without out-of-the-
box language support
● Negatives
– Demands discipline
– Demands skill
– Not widely known or used
– Can slow down
performance, e.g. by
inflating algorithmic
complexity if you're not
careful
35. Hybrid Approach #1
● Contracts + Static Type-Checking
– Maximum concision
– This was the original mix designed into Eiffel
– Challenges?
● High-ish discipline factor
● No out-of-the-box contracts yet in Typed Racket
● For functional programming, rolling your own
higher-order contract support is non-trivial.
36. Hybrid Approach #2
● Tests + Contracts:
– Option 1:
● use explicit pre-conditions
● don't use explicit post-conditions; use tests instead
– Option 2 (my favourite):
● use scenario tests to exercise code and drive Continuous Integration
● Use pre-conditions and post-conditions instead of unit tests
– Option 3:
● automatically generate random unit tests from contracts
●
37. Hybrid Approach #3
● Tests + Contracts + Types:
● Worthwhile once you're comfortable with all three, especially
for large and complex software
● Challenges
– High discipline approach
– Difficult to get everyone in a team on board
38. Conclusion
● If you consistently write automated tests, you have the
necessary self-discipline to try contracts.
● If you are a fan of static type-checking, you can approach
contracts as a logical, dynamic extension.
● Using contracts consistently should
– greatly reduce the time you spend debugging
– make your code, tests, and documentation more concise and
readable
– clarify and simplify your design choices
– change the way you think!
Acknowledgements: Thanks to Matthias Felleisen, Greg Hendershott, Robby
Findler and Russell Sim, respectively for helpful critique and suggestions,
encouragement, a just-in-time correction, and for suggesting I give a talk.
Editor's Notes
I first learned about Design by Contract in 1998 and started using it on a major commercial project that I was designing and implementing in Visual Basic 6 (ugh!). To my joy, the time I spent debugging dropped by 90%. Since then I've experimented with several variants of programming with Contracts in a wide variety of domains and using diverse languages: Eiffel, VB.NET, C#, Python, ActionScript, and – most recently – Racket. The technical pay-off has always been very good, but my ability to persuade colleagues to try this approach has varied from point-blank refusal to reasonable uptake. Since then, the only thing that has had a comparable impact on my approach to software design and quality has been learning and then applying functional programming concepts (starting with SICP). To my mind, both Design by Contract and functional programming have an almost mathematical cleanliness, and indeed the two can be applied together in some interesting ways. With this talk I'd like to introduce you to the basics , share some of what I've learned, and perhaps discuss with you where Design by Contract sits nowadays as a pragmatic approach to Quality in a landscape also populated by TDD and increasingly advanced type systems.
In the first two cases, the blame lies with the client – the calling code Notice that the reasons are intermingled; separate require statements could fix this, but it's a trade-off between concision and precision In the last case the blame lies with the supplier – the implementation code In all cases the stack trace helps locate the problem We could improve the error messages, by including dynamic information about the nature of the violation, and refining the wording, or make use of out-of-the-box or 3 rd party facilities.
Checking types, then numerical relationships, then data is a common pattern You do not have to fully check the result in the post-condition E.g. The final ensure clause in the above example. Some sort of consistency check is often enough
Checking types, then numerical relationships, then data is a common pattern You do not have to fully check the result in the post-condition E.g. The final ensure clause in the above example. Some sort of consistency check is often enough