SlideShare a Scribd company logo
1 of 18
Download to read offline
BT5
Design & Code
11/17/2016 11:30:00 AM
Them’s the Rules: Using a Rules Engine
to Wrangle Complexity
Presented by:
Micah Breedlove
iostudio
Brought to you by:
350 Corporate Way, Suite 400, Orange Park, FL 32073
888--‐268--‐8770 ·∙ 904--‐278--‐0524 - info@techwell.com - http://www.stareast.techwell.com/
Micah Breedlove
iostudio
Micah Breedlove is a senior developer and dev team lead at iostudio. He began
working with PHP in late 1998 and has been developing full time using Symfony
since 2009. Micah has written and maintained applications for companies
including Procter & Gamble, Walmart, and the National Guard. Previously a
senior developer at Franklin American Mortgage, he was instrumental in building
the PHP development team. Micah lives with his wife and three kids in Nashville
where he enjoys growing fruit trees, making maple syrup, and vegetable
gardening. Micah is a firearms enthusiast and enjoys spending time at the range.
Find more about Micah at his website or follow him on Twitter @druid628.
Them’s the Rules
by
Micah Breedlove
Using a Rules Engine to Wrangle
Complexity
PHP Dev since ‘98
Symfony Evangelist
@druid628
Sr. Developer / Team Lead @ iostudio
Who is this guy?
Rules Engines
Drools
Ruler (PHP)
Ruler
Written by Justin Hileman(BobTheCow)
GitHub: https://github.com/bobthecow/Ruler
Packagist: ruler/ruler
Some definitions
Conditional Logic
“hypothetical logic (of a proposition) consisting
of two component propositions... so that the
proposition is false only when the antecedent is
true and the consequent false.”
How we handle the unknown.
Rules Engines
“A business rules engine is a software system
that executes one or more business rules in a
runtime production environment.”
“An added layer of complexity to carry out,
often complicated, business logic of the
application”
in other words...
Business Logic?
● Company policies
● Legal Regulations
Examples
● Discounts on products purchased
○ Combination of products
○ Subscribed services
● Additional Fees
○ Geographical assessment
○ Risk assessment
What is wrong with this?
if ( $obj->getName() == ‘abc’) { } elseif ($obj->getName() == ‘def’) {
} elseif ($obj->getName() == ‘ghi’) { } elseif ($obj->getName() == ‘jkl’ ) {
} elseif ($obj->getName() == ‘mno’ ) {
} elseif ($obj->getName() == ‘pqr’ && $obj->getClient()->getCategory() !==
‘hotChkn’) {
}elseif ($obj->getName() == ‘Hg(CNO)2’ && $obj->getClientKey() == ‘tuco’){
}elseif ($obj->getName() == ‘blueSky’ && $obj->getClientKey() ==
‘losPollosHermanos’) {
} elseif ($obj->getName() == ‘blueSky’ && $obj->getClientKey() ==
‘heisenberg’){}
...
Should be kept trimmed,
maintained and under control
Or else...
Pandemonium Ensues
Conditional statements are like Kudzu
Fixable?
Something to …
● Abstractly handle multiple conditions
With
● Minimal conditional logic
and is
● Reusable
Simplifies a block into a generic block
Support more than a simple/singular condition
Abstraction
Minimize Conditional Logic
● Drop the ever-building conditionals
● Replace with smaller defined block
Reusability
Ability to support all existing conditions
Individual rules can be evaluated in other
RuleSets
The saga begins…
if ($bond->getClient()== ‘client1’ && $event->getName() == ‘bond.create’) {
$this->calculateClient1BondAdjustments($bond);
} elseif ($bond->getClient() == ‘client1’ && $event->getName() == ‘payment.made’) {
$this->calculateClient1Payment($bond, $payment);
} elseif ($bond->getClient() == ‘client2’ && $event->getName() == ‘bond.create’) {
$this->calculateClient2BondAdjustments($bond);
} elseif ($bond->getClient() == ‘client3’ && $event->getName() == ‘bond.create’) {
$this->calculateClient3BondAdjustments($bond);
} ...
$rule = $ruleFactory->getBondRules();
$clientRule = [
‘district’ => ‘collegedale’,
‘district_fee’ => ‘25’,
‘fee_adjustment’ => ‘+’
];
$context = new Context([
‘bond_district’ => $bond->getDistrict(),
‘district’ => $clientRule[‘district’],
‘district_fee’ => $clientRule[‘district_fee’],
‘fee_adjustment’ => $clientRule[‘’fee_adjustment’]
]);
$rule->execute($context);
Rule Elements
Ruler - Elements of the Equation
3 Parts
● Context
● Rule
● Execution/Evaluation
Context - All Applicable Data
Variable Data:
‘bond_district’ => ‘collegedale’,
Control Data:
‘district’ => ‘collegedale’,
‘district_fee’ => ‘25’,
‘fee_adjustment’ => ‘+’
● Variable Data
○ Request
○ User Specific
(includes session)
● Control Data
○ Specific to the Rule
Rule
$rule = $rb->create(
$rb['bond_district']->EqualTo($rb['district'])
);
How the Context Stacks Up
● How to evaluate the data
● What to evaluate
Variable Data:
‘bond_district’ => ‘collegedale’,
Control Data:
‘district’ => ‘collegedale’,
‘district_fee’ => ‘25’,
‘fee_adjustment’ => ‘+’
Rule (cont.)
Compound Rules
$rule = $rb->create(
$rb->LogicalAnd(
$rb['bond_district']->EqualTo($rb['district']),
$rb['bond_amount']->GreaterThan('20000')
)
);
Evaluation/Execution
Evaluate - (boolean) Did it meet the condition?
Execution - (void) If it’s true do something
Evaluation Example
Rule:
$rule = $rb->create(
$rb['bond_district']->EqualTo($rb['district'])
);
$status = $rule->evaluate($context);
echo $status; // false
Control Data:
‘district’ =>
‘collegedale’,
‘district_fee’ => ‘25’,
‘fee_adjustment’ => ‘+’
Variable Data:
‘bond_district’ => ‘collegedale’
Execution Example
$rule->execute($context);
// output: An additional mileage fee will be charged.
Control Data:
‘district’ =>
‘collegedale’,
‘district_fee’ => ‘25’,
‘fee_adjustment’ => ‘+’
Variable Data:
‘bond_district’ => ‘collegedale’
Rule:
$rule = $rb->create(
$rb['bond_district']->EqualTo($rb['district']),
function() {
echo 'An additional mileage fee will be charged.';
}
);
if ($bond->getClient()== ‘client1’ && $event->getName() == ‘bond.create’) {
$this->calculateClient1BondAdjustments($bond);
} elseif ($bond->getClient() == ‘client1’ && $event->getName() == ‘payment.made’) {
$this->calculateClient1Payment($bond, $payment);
} elseif ($bond->getClient() == ‘client2’ && $event->getName() == ‘bond.create’) {
$this->calculateClient2BondAdjustments($bond);
} elseif ($bond->getClient() == ‘client3’ && $event->getName() == ‘bond.create’) {
$this->calculateClient3BondAdjustments($bond);
} ...
Finally this…
...becomes this
$ruleObject = $rulesRepo->get($event->getName()); // assume bond.create
$context = $ruleObject->getContext();
$context[‘bond’] = $bond;
$rule = $ruleObject->getRule();
$rule->execute($context); // one rule to rule them all
Questions?
Demo Time
Thanks!
Slides: http://sthen.es/mqh4ub20
citations
Jesse (Breaking Bad) - http://replygif.net/i/1323.gif
Kudzu - http://2.bp.blogspot.com/_RTswKzWDHeM/SE198zJTgzI/AAAAAAAAA80/ZKj4haQbiSE/s320/kudzu+house.jpg
MC Hammer - http://24.media.tumblr.com/26d1484f43ff55401f8ead9d03432bb9/tumblr_moctg0LbmC1sn8pc2o1_400.gif

