This document discusses software design principles and patterns, including:
1) Generic programming allows code to work with different data types through interfaces and abstract base classes. Reflection allows examining and manipulating objects at runtime.
2) The document discusses separation of concerns, loose coupling, and high cohesion as important design principles. It gives an example of dividing an application by feature and concern.
3) The document uses a duck simulation example to illustrate issues that can arise from rigid class hierarchies and inheritance. It proposes using the strategy pattern by defining behavior interfaces and swapping concrete strategy classes to vary behavior while keeping classes loosely coupled and extensible.
You can get clear knowledge about the functional dependencies in "Normalization". And also the rules, types of FDs and finally the closure and its applications
LR parsing is one type of bottom up parsing. In the LR parsing, "L" stands for left-to-right scanning of the input.
"R" stands for constructing a right most derivation in reverse.
Data Structure Introduction
Data Structure Definition
Data Structure Types
Data Structure Characteristics
Need for Data Structure
Stack Definition
Stack Representation
Stack Operations
Stack Algorithm
Program for Stack in C++
Linked List Definition
Linked List Representation
Linked List Operations
Linked List Algorithm
Program for Linked List in C++
Linked List Defination
Linked List Representation
Linked List Operations
Linked List Algorithm
Program for Linked List in C++
Framhald af umfjöllun um hlutbundna forritun og hönnun. Nú förum við yfir Generic Programming sem sem leið til að búa til sveigjanlega og endurnýtanlegar einingar. Skoðum líka reflection. Þá verður farið fyrir hvernig má hann laustengdar einingar og notum við frægan andarleik sem dæmi.
Þá mun Code Horror Dude kíkja í heimsókn
You can get clear knowledge about the functional dependencies in "Normalization". And also the rules, types of FDs and finally the closure and its applications
LR parsing is one type of bottom up parsing. In the LR parsing, "L" stands for left-to-right scanning of the input.
"R" stands for constructing a right most derivation in reverse.
Data Structure Introduction
Data Structure Definition
Data Structure Types
Data Structure Characteristics
Need for Data Structure
Stack Definition
Stack Representation
Stack Operations
Stack Algorithm
Program for Stack in C++
Linked List Definition
Linked List Representation
Linked List Operations
Linked List Algorithm
Program for Linked List in C++
Linked List Defination
Linked List Representation
Linked List Operations
Linked List Algorithm
Program for Linked List in C++
Framhald af umfjöllun um hlutbundna forritun og hönnun. Nú förum við yfir Generic Programming sem sem leið til að búa til sveigjanlega og endurnýtanlegar einingar. Skoðum líka reflection. Þá verður farið fyrir hvernig má hann laustengdar einingar og notum við frægan andarleik sem dæmi.
Þá mun Code Horror Dude kíkja í heimsókn
Rammar eru almennar aðgerðir og aðferðir sem nota má til að búa til sértækan hugbúnað. Með römmum má endurnýta kóða sem alltaf er eins eða nánast alltaf er eins. Það sem er sérhæft eru ákveðin viðfangsefni en útfærsla á þeim notar rammann. Við skilgreinum ramma og skoðum kosti og galla.
Við skoðum einnig létta gáma eða lightweight containers sem eru forrit sem sjá um lífshlaup (live-cycle) hluta og umhverfi þeirra (context). Þá skoðum við munstrið Dependency Injection sem er mjög hentugt í römmum.
Einnig skoðum við Template Method og Strategy munstrin.
Certification preparation - Net classses and functions.pptxRohit Radhakrishnan
we recap the basic and advanced notions regarding different types of Object types used when working in UiPath environment. We are going to go through the basics (e.g.: concatenation, conversion between different types of data) and deep dive into more advanced topics like linqs or selectors, recap how to work with datatables, from initialization to filtering and touch upon the subject of invoking code inside an UiPath project.
we recap the basic and advanced notions regarding different types of Object types used when working in UiPath environment. We are going to go through the basics (e.g.: concatenation, conversion between different types of data) and deep dive into more advanced topics like linqs or selectors, recap how to work with datatables, from initialization to filtering and touch upon the subject of invoking code inside an UiPath project.
Design patterns describe both problems that occur all the time in our environment and general solutions to these problems. How does knowledge of patterns helps us? When and how to apply it? How refactoring is connected to design patterns?
Fyrirlestur fyrir Félag tölvunarfræðinga og Verkfræðingafélagið þann 18.05.2022
Nýsköpun er forsenda tækniframfara sem eru forsendur framþróunar. Nýsköpun byrjar yfirleitt smátt og þarf margar ítranir til að virka. Frumkvöðlar sem eru að búa til nýjungar þurfa ekki einungis að glíma við tæknina og takmarkanir hennar, heldur einnig skoðanir og álit samtímamanna sem sjá ekki alltaf tilgang með nýrri tækni. Í þessum fyrirlestri skoðar Ólafur Andri nýsköpun og þær framfarir sem hafa orðið. Einnig skoðar hann hvert tækniframfarir nútímans muni leiða okkur á komandi árum.
Ólafur Andri Ragnarsson er aðjúnkt við Háskólann í Reykjavík og kennir þar námskeið um tækniþróun og hvernig tæknibreytingar hafa áhrif á fyrirtæki. Hann er tölvunarfræðingur (Msc) að mennt frá Oregon University í Bandaríkjanum. Ólafur Andri er frumkvöðull og stofnaði, ásamt fleirum, Margmiðlun og síðar Betware. Þá tók Ólafur Andri þátt í að stofna leikjafyrirtækið Raw Fury AB í Stokkhólmi.
Fyrirlestur haldinn fyrir tæknifaghóp Stjórnvísi þann 13. október 2020.
Undanfarna áratugi höfum við séð gríðalegar framfarir í tækni og nýsköpun á heimsvísu. Þessar framfarir hafa skapað mannkyninu öllu aukna hagsæld. Þrátt fyrir veirufaraldur á heimsvísu eru framfarir ekkert að minnka heldur munu bara aukast næstu árum. Gervgreind, róbotar, sýndarveruleiki, hlutanetið og margt fleira er að búa til nýjar lausnir og ný tækifæri. Framtíðin er í senn sveipuð dulúð og getur verið spennandi og ógnvekjandi í senn. Eina sem við vitum fyrir vissu er að framtíðin verður alltaf betri. Í þessu fyrirlestri ætlar Ólafur Andri Ragnarsson kennari við HR að fjalla um nýjustu tækni og framtíðina.
Technology is one of the factors of change. When new disruptive technology is introduced, it can change industries. We have many examples of that and will start this journey it one of the most important innovation that has come in our lifetimes, the smartphone. We will explore the impact of the smartphone and the fate of existing companies at the time when iPhone, the first smartphone as we know them, was introduced to the world.
We will also look at other examples from history. Then we look at the broader picture, past industrial revolutions and the one that we are experiencing now, the fourth industrial revolution. Specifically we look briefly at the technologies that fuel this revolution, for example artificial intelligence, robotics, drones, internet of things and more.
Manlike machines have fascinated humans since ancient times. The modern robots start to take shape with the industrial revolution. In the 20th century robots were mostly industrial machines you would see in factories, like car factories.
Today, robots can have sensors, vision, they can hear and understand. They can connect to the cloud for more information. However, we are still in the early stages of robotics and robots will need to go a long way to become useful as a ubiquitous general purpose devices.
The normal interaction with computers is with keyboard and a mouse. For display a rectangular somewhat small screen is used with 2D windowing systems. The mouse was invented more the 40 years ago and has been for 20 years dominant input. Now we are seeing new types of input devices. Multi-touch adds new dimensions and new applications. Natural user interfaces or gesture interfaces where people point to drag objects. Computers are also beginning to recognize facial expressions of people, so it knows if you are smiling. Voice and natural language understanding is getting to a usable stage. All this calls all types of new applications.
Displays are getting bigger. What if any surface was a screen? If you could spray the wall with screen? Or have you phone project images to the wall.
This lectures explores some of these new types of interactions with computers and software. It makes the old mouse look old.
Local is the Lo in SoLoMo, the buzz word. Local is not only about location, it's also about your digital track record. Over 70% of Netflix users watch the films recommend. Mining data to understand people's behaviour is getting to be a huge and valuable business. Advertisers see opportunities in getting direct to their target groups. Predictive intelligence is also about where you will be at some time in the future, and where somebody you know will be.
It turns out that Facebook and Google know you better than you think you know yourself. The world is about to get really scary.
Over two billion people signed up for Facebook. This site the most used site for people when using the Internet. People are not watching TV so much anymore - they using Facebook, Youtube and Netflix and number of popular web sites.
Some people denote their time working for others online. What drives people to write an article on Wikipedia? They don´t get paid. Companies are enlisting people to help with innovations and sites such as Galaxy Zoo ask people to help identifying images. And why do people have to film themselves singing when they cannot sing and post the video on Youtube?
In this lecture we talk about how people are using the web to interact in new ways, and doing stuff.
With the computer revolution vast amount of digital data has become available. With the Internet and smart connected product, the data is growing exponentially. It is estimated that every year, more data is generated than all history prior. And this has repeated over several years.
With all this data, it becomes a platform for something new of its own. In this lecture, we look at what big data is and look at several examples of how to use data. There are many well-know algorithms to analyse data, like clustering and machine learning.
After the computing industry got started, a new problem quickly emerged. How do you operate this machines and how to you program them. The development of operating systems was relatively slow compared to the advances in hardware. First system were primitive but slowly got better as demand for computing power increased. The ideas of the Graphical User Interfaces or GUI (Gooey) go back to Doug Engelbarts Demo of the Century. However, this did not have much impact on the computer industry. One company though, Xerox, a photocopy company explored these ideas with Palo Alto Park. Steve Jobs of Apple and Bill Gates of Microsoft took notice and Apple introduced first Apple Lisa and the Macintosh.
In this lecture on we look so lessons for the development of software, and see how our business theories apply.
In this lecture on we look so lessons for the development of algorithms or software, and see how our business theories apply.
In the second part we look at where software is going, namely Artificial Intelligence. Resent developments in AI are causing an AI boom and new AI application are coming all the time. We look at machine learning and deep learning to get an understanding of the current trends.
We are currently living in times of great transformation. We have over the last couple of decade seen the Internet become the most powerful disrupting force in the world, connecting everyone and transforming businesses. Now everyday objects - things we use are getting smart with sensors and software. And they are connecting. What does this mean?
We will see the world become alive. Cars will talk to road sensors that talk to systems that guide traffic. Plants will talk to weather systems that talk to scientists that research climate change. Farming fields will talk to the farming system that talks to robots that do fertilising and harvesting. Home appliances like refrigerators, ovens, coffee machines and microwaves ovens will talk to the home food and cooking system that will inform the store that you are running out butter, cheese, laundry detergent and coffee beans, which will inform the robot driver to get this to your house after consulting your calendar upon when someone is at home.
In this lecture we explore the Internet of Things, IoT.
The Internet grew out of US efforts to build the ARPANET, a network of peer computers built during the cold war. The two major players were military and academia. The network was simple and required no efforts for security or social responsibility. The early Internet community was mainly highly educated and respectable scientist. In the early 1990s the World Wide Web, a hypertext system is introduced, and soon browsers start to appear, leading the commercialization of Net. New businesses emerge and a technology boom known as the dot-com era.
The network, now over 40, is being stretched. Problems such as spam, viruses, antisocial behaviour, and demands for more content are prompting reinvention of the Net and threatening its neutrality. Add to this government efforts to regulate and limit the network.
In this lecture we look at the Internet and the impact of the network. We will also look at the future of the Internet.
The Internet grew out of US efforts to build the ARPANET, a network of peer computers built during the cold war. The two major players were military and academia. The network was simple and required no efforts for security or social responsibility. The early Internet community was mainly highly educated and respectable scientist. In the early 1990s the World Wide Web, a hypertext system is introduced, and soon browsers start to appear, leading the commercialisation of Net. New businesses emerge and a technology boom known as the dot-com era.
The network, now over 40, is being stretched. Problems such as spam, viruses, antisocial behaviour, and demands for more content are prompting reinvention of the Net and threatening its neutrality. Add to this government efforts to regulate and limit the network.
In this lecture we look at the Internet and the impact of the network. We will also look at the future of the Internet.
The ideas for cellular phones were developed in the 1940s. However, it was not until the microprocessor becomes available that practical commercial solutions are possible.
Today there are more than 5 billion unique mobile phone subscriptions in the world and of them about 2.5 billion are smartphones. This device is so powerful that people check it over 40 times a day.
In this lecture we look mobile. We also look at the history of communication since the telegraph and how the mobile market developed in the 80s and 90s until the iPhone was released in 2007. That same year Western Union stopped sending telegraph messages.
Did you know that the term "Computer" once meant a profession? And what did people or computers actually do? They computed mathematical problems. Some problems were tedious and error prone. And it is not surprising that people started to develop machines to aid in the effort. The first mechanical computers were actually created to get rid of errors in human computation. Then came tabulating machines and cash registers. It was not until telephone companies were well established that computing machines became practical.
First computers were huge mainframes, but soon minicomputers like DEC’s PDP started to appear. The transistor was introduced in 1947, but its usefulness was not truly realized until in 1958 when the integrated circuit was invented. This led to the invention of the microprocessor. Intel, in 1971, marketed the 4004 – and the personal computer revolution started. One of the first Personal Computers was MITS’ Altair. This was a simple device and soon others saw the opportunities.
In this lecture we start our coverage of computing and look at some of the early machines and the impact they had.
Software is changing the way traditional business operate. People now have smartphones in their pockets - a supercomputer that is 25,000 times more powerful and the minicomputers of the 1960s. This is changing people's behaviour and how people shop and use services. The organisational structure created in the 20th century cannot survive when new digital solution are being offered. Software is changing the way traditional business operate. People now have smartphones in their pockets - a supercomputer that is 25,000 times more powerful and the minicomputers of the 1960s. This is changing people's behaviour and how people shop and use services. The organisational structure created in the 20th century cannot survive when new digital solution are being offered. The hierarchical structure of these established companies assumes high coordination cost due to human activity. But when the coordination cost drops
The organisational structure that companies in the 20th century established was based on the fact that employees needed to do all the work. The coordination cost was high due to the effort and cost of employees, housing etc. Now we have software that can do this for use and the coordination cost drops to close-to-zero. Another thing is that things become free. Consider Flickr. Anybody can sign up and use the service for free. Only a fraction of the users get pro account and pay. How can Flickr make money on that? It turns out that services like this can.
Many businesses make money by giving things away. How can that possibly work? The music business has suffered severely with digital distribution of content. Should musicians put all their songs on YouTube? What is the future business model for music?
One of the great irony of successful companies is how easily they can fail. New companies are founded to take advantage of some new technology. They become highly successful and but when the technology shifts, something new comes along, they are unable to adapt and fail. This is the innovator’s dilemma.
Then there are companies that manage to survive. For example, Kodak survived two platform shift, only til fail the third. IBM has survived over 100 years. What do successful companies do differently?
History has many examples of great innovators who had difficult time convincing their contemporaries of new technology. Even incumbent and powerful companies regarded new technologies as inferior and dismissed it as "toys". Then when disruptive technologies take off they often are overhyped and can cause bubbles like the Internet bubble of the late 1990s.
In this lecture we look at some examples of disruptive technologies and the impact they had. We look at the The Disruptive Innovation Theory by Harvard Professor Clayton Christensen.
Technology evolves in big waves that we call revolutions. The first revolution was the Industrial revolution that started in Britain in 1771. Since than we have see more revolutions come and how we are in the fifth. These revolutions follow a similar path. First there is an installation period where the new technologies are installed and deployed, creating wealth to those who were are the right place at the right time. This is followed by a frenzy, where financial markets wants to be apart. The there is crash and turning point, followed by synergy, a golden age.
In 1908, a new technological revolution started. It was the Age of Oil and Automobile. The technology trigger was Henry Ford´s new assembly line technique that allowed the manufacturing of standardized, low cost automobile. This created the car industry and other manufacturing companies. This also created demand for gas thus creating the oil industry. During the Roaring Twenties the stock prices rose to new levels, until a crash and the Great Depression. Only after World War II, came a turnaround point followed by a golden age in the post-war boom.
In this lecture we look at a framework for understanding technological revolutions. There revolutions completely change societies and replace the old with new technologies. We will explore how these revolutions take place. We should now be in the golden age phase.
We also look at generations.
In the early days of product development, the technology is inferior and lacking in performance. The focus is very much on the technology itself. The users are enthusiast who like the idea of the product, find use for it, and except the lack of performance. Then as the product becomes more mature, other factors become important, such as price, design, features, portability. The product moves from being a technology to become a consumer item, and even a community.
In this lecture we explore the change from technology focus to consumer focus, and look at why people stand in line overnight to buy the latest gadgets.
In the early days of product development, the technology is inferior and lacking in performance. The focus is very much on the technology itself. The users are enthusiast who like the idea of the product, find use for it, and except the lack of performance. Then as the product becomes more mature, other factors become important, such as price, design, features, portability. The product moves from being a technology to become a consumer item, and even a community.
In this lecture we explore the change from technology focus to consumer focus, and look at why people stand in line overnight to buy the latest gadgets.
Sudheer Mechineni, Head of Application Frameworks, Standard Chartered Bank
Discover how Standard Chartered Bank harnessed the power of Neo4j to transform complex data access challenges into a dynamic, scalable graph database solution. This keynote will cover their journey from initial adoption to deploying a fully automated, enterprise-grade causal cluster, highlighting key strategies for modelling organisational changes and ensuring robust disaster recovery. Learn how these innovations have not only enhanced Standard Chartered Bank’s data infrastructure but also positioned them as pioneers in the banking sector’s adoption of graph technology.
Enchancing adoption of Open Source Libraries. A case study on Albumentations.AIVladimir Iglovikov, Ph.D.
Presented by Vladimir Iglovikov:
- https://www.linkedin.com/in/iglovikov/
- https://x.com/viglovikov
- https://www.instagram.com/ternaus/
This presentation delves into the journey of Albumentations.ai, a highly successful open-source library for data augmentation.
Created out of a necessity for superior performance in Kaggle competitions, Albumentations has grown to become a widely used tool among data scientists and machine learning practitioners.
This case study covers various aspects, including:
People: The contributors and community that have supported Albumentations.
Metrics: The success indicators such as downloads, daily active users, GitHub stars, and financial contributions.
Challenges: The hurdles in monetizing open-source projects and measuring user engagement.
Development Practices: Best practices for creating, maintaining, and scaling open-source libraries, including code hygiene, CI/CD, and fast iteration.
Community Building: Strategies for making adoption easy, iterating quickly, and fostering a vibrant, engaged community.
Marketing: Both online and offline marketing tactics, focusing on real, impactful interactions and collaborations.
Mental Health: Maintaining balance and not feeling pressured by user demands.
Key insights include the importance of automation, making the adoption process seamless, and leveraging offline interactions for marketing. The presentation also emphasizes the need for continuous small improvements and building a friendly, inclusive community that contributes to the project's growth.
Vladimir Iglovikov brings his extensive experience as a Kaggle Grandmaster, ex-Staff ML Engineer at Lyft, sharing valuable lessons and practical advice for anyone looking to enhance the adoption of their open-source projects.
Explore more about Albumentations and join the community at:
GitHub: https://github.com/albumentations-team/albumentations
Website: https://albumentations.ai/
LinkedIn: https://www.linkedin.com/company/100504475
Twitter: https://x.com/albumentations
The Art of the Pitch: WordPress Relationships and SalesLaura Byrne
Clients don’t know what they don’t know. What web solutions are right for them? How does WordPress come into the picture? How do you make sure you understand scope and timeline? What do you do if sometime changes?
All these questions and more will be explored as we talk about matching clients’ needs with what your agency offers without pulling teeth or pulling your hair out. Practical tips, and strategies for successful relationship building that leads to closing the deal.
In his public lecture, Christian Timmerer provides insights into the fascinating history of video streaming, starting from its humble beginnings before YouTube to the groundbreaking technologies that now dominate platforms like Netflix and ORF ON. Timmerer also presents provocative contributions of his own that have significantly influenced the industry. He concludes by looking at future challenges and invites the audience to join in a discussion.
Maruthi Prithivirajan, Head of ASEAN & IN Solution Architecture, Neo4j
Get an inside look at the latest Neo4j innovations that enable relationship-driven intelligence at scale. Learn more about the newest cloud integrations and product enhancements that make Neo4j an essential choice for developers building apps with interconnected data and generative AI.
Goodbye Windows 11: Make Way for Nitrux Linux 3.5.0!SOFTTECHHUB
As the digital landscape continually evolves, operating systems play a critical role in shaping user experiences and productivity. The launch of Nitrux Linux 3.5.0 marks a significant milestone, offering a robust alternative to traditional systems such as Windows 11. This article delves into the essence of Nitrux Linux 3.5.0, exploring its unique features, advantages, and how it stands as a compelling choice for both casual users and tech enthusiasts.
Unlocking Productivity: Leveraging the Potential of Copilot in Microsoft 365, a presentation by Christoforos Vlachos, Senior Solutions Manager – Modern Workplace, Uni Systems
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.
Pushing the limits of ePRTC: 100ns holdover for 100 daysAdtran
At WSTS 2024, Alon Stern explored the topic of parametric holdover and explained how recent research findings can be implemented in real-world PNT networks to achieve 100 nanoseconds of accuracy for up to 100 days.
GraphSummit Singapore | The Art of the Possible with Graph - Q2 2024Neo4j
Neha Bajwa, Vice President of Product Marketing, Neo4j
Join us as we explore breakthrough innovations enabled by interconnected data and AI. Discover firsthand how organizations use relationships in data to uncover contextual insights and solve our most pressing challenges – from optimizing supply chains, detecting fraud, and improving customer experiences to accelerating drug discoveries.
A tale of scale & speed: How the US Navy is enabling software delivery from l...sonjaschweigert1
Rapid and secure feature delivery is a goal across every application team and every branch of the DoD. The Navy’s DevSecOps platform, Party Barge, has achieved:
- Reduction in onboarding time from 5 weeks to 1 day
- Improved developer experience and productivity through actionable findings and reduction of false positives
- Maintenance of superior security standards and inherent policy enforcement with Authorization to Operate (ATO)
Development teams can ship efficiently and ensure applications are cyber ready for Navy Authorizing Officials (AOs). In this webinar, Sigma Defense and Anchore will give attendees a look behind the scenes and demo secure pipeline automation and security artifacts that speed up application ATO and time to production.
We will cover:
- How to remove silos in DevSecOps
- How to build efficient development pipeline roles and component templates
- How to deliver security artifacts that matter for ATO’s (SBOMs, vulnerability reports, and policy evidence)
- How to streamline operations with automated policy checks on container images
4. Generic Programming
▪ Programming in an data type independent way
– Same code is used regardless of the data type
▪ Example
– Sort can be applied to any data type
– Generic collection
• Java Collection Framework
▪ Design Principle
– Always use the most generic data type possible
5. Generic Programming
▪ All classes extend Object
– Allows generic algorithms and data structures
static int find (Object[] a, Object key)
{
int i;
for (i=0;i<a.length;i++)
if (a[i].equals(key)) return i;
return -1;
}
Employee[] staff = new Employee[10];
Employee e1 = new Employee("Dilbert");
staff[x] = e1;
int n = find(staff, e1);
6. Generic Programming
▪ Generic collections
– ArrayList is an example class that uses Object
ArrayList al = new ArrayList();
al.add (new Employee ("Dilbert"));
al.add (new Employee ("Wally"));
al.add (new Employee ("Alice"));
Iterator i = al.iterator();
Employee e;
while (i.hasNext())
{
e = (Employee)i.next();
System.out.println(e.getName());
}
Dilbert
Wally
Alice
7. Generic Programming
▪ Generic collections
– The Collections class is another example
List<Employee> list = new ArrayList<Employee>();
list.add (new Employee ("Dilbert"));
list.add (new Employee ("Wally"));
list.add (new Employee ("Alice"));
Collections.sort(list);
for (Employee e: list)
{
System.out.println(e);
}
Alice
Dilbert
Wally
9. Reflection
▪ Reflection allows examination and manipulation of objects at
runtime
– Get information about a class
• Fields, methods, constructors, and super classes
• Constants and method declarations belong to an interface
– Create an instance of a class whose name is not known until
runtime
– Get and set the value of an object's field, even if the field
name is unknown to your program until runtime
– Invoke a method on an object, even if the method is not
known until runtime
10. Reflection
static void showMethods(Object o)
{
Class c = o.getClass();
Method[] theMethods = c.getMethods();
for (int i = 0; i < theMethods.length; i++) {
String methodString = theMethods[i].getName();
System.out.println("Name: " + methodString);
String returnString = theMethods[i].getReturnType().getName();
System.out.println(" Return Type: " + returnString);
Class[] parameterTypes = theMethods[i].getParameterTypes();
System.out.print(" Parameter Types:");
for (int k = 0; k < parameterTypes.length; k ++)
{
String parameterString = parameterTypes[k].getName();
System.out.print(" " + parameterString);
}
System.out.println();
}
} }
11. Bla
public class ReflectMethods
{
public static void main(String[] args)
{
Polygon p = new Polygon();
showMethods(p);
}
Name: getBoundingBox
Return Type: java.awt.Rectangle
Parameter Types:
Name: contains
Return Type: boolean
Parameter Types: java.awt.geom.Point2D
...
Name: toString
Return Type: java.lang.String
Parameter Types:
Reflection
12. ▪ Reflection is very useful in frameworks
– Infrastructure code
– “plumbing” – The “Noise”
▪ Examples
– Create Java objects from XML descriptions
– Load classes at runtime and invoke methods
– Tools and utilities for development
Reflection
13. Dynamically Loading Classes
▪ Classes can be dynamically loaded at runtime
– Offers the flexibility to decide which class to run dynamically
– Class names can be specified in configuration files
▪ Class class
Class instanceClass = Class.forName("RssFeedReader");
reader = (FeedReader)instanceClass.newInstance();
14. A) AB
B) BA
C) ABC
D) Compilation fails
QUIZ
class A
{
public A(String s)
{
System.out.print("A");
}
}
public class B extends A
{
public B(String s) {
System.out.print("B");
}
public static void main(String [] args) {
new B("C");
}
}
15. A) AB
B) BA
C) ABC
D) Compilation fails
QUIZ
✔
class A
{
public A(String s)
{
System.out.print("A");
}
}
public class B extends A
{
public B(String s) {
System.out.print("B");
}
public static void main(String [] args) {
new B("C");
}
}
17. Software Design Principles
Software development has over the years established a
set of principles that apply to building software
Separation of Concern
Coupling
Cohesion
Information Hiding
18. Separation of Concern
The process of dividing the application into distanct
units without overlapping
Concern can be feature, functionality, point of interest,
data, or process
Allows for changing one area without affecting other
areas
Examples: Presentaion, Domain, Data Source
Model View Controller
HTML, CSS, JavaScript
19. Separation of Concern
Divide by Feature - vertical
Customer Wallet
Single
Sign-on
Single
Sign-on
Logging Security Session I18N Caching
Cross-
cutting
concerns
20. Coupling
Refers to the degree of dependence between objects
The objective is to assign responsibility to classes so
that coupling is low
If coupling is high, any
change becomes difficult
Loosely coupled systems
are easier and cheaper to
maintain
Goal is: Low Coupling
21. Cohesion
Refers to the degree to which the elements of a module
belong together
measures the strength of
relationship between pieces
of functionality within
a given module.
In highly cohesive systems
functionality is strongly
related
Goal is: High Cohesion
23. Object Oriented Design
▪ Design and implementation of software needs to be of quality
– Badly designed, well implemented = problem!
– Well designed, badly implemented = problem!
CODE
HORROR!!
CODE HORROR DUDE
24. Object Oriented Design
Good design
Is based on OO principles
Abstracts complex APIs such as J2EE
Is flexible and can be changed
Contains loosely coupled components
27. Getting Started
SimUDuck is highly successful duck pond simulation game
Original design
MallardDuck
display() { }
Duck
quack
swim
display
// other methods
RedHeadDuck
display() { }
28. Change Request!
But now we need the ducks to FLY
MallardDuck
display() { }
Duck
quack
swim
display
// other methods
RedHeadDuck
display() { }
29. Change Request!
Ok just add the fly method to Duck
MallardDuck
display() { }
Duck
quack
swim
display
fly
// other methods
RedHeadDuck
display() { }
30. Problem!
But not all duck fly – We forgot Rubber Duck!
MallardDuck
display() { }
Duck
quack
swim
display
fly
// other methods
RedHeadDuck
display() { }
RubberDuck
display() { }
31. How can we fix this?
Just override fly to do nothing
MallardDuck
display() { }
Duck
quack
swim
display
fly
// other methods
RedHeadDuck
display() { }
RubberDuck
quack() {
// squeck
}
fly() {
// do nothing
}
32. We even think ahead
We fix all non-flyable and non-quackable ducks as well
Duck
quack
swim
display
fly
// other methods
RedHeadDuck
display() { }
RubberDuck
quack() {
// squeck
}
fly() {
// do nothing
DecoyDuck
quack() {
// no sound
}
fly() {
// do nothing
Code smell!
MallardDuck
display() { }
33. Which of the following are disadvantages of using inheritance to
provide Duck behaviour?
A) Code is duplicated across subclasses
B) Runtime behaviour changes are difficult
C) We can’t make ducks dance
D) Hard to gain knowledge of all duck behaviours
E) Ducks can’t fly and quack at the same time
F) Changes can unintentionally affect other ducks
QUIZ
34. Which of the following are disadvantages of using inheritance to
provide Duck behaviour?
A) Code is duplicated across subclasses
B) Runtime behaviour changes are difficult
C) We can’t make ducks dance
D) Hard to gain knowledge of all duck behaviours
E) Ducks can’t fly and quack at the same time
F) Changes can unintentionally affect other ducks
QUIZ
✔
✔
✔
✔
35. The Problem
▪ The problem is this
– Derived classes (RubberDuck) are forced to inherit
behaviour they don’t have
– Derived classes (RubberDuck) needs to be exposed to the
inner workings of the superclass (Duck)
– Users of the base class (Duck) should expect same
functionality
– Violation of the Liskov Substitution Principle
36. Subtypes must be substitutable for
their base types. Code that uses
references to base class must be
able to use objects of derived
classes without knowing it.
Liskov Substitution Principle
37. Trying to fix the Problem
Let’s try using interfaces! Flyable and Quackable
MallardDuck
display() { }
fly() { }
quack() { }
Duck
swim
display
// other methods
RedHeadDuck
display() { }
fly() { }
quack() { }
RubberDuck
display() { }
quack() {
// squeck
}
DecoyDuck
Code
duplication!
Flyable
fly
Quackable
quack
display() { }
38. What is the Problem?
▪ We tried this
– Inheritance changes all subcasses
– Interfaces cause code duplication
▪ The problem is we are mixing different types of code in one
type of classes
▪ Fix
– Separate Variation Design Principle
– Take what varies and encapsulate it so it wont affect the rest
of the code
39. Separate Variations Design Principle
Identify the aspects of your
application that vary and separate
them from what stays the same
40. fly
behaviour
fly
behaviour
Separation of Concerns
FlyWithWings flyBehavior = new FlyWithWings();
DATA TYPE IS TOO SPECIFIC
Duck
class
▪ Separate what changes from what stays the same
– Move duck behaviour to a separate class
fly
behaviour
quack
behaviour
quack
behaviour
quack
behaviour
Duck Behaviours
41. fly
behaviour
fly
behaviour
Separation of Concerns
Duck
class
▪ Duck classes cannot use the concrete behaviour classes!
▪ We need an interface or supertype
fly
behaviour
quack
behaviour
quack
behaviour
quack
behaviour
Duck Behaviours
FlyBehaviour
<interface>
FlyBehavior flyBehavior = new FlyWithWings();
INTERFACE - POLYMORPHISIM
42. The Interface Design Principle (GoF)
Program to an interface, not an
implementation
43. Loose Coupling with Interfaces
▪ Advantages
– The ability to change the implementing class of any
application object without affecting calling code
– Total freedom in implementing interfaces
– The ability to provide simple test implementations and stub
implementations of application interfaces as necessary
44. Program to Interfaces
Program to an implementation
Program to interface/subtype
Program to unknown creation
Dog d = new Dog();
d.bark();
Animal animal = new Dog();
animal.makeSound();
Animal animal = getAnimal();
animal.makeSound();
We are making
classes
responsible for
their
dependencies
45. Program to Interfaces
Another way is to make the caller responsible for setting the
dependency
class Zoo {
private Animal animal;
public setAnimal(Animal animal)
{
this.animal = animal;
}
...
animal.makeSound();
Injection
happens here
Dependency Injection Design Pattern
46. Implementing Behaviour
We can add new behaviour without touching the Duck classes
FlyWithWings
fly() { }
FlyBehaviour
<interface>
fly();
FlyNoWay
fly() { }
Quack
quack() { }
QuackBehaviour
<interface>
quack();
Squeak
quack() { }
implements implements
47. Integrating Behaviour
The Duck classes will now delegate its flying and
quacking behaviour
Duck
QuackBehaviour quackBehaviour;
FlyBehaviour flyBehaviour;
swim() { }
display() { }
performQuack() { }
performFly() { }
Behaviour Interfaces
Performing the behaviour
48. Integrating Behaviour
The Duck classes will now delegate its flying and
quacking behaviour
public class Duck
{
QuackBehavior quackBehavior;
...
public void performQuack()
{
quackBehavior.performQuack()
}
}
We don’t care what this object is
behind the interface, we just call it
49. Integrating Behaviour
But how do we set the behaviour classes?
public class MallardDuck extends Duck
{
public MallardDuck()
{
quackBehavior = new Quack();
flyBehavior = new FlyWithWings();
}
}
This is not
programming to
interfaces!
50. Setting the Behaviour Dynamically
Use Dependency Injection - make the caller responsible
Add two new methods to the Duck class
QuackBehavior quackBehavior;
FlyBehavior flyBehavior;
public void setFlyBehavior(FlyBehavior flyBehavior)
{
this.flyBehavior = flyBehavior
}
public void setQuackBehavior(QuackBehavior quackBehavior)
{
this.quackBehavior = quackBehavior
}
DuckFactory
{
public Duck getMallardDuck()
{
Duck duck = new MallardDuck()
duck.setFlyBehavior(new FlyWithWings());
duck.setQuackBehavior(new Quack());
return duck;
}
}
This is an
assembler class
51. Setting the Behaviour Dynamically
Use Dependency Injection - make the caller responsible
Creating systems using composition give flexibility
You can change the behaviour at runtime
The idea: Don´t think: Mallard is-a flying duck, think: it has-a
flying behaviour
Put two classes together using composition
One is member in the other
53. Object Composition
Problems with concrete inheritance
Class hierarchies are rigid
Difficult to change the implementation
Object Composition is more flexible
Allows the behaviour of an object to be altered at run
time, through delegating part of its behaviour to an
interface and allowing callers to set the implementation
of that interface
54. Generic programming
Using classes, abstract classes and interfaces can lead to
powerful and flexible programs
Reflection
Powerful for building infrastructure
Design
Decouple behaviour of objects from the object them selves
Loosely coupled with interfaces and dependency injection
Program to interfaces
Favour composition over inheritance
Summary