Roles are an excellent object-oriented tool both for allomorphism and for
reuse.
Roles facilitate allomorphism by favoring "does this object do X" versus "is
this object a subclass of X". You often care more about capability than
inheritance. In a sense, roles encode types better than inheritance.
Roles also provide an excellent faculty for reuse. This effectively eliminates
multiple inheritance, which is often the only solution for sharing code between
unrelated classes.
Roles can combine with conflict detection. This eliminates accidental shadowing
of methods that is painful with multiple inheritance and mixins.
Parameterized roles (via MooseX::Role::Parameterized) improve the reusability
of roles by letting each consumer cater the role to its needs. This does
sacrifice some allomorphism, but there are ways to restore it.
Part of a series of talk to help you write your first Perl 6 program today. So its basic syntax and concepts of its object orientation and a comparison to the widely used P5 OO system Moose which is similar by no accident.
There are a lot of operators in Perl 6, so many that it can be called an OOL: operator oriented language. Here I describe most of them from the angle of contexts, which Perl 6 has also much more than Perl 5.
"How was it to switch from beautiful Perl to horrible JavaScript", Viktor Tur...Fwdays
I use JavaScript since 2006. That time I did single-page applications for IE6 in JS (it was ES3) and backend in Perl. JS was a pain. Does it better now? During my talk, I would like to show the fundamental difference between modern JS and Perl. How the same problems can be solved in different ways. Hope to give you a broader view on what programming languages can provide. Be prepared for interaction and to help me with simple tasks/problems in JavaScript :)
This is the Moose talk I gave at YAPC::NA 2012.
It included a practical example of a Moose objects code, a simple app called Comican. The code is not available online. If you want it, just email me (sawyer ATT cpan DOTT org).
PHP 7 – What changed internally? (Forum PHP 2015)Nikita Popov
One of the main selling points of PHP 7 is greatly improved performance, with many real-world applications now running twice as fast… But where do these improvements come from?
At the core of PHP 7 lies an engine rewrite with focus on improving memory usage and performance. This talk provides an overview of the most significant changes, briefly covering everything from data structure changes, over enhancements in the executor, to the new compiler implementation.
Part of a series of talk to help you write your first Perl 6 program today. So its basic syntax and concepts of its object orientation and a comparison to the widely used P5 OO system Moose which is similar by no accident.
There are a lot of operators in Perl 6, so many that it can be called an OOL: operator oriented language. Here I describe most of them from the angle of contexts, which Perl 6 has also much more than Perl 5.
"How was it to switch from beautiful Perl to horrible JavaScript", Viktor Tur...Fwdays
I use JavaScript since 2006. That time I did single-page applications for IE6 in JS (it was ES3) and backend in Perl. JS was a pain. Does it better now? During my talk, I would like to show the fundamental difference between modern JS and Perl. How the same problems can be solved in different ways. Hope to give you a broader view on what programming languages can provide. Be prepared for interaction and to help me with simple tasks/problems in JavaScript :)
This is the Moose talk I gave at YAPC::NA 2012.
It included a practical example of a Moose objects code, a simple app called Comican. The code is not available online. If you want it, just email me (sawyer ATT cpan DOTT org).
PHP 7 – What changed internally? (Forum PHP 2015)Nikita Popov
One of the main selling points of PHP 7 is greatly improved performance, with many real-world applications now running twice as fast… But where do these improvements come from?
At the core of PHP 7 lies an engine rewrite with focus on improving memory usage and performance. This talk provides an overview of the most significant changes, briefly covering everything from data structure changes, over enhancements in the executor, to the new compiler implementation.
Love it or hate it, JavaScript is playing an increasingly important role in the next generation of web and mobile apps. As code continues to move from the server to the client, JavaScript is being used to do more than simple HTML manipulation. Be prepared for this transition and make sure the JavaScript you write is optimized and ready to perform on desktops and devices! In this session, you will learn ten practical tips that you can use today to write faster, more maintainable, memory friendly JavaScript.
A short introduction to the perl debugger's basic commands for executing code, examining data structures. Includes examples of hardwiring breakpoints, tracing sections of code, debugging regexen.
This is the fifth set of slightly updated slides from a Perl programming course that I held some years ago.
I want to share it with everyone looking for intransitive Perl-knowledge.
A table of content for all presentations can be found at i-can.eu.
The source code for the examples and the presentations in ODP format are on https://github.com/kberov/PerlProgrammingCourse
This describes a Functional Programming approach to computing AWS Glacier "tree hash" values, hiding the tail-call elimination in Perl5 with a keyword and also shows how to accomplish the same result in Perl6.
This was the talk actually given at YAPC::NA 2016 by Dr. Conway and myself.
Python's "batteries included" philosophy means that it comes with an astonishing amount of great stuff. On top of that, there's a vibrant world of third-party libraries that help make Python even more wonderful. We'll go on a breezy, example-filled tour through some of my favorites, from treasures in the standard library to great third-party packages that I don't think I could live without, and we'll touch on some of the fuzzier aspects of the Python culture that make it such a joy to be part of.
Performance and testing are just one aspect of code, to really be successful your code needs to be readable, maintainable and generally easier to comprehend and work with. This talk draws from my own experience in applying the techniques of object calisthenics and code readability, within an existing team. It will help you identify trouble areas, learn how to refactor them and train you to write better code in future projects avoiding common pitfalls.
If your not using an ORM (object relational mapper) and are still writing SQL by hand, here's what you need to know.
An introduction into DBIx::Class and some of the concepts and goodies you should be aware off.
PHP 8.0 comes with many long-awaited features: A just-in-time compiler, attributes, union types, and named arguments are just a small part of the list. As a major version, it also includes some backward-incompatible changes, which are centered around stricter error handling and enhanced type safety. Let's have an overview of the important changes in PHP 8.0 and how they might affect you!
Perl, a cross-platform, open-source computer programming language used widely in the commercial and private computing sectors. Perl is a favourite among Web developers for its flexible, continually evolving text-processing and problem-solving capabilities.
One key benefit of Moose is the Object-Oriented jargon it brings to the table.
With Moose, it's very easy to implement common design patterns, as I present in the keynote.
This keynote was part of the Israeli Perl Workshop 2011.
Love it or hate it, JavaScript is playing an increasingly important role in the next generation of web and mobile apps. As code continues to move from the server to the client, JavaScript is being used to do more than simple HTML manipulation. Be prepared for this transition and make sure the JavaScript you write is optimized and ready to perform on desktops and devices! In this session, you will learn ten practical tips that you can use today to write faster, more maintainable, memory friendly JavaScript.
A short introduction to the perl debugger's basic commands for executing code, examining data structures. Includes examples of hardwiring breakpoints, tracing sections of code, debugging regexen.
This is the fifth set of slightly updated slides from a Perl programming course that I held some years ago.
I want to share it with everyone looking for intransitive Perl-knowledge.
A table of content for all presentations can be found at i-can.eu.
The source code for the examples and the presentations in ODP format are on https://github.com/kberov/PerlProgrammingCourse
This describes a Functional Programming approach to computing AWS Glacier "tree hash" values, hiding the tail-call elimination in Perl5 with a keyword and also shows how to accomplish the same result in Perl6.
This was the talk actually given at YAPC::NA 2016 by Dr. Conway and myself.
Python's "batteries included" philosophy means that it comes with an astonishing amount of great stuff. On top of that, there's a vibrant world of third-party libraries that help make Python even more wonderful. We'll go on a breezy, example-filled tour through some of my favorites, from treasures in the standard library to great third-party packages that I don't think I could live without, and we'll touch on some of the fuzzier aspects of the Python culture that make it such a joy to be part of.
Performance and testing are just one aspect of code, to really be successful your code needs to be readable, maintainable and generally easier to comprehend and work with. This talk draws from my own experience in applying the techniques of object calisthenics and code readability, within an existing team. It will help you identify trouble areas, learn how to refactor them and train you to write better code in future projects avoiding common pitfalls.
If your not using an ORM (object relational mapper) and are still writing SQL by hand, here's what you need to know.
An introduction into DBIx::Class and some of the concepts and goodies you should be aware off.
PHP 8.0 comes with many long-awaited features: A just-in-time compiler, attributes, union types, and named arguments are just a small part of the list. As a major version, it also includes some backward-incompatible changes, which are centered around stricter error handling and enhanced type safety. Let's have an overview of the important changes in PHP 8.0 and how they might affect you!
Perl, a cross-platform, open-source computer programming language used widely in the commercial and private computing sectors. Perl is a favourite among Web developers for its flexible, continually evolving text-processing and problem-solving capabilities.
One key benefit of Moose is the Object-Oriented jargon it brings to the table.
With Moose, it's very easy to implement common design patterns, as I present in the keynote.
This keynote was part of the Israeli Perl Workshop 2011.
Using Moose provides many immediate and obvious benefits, starting with the
obviation of typing "use strict" and "use warnings" in your classes.
The real power of Moose, however, rests in its extensibility. By subclassing
Moose's metaclasses, you can augment and change Moose's behavior to suit your
application's needs. This extensibility is powered by the meta-object protocol
of Moose's foundation, Class::MOP.
The motivating example for extending Moose will be the creation of a small web
framework to empower a Twitter-alike. The focus will be creating meta-level
roles so that metaclasses may select exactly which changes in behavior they
wish to exhibit. Modules that will be used include Moose::Exporter (to define
sugary keywords) and Moose::Util::MetaRole (to extend classes composably).
Experience with using Moose to create regular classes is expected. Having some
familiarity with roles will let you get more out of the talk. No experience
with metaprogramming is required.
Test::Class::Moose combines Test::Class, Moose and Test::Most to take test suites to the next level. It gives you unparalleled levels of control and information for you test suite.
jQuery is a different type of JavaScript library, with emphasis on getting the job done with the most efficient code possible. JavaScript DOM manipulation -- even with some existing JavaScript libraries -- can be tedious and uninteresting. But jQuery provides a new and exciting way to wrap existing markup with awesome dynamic functionality in a few lines of code. Not only is the approach powerful, but elegant as well. This presentation will go over the key parts of the jQuery library, including selectors, DOM transversal and manipulations, events, effects, and ajax -- including running code examples.
Running C# in the browser with the Blazor framework needs JavaScript libraries to be successful. In this session well explore the JavaScript Interop for Blazor to see where great libraries can accelerate the platform. We'll learn how you can play a critical role in building a rich ecosystem and extend your skills as a JavaScript developer to share in the success of your .NET team mates.
Lithium: The Framework for People Who Hate FrameworksNate Abele
This is the presentation was given at ConFoo on March 11th by Nate Abele and Joël Perras, and is an introduction to the architectural problems with other frameworks that Lithium was designed to address, and how it addresses them. It also introduces programming paradigms like functional and aspect-oriented programming which address issues that OOP doesn't account for.
Finally, the talk provides a quick overview of the innovative and unparalleled features that Lithium provides, including the data layer, which supports both relational and non-relational databases.
jQuery & 10,000 Global Functions: Working with Legacy JavaScriptGuy Royse
Long ago, in the late days of the first Internet boom, before jQuery, before Underscore, before Angular, there was a web application built by a large corporation. This application was written as a server-side application using server-side technology like Java or PHP. A tiny seed of JavaScript was added to some of the pages of this application to give it a little sizzle.
Over the ages, this tiny bit of JavaScript grew like kudzu. Most of it was embedded in the HTML in
TDC 2014 - JavaScript de qualidade: hoje, amanhã e sempre!Guilherme Carreiro
O JavaScript não escapa da polêmica sobre qualidade de código. Descubra nessa palestra como identificar bad smells que ameaçam a integridade do front-end e aprenda a melhorar seu código usando design patterns e orientação a objetos avançada em JavaScript. Veja através de exemplos práticos as evoluções da API da linguagem com o ECMAScript 6 e como é possível começar a adotar práticas do futuro.
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.
Removing Uninteresting Bytes in Software FuzzingAftab Hussain
Imagine a world where software fuzzing, the process of mutating bytes in test seeds to uncover hidden and erroneous program behaviors, becomes faster and more effective. A lot depends on the initial seeds, which can significantly dictate the trajectory of a fuzzing campaign, particularly in terms of how long it takes to uncover interesting behaviour in your code. We introduce DIAR, a technique designed to speedup fuzzing campaigns by pinpointing and eliminating those uninteresting bytes in the seeds. Picture this: instead of wasting valuable resources on meaningless mutations in large, bloated seeds, DIAR removes the unnecessary bytes, streamlining the entire process.
In this work, we equipped AFL, a popular fuzzer, with DIAR and examined two critical Linux libraries -- Libxml's xmllint, a tool for parsing xml documents, and Binutil's readelf, an essential debugging and security analysis command-line tool used to display detailed information about ELF (Executable and Linkable Format). Our preliminary results show that AFL+DIAR does not only discover new paths more quickly but also achieves higher coverage overall. This work thus showcases how starting with lean and optimized seeds can lead to faster, more comprehensive fuzzing campaigns -- and DIAR helps you find such seeds.
- These are slides of the talk given at IEEE International Conference on Software Testing Verification and Validation Workshop, ICSTW 2022.
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.
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/
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.
Enhancing Performance with Globus and the Science DMZGlobus
ESnet has led the way in helping national facilities—and many other institutions in the research community—configure Science DMZs and troubleshoot network issues to maximize data transfer performance. In this talk we will present a summary of approaches and tips for getting the most out of your network infrastructure using Globus Connect Server.
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
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.
Observability Concepts EVERY Developer Should Know -- DeveloperWeek Europe.pdfPaige Cruz
Monitoring and observability aren’t traditionally found in software curriculums and many of us cobble this knowledge together from whatever vendor or ecosystem we were first introduced to and whatever is a part of your current company’s observability stack.
While the dev and ops silo continues to crumble….many organizations still relegate monitoring & observability as the purview of ops, infra and SRE teams. This is a mistake - achieving a highly observable system requires collaboration up and down the stack.
I, a former op, would like to extend an invitation to all application developers to join the observability party will share these foundational concepts to build on:
The Metaverse and AI: how can decision-makers harness the Metaverse for their...Jen Stirrup
The Metaverse is popularized in science fiction, and now it is becoming closer to being a part of our daily lives through the use of social media and shopping companies. How can businesses survive in a world where Artificial Intelligence is becoming the present as well as the future of technology, and how does the Metaverse fit into business strategy when futurist ideas are developing into reality at accelerated rates? How do we do this when our data isn't up to scratch? How can we move towards success with our data so we are set up for the Metaverse when it arrives?
How can you help your company evolve, adapt, and succeed using Artificial Intelligence and the Metaverse to stay ahead of the competition? What are the potential issues, complications, and benefits that these technologies could bring to us and our organizations? In this session, Jen Stirrup will explain how to start thinking about these technologies as an organisation.
Essentials of Automations: The Art of Triggers and Actions in FMESafe Software
In this second installment of our Essentials of Automations webinar series, we’ll explore the landscape of triggers and actions, guiding you through the nuances of authoring and adapting workspaces for seamless automations. Gain an understanding of the full spectrum of triggers and actions available in FME, empowering you to enhance your workspaces for efficient automation.
We’ll kick things off by showcasing the most commonly used event-based triggers, introducing you to various automation workflows like manual triggers, schedules, directory watchers, and more. Plus, see how these elements play out in real scenarios.
Whether you’re tweaking your current setup or building from the ground up, this session will arm you with the tools and insights needed to transform your FME usage into a powerhouse of productivity. Join us to discover effective strategies that simplify complex processes, enhancing your productivity and transforming your data management practices with FME. Let’s turn complexity into clarity and make your workspaces work wonders!
Encryption in Microsoft 365 - ExpertsLive Netherlands 2024Albert Hoitingh
In this session I delve into the encryption technology used in Microsoft 365 and Microsoft Purview. Including the concepts of Customer Key and Double Key Encryption.
zkStudyClub - Reef: Fast Succinct Non-Interactive Zero-Knowledge Regex ProofsAlex Pruden
This paper presents Reef, a system for generating publicly verifiable succinct non-interactive zero-knowledge proofs that a committed document matches or does not match a regular expression. We describe applications such as proving the strength of passwords, the provenance of email despite redactions, the validity of oblivious DNS queries, and the existence of mutations in DNA. Reef supports the Perl Compatible Regular Expression syntax, including wildcards, alternation, ranges, capture groups, Kleene star, negations, and lookarounds. Reef introduces a new type of automata, Skipping Alternating Finite Automata (SAFA), that skips irrelevant parts of a document when producing proofs without undermining soundness, and instantiates SAFA with a lookup argument. Our experimental evaluation confirms that Reef can generate proofs for documents with 32M characters; the proofs are small and cheap to verify (under a second).
Paper: https://eprint.iacr.org/2023/1886
Dev Dives: Train smarter, not harder – active learning and UiPath LLMs for do...UiPathCommunity
💥 Speed, accuracy, and scaling – discover the superpowers of GenAI in action with UiPath Document Understanding and Communications Mining™:
See how to accelerate model training and optimize model performance with active learning
Learn about the latest enhancements to out-of-the-box document processing – with little to no training required
Get an exclusive demo of the new family of UiPath LLMs – GenAI models specialized for processing different types of documents and messages
This is a hands-on session specifically designed for automation developers and AI enthusiasts seeking to enhance their knowledge in leveraging the latest intelligent document processing capabilities offered by UiPath.
Speakers:
👨🏫 Andras Palfi, Senior Product Manager, UiPath
👩🏫 Lenka Dulovicova, Product Program Manager, UiPath
Dev Dives: Train smarter, not harder – active learning and UiPath LLMs for do...
(Parameterized) Roles
1. (Parameterized)
Roles
Shawn M Moore
Best Practical Solutions
http://sartak.org
2. "The more I use roles, the less I
understand why anyone would
want to use the inheritance
model." - Ovid
"A role-aware type system allows
you to express yourself with
better genericity."
- chromatic
"Roles are the sound of diamond
inheritance that people have
stopped banging their heads
against." - hdp
( )
3. Example Role
package Counter;
use Moose::Role;
has counter => (
is => 'ro',
isa => 'Int',
default => 0,
);
sub increment {
my $self = shift;
$self->counter($self->counter + 1);
}
4. Example Role
package Counter;
use Moose::Role;
has counter => (
is => 'ro',
isa => 'Int',
default => 0,
);
sub increment {
my $self = shift;
$self->counter($self->counter + 1);
}
use Moose
5. Example Role
use MooseX::Declare;
role Counter {
has counter => (
is => 'ro',
isa => 'Int',
default => 0,
);
method increment {
$self->counter($self->counter + 1);
}
}
6. Consuming a Role
class Odometer with Counter {
method reset(Crook $you) {
$you->break_into($self);
$self->counter(0);
$you->plead('innocent');
}
}
with
8. Consuming a Role
class Odometer with Counter {
method reset(Crook $you) {
$you->break_into($self);
$self->counter(0);
$you->plead('innocent');
}
}
counter
9. Consuming a Role
class Odometer extends Widget with Counter {
method reset(Crook $you) {
$you->break_into($self);
$self->counter(0);
$you->plead('innocent');
}
}
10. class Odometer extends Widget {
has counter => (
is => 'ro',
isa => 'Int',
default => 0,
);
method increment {
$self->counter($self->counter + 1);
}
method reset(Crook $you) {
$you->break_into($self);
$self->counter(0);
$you->plead('innocent');
}
}
11. Class Building
Blocks
class Action::Throw
with Action::Role::Direction
with Action::Role::Item {
…
}
class Action::Melee
with Action::Role::Monster
with Action::Role::Direction {
…
}
12. Class Building
Blocks
class Action::Throw
with Action::Role::Direction
with Action::Role::Item {
…
}
class Action::Melee
with Action::Role::Monster
with Action::Role::Direction {
…
}
13. Class Building
Blocks
class Action::Throw
extends Action::Direction
extends Action::Item {
…
}
class Action::Melee
extends Action::Monster
extends Action::Direction {
…
}
20. Multiple Roles
Due to a method name conflict in roles
'Action::Direction' and 'Action::Monster', the
method 'name' must be implemented or
excluded by 'Action::Melee'
Moose
25. class Action::Melee
with Action::Direction
alias { name => 'direction_name' }
with Action::Monster
alias { name => 'monster_name' }
{
method name {
loc '%1 (at %2)',
$self->monster_name,
$self->direction_name;
}
}
2
26. Conflict Resolution
Due to a method name conflict in roles
'Action::Direction' and 'Action::Monster', the
method 'name' must be implemented or
excluded by 'Action::Melee'
27. Conflict Resolution
Due to a method name conflict in roles
'Action::Direction' and 'Action::Monster', the
method 'name' must be implemented or
excluded by 'Action::Melee'
28. Conflict Resolution
Due to a method name conflict in roles
'Action::Direction' and 'Action::Monster', the
method 'name' must be implemented or
excluded by 'Action::Melee'
78. See Also
Moose::Manual::Roles
"The Why of Perl Roles"
"Eliminating Inheritance via Smalltalk-Style
Traits"
"Traits - Composing Classes from Behavioral
Building Blocks"
Editor's Notes
Presented YAPC::Asia, 2009-09-11.
Tokyo Institute of Technology, Tokyo, Japan.
You've probably heard a lot about this new feature called "roles" lately. Not only are a lot of people talking about roles, but a lot of people are using roles. And for good reason!
Before I get into what a role is, and why roles are awesome, I want to just dive into what a role looks like.
You might notice a strong resemblance to regular Moose code. The only difference is that we "use Moose::Role" instead of "use Moose". This means that this package represents a role instead of a class. Oh, damnit, wait a second.
Much better. Anyway, so we have a role named Counter with an attribute and an increment method. Roles are not classes, so we can't call Counter->new. A role is more just a container for methods and attributes.
This is what consuming a role looks like. Here we have a class that needs a counter for keeping track of how many miles you have driven. "with" is the key word for consuming a role, much like "extends" is the key word for subclassing.
It is a very serious crime.
As you can see here, the role has added the counter attribute to Odometer. It also gained the increment method, which is presumably called by other parts of the system.
I must stress that consuming a role is not inheritance. You can still use inheritance alongside roles. What roles do are "flatten" its bits into the class.
The flattening is a lot like copying and pasting the code from the role into its consumer. That's even a pretty good description of what happens behind the scenes, though it doesn't happen at the strings-of-code level.
My favorite feature of roles is their reusability. One way to look at roles is that they are class building blocks.
If we factor out common behavior, we get to name that chunk of behavior, and reuse all that code. We know that these two actions have something to do with direction.
You might be wondering how any of this is better than multiple inheritance. Surely you know multiple inheritance is evil, right? RIGHT?
By the way, did anyone here even know how to use multiple inheritance with MooseX::Declare? I sure didn't until I wrote this slide.
Let's look at an example of why multiple inheritance is maligned. Here we have a class with a "name" method.
Now we have another class. It just has a direction.
And now we have a class that inherits from both of those.
So everything is fine right now. But at some point the requirements change.
We need a "name" method in Action::Direction for some other class.
This used to return monster name. Now this has changed without warning to the direction name, because Action::Direction is the leftmost parent. I hope your tests are very thorough!
This is a huge pain to debug. Code reuse and cleanliness is often not worth this pain, so we avoid multiple inheritance.
If these were roles instead, something very different happens.
Once we add the "name" method to Direction, we get this error. I'll talk about what it means soon, but one nice thing about this error is Moose throws it..
...immediately. You don't have to wait for the class to be instantiated, or the "name" method to be called. Moose throws conflict error at "with" time.
So this code is an error. But as alluded to in the error message, we can resolve this conflict. There are several ways to do this.
The class could define its own method. When a class defines a method and a role it consumes defines the same method, the class wins. So this resolves the conflict by overriding the "name" methods from the two roles. It's kind of like plugging your ears and yelling that everything is okay. But sometimes that really is all you need.
Another option is to exclude one of the conflicting methods. This way, Direction's "name" method is the one that is added to Melee. Obviously you can only use this where it makes sense. It probably doesn't make sense to use it in this example.
XXX: This syntax doesn't actually work yet as of 2009-08-22. A failing test has been submitted!
Another option is to combine the two methods. Here we disambiguate the two conflicting "name" methods, then use them in our own "name" method which serves both roles well enough.
I've found that this is usually the best solution.
So now we know what this error message means.
You can override the conflicting methods in the class, with or without reusing each conflicting method.
Or, if it makes sense, just exclude one of the methods so that it's no longer a conflict.
Try that with multiple inheritance. Yeah right!
Because of the flattening property of roles, and because of this conflict detection and resolution, the diamond inheritance problem doesn't apply to roles. Any ambiguity is a compile-time error, and the programmer has several tools to resolve such ambiguities. Role composition is much more pleasant to work with than multiple inheritance.
Suppose we have a role that assumes a particular method exists in each of its consumers. In this case, we're calling "tile" even though we don't know for sure that each consumer will have that method.
This code will work fine. We consume the role, Action::Chat gets the new methods, and everything is hunky-dory.
But at runtime when we try to call this method, we get an error.
This sucks. The author of the Monster role demands that consumers have a "tile" method. Perhaps the role's documentation does notify you that consumers must have it, but who even reads documentation any more? It would be nice to be able to codify this requirement.
And, of course, you can. If a role calls methods that it doesn't provide itself, the role should require them.
And like a conflict, we get this error at compile time. Much better than a method-missing error at runtime when we try to call ->tile. The Moose team really likes the fail-fast principle.
Here we have a role that requires an "entries" method, then builds on top of it with another method "ages".
We have an example backend that stores its entries in a hash table. We provide the "entries" method that the Scan role requires. That role gives us an "ages" method that calls "entries". Pretty straightforward use of roles.
When I was describing conflict resolution I mentioned how a method defined by the class wins over a method pulled in from a role. That's useful even outside of conflict resolution.
The ages method we define is doing a lot less work than the default implementation provided by the role would do. We don't need to pull in every field of every entry then pick out the values for age.
However, the role's implementation is a good default that would be useful for a lot of these backends. Method overrides permit reuse but allow optimizations or alternate implementations where needed.
You might be asking why we bother to consume Scan even though we don't actually pull in any methods or attributes from it. That's next!
Roles have so many excellent features that I am starting to agree with this (admittedly radical) viewpoint myself.
Allomorphism is a fancy word that means a few things. For one, roles can be part of the type system. It's a lot like duck typing, but more explicit.
Allomorphism also means that a role implies semantics. Basically, every method implemented or required by the role must implement some specified behavior.
These imply similar consequences, so I'm going to explain them together.
Here we have a role that requires "read" and "write" methods from each of its consumers. Given the name of the role, we can guess that the role requires these methods to be nonblocking.
Here we define a class that does the nonblocking interface. Nonblocking::Socket promises that its read and write methods fulfill the socket's nonblocking requirements.
Here's another class, one whose read and write methods do block. Even though it fulfills the method name requirements of Interface::Nonblocking, this class would be lying if it declared that it does the role.
We can ask an object if it does a particular role. This will die if we try to use a Blocking::Socket here.
This is better than checking "isa" because we actually care about capability. We don't care what $s's class is, or what its ancestors are. Any class can declare that it does the Interface::Nonblocking role, as long as it fulfills the role's contract.
Duck typing fulfills this same need. We also don't care about what class $s is, as long as it has the methods we want.
However, the problem with duck typing is that merely having a set of methods does not imply semantics. Perhaps read and write are actually going to do text-to-speech and printing a term paper. Or worse, they might block.
In any case, because the Interface::Nonblocking role requires the write method, we know that $s will not only have it, but we know it will not block.
Moose has support for allomorphism in attributes. Instead of demanding that connection be a particular class...
… we can demand that the value of connection does a particular role.
chromatic's point here is that you can stop caring about hierarchy and start caring about capabilities. Allomorphism means you don't need to subclass someone's crack-fueled module. You need only fulfill its crack-fueled interface. It's OOP freedom.
Here's a quick tip for you. Say you're extending a module. Ordinarily you'd write a subclass, right?
You write good tests, so you subclass its test subclass too.
You also have to subclass all the other subclasses you use. Maybe it'd be better to just monkeypatch WWW::Mechanize. Who'd know?
No! Don't do it! You'll screw it up for anyone else who happens to use that module in your codebase.
Just make your extension a role.
Now you can apply this role to the existing subclasses of the module. There's no dot-dot-dot in the braces here. This is a full class definition.
That's really it. You don't need any other code. All the extension code is in your role. Nice and clean.
There, I said it!
If you can implement your extension as a role, do it. Use inheritance sparingly.
I don't want to spend much time on this, but you can apply a role to a particular object. It doesn't have to be a full-blown class. It also won't affect any other objects. Which is good, because I wouldn't trust Jon with root.
Roles are nice for plugins too. I covered this heavily in my API Design talk. The idea is each plugin is just a role. These two modules make roles-as-plugins very easy.
http://sartak.org/talks/yapc-asia-2009/api-design/
To give you an idea of how to think about roles, here's a pretty simple metaphor that works for me. Classes are nouns.
Methods are verbs. They are simple behaviors. They do things.
Roles are adjectives. These are all good role names. If you think of some piece of behavior as an adjective, that's a good sign that it can be factored out as a role.
This is a very specific kind of parameterized role. Each consumer parameterizes the "ages" method by providing an "entries" method. But that's not really what I'm talking about when I say parameterized role. If you can do this, do it. If you need something more advanced...
Parameterized roles are my biggest contribution to Moose. I'm happy with how they came out.
Here we have our old Counter role, but now each consumer can declare what default it wants for the attribute. If they choose nothing, they get the default of 0.
rafl++ added parameterized role support to MooseX::Declare recently, so my examples get to look much nicer.
Using a parameterized role is pretty much the same. You just pass in the named arguments to "with". This was an example of parameterizing an attribute, and is probably the most common use of p-roles.
Here we have a role that wraps any method you give it with a bit of profiling code. This is sort of the inverse of "requires". Instead of the role telling you what method you need, you tell the role what method it needs to instrument. Someone once praised this type of p-role usage as resembling macros.
One really nice thing about parameterized roles is that they improve code reuse. All the consumer has to do is inform the role of which search engine they want to use. The role takes care of the rest. This means each consumer writes less code, because the parameterized role can build up more structure.
Here's another use case that was raised recently. The parameterized role could perform additional validation on each consumer. This is like "requires" for method names, but stronger.
This is what pre-MooseX::Declare parameterized roles look like, due to language constraints.
Roles are all of these things. I hope I've convinced you to use roles in your next project's design. Thank you!
Thanks to these people who have reviewed my slides and offered excellent advice.
Thank you to Ishigaki-san for translating my slides!