More Related Content

Viewers also liked

Roma Final 2
Roma Final 2Roma Final 2
Roma Final 2
e
 
portfolio_adrián_švec_2017
portfolio_adrián_švec_2017portfolio_adrián_švec_2017
portfolio_adrián_švec_2017
Adrián Švec
 

Viewers also liked (9)

Removing the Silos: When Agile, Lean, and DevOps Aren’t Enough
Removing the Silos: When Agile, Lean, and DevOps Aren’t EnoughRemoving the Silos: When Agile, Lean, and DevOps Aren’t Enough
Removing the Silos: When Agile, Lean, and DevOps Aren’t Enough
 
Build Fail-Proof Tests in Any Browser with Selenium
Build Fail-Proof Tests in Any Browser with SeleniumBuild Fail-Proof Tests in Any Browser with Selenium
Build Fail-Proof Tests in Any Browser with Selenium
 
Enable Your Workers … You’ll Be Amazed What They Can Do
Enable Your Workers … You’ll Be Amazed What They Can DoEnable Your Workers … You’ll Be Amazed What They Can Do
Enable Your Workers … You’ll Be Amazed What They Can Do
 
Competencias en la industria de reproductores mp3 en
Competencias en la industria de reproductores mp3 enCompetencias en la industria de reproductores mp3 en
Competencias en la industria de reproductores mp3 en
 
