The document introduces the SOLID principles of object-oriented design, which are Single Responsibility Principle, Open-Closed Principle, Liskov Substitution Principle, Interface Segregation Principle, and Dependency Inversion Principle. It discusses each principle in detail and provides examples of how to apply them to refactor code and improve design. Design principles help create high-quality software by improving modularity, reusability, and maintainability of code. The SOLID principles in particular help achieve these goals and are fundamental for object-oriented design.
Learning solid principles using c#
S Single Responsibility Principle
O Open Closed Principle
L Liskovs Substitution Principle
I Interface Segregation Principle
D Dependency Inversion principle
Learning solid principles using c#
S Single Responsibility Principle
O Open Closed Principle
L Liskovs Substitution Principle
I Interface Segregation Principle
D Dependency Inversion principle
SOLID Design Principles applied in JavaIonut Bilica
Video: https://www.youtube.com/watch?v=0cU-4LrcWI0
SOLID Design Principles applied in Java: rules to develop scalable and easily maintainable code
Speaker: Ionut Bilica - Senior Software Developer @ Luxoft Romania.
During this talk we will discuss about the SOLID Principles described by Robert C. Martin, applying them in the Java programming language. Each principle will be explained in detail, with practical Java examples.
We will asses how these principles make it easy to develop the software for the entire duration of the project, and how some problems can appear if these principles are not applied. We will present common code fragments that do not respect these principles, and we'll see how we can correct them. Taking the SOLID principles into consideration, we will also analyse a real Java project using a Static Code Analyzer tool (e.g. STAN).
Finally, we will discuss the strategies on how to apply these design principles in "greenfield" projects, as well as "legacy" projects, while offering some tips and tricks.
This presentation is based on a blog post I made:
http://eyalgo.com/2014/02/01/the-single-responsibility-principle/
More details are in that blog post.
I had a presentation at work with these slides.
The theory of SOLID principles was
introduced by Robert C. Martin in his 2000
paper “Design Principles and Design
Patterns”.
SOLID => Single Responsibility, Open/Closed, Liskov Substitution, Interface Segregation, Dependency Inversion.
SOLID : les principes à l’origine du succès de Symfony et de vos applicationsVladyslav Riabchenko
SOLID est un acronyme représentant cinq principes de bases de la programmation orientée objet permettant le développement de logiciels fiables, évolutifs et robustes. Le framework Symfony est un excellent support pour illustrer chacun de ces principes. Nous verrons ainsi que SOLID est à l’origine de sa flexibilité, sa fiabilité mais aussi de sa maintenabilité et son évolutivité. Nous verrons également comment appliquer ces principes pour améliorer son code métier et perfectionner l’architecture de son application.
Functional programming principles are the foundation of design patterns in React. Following FP and design patterns in React leads to optimal solutions. Get to know them!
Domain Driven Design main concepts
This presentation is a summary of the book "Domain Driven Design" from InfoQ.
Here is the link: http://www.infoq.com/minibooks/domain-driven-design-quickly
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.
SOLID Design Principles applied in JavaIonut Bilica
Video: https://www.youtube.com/watch?v=0cU-4LrcWI0
SOLID Design Principles applied in Java: rules to develop scalable and easily maintainable code
Speaker: Ionut Bilica - Senior Software Developer @ Luxoft Romania.
During this talk we will discuss about the SOLID Principles described by Robert C. Martin, applying them in the Java programming language. Each principle will be explained in detail, with practical Java examples.
We will asses how these principles make it easy to develop the software for the entire duration of the project, and how some problems can appear if these principles are not applied. We will present common code fragments that do not respect these principles, and we'll see how we can correct them. Taking the SOLID principles into consideration, we will also analyse a real Java project using a Static Code Analyzer tool (e.g. STAN).
Finally, we will discuss the strategies on how to apply these design principles in "greenfield" projects, as well as "legacy" projects, while offering some tips and tricks.
This presentation is based on a blog post I made:
http://eyalgo.com/2014/02/01/the-single-responsibility-principle/
More details are in that blog post.
I had a presentation at work with these slides.
The theory of SOLID principles was
introduced by Robert C. Martin in his 2000
paper “Design Principles and Design
Patterns”.
SOLID => Single Responsibility, Open/Closed, Liskov Substitution, Interface Segregation, Dependency Inversion.
SOLID : les principes à l’origine du succès de Symfony et de vos applicationsVladyslav Riabchenko
SOLID est un acronyme représentant cinq principes de bases de la programmation orientée objet permettant le développement de logiciels fiables, évolutifs et robustes. Le framework Symfony est un excellent support pour illustrer chacun de ces principes. Nous verrons ainsi que SOLID est à l’origine de sa flexibilité, sa fiabilité mais aussi de sa maintenabilité et son évolutivité. Nous verrons également comment appliquer ces principes pour améliorer son code métier et perfectionner l’architecture de son application.
Functional programming principles are the foundation of design patterns in React. Following FP and design patterns in React leads to optimal solutions. Get to know them!
Domain Driven Design main concepts
This presentation is a summary of the book "Domain Driven Design" from InfoQ.
Here is the link: http://www.infoq.com/minibooks/domain-driven-design-quickly
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.
Success by Challenging Assumptions (Part 2)LaDonna Coy
Part two of a two part workshop on Creating Success by Challenging Assumptions with Stephanie Nestlerode, Omega Point International, Inc. and LaDonna Coy, Learning for Change, Inc. for the Texas SPF SIG community grantees. All materials are located at http://bit.ly/xQSu9
Make yourself replaceable at DevOpsCon 2016 BerlinErno Aapa
"Make yourself replaceable" presentation from DevOpsCon 2016 Berlin, about how to distribute your knowledge and information to build culture which change team to DevOps mindset
Dependency injection is a technique to get rid of tightly coupled code.This session will give an idea about using DI in one's project with various patterns like constructor injection,setter injection and interface injection and demo of DI using Unity container.
SOLID Principles of Refactoring Presentation - Inland Empire User GroupAdnan Masood
Abstract: SOLID is a mnemonic acronym coined by Robert C. Martin (aka Uncle Bob) referring to a collection of design principles of object-oriented programming and design. By using these principles, developers are much more likely to create a system that more maintainable and extensible. SOLID can be used to remove code smells by refactoring. In this session, you will learn about the following SOLID principles with code examples demonstrating the corresponding refactoring.
S – Single Responsibility Principle – An Object should have only one reason to change.
O – Open/Closed Principle – A software entity(module, library, routine) should be closed to any modification but be open to extension
L – Liskov Substitution Principle – Derived classes should be substitutable for the base classes
I – Interface Segregation Principle – Having more fine grained interfaces over fat interfaces
D – Dependency Inversion Principle – Depending on abstractions, not concrete implementations.
Refactoring Applications using SOLID PrinciplesSteven Smith
We’ve all heard about well-designed software projects, where things aren’t (yet) a big ball of mud that’s painful to work with, but many of us aren’t lucky enough to work on these. Nor is it an option for us to get to start a brand new “greenfield” project, where we can leave behind the legacy of spaghetti code and technical debt our current project might have.
But there is hope! By applying refactoring steps based on SOLID principles of object oriented design, we can reduce the technical debt of our existing application, improve our code quality, and hopefully make our application more enjoyable and productive to work with.
In this session, we’ll briefly introduce the SOLID principles and several design patterns, and then we’ll apply these principles and patterns by improving the design of an existing application through several refactoring steps.
Success by Challenging Assumptions (Part I)LaDonna Coy
Part one of a two part workshop on Creating Success by Challenging Assumptions with Stephanie Nestlerode, Omega Point International, Inc. and LaDonna Coy, Learning for Change, Inc. for the Texas SPF SIG community grantees. All materials are located at http://bit.ly/xQSu9
Learn how to leverage functional concepts of Partial Application and Function Composition for Dependency Injection in C#. This is to achieve Simplicity.
Of the SOLID principles, made famous by Robert C. Martin, we'll discuss the Single Responsibility Principle and the Open/Closed Principle, two of the presenter's favorite principles. But at the same time the least understood and used principles. That's why 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 SOLID Principles Illustrated by Design PatternsHayim Makabee
The goal of the SOLID design principles is to improve the Separation of Concerns, through weaker Coupling and stronger Cohesion. The main consequence should be software systems that are easier to maintain and to extend. However the definition of the SOLID principles is quite abstract, and some developers find it difficult to apply them in practice. In my talk I will show how well-known Design Patterns illustrate the application of the SOLID principles, and also show examples of how to follow these principles to Refactor and improve existing designs.
About the speaker:
Hayim Makabee was born in Rio de Janeiro. He immigrated to Israel in 1992 and completed his M.Sc. studies on Computer Sciences at the Technion. Since then he worked for several hi-tech companies, including also some start-ups. Currently he is a co-founder of the International Association of Software Architects (IASA) in Israel. Hayim is the author of a book about Object-Oriented Programming and has published papers in the fields of Software Engineering, Distributed Systems and Genetic Algorithms.
Write Once, Run Everywhere - Ember.js MunichMike North
Ember.js is an opinionated web framework, that allows developers to focus less on boilerplate, and focus more on what makes their app unique. We’ll go over some of the best practices of using Ember for cross-device development, introduce Cordova and NW.js, and then discuss modular design, testing, encapsulation of native functionality in the context of an open source case study project.
The tutorial titled "Applying design principles in practice" was presented in ISEC (India Software Engg Conference) on 18th Feb 2015 in Bengaluru by Tushar Sharma, Ganesh Samarthyam, and Girish Suryanarayana.
Applying Design Principles in Practice - ISEC 2015 TutorialGanesh Samarthyam
It is widely recognized that the systematic application of relevant design principles plays a key role in taming the complexity involved in real-world software development. In our experience as consultant architects and trainers on software architecture and design in a corporate setting, we find that software engineers have a theoretical understanding of design principles but sorely lack knowledge about how to properly apply them to in real-world situations to achieve high-quality design. This half-day tutorial is geared towards bridging this gap. It first introduces fundamental design principles (viz. abstraction, encapsulation, modularization, and hierarchy) and describes how these can be applied using a set of corresponding enabling techniques. Next, it discusses how design smells can be viewed as violations of these enabling techniques, and explains how these design smells can be refactored via the application of relevant design principles. Finally, it highlights useful tools, processes, and practical techniques that support the application of design principles in real-world software projects.
Refactoring Workflows & Techniques Presentation by Valentin StantescuPayU Türkiye
PayU ekibimizden Valentin Stantescu'nun PHP İstanbul Konferansı'nda 'Refactoring Workflows & Techniques' hakkında yapmış olduğu sunuma buradan ulaşabilirsiniz.
PayU hakkında detaylı bilgi için tıklayın; www.payu.com.tr
MODEL DRIVEN ARCHITECTURE, CONTROL SYSTEMS AND ECLIPSEAnže Vodovnik
This paper describes the use of model driven architecture and its application in control system development. It also presents a prototype solution based on the Eclipse framework implemented by the author.
Anže Vodovnik, Klemen Žagar, Cosylab, Ljubljana, Slovenija
Design Pattern Mastery - Momentum Dev Con 19 Apr 2018Steven Smith
Design patterns help developers and teams solve problems using proven approaches. In this talk, you'll learn how to solve a series of real world problems by applying patterns. Not only do patterns help individual developers solve particular problems, but they also enable teams to discuss design decisions using a richer, more descriptive language. By the end, you'll have some concrete tools you can apply, and hopefully the desire to master more patterns as you continue to improve!
Almost everything can be done using refactoring tools:
* How to get buy-in for refactoring? (use Technical Debt quantification tools)
* How to identify refactoring candidates? (use smell detection tools)
* How to prioritize / identify what to refactor first? (use reports from design analysis tools)
* How do I identify dependencies and evaluate impact of refactoring? (use visulization tools)
* How to I actually perform refactoring? (Use IDE support for automated refactoring and use them!)
Deriving from a rich experience in using tools for refactoring in real-world projects, this talk takes you through a whirl-wind tour of refactoring tools (of course for Java). What's more, this talk includes quick demos of some of these tools so you can see them in action.
Presented in BoJUG meetup on 19th Jan in Bangalore - https://www.meetup.com/BangaloreOpenJUG/events/257183518/
Please check out the workshop "AI meets Blockchain" at HIPC 2018, in Bangalore: http://hipc.org/ai-blockchain/
HIPC is a premier conference and hence getting a paper accepted in HIPC workshop would be quite an accomplishment for any blockchain/AI enthusiast. Check out the details in this poster on submissions.
I have been fortunate to have worked with some geeks with incredible coding skills. I felt amazed at how they can play games with compilers, perform magic with their incantations on the shell, and solve some insanely complex algorithm problems with ease. I naively assumed that they are going to achieve greatness in near future. Alas, I was wrong. Really wrong. [Read the rest of the article ... ]
Many students reach out to me asking for project ideas they can do as a summer project for learning. Here is an interesting project idea - implement your own java disassembler (and expand it to a VM later).
Design Patterns - Compiler Case Study - Hands-on ExamplesGanesh Samarthyam
This presentation takes a case-study based approach to design patterns. A purposefully simplified example of expression trees is used to explain how different design patterns can be used in practice. Examples are in C#, but is relevant for anyone who is from object oriented background.
This presentation provides an overview of recently concluded Bangalore Container Conference (07-April-2017). See www.containerconf.in for more details.
Bangalore Container Conference 2017 (BCC '17) is the first conference on container technologies in India happening on 07th April. Organizations are increasingly adopting containers and related technologies in production.Hence, the main focus of this conference is “Containers in Production”. This one-day conference sets the perfect stage for container enthusiasts, developers, users and experts to meet together and learn from each others experiences.
Presented in Bangalore Open Java User Group on 21st Jan 2017
Awareness of design smells - Design comes before code. A care at design level can solve lot of problems.
Indicators of common design problems - helps developers or software engineers understand mistakes made while designing and apply design principles for creating high-quality designs. This presentation provides insights gained from performing refactoring in real-world projects to improve refactoring and reduce the time and costs of managing software projects. The talk also presents insightful anecdotes and case studies drawn from the trenches of real-world projects. By attending this talk, you will know pragmatic techniques for refactoring design smells to manage technical debt and to create and maintain high-quality software in practice. All the examples in this talk are in Java.
Bangalore Container Conference 2017 (BCC '17) is the first conference on container technologies in India. Organizations are increasingly adopting containers and related technologies in production. Hence, the main focus of this conference is “Containers in Production”. This one-day conference sets the perfect stage for container enthusiasts, developers, users and experts to meet together and learn from each others experiences.
This presentation covers quiz questions prepared for the Core Java meetup on 1st October in Accion Labs. It has questions from "Java best practices", "bytecodes", and "elastic search".
This presentation is on advanced debugging using Java bytecodes (presented in Core Java meetup on 1st October in Accion Labs). If you are a Java developer and are interested in knowing advanced debugging techniques or understanding bytecodes, this presentation is for you.
Field Employee Tracking System| MiTrack App| Best Employee Tracking Solution|...informapgpstrackings
Keep tabs on your field staff effortlessly with Informap Technology Centre LLC. Real-time tracking, task assignment, and smart features for efficient management. Request a live demo today!
For more details, visit us : https://informapuae.com/field-staff-tracking/
Innovating Inference - Remote Triggering of Large Language Models on HPC Clus...Globus
Large Language Models (LLMs) are currently the center of attention in the tech world, particularly for their potential to advance research. In this presentation, we'll explore a straightforward and effective method for quickly initiating inference runs on supercomputers using the vLLM tool with Globus Compute, specifically on the Polaris system at ALCF. We'll begin by briefly discussing the popularity and applications of LLMs in various fields. Following this, we will introduce the vLLM tool, and explain how it integrates with Globus Compute to efficiently manage LLM operations on Polaris. Attendees will learn the practical aspects of setting up and remotely triggering LLMs from local machines, focusing on ease of use and efficiency. This talk is ideal for researchers and practitioners looking to leverage the power of LLMs in their work, offering a clear guide to harnessing supercomputing resources for quick and effective LLM inference.
We describe the deployment and use of Globus Compute for remote computation. This content is aimed at researchers who wish to compute on remote resources using a unified programming interface, as well as system administrators who will deploy and operate Globus Compute services on their research computing infrastructure.
Exploring Innovations in Data Repository Solutions - Insights from the U.S. G...Globus
The U.S. Geological Survey (USGS) has made substantial investments in meeting evolving scientific, technical, and policy driven demands on storing, managing, and delivering data. As these demands continue to grow in complexity and scale, the USGS must continue to explore innovative solutions to improve its management, curation, sharing, delivering, and preservation approaches for large-scale research data. Supporting these needs, the USGS has partnered with the University of Chicago-Globus to research and develop advanced repository components and workflows leveraging its current investment in Globus. The primary outcome of this partnership includes the development of a prototype enterprise repository, driven by USGS Data Release requirements, through exploration and implementation of the entire suite of the Globus platform offerings, including Globus Flow, Globus Auth, Globus Transfer, and Globus Search. This presentation will provide insights into this research partnership, introduce the unique requirements and challenges being addressed and provide relevant project progress.
TROUBLESHOOTING 9 TYPES OF OUTOFMEMORYERRORTier1 app
Even though at surface level ‘java.lang.OutOfMemoryError’ appears as one single error; underlyingly there are 9 types of OutOfMemoryError. Each type of OutOfMemoryError has different causes, diagnosis approaches and solutions. This session equips you with the knowledge, tools, and techniques needed to troubleshoot and conquer OutOfMemoryError in all its forms, ensuring smoother, more efficient Java applications.
May Marketo Masterclass, London MUG May 22 2024.pdfAdele Miller
Can't make Adobe Summit in Vegas? No sweat because the EMEA Marketo Engage Champions are coming to London to share their Summit sessions, insights and more!
This is a MUG with a twist you don't want to miss.
Large Language Models and the End of ProgrammingMatt Welsh
Talk by Matt Welsh at Craft Conference 2024 on the impact that Large Language Models will have on the future of software development. In this talk, I discuss the ways in which LLMs will impact the software industry, from replacing human software developers with AI, to replacing conventional software with models that perform reasoning, computation, and problem-solving.
Listen to the keynote address and hear about the latest developments from Rachana Ananthakrishnan and Ian Foster who review the updates to the Globus Platform and Service, and the relevance of Globus to the scientific community as an automation platform to accelerate scientific discovery.
Check out the webinar slides to learn more about how XfilesPro transforms Salesforce document management by leveraging its world-class applications. For more details, please connect with sales@xfilespro.com
If you want to watch the on-demand webinar, please click here: https://www.xfilespro.com/webinars/salesforce-document-management-2-0-smarter-faster-better/
Code reviews are vital for ensuring good code quality. They serve as one of our last lines of defense against bugs and subpar code reaching production.
Yet, they often turn into annoying tasks riddled with frustration, hostility, unclear feedback and lack of standards. How can we improve this crucial process?
In this session we will cover:
- The Art of Effective Code Reviews
- Streamlining the Review Process
- Elevating Reviews with Automated Tools
By the end of this presentation, you'll have the knowledge on how to organize and improve your code review proces
Accelerate Enterprise Software Engineering with PlatformlessWSO2
Key takeaways:
Challenges of building platforms and the benefits of platformless.
Key principles of platformless, including API-first, cloud-native middleware, platform engineering, and developer experience.
How Choreo enables the platformless experience.
How key concepts like application architecture, domain-driven design, zero trust, and cell-based architecture are inherently a part of Choreo.
Demo of an end-to-end app built and deployed on Choreo.
top nidhi software solution freedownloadvrstrong314
This presentation emphasizes the importance of data security and legal compliance for Nidhi companies in India. It highlights how online Nidhi software solutions, like Vector Nidhi Software, offer advanced features tailored to these needs. Key aspects include encryption, access controls, and audit trails to ensure data security. The software complies with regulatory guidelines from the MCA and RBI and adheres to Nidhi Rules, 2014. With customizable, user-friendly interfaces and real-time features, these Nidhi software solutions enhance efficiency, support growth, and provide exceptional member services. The presentation concludes with contact information for further inquiries.
In software engineering, the right architecture is essential for robust, scalable platforms. Wix has undergone a pivotal shift from event sourcing to a CRUD-based model for its microservices. This talk will chart the course of this pivotal journey.
Event sourcing, which records state changes as immutable events, provided robust auditing and "time travel" debugging for Wix Stores' microservices. Despite its benefits, the complexity it introduced in state management slowed development. Wix responded by adopting a simpler, unified CRUD model. This talk will explore the challenges of event sourcing and the advantages of Wix's new "CRUD on steroids" approach, which streamlines API integration and domain event management while preserving data integrity and system resilience.
Participants will gain valuable insights into Wix's strategies for ensuring atomicity in database updates and event production, as well as caching, materialization, and performance optimization techniques within a distributed system.
Join us to discover how Wix has mastered the art of balancing simplicity and extensibility, and learn how the re-adoption of the modest CRUD has turbocharged their development velocity, resilience, and scalability in a high-growth environment.
Developing Distributed High-performance Computing Capabilities of an Open Sci...Globus
COVID-19 had an unprecedented impact on scientific collaboration. The pandemic and its broad response from the scientific community has forged new relationships among public health practitioners, mathematical modelers, and scientific computing specialists, while revealing critical gaps in exploiting advanced computing systems to support urgent decision making. Informed by our team’s work in applying high-performance computing in support of public health decision makers during the COVID-19 pandemic, we present how Globus technologies are enabling the development of an open science platform for robust epidemic analysis, with the goal of collaborative, secure, distributed, on-demand, and fast time-to-solution analyses to support public health.
4. Poor software quality costs
more than $150 billion per year
in U.S. and greater than $500
billion per year worldwide
- Capers Jones
5. The city metaphor
Source: http://indiatransportportal.com/wp-content/uploads/2012/04/Traffic-congestion1.jpg
6. The city metaphor
“Cities grow, cities evolve, cities
have parts that simply die while other
parts flourish; each city has to be
renewed in order to meet the needs of its
populace… Software-intensive systems
are like that. They grow, they evolve,
sometimes they wither away, and
sometimes they flourish…”
Grady Booch in the foreword for “Refactoring for Software Design Smells: Managing Technical Debt”, Girish Suryanarayana, Ganesh Samarthyam, Tushar Sharma, Morgan Kaufmann/Elsevier, 2014.
7.
8. Modularisation in Java 9
Modularize JDK & JRE
Hide platform internal details such as sun.misc
Provide a module system for Java developers
Reference: http://paulbakker.io/java/java-9-modularity/
9. Example of beautiful design
int arr[] = {1, 4, 9, 16, 25}; // some values
// find the first occurrence of 9 in the array
int * arr_pos = find(arr, arr + 4, 9);
std::cout<< “array pos = “<< arr_pos - arr << endl;
vector<int> int_vec;
for(int i = 1; i <= 5; i++)
int_vec.push_back(i*i);
vector<int>::iterator vec_pos = find (int_vec.begin(), int_vec.end(), 9);
std::cout<< “vector pos = “<< (vec_pos - int_vec.begin());
11. What do we mean by “principles”?
“Design principles are key notions considered
fundamental to many different software design
approaches and concepts.”
- SWEBOK v3 (2014)
12. "The critical design tool for software development
is a mind well educated in design principles"
- Craig Larman
15. Michael Feathers
Michael Feathers coined the acronym
SOLID in 2000s to remember first five of the
numerous principles by Robert C. Martin
16. SOLID principles
S
Single Responsibility
Principle
Every object should have a single responsibility and
that should be encapsulated by the class
O Open Closed Principle
Software should be open for extension, but closed for
modification
L
Liskov’s Substitution
Principle
Any subclass should always be usable instead of its
parent class
I
Interface Segregation
Principle
Many client specific interfaces are better than one
general purpose interface
D
Dependency Inversion
Principle
Abstractions should not depend upon details. Details
should depend upon abstractions
19. How to apply principles in practice?
Design principles
Code
How to bridge
the gap?
20. Why care about refactoring?
As an evolving program is
continually changed, its
complexity, reflecting
deteriorating structure,
increases unless work is done
to maintain or reduce it
- Lehman's law of Increasing Complexity
21. What is refactoring?
Refactoring (noun): a change
made to the internal structure of
software to make it easier to
understand and cheaper to
modify without changing its
observable behavior
Refactor (verb): to restructure
software by applying a series
of refactorings without
changing its observable
behavior
46. Scenario
How to separate:
a) code generation logic
from node types?
b) how to support different
target types?
class Plus extends Expr {
private Expr left, right;
public Plus(Expr arg1, Expr arg2) {
left = arg1;
right = arg2;
}
public void genCode() {
left.genCode();
right.genCode();
if(t == Target.JVM) {
System.out.println("iadd");
}
else { // DOTNET
System.out.println("add");
}
}
}
48. A solution using Visitor pattern
class Plus extends Expr {
private Expr left, right;
public Plus(Expr arg1, Expr arg2) {
left = arg1;
right = arg2;
}
public Expr getLeft() {
return left;
}
public Expr getRight() {
return right;
}
public void accept(Visitor v) {
v.visit(this);
}
}
class DOTNETVisitor extends Visitor {
public void visit(Constant arg) {
System.out.println("ldarg " + arg.getVal());
}
public void visit(Plus plus) {
genCode(plus.getLeft());
genCode(plus.getRight());
System.out.println("add");
}
public void visit(Sub sub) {
genCode(sub.getLeft());
genCode(sub.getRight());
System.out.println("sub");
}
public void genCode(Expr expr) {
expr.accept(this);
}
}
49. Visitor pattern: structure
Source: “Design Patterns: Elements of Reusable Object-Oriented Software”, Erich Gamma, Richard Helm, Ralph Johnson and John Vlissides, Addison-Wesley,1994
50. Visitor pattern: call sequence
Source: “Design Patterns: Elements of Reusable Object-Oriented Software”, Erich Gamma, Richard Helm, Ralph Johnson and John Vlissides, Addison-Wesley,1994
51. Visitor pattern: Discussion
❖ Many distinct and unrelated
operations need to be
performed on objects in an
object structure, and you want
to avoid “polluting” their
classes with these operations
Represent an operation to be performed on the elements of an object structure.
Visitor lets you define a new operation without changing the classes of the
elements on which it operations
❖ Create two class
hierarchies:
❖ One for the elements
being operated on
❖ One for the visitors that
define operations on the
elements
54. Real scenario #1
❖ How will you refactor such
that:
❖ A specific DES, AES, TDES,
… can be “plugged” at
runtime?
❖ Reuse these algorithms in
new contexts?
❖ Easily add support for new
algorithms in Encryption?
Next change:
smelly design
61. Strategy pattern: Discussion
❖ Useful when there is a set of
related algorithms and a client
object needs to be able to
dynamically pick and choose
an algorithm that suits its
current need
Defines a family of algorithms, encapsulates each one, and makes
them interchangeable. Strategy lets the algorithm vary
independently from clients that use it
❖ The implementation of each of the
algorithms is kept in a separate
class referred to as a strategy.
❖ An object that uses a Strategy
object is referred to as a context
object.
❖ Changing the behavior of a
Context object is a matter of
changing its Strategy object to the
one that implements the required
algorithm
69. Open Closed Principle (OCP)
Bertrand Meyer
Software entities should be open for
extension, but closed for modification
70. Variation Encapsulation Principle (VEP)
Erich Gamma, Richard Helm, Ralph Johnson and John Vlissides
Encapsulate the concept that varies
71. Fundamental principle: Encapsulation
The principle of encapsulation advocates separation of concerns and
information hiding through techniques such as hiding implementation
details of abstractions and hiding variations
78. Real scenario
Source: “Design Patterns: Elements of Reusable Object-Oriented Software”, Erich Gamma, Richard Helm, Ralph Johnson and John Vlissides, Addison-Wesley,1994
80. Real scenario
❖ How will you refactor such
that:
❖ You don't have to “multiply-
out” sub-types? (i.e., avoid
“explosion of classes”)
❖ Add or remove
responsibilities (e.g.,
scrolling) at runtime?
Next change:
smelly design
81. How about this solution?
VisualComponent
+ Draw()
TextView
+ Draw()
ScrollDecortor BorderDecorator
+ Draw()
+ ScrollTo()
- ScrollPosition
+ Draw()
+ DrawBorder()
- borderWidth
Decorator
+ Draw() component->Draw()
Decorator::Draw()
DrawBorder()
Decorator::Draw()
ScrollTo()
Source: “Design Patterns: Elements of Reusable Object-Oriented Software”, Erich Gamma, Richard Helm, Ralph Johnson and John Vlissides, Addison-Wesley,1994
82. At runtime (object diagram)
Source: “Design Patterns: Elements of Reusable Object-Oriented Software”, Erich Gamma, Richard Helm, Ralph Johnson and John Vlissides, Addison-Wesley,1994
83. Can you identify the pattern?
VisualComponent
+ Draw()
TextView
+ Draw()
ScrollDecortor BorderDecorator
+ Draw()
+ ScrollTo()
- ScrollPosition
+ Draw()
+ DrawBorder()
- borderWidth
Decorator
+ Draw() component->Draw()
Decorator::Draw()
DrawBorder()
Decorator::Draw()
ScrollTo()
Source: “Design Patterns: Elements of Reusable Object-Oriented Software”, Erich Gamma, Richard Helm, Ralph Johnson and John Vlissides, Addison-Wesley,1994
84. You’re right: Its Decorator pattern!
Source: “Design Patterns: Elements of Reusable Object-Oriented Software”, Erich Gamma, Richard Helm, Ralph Johnson and John Vlissides, Addison-Wesley,1994
85. Decorator pattern: Discussion
❖ Want to add responsibilities to
individual objects (not an
entire class)
❖ One way is to use inheritance
❖ Inflexible; static choice
❖ Hard to add and remove
responsibilities dynamically
Attach additional responsibilities to an object dynamically. Decorators
provide a flexible alternative to subclassing for extending functionality
❖ Add responsibilities through
decoration
❖ in a way transparent to the
clients
❖ Decorator forwards the requests to
the contained component to
perform additional actions
❖ Can nest recursively
❖ Can add an unlimited number
of responsibilities dynamically
86. Identify pattern used in this code
LineNumberReader lnr =
new LineNumberReader(
new BufferedReader(
new FileReader(“./test.c")));
String str = null;
while((str = lnr.readLine()) != null)
System.out.println(lnr.getLineNumber() + ": " + str);
90. Composite pattern
Source: “Design Patterns: Elements of Reusable Object-Oriented Software”, Erich Gamma, Richard Helm, Ralph Johnson and John Vlissides, Addison-Wesley,1994
91. Composite pattern: Discussion
❖ There are many situations where
a group of components form
larger components
❖ Simplistic approach: Make
container component contain
primitive ones
❖ Problem: Code has to treat
container and primitive
components differently
Compose objects into tree structures to represent part-whole hierarchies. Composite
lets client treat individual objects and compositions of objects uniformly.
❖ Perform recursive
composition of
components
❖ Clients don’t have to
treat container and
primitive components
differently
92. Decorator vs. Composite
Decorator and composite structure looks similar:
Decorator is a degenerate form of Composite!
Decorator Composite
At max. one component Can have many components
Adds responsibilities Aggregates objects
Does not make sense to have
methods such as Add(),
Remove(), GetChid() etc.
Has methods such as Add(),
Remove(), GetChild(), etc.
108. How java.util.Date violates ISP
// using java.util.Date
Date today = new Date();
System.out.println(today);
$ java DateUse
Wed Dec 02 17:17:08 IST 2015
Why should we get the
time and timezone details
if I only want a date? Can
I get rid of these parts?
No!
110. How java.time API follows ISP
// using java.time.LocalDate
LocalDate today = LocalDate.now();
System.out.println(today);
$ java DateUse
2015-12-02
I can use (and hence
depend upon) only date
related functionality (not
time, zone, etc)
111. How java.time API follows ISP
You can use only date,
time, or even timezone,
and combine them as
needed!
LocalDate today = LocalDate.now();
System.out.println(today);
LocalTime now = LocalTime.now();
System.out.println(now);
LocalDateTime todayAndNow = LocalDateTime.now();
System.out.println(todayAndNow);
ZonedDateTime todayAndNowInTokyo = ZonedDateTime.now(ZoneId.of("Asia/Tokyo"));
System.out.println(todayAndNowInTokyo);
2015-12-02
17:37:22.647
2015-12-02T17:37:22.648
2015-12-02T21:07:22.649+09:00[Asia/Tokyo]
113. How about this one?
public interface MouseListener extends EventListener {
/**
* Invoked when the mouse button has been clicked (pressed
* and released) on a component.
*/
public void mouseClicked(MouseEvent e);
/**
* Invoked when a mouse button has been pressed on a component.
*/
public void mousePressed(MouseEvent e);
/**
* Invoked when a mouse button has been released on a component.
*/
public void mouseReleased(MouseEvent e);
/**
* Invoked when the mouse enters a component.
*/
public void mouseEntered(MouseEvent e);
/**
* Invoked when the mouse exits a component.
*/
public void mouseExited(MouseEvent e);
}
114. Dependency Inversion Principle (DIP)
A. High level modules should not depend upon low level modules.
Both should depend upon abstractions.
B. Abstractions should not depend upon details. Details should depend
upon abstractions.
125. Applying DIP in OO Design
Use references to interfaces/abstract classes as fields members, as
argument types and return types
Do not derive from concrete classes
Use creational patterns such as factory method and abstract factory
for instantiation
Do not have any references from base classes to its derived classes
126. Applying principles in practice
Principle
Violating
principles
Adherence to
principles
Refactoring
Bad design
(with smells)
Good design
(with patterns)