Interface in java ,multiple inheritance in java, interface implementationHoneyChintal
multiple inheritance in java, interface implementation, abstraction,
multiple inheritance in java using interface, how to use interface,
how to use java, how to execute a java code
Http4s, Doobie and Circe: The Functional Web StackGaryCoady
Http4s, Doobie and Circe together form a nice platform for building web services. This presentations provides an introduction to using them to build your own service.
Interface in java ,multiple inheritance in java, interface implementationHoneyChintal
multiple inheritance in java, interface implementation, abstraction,
multiple inheritance in java using interface, how to use interface,
how to use java, how to execute a java code
Http4s, Doobie and Circe: The Functional Web StackGaryCoady
Http4s, Doobie and Circe together form a nice platform for building web services. This presentations provides an introduction to using them to build your own service.
Every value in Java has a data type. Java supports two kinds of data types: primitive data types and reference data types. Primitive data types represent atomic, indivisible values. Java has eight Numeric data types: byte, short, int,
An operator is a symbol that is used to perform some type of computation on its operands. Java contains a rich set of
operators. Operators are categorized as unary, binary, or ternary based on the number of operands they take. They are categorized as arithmetic, relational, logical, etc. based on the operation they perform on their operands.
long, float, double, char, and boolean. Literals of primitive data types are constants. Reference data types represent
references of objects in memory. Java is a statically typed programming language. That is, it checks the data types of all values at compile time.
Abstraction is a process by which concepts are derived from the usage and classification of literal ("real" or "concrete") concepts.
Abstraction is a concept that acts as a super-categorical noun for all subordinate concepts, and connects any related concepts as a group, field, or category.
A Separation of Concerns: Clean Architecture on AndroidOutware Mobile
Presented at YOW! Connected 2015 by Kamal Kamal Mohamed & Ryan Hodgman
As an Android developer, I want to deliver features without making compromises on code quality.
Scenario 1 - Given I am dealing with 1000+ line activities, When I have to develop a complicated feature, Then I waste time orienting myself and fixing bugs.
Scenario 2 - Given I have integrated a backend API directly into my app logic, When that API changes, Then I have to refactor large segments of unrelated logic in order to utilise the new API.
Scenario 3 - Given I have cleanly architected my application, When business/presentation/backend logic changes, Then I can easily update the relevant code without breaking unrelated features!
In this talk, two Android developers will present their take on what a cleanly architected app looks like and why it makes our lives easier. A well-defined separation of concerns has benefits not just for our sanity as developers, but also for the project workflow as it allows multiple developers to collaborate on a single feature with ease. We will be exploring how the domain-driven approach can improve code clarity, allow you to easily write tests, and provide a scalable infrastructure for you to quickly iterate on. Join us on our path of discovery as we discuss the advantages, drawbacks and implementation specifics in the context of a small sample project.
Every value in Java has a data type. Java supports two kinds of data types: primitive data types and reference data types. Primitive data types represent atomic, indivisible values. Java has eight Numeric data types: byte, short, int,
An operator is a symbol that is used to perform some type of computation on its operands. Java contains a rich set of
operators. Operators are categorized as unary, binary, or ternary based on the number of operands they take. They are categorized as arithmetic, relational, logical, etc. based on the operation they perform on their operands.
long, float, double, char, and boolean. Literals of primitive data types are constants. Reference data types represent
references of objects in memory. Java is a statically typed programming language. That is, it checks the data types of all values at compile time.
Abstraction is a process by which concepts are derived from the usage and classification of literal ("real" or "concrete") concepts.
Abstraction is a concept that acts as a super-categorical noun for all subordinate concepts, and connects any related concepts as a group, field, or category.
A Separation of Concerns: Clean Architecture on AndroidOutware Mobile
Presented at YOW! Connected 2015 by Kamal Kamal Mohamed & Ryan Hodgman
As an Android developer, I want to deliver features without making compromises on code quality.
Scenario 1 - Given I am dealing with 1000+ line activities, When I have to develop a complicated feature, Then I waste time orienting myself and fixing bugs.
Scenario 2 - Given I have integrated a backend API directly into my app logic, When that API changes, Then I have to refactor large segments of unrelated logic in order to utilise the new API.
Scenario 3 - Given I have cleanly architected my application, When business/presentation/backend logic changes, Then I can easily update the relevant code without breaking unrelated features!
In this talk, two Android developers will present their take on what a cleanly architected app looks like and why it makes our lives easier. A well-defined separation of concerns has benefits not just for our sanity as developers, but also for the project workflow as it allows multiple developers to collaborate on a single feature with ease. We will be exploring how the domain-driven approach can improve code clarity, allow you to easily write tests, and provide a scalable infrastructure for you to quickly iterate on. Join us on our path of discovery as we discuss the advantages, drawbacks and implementation specifics in the context of a small sample project.
A 1-day course notes on practising functional programming in Java 8. Coding examples can be downloaded from https://sites.google.com/site/omarbashirsite/home/library/functional-programming-in-java-8.
Cloud migration challenges london ct osOmar Bashir
Approaching a cloud migration like a traditional technology project is fraught with risks. Businesses wish to migrate to cloud to reap certain benefits. A successful migration approach uses strategies and practices that target those benefits and and enhance confidence along the way. This talk ends with 4 key principles that help cloud migration initiatives align with the business objectives.
5 Software Development Lessons From a MountaineerOmar Bashir
What could be common between software development and mountaineering? A lot actually. A mountaineer may not teach a programmer coding skills and practices. But they can inspire discipline, personal management and team building that enhance productivity, motivation and well being.
Java has undergone considerable change in the past few years to add features that make it more versatile when compared with other JVM based languages. It still has challenges but its flexible style makes it more inclusive to programmers with different abilities. Hence, it remains the most widely used programming language.
Discussing this with other speakers at the JVM Wars organised by Orbis Consultants last week was illuminating. Key takeaways,
1. Frameworks are not the language. If a certain framework makes a language restrictive or unusable, its not the fault of the language. Choose a better framework or work without frameworks.
2. Choose languages and frameworks that help solve business problems intuitively.
3. Be more inclusive with the choice and use of languages, frameworks and tools.
Agility is the ability of an organisation to respond to evolving business landscape thus avoiding disruption. A technology enabled business may not achieve this responsiveness if business concepts do not align with representations in technology implementation. Domain Driven Design (DDD) achieves a closer alignment between business concepts and technology implementation, independence between domain model and infrastructure and independence between teams working on different subsystems. Functional software built using DDD is mapped to an architecture that supports NFRs (Non-Functional Requirements) of the system. System NFRs also evolve with the passage of time requiring architectural changes to achieve emerging qualities. A functional design that is loosely coupled with the underlying architecture will significantly reduce the refactoring effort associated with the architectural changes. This talk discusses how DDD localises impact of changes thus enhancing organisational agility in disruptive environments.
The ability to deliver software to production speedily and reliably is critical to supporting a disruptive business landscape and covering implementation gaps. A key factor inhibiting this is testing. DevOps practices encourage shifting left, i.e., testing more during development using unit and component test rather than with QA using end-to-end tests. However, unit and component testing lack functional coverage that may exist in QA end-to-end tests. Shifting left with a domain focus may lead to component and unit tests that don't just guarantee that the software is built right but also that the right software is build.
One of the main objectives of agile software development is to respond to emerging user requirements in a timely manner to ensure that business retains their competitive advantage.
Agile processes and frameworks alone cannot ensure this. The technology in development or supporting the business needs to be flexible and extensible to support emerging business requirements.
These slides describe a framework that developers and architects can employ to achieve technological agility.
For more details, please see https://www.linkedin.com/pulse/achieving-technological-agility-deliver-business-omar-bashir/
Technical debt is difficult to quantify and estimate as a single metric. Optimising on convential metrics based on code quality, testability and defect trends can keep technical debt in control. But accepting technical debt leads to side effects which may provide more realistic metrics of technical debt.
Distilling Agile for Effective ExecutionOmar Bashir
The objective of agility in software is to fulfill evolving customer requirements while delivering high quality software on time and within budget. A number of agile methodologies have been developed promising to achieve this objective. But their adoption has proven to be challenging leading to cargo culting and bikeshedding practices that challenge project success. A review of Agile Manifesto and principles of agile methodologies distills them into 3 fundamental components. This talk suggests that a disciplined pursuit of these fundamentals while adopting agile practices increases an organisation’s chances of success.
Reduction is key to agility. It is of fundamental consequence to not just iteration planning and execution but in all aspects of project execution. Smaller stories simplify estimation, implementation and pivoting in addition to reducing intra-team dependencies. Smaller merge sizes reduce risk of merge conflicts and enable focused reviews leading to better code quality. Fewer technical dependencies make software flexible. Fewer inter-team and intra-team dependencies increase flow. Finally smaller team sizes focused on features and functionality enhance team cohesion and reduce inter-team dependencies.
Focus ensures that teams’ eyes are on the prize. Sprints need to be thematic focused on delivering end-to-end features that can be demonstrated to customers to obtain and act on feedback. Large features may not be completely delivered in a single sprint. In such cases, sprints may be grouped into packages which incrementally deliver features. Hence packages, unlike sprints, may not all be of the same length but all sprints within a package must focus on incremental completion of a feature. Cross functional teams tend to deliver end to end features better than technology specialist teams.
Finally, visibility is essential for teams to review their progress and make arrangement to reduce risks. It is important to create necessary and useful information radiators for the team members. These include sprint dashboards showing the progress on stories, burndown charts and defect trends. Additionally RAID (Risks, Assumptions, Issues and Dependencies) logs and dependency matrices highlight risks that teams face in achieving their targets.
Authorisation: Concepts and ImplementationOmar Bashir
Slides from the workshop on Authorisation at LJC's (London Java Community) Workshop Day on 28 July 2018.
The workshop was aimed at intermediate and skilled Java developers who are interested in learning about information security in general and authorisation in particular.
The workshop starts with an introduction to authorisation and explains the difference between authorisation and authentication, which is often misunderstood. Apache Shiro, an open source Java security framework is then introduced with a focus on its authorisation features. This is followed by a hands-on coding exercise involving the use of Shiro to secure a simple console application. Introduction to an extension to Shiro’s domain model is presented which can facilitate application domain level authorisation abstractions like application licensing, compound entitlements etc.
Slides of a talk delivered to primary school children on how programming helps people in their work and their daily lives.
The 15 minute talk explains why computers are better at certain tasks but lack intelligence. Hence humans have to describe tasks that need done as lists of instructions that computers can perform repetitively without getting tired or bored.
The talk ends with a personal introduction on how I got into programming and how it has enriched my life personally and professionally.
High Speed Networks - Applications in FinanceOmar Bashir
Speed and agility in finance and banking is essential in executing a successful trade. In modern banking systems, including algorithmic and high frequency trading platforms, high speed networks communicate timely market data and liquidity information and carry execution instructions to trading venues and counterparties. Suboptimal networks, protocol stacks and applications can easily result in a financial impact when execution instructions are delayed or are based on stale market data.
This talk suggest optimisation opportunities in computer networks and introduces performant banking systems.
Computing at Schools: A Guide to ParentsOmar Bashir
Computing has been introduced as a mainstream subject in primary and secondary schools in the UK. This presentation is a guide to the parents on the broader subject, the curriculum and how they can contribute to its education at home and in the community.
I gave a talk to year 8 students on the applicability of programming in maths. The talk introduced to them how computers interpreted and executed programs with an example in BASIC performing simple arithmetic operations and an example in Python calculating the average of a list of numbers.
Lightening talk delivered at the Code Club Christmas Meet up, London 2014. Discusses the new computing curriculum being taught in primary schools in England and the challenges being faced in implementing it.
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.
Globus Connect Server Deep Dive - GlobusWorld 2024Globus
We explore the Globus Connect Server (GCS) architecture and experiment with advanced configuration options and use cases. This content is targeted at system administrators who are familiar with GCS and currently operate—or are planning to operate—broader deployments at their institution.
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/
Enhancing Research Orchestration Capabilities at ORNL.pdfGlobus
Cross-facility research orchestration comes with ever-changing constraints regarding the availability and suitability of various compute and data resources. In short, a flexible data and processing fabric is needed to enable the dynamic redirection of data and compute tasks throughout the lifecycle of an experiment. In this talk, we illustrate how we easily leveraged Globus services to instrument the ACE research testbed at the Oak Ridge Leadership Computing Facility with flexible data and task orchestration capabilities.
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
Introducing Crescat - Event Management Software for Venues, Festivals and Eve...Crescat
Crescat is industry-trusted event management software, built by event professionals for event professionals. Founded in 2017, we have three key products tailored for the live event industry.
Crescat Event for concert promoters and event agencies. Crescat Venue for music venues, conference centers, wedding venues, concert halls and more. And Crescat Festival for festivals, conferences and complex events.
With a wide range of popular features such as event scheduling, shift management, volunteer and crew coordination, artist booking and much more, Crescat is designed for customisation and ease-of-use.
Over 125,000 events have been planned in Crescat and with hundreds of customers of all shapes and sizes, from boutique event agencies through to international concert promoters, Crescat is rigged for success. What's more, we highly value feedback from our users and we are constantly improving our software with updates, new features and improvements.
If you plan events, run a venue or produce festivals and you're looking for ways to make your life easier, then we have a solution for you. Try our software for free or schedule a no-obligation demo with one of our product specialists today at crescat.io
In the ever-evolving landscape of technology, enterprise software development is undergoing a significant transformation. Traditional coding methods are being challenged by innovative no-code solutions, which promise to streamline and democratize the software development process.
This shift is particularly impactful for enterprises, which require robust, scalable, and efficient software to manage their operations. In this article, we will explore the various facets of enterprise software development with no-code solutions, examining their benefits, challenges, and the future potential they hold.
Atelier - Innover avec l’IA Générative et les graphes de connaissancesNeo4j
Atelier - Innover avec l’IA Générative et les graphes de connaissances
Allez au-delà du battage médiatique autour de l’IA et découvrez des techniques pratiques pour utiliser l’IA de manière responsable à travers les données de votre organisation. Explorez comment utiliser les graphes de connaissances pour augmenter la précision, la transparence et la capacité d’explication dans les systèmes d’IA générative. Vous partirez avec une expérience pratique combinant les relations entre les données et les LLM pour apporter du contexte spécifique à votre domaine et améliorer votre raisonnement.
Amenez votre ordinateur portable et nous vous guiderons sur la mise en place de votre propre pile d’IA générative, en vous fournissant des exemples pratiques et codés pour démarrer en quelques minutes.
Need for Speed: Removing speed bumps from your Symfony projects ⚡️Łukasz Chruściel
No one wants their application to drag like a car stuck in the slow lane! Yet it’s all too common to encounter bumpy, pothole-filled solutions that slow the speed of any application. Symfony apps are not an exception.
In this talk, I will take you for a spin around the performance racetrack. We’ll explore common pitfalls - those hidden potholes on your application that can cause unexpected slowdowns. Learn how to spot these performance bumps early, and more importantly, how to navigate around them to keep your application running at top speed.
We will focus in particular on tuning your engine at the application level, making the right adjustments to ensure that your system responds like a well-oiled, high-performance race car.
Providing Globus Services to Users of JASMIN for Environmental Data AnalysisGlobus
JASMIN is the UK’s high-performance data analysis platform for environmental science, operated by STFC on behalf of the UK Natural Environment Research Council (NERC). In addition to its role in hosting the CEDA Archive (NERC’s long-term repository for climate, atmospheric science & Earth observation data in the UK), JASMIN provides a collaborative platform to a community of around 2,000 scientists in the UK and beyond, providing nearly 400 environmental science projects with working space, compute resources and tools to facilitate their work. High-performance data transfer into and out of JASMIN has always been a key feature, with many scientists bringing model outputs from supercomputers elsewhere in the UK, to analyse against observational or other model data in the CEDA Archive. A growing number of JASMIN users are now realising the benefits of using the Globus service to provide reliable and efficient data movement and other tasks in this and other contexts. Further use cases involve long-distance (intercontinental) transfers to and from JASMIN, and collecting results from a mobile atmospheric radar system, pushing data to JASMIN via a lightweight Globus deployment. We provide details of how Globus fits into our current infrastructure, our experience of the recent migration to GCSv5.4, and of our interest in developing use of the wider ecosystem of Globus services for the benefit of our user community.
Understanding Nidhi Software Pricing: A Quick Guide 🌟
Choosing the right software is vital for Nidhi companies to streamline operations. Our latest presentation covers Nidhi software pricing, key factors, costs, and negotiation tips.
📊 What You’ll Learn:
Key factors influencing Nidhi software price
Understanding the true cost beyond the initial price
Tips for negotiating the best deal
Affordable and customizable pricing options with Vector Nidhi Software
🔗 Learn more at: www.vectornidhisoftware.com/software-for-nidhi-company/
#NidhiSoftwarePrice #NidhiSoftware #VectorNidhi
Custom Healthcare Software for Managing Chronic Conditions and Remote Patient...Mind IT Systems
Healthcare providers often struggle with the complexities of chronic conditions and remote patient monitoring, as each patient requires personalized care and ongoing monitoring. Off-the-shelf solutions may not meet these diverse needs, leading to inefficiencies and gaps in care. It’s here, custom healthcare software offers a tailored solution, ensuring improved care and effectiveness.
Climate Science Flows: Enabling Petabyte-Scale Climate Analysis with the Eart...Globus
The Earth System Grid Federation (ESGF) is a global network of data servers that archives and distributes the planet’s largest collection of Earth system model output for thousands of climate and environmental scientists worldwide. Many of these petabyte-scale data archives are located in proximity to large high-performance computing (HPC) or cloud computing resources, but the primary workflow for data users consists of transferring data, and applying computations on a different system. As a part of the ESGF 2.0 US project (funded by the United States Department of Energy Office of Science), we developed pre-defined data workflows, which can be run on-demand, capable of applying many data reduction and data analysis to the large ESGF data archives, transferring only the resultant analysis (ex. visualizations, smaller data files). In this talk, we will showcase a few of these workflows, highlighting how Globus Flows can be used for petabyte-scale climate analysis.
OpenMetadata Community Meeting - 5th June 2024OpenMetadata
The OpenMetadata Community Meeting was held on June 5th, 2024. In this meeting, we discussed about the data quality capabilities that are integrated with the Incident Manager, providing a complete solution to handle your data observability needs. Watch the end-to-end demo of the data quality features.
* How to run your own data quality framework
* What is the performance impact of running data quality frameworks
* How to run the test cases in your own ETL pipelines
* How the Incident Manager is integrated
* Get notified with alerts when test cases fail
Watch the meeting recording here - https://www.youtube.com/watch?v=UbNOje0kf6E
Quarkus Hidden and Forbidden ExtensionsMax Andersen
Quarkus has a vast extension ecosystem and is known for its subsonic and subatomic feature set. Some of these features are not as well known, and some extensions are less talked about, but that does not make them less interesting - quite the opposite.
Come join this talk to see some tips and tricks for using Quarkus and some of the lesser known features, extensions and development techniques.
2. Coding Humanely
● What if our code had feelings ?
● What if we treated people like we treat code ?
– e.g., Sir, you will need a foot transplant to be able to
use our latest range of trainers.
3. Desirable Code Qualities
● Simplicity
– Ease of understanding.
● Extensibility
– Ease of extending functionality.
● Flexibility
– Ease of adapting to the operating environment.
● Testability
– Ease of testing from units of code to the entire
systems
4. Challenges: Size and Complexity
● Problems
– Most real world problems requiring automation are
complex.
● Requirements
– Increasing demand for comprehensive automation.
● Solutions
– Resulting solutions are large and sophisticated.
5.
6. Modularisation
● Decomposing large systems into smaller and
simpler parts.
– Functions and procedures.
– Classes and modules.
● Building the parts.
● Assembling the parts to complete the system.
● To achieve desirable code qualities parts should
be interchangeable.
7. Keys to Interchangeability
● Coupling
– Interdependence between different software modules.
– Low coupling is preferred as it allows flexibility and
extensibility.
– Low coupling via simple and stable interfaces.
● Cohesion
– Degree to which elements of a module functionally
belong together.
– Higher cohesion reduces complexity of components.
● Higher cohesion and low coupling enables
interchangeability.
8. Spot Issues ?
package app;
import calc.Calculator;
public class App {
public static void main(String[] args) {
String line = System.console().readLine();
String[] parts = line.split(" ");
Calculator.operand1 = Double.parseDouble(parts[0]);
Calculator.operator = parts[1].charAt(0);
Calculator.operand2 = Double.parseDouble(parts[2]);
Calculator.calculate();
}
}
9. Spot Issues ?
package app;
import calc.Calculator;
public class App {
public static void main(String[] args) {
String line = System.console().readLine();
String[] parts = line.split(" ");
Calculator.operand1 = Double.parseDouble(parts[0]);
Calculator.operator = parts[1].charAt(0);
Calculator.operand2 = Double.parseDouble(parts[2]);
Calculator.calculate();
}
}
High Coupling
10. Spot Issues ?
package calc;
public class Calculator {
public static double operand1;
public static double operand2;
public static char operator;
public static void calculate() {
double result = Double.NaN;
switch(operator) {
case '+':
result = operand1 + operand2;
break;
case '-':
result = operand1 - operand2;
break;
case '*':
result = operand1 * operand2;
break;
case '/':
result = operand1 / operand2;
break;
default:
System.out.printf("Unrecognised operator %cn", operator);
}
System.out.printf("%f %c %f = %fn",
operand1, operator, operand2, result);
}
}
11. Spot Issues
package calc;
public class Calculator {
public static double operand1;
public static double operand2;
public static char operator;
public static void calculate() {
double result = Double.NaN;
switch(operator) {
case '+':
result = operand1 + operand2;
break;
case '-':
result = operand1 - operand2;
break;
case '*':
result = operand1 * operand2;
break;
case '/':
result = operand1 / operand2;
break;
default:
System.out.printf("Unrecognised operator %cn", operator);
}
System.out.printf("%f %c %f = %fn",
operand1, operator, operand2, result);
}
}
High Coupling
Low Cohesion
12. Simplifying with SOLID
● Types of coupling
– Content coupling, Common coupling, Stamp coupling,
Control coupling, Data coupling.
● Types of cohesion
– Co-incidental cohesion, Logical cohesion, Temporal
cohesion, Procedural cohesion, Communicational
cohesion, Sequential cohesion, Functional cohesion.
● SOLID
– Five principles of object oriented programming.
– Aims to deliver extensible and maintainable software.
13. SOLID
● Single Responsibility Principle (SRP)
– A class should have a single responsibility.
● Open Close Principle (OCP)
– Open for extension but closed for modification.
● Liskov Substitution Principle (LSP)
– Substitution of objects by instances of sub-classes.
● Interface Segregation Principle (ISP)
– Many client specific interfaces instead of one big one.
● Dependency Inversion Principle (DIP)
– Depend on abstractions instead of implementations.
15. Single Responsibility Principle
● A class should have one and only one reason
to change.
– A class should have only one responsibility.
● Promotes high cohesion and low coupling.
– High cohesion because of focused classes.
– Low coupling because of dependency on other
cohesive classes.
16. Example
public class MeanCalculator {
public double calculate(final String data) {
double sum = 0.0;
final String[] parsedData = data.split(",");
for (String item : parsedData) {
sum += Double.parseDouble(item);
}
return sum/parsedData.length;
}
}
17. Example
public class MeanCalculator {
public double calculate(final String data) {
double sum = 0.0;
final String[] parsedData = data.split(",");
for (String item : parsedData) {
sum += Double.parseDouble(item);
}
return sum/parsedData.length;
}
}
18. Example
public class MeanCalculator {
public double calculate(final String data) {
double sum = 0.0;
final String[] parsedData = data.split(",");
for (String item : parsedData) {
sum += Double.parseDouble(item);
}
return sum/parsedData.length;
}
}
Two reasons to change
1. Parsing
2. Computation
19. Example
Functional (Java 8) Implementation
public class MeanCalculator {
public double calculate(final List<Double> data) {
double sum = 0.0;
for (Double item : data) {
sum += item;
}
return sum/data.size();
}
}
public class MeanCalculator {
public double calculate(final List<Double> data) {
return data.
stream().
collect(Collectors.
averagingDouble(item -> item));
}
}
21. Open/Close Principle
● Software entities (Classes, methods, modules
etc.) should be open for extension but closed
for modification.
– Changing functionality need not require modifying
existing code.
● Preferred approaches,
– Inheritance,
– Composition of abstractions (plugins).
22. Example
public class Parser {
List<Double> parse(final String data) {
final String[] parsedCsv = data.split(",");
return toDoubleList(parsedCsv);
}
private List<Double> toDoubleList(final String[] data) {
final List<Double> list = new ArrayList<>();
for(String item: data) {
list.add(Double.parseDouble(item));
}
return list;
}
}
23. Example:Extendinga
ClosedParser
public class Parser {
public List<Double> parse(final String data, final Format format) {
String[] parsedData = null;
switch(format){
case CSV:
parsedData = data.split(",");
break;
case XML:
try {
parsedData = parseXml(data);
} catch (Exception exp) {
throw new IllegalArgumentException(exp);
}
break;
default:
throw new IllegalArgumentException(String.format("Unknown format %s", format));
}
return toDoubleList(parsedData);
}
/**
* Format: <DataList><Item>3</Item><Item>4.5</Item><Item>7.5</Item></DataList>
*/
private String[] parseXml(final String xmlString) throws Exception {
final Document xmlDoc = DocumentBuilderFactory.
newInstance().
newDocumentBuilder().
parse(new ByteArrayInputStream(xmlString.getBytes()));
final NodeList nodes = xmlDoc.getElementsByTagName("Item");
final String[] textList = new String[nodes.getLength()];
for (int i = 0; i < nodes.getLength(); i++) {
textList[i] = nodes.item(i).getTextContent().trim();
}
return textList;
}
private List<Double> toDoubleList(final String[] data) {
final List<Double> list = new ArrayList<>();
for(String item: data) {
list.add(Double.parseDouble(item));
}
return list;
}
}
24. public List<Double> parse(final String data,
final Format format) {
String[] parsedData = null;
switch(format){
case CSV:
parsedData = data.split(",");
break;
case XML:
try {
parsedData = parseXml(data);
} catch (Exception exp) {
throw new IllegalArgumentException(exp);
}
break;
default:
throw new IllegalArgumentException(
String.format("Unknown format %s", format));
}
25. Example: Opening With Template
Method
public abstract class Parser {
public List<Double> parse(final String data) {
final String[] parsedData = split(data);
return toDoubleList(parsedData);
}
protected abstract String[] split(final String data);
private List<Double> toDoubleList(final String[] data) {
final List<Double> list = new ArrayList<>();
for(String item: data) {
list.add(Double.parseDouble(item));
}
return list;
}
}
26. Example: Parser Using Streams
public abstract class Parser {
public List<Double> parse(final String data) {
final String[] parsedData = split(data);
return Arrays.asList(parsedData).stream().
map(item -> Double.parseDouble(item)).
collect(Collectors.toList());
}
protected abstract String[] split(final String data);
}
27. Example: Opening With Template
Method
public class CsvParser extends Parser {
@Override
protected String[] split(String data) {
return data.split(",");
}
}
28. public class XmlParser extends Parser {
/**
* Format:
* <DataList><Item>3</Item><Item>4.5</Item><Item>7.5</Item></DataList>
*/
@Override
protected String[] split(String data) {
String[] textList = null;
try {
final Document xmlDoc = DocumentBuilderFactory.
newInstance().
newDocumentBuilder().
parse(new ByteArrayInputStream(data.getBytes()));
final NodeList nodes = xmlDoc.getElementsByTagName("Item");
textList = new String[nodes.getLength()];
for (int i = 0; i < nodes.getLength(); i++) {
textList[i] = nodes.item(i).getTextContent().trim();
}
} catch (Exception exp) {
throw new IllegalArgumentException(exp);
}
return textList;
}
}
30. Liskov Substitution Principle
● Named after MIT professor Barbara Liskov.
● Functions that use references to base classes
must be able to use objects of the derived class
without knowing it.
– Derived classes must be substitutable for base class.
● Caution,
– Should not alter the behaviour of the application.
– Inheritance hierarchies should not violate domain
concepts.
● E.g., a square is a rectangle instead of both are shapes.
31. public class AvergerApp {
public static void main(String[] args) {
final List<String> params = Arrays.asList(args);
if ((params.size() != 2) ||
(params.stream().filter(i -> i.contains("=")).count() != 2)) {
System.err.println("Parameters: f=<CSV/XML> m=<message>");
} else {
final String format = params.stream().
filter(str -> str.contains("f")).findFirst().get().split("=")[1];
final String message = params.stream().
filter(str -> str.contains("m")).findFirst().get().split("=")[1];
final Parser parser = getParser(format);
final List<Double> data = parser.parse(message);
final double avg = new MeanCalculator().calculate(data);
System.out.printf("Average(%s) = %f", data, avg);
}
}
private static Parser getParser(final String format) {
Parser parser = null;
switch (format) {
case "CSV":
parser = new CsvParser();
break;
case "XML":
parser = new XmlParser();
break;
default:
throw new IllegalArgumentException("Unknown format " + format));
}
return parser;
}
}
32. public class AvergerApp {
public static void main(String[] args) {
final List<String> params = Arrays.asList(args);
if ((params.size() != 2) ||
(params.stream().filter(i -> i.contains("=")).count() != 2)) {
System.err.println("Parameters: f=<CSV/XML> m=<message>");
} else {
final String format = params.stream().
filter(str -> str.contains("f")).findFirst().get().split("=")[1];
final String message = params.stream().
filter(str -> str.contains("m")).findFirst().get().split("=")[1];
final Parser parser = getParser(format);
final List<Double> data = parser.parse(message);
final double avg = new MeanCalculator().calculate(data);
System.out.printf("Average(%s) = %f", data, avg);
}
}
private static Parser getParser(final String format) {
Parser parser = null;
switch (format) {
case "CSV":
parser = new CsvParser();
break;
case "XML":
parser = new XmlParser();
break;
default:
throw new IllegalArgumentException("Unknown format " + format));
}
return parser;
}
}
34. Interface Segragation Principle
● Multiple fine grained client or domain specific
interfaces are better than few coarse grained
interfaces.
● Consequences
– Classes only implement interfaces that are
requirement specific.
– Client classes are exposed only to the functionality
that they need.
40. Dependency Inversion Principle
● 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.
● Dependencies are a risk,
– Details bind dependants to concrete implementations.
● This limits flexibility and extensibility.
– Abstractions provides independence to dependants.
● Dependants are able to select most suitable
implementations.
41. Example: Averaging Calculator
● A class that uses
– An averaging algorithm to process input.
– A parser to parse text input to a collection of doubles.
– Input and output classes.
● Input formats can change.
– Binding the calculator to a concrete parser and IO
makes it inflexible.
– Averaging calculator references a parser, an input and
an output interface.
– The application specifies the parser and IO needed.
42. Example: Parser
public interface IParser {
List<Double> parse(final String data);
}
public abstract class Parser implements IParser {
public List<Double> parse(final String data) {
final String[] parsedData = split(data);
return Arrays.asList(parsedData).stream().
map(item -> Double.parseDouble(item)).
collect(Collectors.toList());
}
protected abstract String[] split(final String data);
}
43. Example: Input
public interface IInput {
String read();
}
public class FixedInput implements IInput {
private final String data;
public FixedInput(final String data) {
this.data = data;
}
@Override
public String read() {
return data;
}
}
44. Example: Output
public interface IOutput {
void write(final List<Double> data,
final double average);
}
public class ConsoleOutput implements IOutput {
@Override
public void write(final List<Double> data,
final double average) {
System.out.printf("Average%s = %fn",
data, average);
}
}
45. Example: Mean Processor
public interface IProcessor {
double process(List<Double> data);
}
public class MeanProcessor implements IProcessor {
public double process(final List<Double> data) {
return data.stream().
collect(Collectors.
averagingDouble(item -> item));
}
}
46. Example: Averaging Calculator
public class AveragingCalculator {
final private IInput input;
final private IOutput output;
final private IProcessor algo;
final private IParser parser;
public AveragingCalculator(final IProcessor algo,
final IParser parser,
final IInput input,
final IOutput output) {
this.algo = algo;
this.parser = parser;
this.input = input;
this.output = output;
}
public void run() {
final String inputData = input.read();
final List<Double> data = parser.parse(inputData);
final double average = algo.process(data);
output.write(data, average);
}
}
47. Example: CSV Averaging App
public class CsvAveragingApp {
public static void main(String[] args) {
final IInput input = new FixedInput(args[0]);
final IOutput output = new ConsoleOutput();
final IParser parser = new CsvParser();
final IProcessor algo = new MeanProcessor();
final AveragingCalculator calc =
new AveragingCalculator(algo,
parser,
input,
Output);
calc.run();
}
}
48. Example: XML Averaging App
public class XmlAveragingApp {
public static void main(String[] args) {
final IInput input = new FixedInput(args[0]);
final IOutput output = new ConsoleOutput();
final IParser parser = new XmlParser();
final IProcessor algo = new MeanProcessor();
final AveragingCalculator calc =
new AveragingCalculator(algo,
parser,
input,
output);
calc.run();
}
}
49.
50. Opposite of SOLID
Single Responsibility Principle
Open Close Principle
Liskov Substitution Principle
Interface Segregation Principle
Dependency Inversion Principle
51. Opposite of SOLID
Single Responsibility Principle
Open Close Principle
Liskov Substitution Principle
Interface Segregation Principle
Dependency Inversion Principle
S
T
U
P
I
D
52. Opposite of SOLID
Single Responsibility Principle
Open Close Principle
Liskov Substitution Principle
Interface Segregation Principle
Dependency Inversion Principle
Singletons
Tight Coupling
Untestability
Premature Optimisation
Indescriptive Naming
Duplication