Cuestionario botanica sistemantica ii
Cuestionario botanica sistemantica iiCuestionario botanica sistemantica ii
Cuestionario botanica sistemantica ii
 
21. extremidad superior
21. extremidad superior21. extremidad superior
21. extremidad superior
 
Roma Final 2
Roma Final 2Roma Final 2
Roma Final 2
 
portfolio_adrián_švec_2017
portfolio_adrián_švec_2017portfolio_adrián_švec_2017
portfolio_adrián_švec_2017
 
15. columna vertebral lumbar
15. columna vertebral lumbar15. columna vertebral lumbar
15. columna vertebral lumbar
 

Similar to Them’s the Rules: Using a Rules Engine to Wrangle Complexity

2-1 Remember the Help Desk with AFCU - Jared Flanders, Final
2-1 Remember the Help Desk with AFCU - Jared Flanders, Final2-1 Remember the Help Desk with AFCU - Jared Flanders, Final
2-1 Remember the Help Desk with AFCU - Jared Flanders, Final
Jared Flanders
 
Running Intelligent Applications inside a Database: Deep Learning with Python...
Running Intelligent Applications inside a Database: Deep Learning with Python...Running Intelligent Applications inside a Database: Deep Learning with Python...
Running Intelligent Applications inside a Database: Deep Learning with Python...
Miguel González-Fierro
 
Building Better Applications with Data::Manager
Building Better Applications with Data::ManagerBuilding Better Applications with Data::Manager
Building Better Applications with Data::Manager
Jay Shirley
 
Java Tech & Tools | Deploying Java & Play Framework Apps to the Cloud | Sande...
Java Tech & Tools | Deploying Java & Play Framework Apps to the Cloud | Sande...Java Tech & Tools | Deploying Java & Play Framework Apps to the Cloud | Sande...
Java Tech & Tools | Deploying Java & Play Framework Apps to the Cloud | Sande...
JAX London
 
Data Mining Open Ap Is
Data Mining Open Ap IsData Mining Open Ap Is
Data Mining Open Ap Is
oscon2007
 

Similar to Them’s the Rules: Using a Rules Engine to Wrangle Complexity (20)

Them's the Rules - Using a Rules Engine to Wrangle Complexity
Them's the Rules - Using a Rules Engine to Wrangle ComplexityThem's the Rules - Using a Rules Engine to Wrangle Complexity
Them's the Rules - Using a Rules Engine to Wrangle Complexity
 
2-1 Remember the Help Desk with AFCU - Jared Flanders, Final
2-1 Remember the Help Desk with AFCU - Jared Flanders, Final2-1 Remember the Help Desk with AFCU - Jared Flanders, Final
2-1 Remember the Help Desk with AFCU - Jared Flanders, Final
 
Game Playing RL Agent
Game Playing RL AgentGame Playing RL Agent
Game Playing RL Agent
 
Grokking Engineering - Data Analytics Infrastructure at Viki - Huy Nguyen
Grokking Engineering - Data Analytics Infrastructure at Viki - Huy NguyenGrokking Engineering - Data Analytics Infrastructure at Viki - Huy Nguyen
Grokking Engineering - Data Analytics Infrastructure at Viki - Huy Nguyen
 
Apache Calcite Tutorial - BOSS 21
Apache Calcite Tutorial - BOSS 21Apache Calcite Tutorial - BOSS 21
Apache Calcite Tutorial - BOSS 21
 
Running Intelligent Applications inside a Database: Deep Learning with Python...
Running Intelligent Applications inside a Database: Deep Learning with Python...Running Intelligent Applications inside a Database: Deep Learning with Python...
Running Intelligent Applications inside a Database: Deep Learning with Python...
 
Agile data presentation 3 - cambridge
Agile data   presentation 3 - cambridgeAgile data   presentation 3 - cambridge
Agile data presentation 3 - cambridge
 
