An idea of how to make JavaScript testable, presented at Stir Trek 2011. The world of JavaScript frameworks has changed greatly since then, but I still agree with the concepts.
Callbacks, Promises, and Coroutines (oh my!): Asynchronous Programming Patter...Domenic Denicola
This talk takes a deep dive into asynchronous programming patterns and practices, with an emphasis on the promise pattern.
We go through the basics of the event loop, highlighting the drawbacks of asynchronous programming in a naive callback style. Fortunately, we can use the magic of promises to escape from callback hell with a powerful and unified interface for async APIs. Finally, we take a quick look at the possibilities for using coroutines both in current and future (ECMAScript Harmony) JavaScript.
Love it or hate it, JavaScript is playing an increasingly important role in the next generation of web and mobile apps. As code continues to move from the server to the client, JavaScript is being used to do more than simple HTML manipulation. Be prepared for this transition and make sure the JavaScript you write is optimized and ready to perform on desktops and devices! In this session, you will learn ten practical tips that you can use today to write faster, more maintainable, memory friendly JavaScript.
Ten useful JavaScript tips & best practicesAnkit Rastogi
In this presentation there are ten useful JavaScript techniques which can be included in your application easily with less friction along with some AngularJs tips and best practices as a bonus. These tips and best practices are accompanied by examples & will cover script loading, design pattern, performance optimization and other areas.
Since best practices are very subjective topics, proper benchmarking needs to be done.
Rich Model And Layered Architecture in SF2 ApplicationKirill Chebunin
Presentation for Symfony Camp UA 2012.
* What are Rich Model, Service Layer & Layered Architecture
* Layered architecture in Sf2 Application
* Integration with 3rd party bundles
An idea of how to make JavaScript testable, presented at Stir Trek 2011. The world of JavaScript frameworks has changed greatly since then, but I still agree with the concepts.
Callbacks, Promises, and Coroutines (oh my!): Asynchronous Programming Patter...Domenic Denicola
This talk takes a deep dive into asynchronous programming patterns and practices, with an emphasis on the promise pattern.
We go through the basics of the event loop, highlighting the drawbacks of asynchronous programming in a naive callback style. Fortunately, we can use the magic of promises to escape from callback hell with a powerful and unified interface for async APIs. Finally, we take a quick look at the possibilities for using coroutines both in current and future (ECMAScript Harmony) JavaScript.
Love it or hate it, JavaScript is playing an increasingly important role in the next generation of web and mobile apps. As code continues to move from the server to the client, JavaScript is being used to do more than simple HTML manipulation. Be prepared for this transition and make sure the JavaScript you write is optimized and ready to perform on desktops and devices! In this session, you will learn ten practical tips that you can use today to write faster, more maintainable, memory friendly JavaScript.
Ten useful JavaScript tips & best practicesAnkit Rastogi
In this presentation there are ten useful JavaScript techniques which can be included in your application easily with less friction along with some AngularJs tips and best practices as a bonus. These tips and best practices are accompanied by examples & will cover script loading, design pattern, performance optimization and other areas.
Since best practices are very subjective topics, proper benchmarking needs to be done.
Rich Model And Layered Architecture in SF2 ApplicationKirill Chebunin
Presentation for Symfony Camp UA 2012.
* What are Rich Model, Service Layer & Layered Architecture
* Layered architecture in Sf2 Application
* Integration with 3rd party bundles
Singletons in PHP - Why they are bad and how you can eliminate them from your...go_oh
While Singletons have become a Pattern-Non-Grata over the years, you still find it surprisingly often in PHP applications and frameworks. This talk will explain what the Singleton pattern is, how it works in PHP and why you should avoid it in your application.
Developing application for Windows Phone 7 in TDDMichele Capra
A real example of how to develop an application for Windows Phone 7 with Test Driven Development approach. In this presentation you'll see also hoew to implements the Model-View-ViewModel (MVVM) pattern.
Powerful JavaScript Tips and Best PracticesDragos Ionita
Javascript Best Practices, IIFE, Immediately invoked function expressions, typeof, instanceof, constructor, random items from an array, generate an array of numbers, append an array to another array, is a number, is an array, remove an item from an array
Building a Pyramid: Symfony Testing StrategiesCiaranMcNulty
The last few years have seen a huge adoption of testing practices, and an explosion of different testing tools, in the PHP space. The difficulties come when we have to choose which tools to use, in what combinations, and how to apply them to existing codebases.
In this talk we will look at what tools are available, what their strengths are, how to decide which set of tools to use for new or legacy projects, and when to prioritise decoupling and testability over the convenience we get from our frameworks.
Illustrate general good design principles in software engineering such as low coupling, high cohesion, modularity, abstraction, separation of interface and implementation. With examples.
Singletons in PHP - Why they are bad and how you can eliminate them from your...go_oh
While Singletons have become a Pattern-Non-Grata over the years, you still find it surprisingly often in PHP applications and frameworks. This talk will explain what the Singleton pattern is, how it works in PHP and why you should avoid it in your application.
Developing application for Windows Phone 7 in TDDMichele Capra
A real example of how to develop an application for Windows Phone 7 with Test Driven Development approach. In this presentation you'll see also hoew to implements the Model-View-ViewModel (MVVM) pattern.
Powerful JavaScript Tips and Best PracticesDragos Ionita
Javascript Best Practices, IIFE, Immediately invoked function expressions, typeof, instanceof, constructor, random items from an array, generate an array of numbers, append an array to another array, is a number, is an array, remove an item from an array
Building a Pyramid: Symfony Testing StrategiesCiaranMcNulty
The last few years have seen a huge adoption of testing practices, and an explosion of different testing tools, in the PHP space. The difficulties come when we have to choose which tools to use, in what combinations, and how to apply them to existing codebases.
In this talk we will look at what tools are available, what their strengths are, how to decide which set of tools to use for new or legacy projects, and when to prioritise decoupling and testability over the convenience we get from our frameworks.
Illustrate general good design principles in software engineering such as low coupling, high cohesion, modularity, abstraction, separation of interface and implementation. With examples.
This course provides a detailed introduction to the Object Oriented techniques identified by Robert Martin as the SOLID principles of software design. Intended for both novice and intermediary developers, each of the five principles are fully defined and explored. Real-world coding examples are provided for each software tenant to help fully expound upon the design techniques. By the end of the session, developers will be able to identify common code smells while applying SOLID programming practices that ensure clean and maintainable code.
Of the SOLID principles, made famous by Robert C. Martin, we'll discuss the Interface Segregation Principle and the Dependency Inversion Principle. This session will explain them thoroughly and give real life examples instead of the regular customer & order examples. You'll walk away knowing what the benefits are and how to use them properly.
The presentation discusses software design. It discusses the characteristics of a good and bad design. Then it talks about how to achieve a good design. Then finally we discuss the SOLID Principles of Object Oriented Design. These are 5 principles compiled by Rober Cecil Martin aka Uncle Bob. The benefit of these principles is to achieve a good OO design which is high in cohesion and low in coupling thus easily adaptable to change
This presentation talks about the five SOLID principles of Object Oriented Design described by Rober C. Martin in his best-seller book "Agile Principles, Patterns, and Practices in C#". The five principle described are:
- Single Responsibility Principle
- Open-Close Principle
- Liskov Substitution Principle
- Interface Segregation Principle
- Dependency Inversion Principle
The presentation is took from the Software Engineering course I run in the bachelor-level informatics curriculum at the University of Padova.
Come to this talk prepared to learn about the Doctrine PHP open source project. The Doctrine project has been around for over a decade and has evolved from database abstraction software that dates back to the PEAR days. The packages provided by the Doctrine project have been downloaded almost 500 million times from packagist. In this talk we will take you through how to get started with Doctrine and how to take advantage of some of the more advanced features.
That’s My App - Running in Your Background - Draining Your BatteryMichael Galpin
You have seen the ads where Android based devices like to brag about how awesome their multitasking is and now even the iPhone claims to have multitasking. Unfortunately it’s pseudo-multitasking borrowed from Android, but fear not. Android has “real” multitasking as well. It’s easy to do, but even easier to screw up. In this talk you’ll learn how to do it right, and how to do it without killing a phone’s battery. We’ll discuss the dreaded “P” word (polling), as well as alternatives such as Android’s cloud to device messaging and persistent connections.
We like the architecture of our applications to revolve around the business logic, not around technical details (and especially not around the database).
In my team at Sky Network Services we use the Clean Architecture and it has given us a great deal of benefits: the business logic is explicit, we are free to change our technical decisions, the app is easy to test, working on it is faster and scalable, it’s hard to do the wrong thing, and many more.
But it comes at a cost, of course. In this talk I’ll tell you the story of our experience with Clean Architecture and give you some tips to get the most out of it.
Example Project
https://github.com/mattia-battiston/clean-architecture-example
Downloads
Online: https://goo.gl/DTxftJ
PDF: https://goo.gl/ZAtdBN
Powerpoint: https://goo.gl/D54wdZ (but you need to install these fonts to see it properly: https://goo.gl/iH8SO5)
Code smells são um dos maiores vilões nos nosso código, onde muita vezes dificultam o entendimento do código, proporcionam armadilhas nas implementações e frequentemente ocasionam bugs em produção, com isso, essa apresentação tem como objetivo mostrar os benefícios de produzir códigos limpos através de boas práticas como SOLID, clean code, entre outras, que promovem hábitos de desenvolvimento para não cairmos nessas armadilhas causadas pelos code smells.
Pragmatic Functional Refactoring with Java 8Codemotion
by Raoul-Gabriel Urma - You may be hearing a lot of buzz around functional programming. For example, Java 8 recently introduced new features and APIs inspired from functional ideas such as first-class functions, composition and immutability. In this talk we show how you can refactor your traditional object-oriented Java to using FP features and APIs from Java 8 in a beneficial manner. - How to adapt to requirement changes using first-class functions - How you can enhance code reusability using currying - How you can make your code more robust by favouring immutability over mutability - and more!
Everybody knows : Web is the platform of the future. Developing for the browser unfortunately requires us to learn and write JavaScript. Not only that but we also have to integrate the JavaScript client code with the server side, which often runs on the JVM (i.e. is written in Java). So we have to work in two different languages with completely different tools and APIs, and cannot share code between the client and the server.
The Google Web Toolkit (GWT) provides a way to write your client side web application entirely in Java and have it automatically translated to fast and compact JavaScript. It allows you to access all the browser functionality through a statically typed API. You only have to learn and use one language and you can use your code on the client as well as on the server.
The downside : Java is a bad match for the asynchronous programming model required on the browser and generally forces us to write and read a lot of boilerplate code.
In this session you'll see how programming GWT applications with Eclipse Xtend provides the best of both worlds:
Static typing with advanced IDE support meets a powerful and expressive language - right at your finger tips.
Generating a custom Ruby SDK for your web service or Rails API using Smithyg2nightmarescribd
Have you ever wanted a Ruby client API to communicate with your web service? Smithy is a protocol-agnostic language for defining services and SDKs. Smithy Ruby is an implementation of Smithy that generates a Ruby SDK using a Smithy model. In this talk, we will explore Smithy and Smithy Ruby to learn how to generate custom feature-rich SDKs that can communicate with any web service, such as a Rails JSON API.
Slack (or Teams) Automation for Bonterra Impact Management (fka Social Soluti...Jeffrey Haguewood
Sidekick Solutions uses Bonterra Impact Management (fka Social Solutions Apricot) and automation solutions to integrate data for business workflows.
We believe integration and automation are essential to user experience and the promise of efficient work through technology. Automation is the critical ingredient to realizing that full vision. We develop integration products and services for Bonterra Case Management software to support the deployment of automations for a variety of use cases.
This video focuses on the notifications, alerts, and approval requests using Slack for Bonterra Impact Management. The solutions covered in this webinar can also be deployed for Microsoft Teams.
Interested in deploying notification automations for Bonterra Impact Management? Contact us at sales@sidekicksolutionsllc.com to discuss next steps.
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.
Epistemic Interaction - tuning interfaces to provide information for AI supportAlan Dix
Paper presented at SYNERGY workshop at AVI 2024, Genoa, Italy. 3rd June 2024
https://alandix.com/academic/papers/synergy2024-epistemic/
As machine learning integrates deeper into human-computer interactions, the concept of epistemic interaction emerges, aiming to refine these interactions to enhance system adaptability. This approach encourages minor, intentional adjustments in user behaviour to enrich the data available for system learning. This paper introduces epistemic interaction within the context of human-system communication, illustrating how deliberate interaction design can improve system understanding and adaptation. Through concrete examples, we demonstrate the potential of epistemic interaction to significantly advance human-computer interaction by leveraging intuitive human communication strategies to inform system design and functionality, offering a novel pathway for enriching user-system engagements.
Builder.ai Founder Sachin Dev Duggal's Strategic Approach to Create an Innova...Ramesh Iyer
In today's fast-changing business world, Companies that adapt and embrace new ideas often need help to keep up with the competition. However, fostering a culture of innovation takes much work. It takes vision, leadership and willingness to take risks in the right proportion. Sachin Dev Duggal, co-founder of Builder.ai, has perfected the art of this balance, creating a company culture where creativity and growth are nurtured at each stage.
Software Delivery At the Speed of AI: Inflectra Invests In AI-Powered QualityInflectra
In this insightful webinar, Inflectra explores how artificial intelligence (AI) is transforming software development and testing. Discover how AI-powered tools are revolutionizing every stage of the software development lifecycle (SDLC), from design and prototyping to testing, deployment, and monitoring.
Learn about:
• The Future of Testing: How AI is shifting testing towards verification, analysis, and higher-level skills, while reducing repetitive tasks.
• Test Automation: How AI-powered test case generation, optimization, and self-healing tests are making testing more efficient and effective.
• Visual Testing: Explore the emerging capabilities of AI in visual testing and how it's set to revolutionize UI verification.
• Inflectra's AI Solutions: See demonstrations of Inflectra's cutting-edge AI tools like the ChatGPT plugin and Azure Open AI platform, designed to streamline your testing process.
Whether you're a developer, tester, or QA professional, this webinar will give you valuable insights into how AI is shaping the future of software delivery.
GraphRAG is All You need? LLM & Knowledge GraphGuy Korland
Guy Korland, CEO and Co-founder of FalkorDB, will review two articles on the integration of language models with knowledge graphs.
1. Unifying Large Language Models and Knowledge Graphs: A Roadmap.
https://arxiv.org/abs/2306.08302
2. Microsoft Research's GraphRAG paper and a review paper on various uses of knowledge graphs:
https://www.microsoft.com/en-us/research/blog/graphrag-unlocking-llm-discovery-on-narrative-private-data/
Dev Dives: Train smarter, not harder – active learning and UiPath LLMs for do...UiPathCommunity
💥 Speed, accuracy, and scaling – discover the superpowers of GenAI in action with UiPath Document Understanding and Communications Mining™:
See how to accelerate model training and optimize model performance with active learning
Learn about the latest enhancements to out-of-the-box document processing – with little to no training required
Get an exclusive demo of the new family of UiPath LLMs – GenAI models specialized for processing different types of documents and messages
This is a hands-on session specifically designed for automation developers and AI enthusiasts seeking to enhance their knowledge in leveraging the latest intelligent document processing capabilities offered by UiPath.
Speakers:
👨🏫 Andras Palfi, Senior Product Manager, UiPath
👩🏫 Lenka Dulovicova, Product Program Manager, UiPath
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.
2. Definition:
“A method of programming based on a hierarchy of
classes, and well-defined and cooperating objects.”
The SOLID principles are principles of object-
oriented class design
3.
4.
5. Your code is going to change
Make your code more reusable (DRY)
Testability
Make our lives easier!
6. Fewer bugs – it costs money to find bugs, fix
bugs, and clean up the mess created by bugs.
More flexibility – since code will need to change, it
should be easy to change
7.
8. It costs money to develop software
It costs money to fix bugs
It costs money to make changes to software
10. Clean Code: A Handbook of
Agile Software Craftsmanship,
by Robert C. Martin (aka
“Uncle Bob” Martin)
11. These are guidelines, not hard and fast rules
Use your brain – do what makes sense
Ask why
12. Software should be:
Easy to test
Easy to change
Easy to add features to
Easy != not learning a new way of doing things
13. Have only as much complexity as you need – have a
reason for complexity
“I don’t want to learn this new way” != too complex
14. A class should have one, and only one, reason to
change.
15.
16. public class Person
{
private const decimal _minimumRequiredBalance = 10m;
public string Name { get; set; }
public decimal Balance { get; set; }
public decimal AvailableFunds
{
get { return Balance - _minimumRequiredBalance; }
}
public void DeductFromBalanceBy(decimal amountToDeduct)
{
if (amountToDeduct > Balance)
throw new InvalidOperationException(“Insufficient funds.”);
Balance -= amountToDeduct;
}
}
17. public class Account
{
private const decimal _minimumRequiredBalance = 10m;
public decimal Balance { get; set; }
public IList<Person> AccountHolders { get; set; }
public decimal AvailableFunds
{
get { return Balance - _minimumRequiredBalance; }
}
public void DeductFromBalanceBy(decimal amountToDeduct)
{
if (amountToDeduct > Balance)
throw new InvalidOperationException(“Insufficient funds.”);
Balance -= amountToDeduct;
}
}
18. public class Person
{
public string Name { get; set; }
public Account Account { get; set; }
public decimal AvailableFunds
{
get { return Account.AvailableFunds; }
}
public decimal AccountBalance
{
get { return Account.Balance; }
}
public void DeductFromBalanceBy(decimal amountToDeduct)
{
Account.DeductFromBalanceBy(amountToDeduct);
}
}
19. public class OrderProcessingModule {
public void Process(OrderStatusMessage orderStatusMessage) {
// Get the connection string from configuration
SRP string connectionString = ConfigurationManager.ConnectionStrings["Main"].ConnectionString;
Order order = null;
Violation - using (SqlConnection connection = new SqlConnection(connectionString)) {
Spaghetti // go get some data from the database
order = fetchData(orderStatusMessage, connection);
}
Code // Apply the changes to the Order from the OrderStatusMessage
updateTheOrder(order);
// International orders have a unique set of business rules
if (order.IsInternational)
processInternationalOrder(order);
// We need to treat larger orders in a special manner
else if (order.LineItems.Count > 10)
processLargeDomesticOrder(order);
// Smaller domestic orders
else
processRegularDomesticOrder(order);
// Ship the order if it's ready
if (order.IsReadyToShip()) {
ShippingGateway gateway = new ShippingGateway();
// Transform the Order object into a Shipment
ShipmentMessage message = createShipmentMessageForOrder(order);
gateway.SendShipment(message);
}
}
21. public class OrderService
{
public Order Get(int orderId) { ... }
public Order Save(Order order) { ... }
public Order SubmitOrder(Order order) { ... }
public Order GetOrderByName(string name) { ... }
public void CancelOrder(int orderId) { ... }
public void ProcessOrderReturn(int orderId) { ... }
public IList<Order> GetAllOrders { ... }
public IList<Order> GetShippedOrders { ... }
public void ShipOrder { ... }
}
22. Fill out the XML doc comments for the class – be
wary of words like if, and, but, except, when, etc.
/// <summary>
/// Gets, saves, and submits orders.
/// </summary>
public class OrderService
{
public Order Get(int orderId) { ... }
public Order Save(Order order) { ... }
public Order SubmitOrder(Order order) { ... }
}
23. Domain services should have a verb in the class
name
public class GetOrderService
{
public Order Get(int orderId) { ... }
}
public class SaveOrderService
{
public Order Save(Order order) { ... }
}
public class SubmitOrderService
{
public Order SubmitOrder(Order order) { ... }
}
24. We want it to be easy to reuse code
Big classes are more difficult to change
Big classes are harder to read
Smaller classes and smaller methods will give you
more flexibility, and you don’t have to write much
extra code (if any) to do it!
25. The violating class is not going to be reused and
other classes don’t depend on it
The violating class does not have private fields that
store values that the class uses
Your common sense says so
Example: ASP.NET MVC controller classes, web
services
26. Don’t code for situations that you won’t ever need
Don’t create unneeded complexity
However, more class files != more complicated
Remember, this is supposed to make your lives
easier! (but not easier to be lazy)
You can always refactor later (if you write tests)
27.
28. A method should have one purpose (reason to
change)
Easier to read and write, which means you are less
likely to write bugs
Write out the steps of a method using plain English
method names
29. public void SubmitOrder(Order order)
{
// validate order
if (order.Products.Count == 0)
{
throw new InvalidOperationException(
"Select a product.");
}
// calculate tax
order.Tax = order.Subtotal * 1.0675;
// calculate shipping
if (order.Subtotal < 25)
order.ShippingCharges = 5;
else
order.ShippingCharges = 10;
// submit order
_orderSubmissionService.SubmitOrder(order);
}
35. public class GetUserService
{
public IList<UserSummary> FindUsers(UserSearchType type)
{
IList<User> users;
switch (type)
{
case UserSearchType.AllUsers:
// load the “users” variable here
break;
case UserSearchType.AllActiveUsers:
// load the “users” variable here
break;
case UserSearchType.ActiveUsersThatCanEditQuotes:
// load the “users” variable here
break;
}
return ConvertToUserSummaries(users);
}
}
36. public interface IUserQuery
{
IList<User> FilterUsers(IList<User> allUsers);
}
public class GetUserService
{
public IList<UserSummary> FindUsers(IUserQuery query)
{
IList<User> users = query.FilterUsers(GetAllUsers());
return ConvertToUserSummaries(users);
}
}
37. Anytime you change code, you have the potential to
break it
Sometimes you can’t change libraries (e.g. code that
isn’t yours)
May have to change code in many different places
to add support for a certain type of situation
38. When the number of options in the if or switch
statement is unlikely to change (e.g. switch on enum)
public void UpdateFontStyle (Paragraph paragraph)
{
switch (IsBoldCheckBox.CheckState)
{
case CheckState.Checked:
paragraph.IsBold = true;
break;
case CheckState.Unchecked:
paragraph.IsBold = false;
break;
case CheckState.Indeterminate:
break;
}
}
39. Use if/switch if the number of cases is unlikely to
change
Use strategy pattern when the number of cases are
likely to change
Always use common sense!
40. Don’t code for situations that you won’t ever need
Don’t create unneeded complexity
However, more class files != more complicated
Remember, this is supposed to make your lives
easier!
You can always refactor later (if you write tests)
41.
42. Functions that use references to base classes must be
able to use objects of derived classes without knowing
it.
43.
44. public class Product
{
public string Name { get; set; }
public string Author { get; set; }
}
public class Book : Product {}
public class Movie : Product {}
If someone had a Product object (which was actually
a Movie) and asked for the Author, what should it do
(a Movie doesn’t have an Author)?
45. People using derived classes should not encounter
unexpected results when using your derived class.
46. public class MyList<T> : IList<T>
{
private readonly List<T> _innerList = new List<T>();
public void Add(T item)
{
if (_innerList.Contains(item))
return;
_innerList.Add(item);
}
public int Count
{
get { return _innerList.Count; }
}
}
47. Throw exceptions for cases that you can’t support (still
not recommended)
public class Rectangle : Shape
{
public double Width { get; set; }
public double Height { get; set; }
public override double Area
{
get { return Width * Height; }
}
}
public class Cube : Shape
{
public override double Area
{
get { throw new NotSupportedException(); }
}
}
48.
49. Clients should not be forced to depend on interfaces
that they do not use.
52. If you implement an interface or derive from a base
class and you have to throw an exception in a method
because you don’t support it, the interface is probably
too big.
53. Single Responsibility Principle for interfaces/base
classes
If your interface has members that are not used by
some inheritors, those inheritors may be affected by
changes in the interface, even though the methods
that they use did not change.
56. High level modules should not depend on low level
modules. Both should depend on abstractions.
Abstractions should not depend on details. Details
should depend on abstractions.
57.
58. Two classes are “tightly coupled” if they are linked
together and are dependent on each other
Tightly coupled classes can not work independent of
each other
Makes changing one class difficult because it could
launch a wave of changes through tightly coupled
classes
60. UI
Interfaces
Business Logic (Domain Model)
Interfaces
Data Access
Database
61. Each layer should not know anything about the
details of how the other layers work.
Example: your domain model should not know how
data access is done – it shouldn’t know if you’re using
stored procedures, an ORM, etc.
62. Tight coupling is bad – if your business layer
contains code related to data access, changes to how
data access is done will affect business logic
Harder to test because you have to deal with
implementation details of something you’re not trying
to test
63. How do you know that your code is working?
How do you know that your code will continue to
work after you change it?
64. Unit tests:
Tests a small unit of functionality
Mock or “fake out” external dependencies (e.g. databases)
Run fast
Integration tests:
Test the whole system working together
Can run slow
Can be brittle
65. Stubs, mocks, and fakes in unit tests are only
possible when we have an interface to implement
The main reason for the Dependency Inversion
Principle is to help us write unit tests.
66. public class ProductRepository : IProductRepository
{
public Product Get(int id) { ... }
}
public interface IProductRepository
{
Product Get(int id);
}
67. public class GetProductService : IGetProductService
{
private IProductRepository _productRepository;
public GetProductService(
IProductRepository productRepository)
{
_productRepository = productRepository;
}
public IList<Product> GetProductById(int id)
{
return _productRepository.Get(id);
}
}
68. Use of “new”
public class GetProductService
{
public IList<Product> GetProductById(int id)
{
var productRepository = new ProductRepository();
return productRepository.Get(id);
}
}
69. Use of “static”
public class SecurityService
{
public static User GetCurrentUser()
{
// do something
}
}
70. Use of singletons using “static”
public class ProductCache
{
private static readonly _instance = new ProductCache();
public static ProductCache Instance
{
get { return _instance; }
}
}
71. public class GetProductService : IGetProductService
{
private IProductRepository _productRepository;
public GetProductService(
IProductRepository productRepository)
{
_productRepository = productRepository;
}
public IList<Product> GetProductById(int id)
{
return _productRepository.Get(id);
}
}
Problem: How do we create these objects?
72. Creates objects that are ready for you to use
Knows how to create objects and their
dependencies
Knows how to initialize objects when they are
created (if necessary)
73. Popular .NET choices:
StructureMap, Ninject
Other .NET choices:
Unity, Castle Windsor, Autofac, Spring .NET
Java
Spring
Ruby
We don’t need no stinkin’ DI containers!
75. ObjectFactory.Initialize(x =>
{
x.Scan(scan =>
{
scan.WithDefaultConventions();
scan.AssemblyContainingType<IProductRepository>();
});
});
Automatically map “ISomething” interface to
“Something” class
76. ObjectFactory.Initialize(x =>
{
x.For<IProductRepository>()
.Use<ProductRepository>()
.OnCreation(repository =>
repository.ConnectionString =
ConfigurationManager.AppSettings["MainDB"]);
});
We just reduced duplication and complexity by
setting this up here!
77. ObjectFactory.Initialize(x =>
{
x.ForSingletonOf<IProductCache>().Use<ProductCache>();
});
There will only ever be one IProductCache
We don’t violate DIP by having static variables
78. ObjectFactory.Initialize(x =>
{
x.For<ICurrentUser>()
.Use(c => new CurrentUser(Thread.CurrentPrincipal));
});
Testing will be easier because we won’t reference
Thread.CurrentPrincipal
79. Don’t “new” up anything that is a dependency
Don’t new up classes that you want to create a fake for in a test
Do new up entity objects
Do new up value types (e.g. string, DateTime, etc.)
Do new up .NET Framework types (e.g. SqlConnection)
Entity objects should not have dependencies
If you have to have static variables, isolate them
behind the DI container (e.g. example in previous
slide)
Use ObjectFactory.GetInstance() to create objects
when you can’t take them in as constructor
parameters
Don’t use the DI container when writing unit tests
82. Uncle Bob’s SOLID articles
http://bit.ly/solid1
Uncle Bob talking about SOLID on Hanselminutes
http://bit.ly/solid2
My slides
http://bit.ly/solid3
ALT.NET mailing list
http://bit.ly/solid4
My Info:
email: jon@jonkruger.com
twitter: @jonkruger / blog: http://jonkruger.com/blog
TDD training: http://tddbootcamp.com
Editor's Notes
Each of these Legos have a very specific purpose and a way to interact with each other. Using these simple blocks, you can create amazing Lego structures.
-Imagine if some of our Lego blocks were missing the pins on the top, some were very weird shapes, some couldn’t attach anything to the bottom, some were glued together, etc. – if would be really hard to build different things with them or change what we were building
DRY – if you write less code, you will write less bugs (and you have to do less work)Good software design and testing go hand in hand – testable code is usually well designed code (and vice versa)
I will try to explain situations where (I think) you can not follow these principlesThe goal is to make software development easier. This DOES NOT mean that you shouldn’t follow these principles just because you don’t understand it or don’t know how to do it. Try to understand why you are doing things the way you are doing it. Do what makes sense to you – but make sure you do your homework and make sure you are doing the right thingDon’t just do something because someone says you should – learn why you should do it that way (they could be wrong)You should be able to explain why you made a decision – not “Microsoft told me to do it” or “someone says this is the right way to do it” or “this is how we’ve always done it in the past” Have seen projects that took these principles to extremes, or added unnecessary complexity without knowing why they were doing it, and the project suffered or failed because of it
If you’re not willing to use a technology because you’re not willing to learn something new, that is a big problem not saying that you need to spend all of your time outside of work learning new stuff be open to change and new ideas
- Imagine trying to use this thing! It can do everything you want, but doing what you want will be difficult.
- What happens if the requirements change and now you can have a joint account that is held by two people?
- Person still has methods and properties dealing with accounts, but now all of the account logic is correctly encapsulated in the Account class
- small, useful Lego blocks instead of oddly-shaped ones
Explain what a domain service is – not a web service
- This is not added complexity – I’m not writing any more code than I did when it was all one class
Big classes are harder to read, write, change, or testBig classes often mean tight coupling, so it’s difficult to change one part of the class without affecting the other parts of it
- Common sense – go with your gut – don’t sit there for half an hour trying to figure out if a class violates SRP. If you can’t make a decision, just leave it how it is, you can come back and refactor later if you need to.
- What is this method doing? You can figure it out, but you have to read it carefully and figure out what’s going on, even for this simple example.
- What is this method doing? Even a non-programmer could tell you!
- When you’re writing a one line method, it’s a lot easier because you can concentrate on what that one line is supposed to do… you don’t have to think about the overall flow and logic of what you’re trying to do overall
- We are trying to do 2 things here – find subsets of users, and return user summaries
Now the IUserQuery is responsible for filtering the users, and the FindUsers() method is only responsible for return user summaries for a list of users We can reuse the IUserQuery in other places, and now we don’t have to modify GetUserService.FindUsers() in order to create a new type of query.
- Comments that say “if you want to add another X, you have to add code in these 5 places”
- Probably need a 2DShape and 3DShape base class
- Example – going to a friend’s house and they have the complicated home theater system and you want to watch TV
- example: I want to test my validation code. I just want to test the validation logic, so why should I have to actually save something to the database to do this?
Java: SpringRuby: we don’t need no stinkin’ DI containers!