non-strict functions, bottom and scala by-name parametersPhilip Schwarz
Download for perfect quality.
Non strict functions, bottom and scala by-name parameters - ‘a close look’, through the work of Runar Bjarnason, Paul Chiusano, Martin Odersky, Bill Venners, Lex Spoon, Alvin Alexander, Mark Lewis and Aleksandar Prokopec.
This talk was presented on Aug 3rd 2023 during the Scala in the City event a ITV in London https://www.meetup.com/scala-in-the-city/events/292844968/
Visit the following for a description, slideshow, all slides with transcript, pdf, github repo, and eventually a video recording: http://fpilluminated.com/assets/n-queens-combinatorial-puzzle-meets-cats.html
At the centre of this talk is the N-Queens combinatorial puzzle. The reason why this puzzle features in the Scala book and functional programming course by Martin Odersky (the language’s creator), is that such puzzles are a particularly suitable application area of 'for comprehensions'.
We’ll start by (re)acquainting ourselves with the puzzle, and seeing the role played in it by permutations. Next, we’ll see how, when wanting to visualise candidate puzzle solutions, Cats’ monoidal functions fold and foldMap are a great fit for combining images.
While we are all very familiar with the triad providing the bread, butter and jam of functional programming, i.e. map, filter and fold, not everyone knows about the corresponding functions in Cats’ monadic variant of the triad, i.e. mapM, filterM and foldM, which we are going to learn about next.
As is often the case in functional programming, the traverse function makes an appearance, and we shall grab the opportunity to point out the symmetry that exists in the interrelation of flatMap / foldMap / traverse and flatten / fold / sequence.
Armed with an understanding of foldM, we then look at how such a function can be used to implement an iterative algorithm for the N-Queens puzzle.
The talk ends by pointing out that the iterative algorithm is smarter than the recursive one, because it ‘remembers’ where it has already placed previous queens.
Download for better quality.
Monads do not Compose. Not in a generic way - There is no general way of composing monads.
A comment from Rúnar Bjarnason, coauthor of FP in Scala: "They do compose in a different generic way. For any two monads F and G we can take the coproduct which is roughly Free of Either F or G (up to normalization)".
Another comment from Sergei Winitzki (which caused me to upload https://www.slideshare.net/pjschwarz/addendum-to-monads-do-not-compose): "It is a mistake to think that a traversable monad can be composed with another monad. It is true that, given `Traversable`, you can implement the monad's methods (pure and flatMap) for the composition with another monad (as in your slides 21 to 26), but this is a deceptive appearance. The laws of the `Traversable` typeclass are far insufficient to guarantee the laws of the resulting composed monad. The only traversable monads that work correctly are Option, Either, and Writer. It is true that you can implement the type signature of the `swap` function for any `Traversable` monad. However, the `swap` function for monads needs to satisfy very different and stronger laws than the `sequence` function from the `Traversable` type class. I'll have to look at the "Book of Monads"; but, if my memory serves, the FPiS book does not derive any of these laws." See https://www.linkedin.com/feed/update/urn:li:groupPost:41001-6523141414614814720?commentUrn=urn%3Ali%3Acomment%3A%28groupPost%3A41001-6523141414614814720%2C6532108273053761536%29
Rust
Why do you care about Rust? Who has the time to learn all these new languages? It seems like a new one is popping up every other week and this trend is growing at an exponential rate. Good news, a fair number of them are crafted really well and efficiently solve specific problems. Bad news, how do you keep up with all of this, let alone decide which languages to include in your companies technology portfolio.
Despite the challenges of all these new languages, a majority of developers are intrigued about the idea of becoming a polyglot, but don't know where to begin or don't have the time. In my polyglot travels, there is one language of late that is the sure-fire answer to the above questions, Rust.
In this talk I’ll explore the value behind becoming more polyglotic as a developer, how to pick languages to learn, and then dive deep in the the language of Rust. Which in my opinion, is hands down the best up and coming languages to learn.
About the Presenter
Anthony Broad-Crawford has been a developer since the year 2000 with a short side stint as a semi-professional poker player. Since his transition to software development Anthony has...
1. Built 8 patent receiving technologies
2. Founded two global companies
3. Been a CTO (3x), CPO (1x), and CEO (1x)
and is currently the CTO at Fooda where he manages product, user experience, and engineering. Fooda is predominantly web and mobile technology company focused on bringing great & healthy food from the best restaurant's to people while at the office.
Through his career, in production applications Anthony has used Ruby, Java, Jave (Android), Objective-C and Swift, .NET, Erlang, Scala, Node.JS, LISP, Smalltalk, and even assembly, with his recent favorite, Rust . No, not all at the same time in the same application.
Anthony now spends his time building great teams, that leverage great technology, to build great products, but still looks to codes every chance he can get :)
Developers often wonder how to implement a certain functionality
(e.g., how to parse XML files) using APIs. Obtaining
an API usage sequence based on an API-related natural
language query is very helpful in this regard. Given a query,
existing approaches utilize information retrieval models to
search for matching API sequences. These approaches treat
queries and APIs as bags-of-words and lack a deep understanding
of the semantics of the query.
We propose DeepAPI, a deep learning based approach to
generate API usage sequences for a given natural language
query. Instead of a bag-of-words assumption, it learns the
sequence of words in a query and the sequence of associated
APIs. DeepAPI adapts a neural language model named
RNN Encoder-Decoder. It encodes a word sequence (user
query) into a fixed-length context vector, and generates an
API sequence based on the context vector. We also augment
the RNN Encoder-Decoder by considering the importance
of individual APIs. We empirically evaluate our approach
with more than 7 million annotated code snippets collected
from GitHub. The results show that our approach generates
largely accurate API sequences and outperforms the related
approaches.
non-strict functions, bottom and scala by-name parametersPhilip Schwarz
Download for perfect quality.
Non strict functions, bottom and scala by-name parameters - ‘a close look’, through the work of Runar Bjarnason, Paul Chiusano, Martin Odersky, Bill Venners, Lex Spoon, Alvin Alexander, Mark Lewis and Aleksandar Prokopec.
This talk was presented on Aug 3rd 2023 during the Scala in the City event a ITV in London https://www.meetup.com/scala-in-the-city/events/292844968/
Visit the following for a description, slideshow, all slides with transcript, pdf, github repo, and eventually a video recording: http://fpilluminated.com/assets/n-queens-combinatorial-puzzle-meets-cats.html
At the centre of this talk is the N-Queens combinatorial puzzle. The reason why this puzzle features in the Scala book and functional programming course by Martin Odersky (the language’s creator), is that such puzzles are a particularly suitable application area of 'for comprehensions'.
We’ll start by (re)acquainting ourselves with the puzzle, and seeing the role played in it by permutations. Next, we’ll see how, when wanting to visualise candidate puzzle solutions, Cats’ monoidal functions fold and foldMap are a great fit for combining images.
While we are all very familiar with the triad providing the bread, butter and jam of functional programming, i.e. map, filter and fold, not everyone knows about the corresponding functions in Cats’ monadic variant of the triad, i.e. mapM, filterM and foldM, which we are going to learn about next.
As is often the case in functional programming, the traverse function makes an appearance, and we shall grab the opportunity to point out the symmetry that exists in the interrelation of flatMap / foldMap / traverse and flatten / fold / sequence.
Armed with an understanding of foldM, we then look at how such a function can be used to implement an iterative algorithm for the N-Queens puzzle.
The talk ends by pointing out that the iterative algorithm is smarter than the recursive one, because it ‘remembers’ where it has already placed previous queens.
Download for better quality.
Monads do not Compose. Not in a generic way - There is no general way of composing monads.
A comment from Rúnar Bjarnason, coauthor of FP in Scala: "They do compose in a different generic way. For any two monads F and G we can take the coproduct which is roughly Free of Either F or G (up to normalization)".
Another comment from Sergei Winitzki (which caused me to upload https://www.slideshare.net/pjschwarz/addendum-to-monads-do-not-compose): "It is a mistake to think that a traversable monad can be composed with another monad. It is true that, given `Traversable`, you can implement the monad's methods (pure and flatMap) for the composition with another monad (as in your slides 21 to 26), but this is a deceptive appearance. The laws of the `Traversable` typeclass are far insufficient to guarantee the laws of the resulting composed monad. The only traversable monads that work correctly are Option, Either, and Writer. It is true that you can implement the type signature of the `swap` function for any `Traversable` monad. However, the `swap` function for monads needs to satisfy very different and stronger laws than the `sequence` function from the `Traversable` type class. I'll have to look at the "Book of Monads"; but, if my memory serves, the FPiS book does not derive any of these laws." See https://www.linkedin.com/feed/update/urn:li:groupPost:41001-6523141414614814720?commentUrn=urn%3Ali%3Acomment%3A%28groupPost%3A41001-6523141414614814720%2C6532108273053761536%29
Rust
Why do you care about Rust? Who has the time to learn all these new languages? It seems like a new one is popping up every other week and this trend is growing at an exponential rate. Good news, a fair number of them are crafted really well and efficiently solve specific problems. Bad news, how do you keep up with all of this, let alone decide which languages to include in your companies technology portfolio.
Despite the challenges of all these new languages, a majority of developers are intrigued about the idea of becoming a polyglot, but don't know where to begin or don't have the time. In my polyglot travels, there is one language of late that is the sure-fire answer to the above questions, Rust.
In this talk I’ll explore the value behind becoming more polyglotic as a developer, how to pick languages to learn, and then dive deep in the the language of Rust. Which in my opinion, is hands down the best up and coming languages to learn.
About the Presenter
Anthony Broad-Crawford has been a developer since the year 2000 with a short side stint as a semi-professional poker player. Since his transition to software development Anthony has...
1. Built 8 patent receiving technologies
2. Founded two global companies
3. Been a CTO (3x), CPO (1x), and CEO (1x)
and is currently the CTO at Fooda where he manages product, user experience, and engineering. Fooda is predominantly web and mobile technology company focused on bringing great & healthy food from the best restaurant's to people while at the office.
Through his career, in production applications Anthony has used Ruby, Java, Jave (Android), Objective-C and Swift, .NET, Erlang, Scala, Node.JS, LISP, Smalltalk, and even assembly, with his recent favorite, Rust . No, not all at the same time in the same application.
Anthony now spends his time building great teams, that leverage great technology, to build great products, but still looks to codes every chance he can get :)
Developers often wonder how to implement a certain functionality
(e.g., how to parse XML files) using APIs. Obtaining
an API usage sequence based on an API-related natural
language query is very helpful in this regard. Given a query,
existing approaches utilize information retrieval models to
search for matching API sequences. These approaches treat
queries and APIs as bags-of-words and lack a deep understanding
of the semantics of the query.
We propose DeepAPI, a deep learning based approach to
generate API usage sequences for a given natural language
query. Instead of a bag-of-words assumption, it learns the
sequence of words in a query and the sequence of associated
APIs. DeepAPI adapts a neural language model named
RNN Encoder-Decoder. It encodes a word sequence (user
query) into a fixed-length context vector, and generates an
API sequence based on the context vector. We also augment
the RNN Encoder-Decoder by considering the importance
of individual APIs. We empirically evaluate our approach
with more than 7 million annotated code snippets collected
from GitHub. The results show that our approach generates
largely accurate API sequences and outperforms the related
approaches.
Composition is a fundamental principle of functional programming, but how is it different from an object-oriented approach, and how do you use it in practice?
In this talk for beginners, we'll start by going over the basic concepts of functional programming, and then look at some different ways that composition can be used to build large things from small things.
After that, we'll see how composition is used in practice, beginning with a simple FizzBuzz example, and ending with a complete (object-free!) web application.
Sometimes we want to keep or collect errors for later examination. We’ll use Cats to help us pick the story we want to tell when handling errors; accumulated errors or first error wins. Monads will be included!
After a recap of implicits I introduce the type class mechanics in Scala. Then I have a look at ways for good non-intrusive type class design. The main focus of this presentation are type classes in Scala. In the last chapter I show the Haskell implementation of my example.
Trends and future of C++: Evolving a systems language for performance - by Bj...devstonez
Bjarne Stroustrup presentation at Universidad Carlos III de Madrid, march 18 2011 on :
- The design of C++0x
- C++: Machine model and resource management
Accurate and Efficient Refactoring Detection in Commit HistoryNikolaos Tsantalis
Refactoring detection algorithms have been crucial to a variety of applications: (i) empirical studies about the evolution of code, tests, and faults, (ii) tools for library API migration, (iii) improving the comprehension of changes and code reviews, etc. However, recent research has questioned the accuracy of the state-of-the-art refactoring detection tools, which poses threats to the reliability of their application. Moreover, previous refactoring detection tools are very sensitive to user-provided similarity thresholds, which further reduces their practical accuracy. In addition, their requirement to build the project versions/revisions under analysis makes them inapplicable in many real-world scenarios. To reinvigorate a previously fruitful line of research that has stifled, we designed, implemented, and evaluated RefactoringMiner, a technique that overcomes the above limitations. At the heart of RefactoringMiner is an AST-based statement matching algorithm that determines refactoring candidates without requiring user-defined thresholds. To empirically evaluate RefactoringMiner, we created the most comprehensive oracle to date that uses triangulation to create a dataset with considerably reduced bias, representing 3,188 refactorings from 185 open-source projects. Using this oracle, we found that RefactoringMiner has a precision of 98% and recall of 87%, which is a significant improvement over the previous state-of-the-art.
Towards Functional Programming through Hexagonal ArchitectureCodelyTV
Slides of for the talk "Towards Functional Programming through Hexagonal Architecture" delivered at the Software Crafters Barcelona 2018 conference #scbcn18 by Juanma Serrano from Habla Computing and Javier Ferrer from CodelyTV
Functional Core and Imperative Shell - Game of Life Example - Haskell and ScalaPhilip Schwarz
See a program structure flowchart used to highlight how an FP program breaks down into a functional core and imperative shell
View a program structure flowchart for the Game of Life
See the code for Game of Life’s functional core and imperative shell, both in Haskell and in Scala.
Code:
https://github.com/philipschwarz/functional-core-imperative-shell-scala
https://github.com/philipschwarz/functional-core-imperative-shell-haskell
Composition is a fundamental principle of functional programming, but how is it different from an object-oriented approach, and how do you use it in practice?
In this talk for beginners, we'll start by going over the basic concepts of functional programming, and then look at some different ways that composition can be used to build large things from small things.
After that, we'll see how composition is used in practice, beginning with a simple FizzBuzz example, and ending with a complete (object-free!) web application.
Sometimes we want to keep or collect errors for later examination. We’ll use Cats to help us pick the story we want to tell when handling errors; accumulated errors or first error wins. Monads will be included!
After a recap of implicits I introduce the type class mechanics in Scala. Then I have a look at ways for good non-intrusive type class design. The main focus of this presentation are type classes in Scala. In the last chapter I show the Haskell implementation of my example.
Trends and future of C++: Evolving a systems language for performance - by Bj...devstonez
Bjarne Stroustrup presentation at Universidad Carlos III de Madrid, march 18 2011 on :
- The design of C++0x
- C++: Machine model and resource management
Accurate and Efficient Refactoring Detection in Commit HistoryNikolaos Tsantalis
Refactoring detection algorithms have been crucial to a variety of applications: (i) empirical studies about the evolution of code, tests, and faults, (ii) tools for library API migration, (iii) improving the comprehension of changes and code reviews, etc. However, recent research has questioned the accuracy of the state-of-the-art refactoring detection tools, which poses threats to the reliability of their application. Moreover, previous refactoring detection tools are very sensitive to user-provided similarity thresholds, which further reduces their practical accuracy. In addition, their requirement to build the project versions/revisions under analysis makes them inapplicable in many real-world scenarios. To reinvigorate a previously fruitful line of research that has stifled, we designed, implemented, and evaluated RefactoringMiner, a technique that overcomes the above limitations. At the heart of RefactoringMiner is an AST-based statement matching algorithm that determines refactoring candidates without requiring user-defined thresholds. To empirically evaluate RefactoringMiner, we created the most comprehensive oracle to date that uses triangulation to create a dataset with considerably reduced bias, representing 3,188 refactorings from 185 open-source projects. Using this oracle, we found that RefactoringMiner has a precision of 98% and recall of 87%, which is a significant improvement over the previous state-of-the-art.
Towards Functional Programming through Hexagonal ArchitectureCodelyTV
Slides of for the talk "Towards Functional Programming through Hexagonal Architecture" delivered at the Software Crafters Barcelona 2018 conference #scbcn18 by Juanma Serrano from Habla Computing and Javier Ferrer from CodelyTV
Functional Core and Imperative Shell - Game of Life Example - Haskell and ScalaPhilip Schwarz
See a program structure flowchart used to highlight how an FP program breaks down into a functional core and imperative shell
View a program structure flowchart for the Game of Life
See the code for Game of Life’s functional core and imperative shell, both in Haskell and in Scala.
Code:
https://github.com/philipschwarz/functional-core-imperative-shell-scala
https://github.com/philipschwarz/functional-core-imperative-shell-haskell
Constructor is a special member method which will be called automatically when you create an object of any class.
The main purpose of using constructor is to initialize an object.
http://www.tutorial4us.com/java/java-constructor
Effective Java - Chapter 2: Creating and Destroying Objectsİbrahim Kürce
Creating and Destroying Objects: This chapter concerns creating and destroying objects: when and how to create them, when and how to avoid creating them, how to ensure they are destroyed in a timely manner, and how to manage any cleanup actions that must precede their destruction.
This presentation is about Dependency Injection using dagger2 in Android. I highly hope these slides would help you to understand dagger2.
Also, I provide a sample dagger2 repo. So if you want to add dagger2 in your project feel free to use this repo:
https://github.com/javadhme/dagger-master-project
One more thing, If these assets help you to understand dagger2 do not forget to star my github repo.
This is an intermediate conversion course for C++, suitable for second year computing students who may have learned Java or another language in first year.
Effective Java by Joshua Bloch is one of the best handbook to refer while using the Java Language. The presentation covers some of the items and best principles while implementing in Java language.
This workshop is about testing the right way. Get a clear view on how to test your code in an efficient and useful way!
This first testing-related workshop is about all aspects of unit testing. Integration testing and TDD will have their own dedicated workshops.
What a lot of people don't realize is that Google has a lot of powerful tricks hidden up it's sleeve. Here are some of those commands and how they can be best used by a developer.
SAP Sapphire 2024 - ASUG301 building better apps with SAP Fiori.pdfPeter Spielvogel
Building better applications for business users with SAP Fiori.
• What is SAP Fiori and why it matters to you
• How a better user experience drives measurable business benefits
• How to get started with SAP Fiori today
• How SAP Fiori elements accelerates application development
• How SAP Build Code includes SAP Fiori tools and other generative artificial intelligence capabilities
• How SAP Fiori paves the way for using AI in SAP apps
State of ICS and IoT Cyber Threat Landscape Report 2024 previewPrayukth K V
The IoT and OT threat landscape report has been prepared by the Threat Research Team at Sectrio using data from Sectrio, cyber threat intelligence farming facilities spread across over 85 cities around the world. In addition, Sectrio also runs AI-based advanced threat and payload engagement facilities that serve as sinks to attract and engage sophisticated threat actors, and newer malware including new variants and latent threats that are at an earlier stage of development.
The latest edition of the OT/ICS and IoT security Threat Landscape Report 2024 also covers:
State of global ICS asset and network exposure
Sectoral targets and attacks as well as the cost of ransom
Global APT activity, AI usage, actor and tactic profiles, and implications
Rise in volumes of AI-powered cyberattacks
Major cyber events in 2024
Malware and malicious payload trends
Cyberattack types and targets
Vulnerability exploit attempts on CVEs
Attacks on counties – USA
Expansion of bot farms – how, where, and why
In-depth analysis of the cyber threat landscape across North America, South America, Europe, APAC, and the Middle East
Why are attacks on smart factories rising?
Cyber risk predictions
Axis of attacks – Europe
Systemic attacks in the Middle East
Download the full report from here:
https://sectrio.com/resources/ot-threat-landscape-reports/sectrio-releases-ot-ics-and-iot-security-threat-landscape-report-2024/
Key Trends Shaping the Future of Infrastructure.pdfCheryl Hung
Keynote at DIGIT West Expo, Glasgow on 29 May 2024.
Cheryl Hung, ochery.com
Sr Director, Infrastructure Ecosystem, Arm.
The key trends across hardware, cloud and open-source; exploring how these areas are likely to mature and develop over the short and long-term, and then considering how organisations can position themselves to adapt and thrive.
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
GraphRAG is All You need? LLM & Knowledge GraphGuy Korland
Guy Korland, CEO and Co-founder of FalkorDB, will review two articles on the integration of language models with knowledge graphs.
1. Unifying Large Language Models and Knowledge Graphs: A Roadmap.
https://arxiv.org/abs/2306.08302
2. Microsoft Research's GraphRAG paper and a review paper on various uses of knowledge graphs:
https://www.microsoft.com/en-us/research/blog/graphrag-unlocking-llm-discovery-on-narrative-private-data/
Accelerate your Kubernetes clusters with Varnish CachingThijs Feryn
A presentation about the usage and availability of Varnish on Kubernetes. This talk explores the capabilities of Varnish caching and shows how to use the Varnish Helm chart to deploy it to Kubernetes.
This presentation was delivered at K8SUG Singapore. See https://feryn.eu/presentations/accelerate-your-kubernetes-clusters-with-varnish-caching-k8sug-singapore-28-2024 for more details.
Elevating Tactical DDD Patterns Through Object CalisthenicsDorra BARTAGUIZ
After immersing yourself in the blue book and its red counterpart, attending DDD-focused conferences, and applying tactical patterns, you're left with a crucial question: How do I ensure my design is effective? Tactical patterns within Domain-Driven Design (DDD) serve as guiding principles for creating clear and manageable domain models. However, achieving success with these patterns requires additional guidance. Interestingly, we've observed that a set of constraints initially designed for training purposes remarkably aligns with effective pattern implementation, offering a more ‘mechanical’ approach. Let's explore together how Object Calisthenics can elevate the design of your tactical DDD patterns, offering concrete help for those venturing into DDD for the first time!
GDG Cloud Southlake #33: Boule & Rebala: Effective AppSec in SDLC using Deplo...James Anderson
Effective Application Security in Software Delivery lifecycle using Deployment Firewall and DBOM
The modern software delivery process (or the CI/CD process) includes many tools, distributed teams, open-source code, and cloud platforms. Constant focus on speed to release software to market, along with the traditional slow and manual security checks has caused gaps in continuous security as an important piece in the software supply chain. Today organizations feel more susceptible to external and internal cyber threats due to the vast attack surface in their applications supply chain and the lack of end-to-end governance and risk management.
The software team must secure its software delivery process to avoid vulnerability and security breaches. This needs to be achieved with existing tool chains and without extensive rework of the delivery processes. This talk will present strategies and techniques for providing visibility into the true risk of the existing vulnerabilities, preventing the introduction of security issues in the software, resolving vulnerabilities in production environments quickly, and capturing the deployment bill of materials (DBOM).
Speakers:
Bob Boule
Robert Boule is a technology enthusiast with PASSION for technology and making things work along with a knack for helping others understand how things work. He comes with around 20 years of solution engineering experience in application security, software continuous delivery, and SaaS platforms. He is known for his dynamic presentations in CI/CD and application security integrated in software delivery lifecycle.
Gopinath Rebala
Gopinath Rebala is the CTO of OpsMx, where he has overall responsibility for the machine learning and data processing architectures for Secure Software Delivery. Gopi also has a strong connection with our customers, leading design and architecture for strategic implementations. Gopi is a frequent speaker and well-known leader in continuous delivery and integrating security into software delivery.
Securing your Kubernetes cluster_ a step-by-step guide to success !KatiaHIMEUR1
Today, after several years of existence, an extremely active community and an ultra-dynamic ecosystem, Kubernetes has established itself as the de facto standard in container orchestration. Thanks to a wide range of managed services, it has never been so easy to set up a ready-to-use Kubernetes cluster.
However, this ease of use means that the subject of security in Kubernetes is often left for later, or even neglected. This exposes companies to significant risks.
In this talk, I'll show you step-by-step how to secure your Kubernetes cluster for greater peace of mind and reliability.
3. Preface (Summary)
In preface, static factory methods and public constructors both have
their uses, and it pays to understand their relative merits. Often static
factories are preferable, so avoid the reflex to provide public
constructors without first considering static factories.
4. Static Factory Methods
• The normal way for a class to allow a client to obtain an instance of
itself is to provide a public constructor. There is another technique
that should be a part of every programmer’s toolkit.
• A class can provide a public static factory method, which is simply a
static method that returns an instance of the class.
5. Static Factory Methods
Here’s a simple example from Boolean (the boxed primitive class for
the primitive type boolean). This method translates a boolean primitive
value into a Boolean object reference:
public static Boolean valueOf(boolean b) {
return b ? Boolean.TRUE : Boolean.FALSE;
}
A class can provide its clients with static factory methods instead of, or
in addition to, constructors. Providing a static factory method instead of
a public constructor has both advantages and disadvantages.
6. Advantages
First advantage of static factory methods is that, unlike
constructors, they have names.
• If the parameters to a constructor do not, in and of themselves,
describe the object being returned, a static factory with a well-chosen
name is easier to use and the resulting client code easier to read.
• Now let’s seen by an example.
7. Advantages
• Look at the following example.
• We have a RandomIntGenerator class that, as the name suggests,
generates random int numbers. Something like:
public class RandomIntGenerator {
private final int min;
private final int max;
public int next() {...}
}
8. Advantages
• Our generator takes a minimum and maximum and then generates
random numbers between those 2 values. Notice that the two
attributes are declared final so we have to initialize them either on
their declaration or in the class constructor. Let’s go with the
constructor:
public RandomIntGenerator(int min, int max) {
this.min = min;
this.max = max;
}
9. Advantages
• Now, we also want to give our clients the possibility to specify just a
minimum value and then generate random values between that
minimum and the max possible value for ints. So we add a second
constructor:
public RandomIntGenerator(int min) {
this.min = min;
this.max = Integer.MAX_VALUE;
}
10. Advantages
• So far so good, right? But in the same way that we provided a
constructor to just specify the minimum value, we want to do the
same for just the maximum. We’ll just add a third constructor like:
public RandomIntGenerator(int max) {
this.min = Integer.MIN_VALUE;
this.max = max;
}
• If you try that, you’ll get a compilation error that goes: Duplicate
method RandomIntGenerator(int) in type RandomIntGenerator.
What’s wrong?
11. Advantages
• Full script:
public class RandomIntGenerator {
private final int min;
private final int max;
public int next() {...}
public RandomIntGenerator(int min, int max) {
this.min = min;
this.max = max;
}
public RandomIntGenerator(int min) {
this.min = min;
this.max = Integer.MAX_VALUE;
}
/* Compilation error will be occurred. */
public RandomIntGenerator(int max) {
this.min = Integer.MIN_VALUE;
this.max = max;
}
}
12. Advantages
• The problem is that constructors, by definition, have no names. As
such, a class can only have one constructor with a given signature in
the same way that you can’t have two methods with the same
signature (same return type, name and parameters type).
• That is why when we tried to add the RandomIntGenerator(int
max) constructor we got that compilation error, because we already
had the RandomIntGenerator(int min) one.
13. Advantages
• Now let’s apply static factories to our RandomIntGenerator example, we could
get:
public class RandomIntGenerator {
private final int min;
private final int max;
// private constructor to non-institate class
private RandomIntGenerator(int min, int max) {
this.min = min;
this.max = max;
}
public static RandomIntGenerator between(int max, int min) {
return new RandomIntGenerator(min, max);
}
public static RandomIntGenerator biggerThan(int min) {
return new RandomIntGenerator(min, Integer.MAX_VALUE);
}
public static RandomIntGenerator smallerThan(int max) {
return new RandomIntGenerator(Integer.MIN_VALUE, max);
}
public int next() {...}
}
14. Advantages
• Note : How the constructor was made private to ensure that the
class is only instantiated through its public static factory methods.
• Also note how your intent is clearly expressed when you have a client
with RandomIntGenerator.between(10,20) instead of
new RandomIntGenerator(10,20)
• Point is clear, we replace the constructors with static factory methods
and carefully chosen names to highlight their differences.
15. Advantages
A second advantage of static factory methods is that, unlike
constructors, they are not required to create a new object each
time they’re invoked.
This is extremely useful when working with immutable classes to
provide constant objects for common used values and avoid creating
unnecessary duplicate objects. (You can refer avoid creating uncessary objects in this link
http://www.slideshare.net/mysky14/avoid-creating-unncessary-objects)
16. Advantages
public static Boolean valueOf(boolean b) {
return b ? Boolean.TRUE : Boolean.FALSE;
}
• The Boolean.valueOf code that I showed previously illustrates this
point perfectly. Notice that this static method returns either TRUE
or FALSE, both immutable Boolean objects.
• This technique is similar to the Flyweight pattern (I am promise I will post about this
pattern in near future, please don’t forget to following me at slideshare.). It can greatly improve
performance if equivalent objects are requested often, especially if
they are expensive to create.
17. Advantages
A third advantage of static factory methods is that, unlike
constructors, they can return an object of any subtype of their return
type.
• This gives you great flexibility in choosing the class of the returned
object.
• Moreover, you can hide implementation classes and have an interface-
based API (I am promise I will post about this interface-based framework in near future, please don’t forget to following me at slideshare.),
which is usually a really good idea.
• But I think this can be better seen by an example.
18. Advantages
• Look at the following example.
• Imagine that we now want to provide random generators not just for
integers but for other data-types like String, Double or Long. They are
all going to have a next() method that returns a random object of a
particular type, so we could start with an interface like:
public interface RandomGenerator<T> {
T next();
}
19. Advantages
• Our first implementation of the RandomIntGenerator now becomes:
class RandomIntGenerator implements RandomGenerator<Integer> {
private final int min;
private final int max;
RandomIntGenerator(int min, int max) {
this.min = min;
this.max = max;
}
public Integer next() {...}
}
20. Advantages
• We could also have a String generator:
class RandomStringGenerator implements RandomGenerator<String>
{
private final String prefix;
RandomStringGenerator(String prefix) {
this.prefix = prefix;
}
public String next() {...}
}
21. Advantages
• Notice how all the classes are declared package-private (default scope) and so
are their constructors. This means that no client outside of their package can
create instances of these generators. So what do we do? Tip: It starts with
“static” and ends with “methods”. Consider the following class:
public final class RandomGenerators {
// Suppresses default constructor, ensuring non-instantiability.
private RandomGenerators() {}
public static final RandomGenerator<Integer> getIntGenerator() {
return new RandomIntGenerator(Integer.MIN_VALUE, Integer.MAX_VALUE);
}
public static final RandomGenerator<String> getStringGenerator() {
return new RandomStringGenerator("");
}
}
22. Advantages
• RandomGenerators is just a noninstantiable utility class with nothing
else than static factory methods. Being on the same package as the
different generators this class can effectively access and instantiate
those classes. But here comes the interesting part.
• Note that the methods only return the RandomGenerator interface,
and that’s all the clients need really.
• If they get a RandomGenerator<Integer> they know that they can
call next() and get a random integer.
23. Advantages
Not only can the class of an object returned by a public static factory
method be nonpublic, but the class can vary from invocation to
invocation depending on the values of the parameters to the static
factory.
Any class that is a subtype of the declared return type is permissible.
The class of the returned object can also vary from release to release
for enhanced software maintainability and performance.
24. Advantages
• A fourth advantage of static factory methods is that they reduce
the verbosity of creating parameterized type instances.
• Have you ever had to write code like this?
Map<String, List<String>> map = new HashMap<String,List<String>>();
25. Advantages
• You are repeating the same parameters twice on the same line of
code. Wouldn’t it be nice if the right side of the assign could
be inferred from the left side?
• Well, with static factories it can. The following code is taken from
Guava’s Maps class:
public static <K, V> HashMap<K, V> newHashMap() {
return new HashMap<K, V>();
}
• So now our client code becomes:
Map<String, List<String>> map = Maps.newHashMap();
26. Advantages
• Pretty nice, isn’t it? This capability is known as Type inference. It’s
worth mentioning that Java 7 introduced type inference through the
use of the diamond operator. So if you’re using Java 7 you can write
the previous example as:
Map<String, List<String>> map = new HashMap<>();
• Unfortunately, the standard collection implementations such as
HashMap do not have factory methods as of release 1.6, but you can
put these methods in your own utility class.
• More importantly, you can provide such static factories in your
own parameterized classes.
27. Disadvantages
The main disadvantage of static factories is that classes without
public or protected constructors cannot be extended. But this might
be actually a good thing in some cases because it encourages
developers to favor composition over inheritance. (I am promise I will post about this
interface-based framework in near future, please don’t forget to following me at slideshare.)
• The same is true for nonpublic classes returned by public static factories.
For example, it is impossible to subclass any of the convenience
implementation classes in the Collections Framework.
• But I think this can be better seen by an our own example.
28. Disadvantages
• Suppose you have a class called Person:
class Person {
public static Person createWithFirstName(String firstName) {
return new Person(firstName, null, null);
}
// etc. - more factory methods
// private constructor
private Person(String firstName, String lastName, String nickname) { }
// useful method
public String getDisplayName() { }
}
29. Disadvantages
• It's all good and dandy. But now you also need a class
called Programmer, and you suddenly realize the programmers
are persons too!
• But all of a sudden, you can't just
class Programmer extends Person { }
• since Person doesn't have any public constructors.
• You can’t not subclassed which are not have public or protected
constructor.
30. Summary (Preface)
• In summary, static factory methods and public constructors both have
their uses, and it pays to understand their relative merits. Often static
factories are preferable, so avoid the reflex to provide public
constructors without first considering static factories.