Building Better Applications with Data::Manager
Building Better Applications with Data::ManagerBuilding Better Applications with Data::Manager
Building Better Applications with Data::Manager
 
Beyond PHP - It's not (just) about the code
Beyond PHP - It's not (just) about the codeBeyond PHP - It's not (just) about the code
Beyond PHP - It's not (just) about the code
 
NZYP Project Casestudy using SilverStripe CMS
NZYP Project Casestudy using SilverStripe CMSNZYP Project Casestudy using SilverStripe CMS
NZYP Project Casestudy using SilverStripe CMS
 
Apache Pinot Meetup Sept02, 2020
Apache Pinot Meetup Sept02, 2020Apache Pinot Meetup Sept02, 2020
Apache Pinot Meetup Sept02, 2020
 
MySQL 8.0 Released Update
MySQL 8.0 Released UpdateMySQL 8.0 Released Update
MySQL 8.0 Released Update
 
Scaling AutoML-Driven Anomaly Detection With Luminaire
Scaling AutoML-Driven Anomaly Detection With LuminaireScaling AutoML-Driven Anomaly Detection With Luminaire
Scaling AutoML-Driven Anomaly Detection With Luminaire
 
MySQL NoSQL JSON JS Python "Document Store" demo
MySQL NoSQL JSON JS Python "Document Store" demoMySQL NoSQL JSON JS Python "Document Store" demo
MySQL NoSQL JSON JS Python "Document Store" demo
 
Oracle SQL Tuning
Oracle SQL TuningOracle SQL Tuning
Oracle SQL Tuning
 
What Does It Cost for Microsoft Dynamics in the Cloud?
What Does It Cost for Microsoft Dynamics in the Cloud?What Does It Cost for Microsoft Dynamics in the Cloud?
What Does It Cost for Microsoft Dynamics in the Cloud?
 
Lightning components performance best practices
Lightning components performance best practicesLightning components performance best practices
Lightning components performance best practices
 
Java Tech & Tools | Deploying Java & Play Framework Apps to the Cloud | Sande...
Java Tech & Tools | Deploying Java & Play Framework Apps to the Cloud | Sande...Java Tech & Tools | Deploying Java & Play Framework Apps to the Cloud | Sande...
Java Tech & Tools | Deploying Java & Play Framework Apps to the Cloud | Sande...
 
Data Mining Open Ap Is
Data Mining Open Ap IsData Mining Open Ap Is
Data Mining Open Ap Is
 
Data Models Breakout Session
Data Models Breakout SessionData Models Breakout Session
Data Models Breakout Session
 

More from TechWell

More from TechWell (20)

Failing and Recovering
Failing and RecoveringFailing and Recovering
Failing and Recovering
 
Instill a DevOps Testing Culture in Your Team and Organization
Instill a DevOps Testing Culture in Your Team and Organization Instill a DevOps Testing Culture in Your Team and Organization
Instill a DevOps Testing Culture in Your Team and Organization
 
Test Design for Fully Automated Build Architecture
Test Design for Fully Automated Build ArchitectureTest Design for Fully Automated Build Architecture
Test Design for Fully Automated Build Architecture
 
System-Level Test Automation: Ensuring a Good Start
System-Level Test Automation: Ensuring a Good StartSystem-Level Test Automation: Ensuring a Good Start
System-Level Test Automation: Ensuring a Good Start
 
Build Your Mobile App Quality and Test Strategy
Build Your Mobile App Quality and Test StrategyBuild Your Mobile App Quality and Test Strategy
Build Your Mobile App Quality and Test Strategy
 
Testing Transformation: The Art and Science for Success
Testing Transformation: The Art and Science for SuccessTesting Transformation: The Art and Science for Success
Testing Transformation: The Art and Science for Success
 
Implement BDD with Cucumber and SpecFlow
Implement BDD with Cucumber and SpecFlowImplement BDD with Cucumber and SpecFlow
Implement BDD with Cucumber and SpecFlow
 
Develop WebDriver Automated Tests—and Keep Your Sanity
Develop WebDriver Automated Tests—and Keep Your SanityDevelop WebDriver Automated Tests—and Keep Your Sanity
Develop WebDriver Automated Tests—and Keep Your Sanity
 
Ma 15
Ma 15Ma 15
Ma 15
 
Eliminate Cloud Waste with a Holistic DevOps Strategy
Eliminate Cloud Waste with a Holistic DevOps StrategyEliminate Cloud Waste with a Holistic DevOps Strategy
Eliminate Cloud Waste with a Holistic DevOps Strategy
 
Transform Test Organizations for the New World of DevOps
Transform Test Organizations for the New World of DevOpsTransform Test Organizations for the New World of DevOps
Transform Test Organizations for the New World of DevOps
 
The Fourth Constraint in Project Delivery—Leadership
The Fourth Constraint in Project Delivery—LeadershipThe Fourth Constraint in Project Delivery—Leadership
The Fourth Constraint in Project Delivery—Leadership
 
Resolve the Contradiction of Specialists within Agile Teams
Resolve the Contradiction of Specialists within Agile TeamsResolve the Contradiction of Specialists within Agile Teams
Resolve the Contradiction of Specialists within Agile Teams
 
Pin the Tail on the Metric: A Field-Tested Agile Game
Pin the Tail on the Metric: A Field-Tested Agile GamePin the Tail on the Metric: A Field-Tested Agile Game
Pin the Tail on the Metric: A Field-Tested Agile Game
 
Agile Performance Holarchy (APH)—A Model for Scaling Agile Teams
Agile Performance Holarchy (APH)—A Model for Scaling Agile TeamsAgile Performance Holarchy (APH)—A Model for Scaling Agile Teams
Agile Performance Holarchy (APH)—A Model for Scaling Agile Teams
 
A Business-First Approach to DevOps Implementation
A Business-First Approach to DevOps ImplementationA Business-First Approach to DevOps Implementation
A Business-First Approach to DevOps Implementation
 
Databases in a Continuous Integration/Delivery Process
Databases in a Continuous Integration/Delivery ProcessDatabases in a Continuous Integration/Delivery Process
Databases in a Continuous Integration/Delivery Process
 
Mobile Testing: What—and What Not—to Automate
Mobile Testing: What—and What Not—to AutomateMobile Testing: What—and What Not—to Automate
Mobile Testing: What—and What Not—to Automate
 
Cultural Intelligence: A Key Skill for Success
Cultural Intelligence: A Key Skill for SuccessCultural Intelligence: A Key Skill for Success
Cultural Intelligence: A Key Skill for Success
 
Turn the Lights On: A Power Utility Company's Agile Transformation
Turn the Lights On: A Power Utility Company's Agile TransformationTurn the Lights On: A Power Utility Company's Agile Transformation
Turn the Lights On: A Power Utility Company's Agile Transformation
 

Recently uploaded

Abortion Pill Prices Tembisa [(+27832195400*)] 🏥 Women's Abortion Clinic in T...
Abortion Pill Prices Tembisa [(+27832195400*)] 🏥 Women's Abortion Clinic in T...Abortion Pill Prices Tembisa [(+27832195400*)] 🏥 Women's Abortion Clinic in T...
Abortion Pill Prices Tembisa [(+27832195400*)] 🏥 Women's Abortion Clinic in T...
Medical / Health Care (+971588192166) Mifepristone and Misoprostol tablets 200mg
 

Recently uploaded (20)

OpenChain - The Ramifications of ISO/IEC 5230 and ISO/IEC 18974 for Legal Pro...
OpenChain - The Ramifications of ISO/IEC 5230 and ISO/IEC 18974 for Legal Pro...OpenChain - The Ramifications of ISO/IEC 5230 and ISO/IEC 18974 for Legal Pro...
OpenChain - The Ramifications of ISO/IEC 5230 and ISO/IEC 18974 for Legal Pro...
 
WSO2CON 2024 - IoT Needs CIAM: The Importance of Centralized IAM in a Growing...
WSO2CON 2024 - IoT Needs CIAM: The Importance of Centralized IAM in a Growing...WSO2CON 2024 - IoT Needs CIAM: The Importance of Centralized IAM in a Growing...
WSO2CON 2024 - IoT Needs CIAM: The Importance of Centralized IAM in a Growing...
 
WSO2Con2024 - Navigating the Digital Landscape: Transforming Healthcare with ...
WSO2Con2024 - Navigating the Digital Landscape: Transforming Healthcare with ...WSO2Con2024 - Navigating the Digital Landscape: Transforming Healthcare with ...
WSO2Con2024 - Navigating the Digital Landscape: Transforming Healthcare with ...
 
Architecture decision records - How not to get lost in the past
Architecture decision records - How not to get lost in the pastArchitecture decision records - How not to get lost in the past
Architecture decision records - How not to get lost in the past
 
WSO2Con204 - Hard Rock Presentation - Keynote
WSO2Con204 - Hard Rock Presentation - KeynoteWSO2Con204 - Hard Rock Presentation - Keynote
WSO2Con204 - Hard Rock Presentation - Keynote
 
WSO2Con2024 - WSO2's IAM Vision: Identity-Led Digital Transformation
WSO2Con2024 - WSO2's IAM Vision: Identity-Led Digital TransformationWSO2Con2024 - WSO2's IAM Vision: Identity-Led Digital Transformation
WSO2Con2024 - WSO2's IAM Vision: Identity-Led Digital Transformation
 
WSO2Con2024 - Software Delivery in Hybrid Environments
WSO2Con2024 - Software Delivery in Hybrid EnvironmentsWSO2Con2024 - Software Delivery in Hybrid Environments
WSO2Con2024 - Software Delivery in Hybrid Environments
 
WSO2Con2024 - GitOps in Action: Navigating Application Deployment in the Plat...
WSO2Con2024 - GitOps in Action: Navigating Application Deployment in the Plat...WSO2Con2024 - GitOps in Action: Navigating Application Deployment in the Plat...
WSO2Con2024 - GitOps in Action: Navigating Application Deployment in the Plat...
 
%in Stilfontein+277-882-255-28 abortion pills for sale in Stilfontein
%in Stilfontein+277-882-255-28 abortion pills for sale in Stilfontein%in Stilfontein+277-882-255-28 abortion pills for sale in Stilfontein
%in Stilfontein+277-882-255-28 abortion pills for sale in Stilfontein
 
Abortion Pill Prices Tembisa [(+27832195400*)] 🏥 Women's Abortion Clinic in T...
Abortion Pill Prices Tembisa [(+27832195400*)] 🏥 Women's Abortion Clinic in T...Abortion Pill Prices Tembisa [(+27832195400*)] 🏥 Women's Abortion Clinic in T...
Abortion Pill Prices Tembisa [(+27832195400*)] 🏥 Women's Abortion Clinic in T...
 
Devoxx UK 2024 - Going serverless with Quarkus, GraalVM native images and AWS...
Devoxx UK 2024 - Going serverless with Quarkus, GraalVM native images and AWS...Devoxx UK 2024 - Going serverless with Quarkus, GraalVM native images and AWS...
Devoxx UK 2024 - Going serverless with Quarkus, GraalVM native images and AWS...
 
WSO2Con2024 - From Blueprint to Brilliance: WSO2's Guide to API-First Enginee...
WSO2Con2024 - From Blueprint to Brilliance: WSO2's Guide to API-First Enginee...WSO2Con2024 - From Blueprint to Brilliance: WSO2's Guide to API-First Enginee...
WSO2Con2024 - From Blueprint to Brilliance: WSO2's Guide to API-First Enginee...
 
What Goes Wrong with Language Definitions and How to Improve the Situation
What Goes Wrong with Language Definitions and How to Improve the SituationWhat Goes Wrong with Language Definitions and How to Improve the Situation
What Goes Wrong with Language Definitions and How to Improve the Situation
 
WSO2CON 2024 - How to Run a Security Program
WSO2CON 2024 - How to Run a Security ProgramWSO2CON 2024 - How to Run a Security Program
WSO2CON 2024 - How to Run a Security Program
 
WSO2Con2024 - Simplified Integration: Unveiling the Latest Features in WSO2 L...
WSO2Con2024 - Simplified Integration: Unveiling the Latest Features in WSO2 L...WSO2Con2024 - Simplified Integration: Unveiling the Latest Features in WSO2 L...
WSO2Con2024 - Simplified Integration: Unveiling the Latest Features in WSO2 L...
 
WSO2Con2024 - Low-Code Integration Tooling
WSO2Con2024 - Low-Code Integration ToolingWSO2Con2024 - Low-Code Integration Tooling
WSO2Con2024 - Low-Code Integration Tooling
 
AzureNativeQumulo_HPC_Cloud_Native_Benchmarks.pdf
AzureNativeQumulo_HPC_Cloud_Native_Benchmarks.pdfAzureNativeQumulo_HPC_Cloud_Native_Benchmarks.pdf
AzureNativeQumulo_HPC_Cloud_Native_Benchmarks.pdf
 
%in Soweto+277-882-255-28 abortion pills for sale in soweto
%in Soweto+277-882-255-28 abortion pills for sale in soweto%in Soweto+277-882-255-28 abortion pills for sale in soweto
%in Soweto+277-882-255-28 abortion pills for sale in soweto
 
WSO2CON 2024 - Not Just Microservices: Rightsize Your Services!
WSO2CON 2024 - Not Just Microservices: Rightsize Your Services!WSO2CON 2024 - Not Just Microservices: Rightsize Your Services!
WSO2CON 2024 - Not Just Microservices: Rightsize Your Services!
 
WSO2Con2024 - From Code To Cloud: Fast Track Your Cloud Native Journey with C...
WSO2Con2024 - From Code To Cloud: Fast Track Your Cloud Native Journey with C...WSO2Con2024 - From Code To Cloud: Fast Track Your Cloud Native Journey with C...
WSO2Con2024 - From Code To Cloud: Fast Track Your Cloud Native Journey with C...
 

Them’s the Rules: Using a Rules Engine to Wrangle Complexity

  • 1. BT5 Design & Code 11/17/2016 11:30:00 AM Them’s the Rules: Using a Rules Engine to Wrangle Complexity Presented by: Micah Breedlove iostudio Brought to you by: 350 Corporate Way, Suite 400, Orange Park, FL 32073 888--‐268--‐8770 ·∙ 904--‐278--‐0524 - info@techwell.com - http://www.stareast.techwell.com/
  • 2. Micah Breedlove iostudio Micah Breedlove is a senior developer and dev team lead at iostudio. He began working with PHP in late 1998 and has been developing full time using Symfony since 2009. Micah has written and maintained applications for companies including Procter & Gamble, Walmart, and the National Guard. Previously a senior developer at Franklin American Mortgage, he was instrumental in building the PHP development team. Micah lives with his wife and three kids in Nashville where he enjoys growing fruit trees, making maple syrup, and vegetable gardening. Micah is a firearms enthusiast and enjoys spending time at the range. Find more about Micah at his website or follow him on Twitter @druid628.
  • 3. Them’s the Rules by Micah Breedlove Using a Rules Engine to Wrangle Complexity PHP Dev since ‘98 Symfony Evangelist @druid628 Sr. Developer / Team Lead @ iostudio Who is this guy?
  • 4. Rules Engines Drools Ruler (PHP) Ruler Written by Justin Hileman(BobTheCow) GitHub: https://github.com/bobthecow/Ruler Packagist: ruler/ruler
  • 5. Some definitions Conditional Logic “hypothetical logic (of a proposition) consisting of two component propositions... so that the proposition is false only when the antecedent is true and the consequent false.” How we handle the unknown.
  • 6. Rules Engines “A business rules engine is a software system that executes one or more business rules in a runtime production environment.” “An added layer of complexity to carry out, often complicated, business logic of the application” in other words... Business Logic? ● Company policies ● Legal Regulations
  • 7. Examples ● Discounts on products purchased ○ Combination of products ○ Subscribed services ● Additional Fees ○ Geographical assessment ○ Risk assessment What is wrong with this? if ( $obj->getName() == ‘abc’) { } elseif ($obj->getName() == ‘def’) { } elseif ($obj->getName() == ‘ghi’) { } elseif ($obj->getName() == ‘jkl’ ) { } elseif ($obj->getName() == ‘mno’ ) { } elseif ($obj->getName() == ‘pqr’ && $obj->getClient()->getCategory() !== ‘hotChkn’) { }elseif ($obj->getName() == ‘Hg(CNO)2’ && $obj->getClientKey() == ‘tuco’){ }elseif ($obj->getName() == ‘blueSky’ && $obj->getClientKey() == ‘losPollosHermanos’) { } elseif ($obj->getName() == ‘blueSky’ && $obj->getClientKey() == ‘heisenberg’){}
  • 8. ... Should be kept trimmed, maintained and under control Or else... Pandemonium Ensues Conditional statements are like Kudzu
  • 9. Fixable? Something to … ● Abstractly handle multiple conditions With ● Minimal conditional logic and is ● Reusable Simplifies a block into a generic block Support more than a simple/singular condition Abstraction
  • 10. Minimize Conditional Logic ● Drop the ever-building conditionals ● Replace with smaller defined block Reusability Ability to support all existing conditions Individual rules can be evaluated in other RuleSets
  • 11. The saga begins… if ($bond->getClient()== ‘client1’ && $event->getName() == ‘bond.create’) { $this->calculateClient1BondAdjustments($bond); } elseif ($bond->getClient() == ‘client1’ && $event->getName() == ‘payment.made’) { $this->calculateClient1Payment($bond, $payment); } elseif ($bond->getClient() == ‘client2’ && $event->getName() == ‘bond.create’) { $this->calculateClient2BondAdjustments($bond); } elseif ($bond->getClient() == ‘client3’ && $event->getName() == ‘bond.create’) { $this->calculateClient3BondAdjustments($bond); } ... $rule = $ruleFactory->getBondRules(); $clientRule = [ ‘district’ => ‘collegedale’, ‘district_fee’ => ‘25’, ‘fee_adjustment’ => ‘+’ ]; $context = new Context([ ‘bond_district’ => $bond->getDistrict(), ‘district’ => $clientRule[‘district’], ‘district_fee’ => $clientRule[‘district_fee’], ‘fee_adjustment’ => $clientRule[‘’fee_adjustment’] ]); $rule->execute($context); Rule Elements
  • 12. Ruler - Elements of the Equation 3 Parts ● Context ● Rule ● Execution/Evaluation Context - All Applicable Data Variable Data: ‘bond_district’ => ‘collegedale’, Control Data: ‘district’ => ‘collegedale’, ‘district_fee’ => ‘25’, ‘fee_adjustment’ => ‘+’ ● Variable Data ○ Request ○ User Specific (includes session) ● Control Data ○ Specific to the Rule
  • 13. Rule $rule = $rb->create( $rb['bond_district']->EqualTo($rb['district']) ); How the Context Stacks Up ● How to evaluate the data ● What to evaluate Variable Data: ‘bond_district’ => ‘collegedale’, Control Data: ‘district’ => ‘collegedale’, ‘district_fee’ => ‘25’, ‘fee_adjustment’ => ‘+’ Rule (cont.) Compound Rules $rule = $rb->create( $rb->LogicalAnd( $rb['bond_district']->EqualTo($rb['district']), $rb['bond_amount']->GreaterThan('20000') ) );
  • 14. Evaluation/Execution Evaluate - (boolean) Did it meet the condition? Execution - (void) If it’s true do something Evaluation Example Rule: $rule = $rb->create( $rb['bond_district']->EqualTo($rb['district']) ); $status = $rule->evaluate($context); echo $status; // false Control Data: ‘district’ => ‘collegedale’, ‘district_fee’ => ‘25’, ‘fee_adjustment’ => ‘+’ Variable Data: ‘bond_district’ => ‘collegedale’
  • 15. Execution Example $rule->execute($context); // output: An additional mileage fee will be charged. Control Data: ‘district’ => ‘collegedale’, ‘district_fee’ => ‘25’, ‘fee_adjustment’ => ‘+’ Variable Data: ‘bond_district’ => ‘collegedale’ Rule: $rule = $rb->create( $rb['bond_district']->EqualTo($rb['district']), function() { echo 'An additional mileage fee will be charged.'; } ); if ($bond->getClient()== ‘client1’ && $event->getName() == ‘bond.create’) { $this->calculateClient1BondAdjustments($bond); } elseif ($bond->getClient() == ‘client1’ && $event->getName() == ‘payment.made’) { $this->calculateClient1Payment($bond, $payment); } elseif ($bond->getClient() == ‘client2’ && $event->getName() == ‘bond.create’) { $this->calculateClient2BondAdjustments($bond); } elseif ($bond->getClient() == ‘client3’ && $event->getName() == ‘bond.create’) { $this->calculateClient3BondAdjustments($bond); } ... Finally this…
  • 16. ...becomes this $ruleObject = $rulesRepo->get($event->getName()); // assume bond.create $context = $ruleObject->getContext(); $context[‘bond’] = $bond; $rule = $ruleObject->getRule(); $rule->execute($context); // one rule to rule them all Questions?
  • 18. Slides: http://sthen.es/mqh4ub20 citations Jesse (Breaking Bad) - http://replygif.net/i/1323.gif Kudzu - http://2.bp.blogspot.com/_RTswKzWDHeM/SE198zJTgzI/AAAAAAAAA80/ZKj4haQbiSE/s320/kudzu+house.jpg MC Hammer - http://24.media.tumblr.com/26d1484f43ff55401f8ead9d03432bb9/tumblr_moctg0LbmC1sn8pc2o1_400.gif