SlideShare ist ein Scribd-Unternehmen logo
1 von 37
Business Rules with

      Brick
          brian d foy
  Nordic Perl Workshop 2007
Field validation is too low-level

 Business rules are high-level

   Code is for programmers

Connect coders and business
Field validation
  is too simple
    is_number( $age );

cookie_expired( $cookie );

amount_ok( $n + $m + $o );

    required( @fields );
Errors too vague

    “Number is out of range”

“Password has invalid characters”

      “Field foo is missing”
Helpful messages

“Number was %s but needs to be %s”

“Password can only be alphabetic, but
            I found %s”

 “Field bar requires field foo, which
             was blank”
Loose coupling

Remove business logic from code

  Avoid lock-in to technology

     Separate architecture
Data::FormValidator
Perfectly fine for simple things

        Based on fields

Relationships tough to specify

     Poor error reporting

       Tried to subclass

       Tried to refactor
Easy for programmers
        presence

      right format

      allowed value

       one-to-one

     ignore business
Hard for business
Many-to-many relationships

 Out-of-band information

      Legacy rules

       Exceptions

     Don’t know Perl
Programmers think...
Business is...
Full validation
    Presence

      Format

    Valid Value

   Relationships

   Right Value
Programmers
 write code


No one else does
Programmers
 read code


No one else does
Business people
 know the rules


No one else does
Connect both sides
Describe the validation

   Turn it into code

Explain the validation

 Apply it to input data

  Explain the results
Brick
Business

Rules

in

Closures,

‘Kay
A rule is simple

Complex rules compose simple rules

  Rules divorced from input fields

 Re-useable rules close over setup
Still alpha

In active use at a major client

 Detailed, user-defined error
          messages
Describe the situation
     Make it look less like code
@Description = (

    [ label => method_name => %setup ],

	

 	

 );



  Might come from a config file
Explain profile
some_label
   __compose_AND
   __compose_ONE_OF
            __fields_are_something
            __compose_AND
                 __compose_AND
                     _value_length_is_equal_to_greater_than
                     _value_length_is_equal_to_less_than
                 _is_only_decimal_digits
                     _is_only_decimal_digits
        __compose_ONE_OF
            __fields_are_something
            __compose_AND
                 _is_YYYYMMDD_date_format
                 _is_valid_date
        __compose_ONE_OF
            __fields_are_something
            __compose_AND
                 _is_YYYYMMDD_date_format
                 _is_valid_date
Putting it together
@Description = (

    [ label => constraint_name => %setup ],

	

 	

 );

my $Brick = Brick->new();

my $profile =

    $Brick->profile_class->new( @Description );

my $result = $Brick->apply( $profile, %Input );
Results object
             Tree data structure

 Brick::Result can play with it

@Results = (

    [ label => [ 1 | 0 ] => %errors ],

	

 	

 );
Error Hash

$errors = [

	

 { handler => $method1, message => ...,

       errors => [ ... ] },

	

 { handler => $method2, message => ...,

       errors => [ ... ] },

	

 ...	

];
Describe what happened
just_right: passed three_digit_odd_number

too_long: failed three_digit_odd_number
    long_number: _value_length: [12345] isn't 3 or fewer characters

too_short: failed three_digit_odd_number
    short_number: _value_length: [13] isn't 3 or more characters

even_number: failed three_digit_odd_number
    even_number: _matches_regex: [24] did not match the pattern
    even_number: _value_length: [24] isn't 3 or more characters

two_fields: failed twofer
    even_number: _matches_regex: [24] did not match the pattern
    short_number: _value_length: [13] isn't 3 or more characters
The brick interface

  Closes over setup data

  Has access to all input

  True if everything is okay

die with a reference if it isn’t
A validation routine
my $sub = sub {

  my $input = shift;

  return 1 if exists $input->{cat};

  die { # result error message

      handler      => 'Cat key check',

      failed_field => 'cat'

      message      => quot;No field named 'cat'quot;,

      };

  }
Add to bucket
    Put it in the communal bucket

Use the brick in different relationships
   $brick = $bucket->add_to_bucket( {

     name        => 'cat key checker',

     description => quot;Has field named 'cat'quot;,

     code        => $sub

     } );
Compose bricks
sub _us_postal_code_format
	

 {
	

 my( $bucket, $setup ) = @_;
	

	

 $setup->{exact_length} = 5;
	

	

 my $composed = $bucket->__compose_satisfy_all(
	

 	

 $bucket->_value_length_is_exactly( $setup ),	

	

	

 	

 $bucket->_is_only_decimal_digits( $setup ),
	

 	

 );
	

 }
Make trees
my $postal   = $brick->_postal_code_format( { ... } );
my $street   = $brick->_address_format( { ... } );
my $usps     = $brick->_usps_check( { ... } );

my $address = $brick->__compose_satisfy_all(
 $postal, $street, $usps );

my $basket   = $brick->__compose_satisfy_all( ... );


my $order = $brick->__compose_satisfy_all(
 $address, $basket, ... );
Validation profile
 some_label
__compose_AND
  __compose_ONE_OF
                   __fields_are_something
                   __compose_AND
                            __compose_AND
                                    _value_length_is_equal_to_greater_than
                                    _value_length_is_equal_to_less_than
                           _is_only_decimal_digits
                                    _is_only_decimal_digits
           __compose_ONE_OF
                   __fields_are_something
                   __compose_AND
                           _is_YYYYMMDD_date_format
                           _is_valid_date
           __compose_ONE_OF
                   __fields_are_something
                   __compose_AND
                           _is_YYYYMMDD_date_format
                           _is_valid_date
Get the results
foreach my $item ( @profile ) {
  my $label   = $item->[0];
  my $method = $item->[1];
  my $result =
      eval{ $brick->$method->( $input ) }
  my $eval_error = $@;
  $result = 0 if ref $eval_error;
  push @results,
      [ $label, $method, $result, $@ ];
  }
How to use Brick

     Plug-in validation (MVC)

        Subclass to adapt

Store all business logic separately
Didn’t cover...

       Filters

     Selectors

     Subclasses

Configuration as code
Conclusion

Many-to-many relationships

Descriptive error messages

    Replay validation

Weitere ähnliche Inhalte

Was ist angesagt?

PHPCon 2016: PHP7 by Witek Adamus / XSolve
PHPCon 2016: PHP7 by Witek Adamus / XSolvePHPCon 2016: PHP7 by Witek Adamus / XSolve
PHPCon 2016: PHP7 by Witek Adamus / XSolveXSolve
 
Design Patterns in PHP5
Design Patterns in PHP5 Design Patterns in PHP5
Design Patterns in PHP5 Wildan Maulana
 
Advanced php testing in action
Advanced php testing in actionAdvanced php testing in action
Advanced php testing in actionJace Ju
 
Functional Structures in PHP
Functional Structures in PHPFunctional Structures in PHP
Functional Structures in PHPMarcello Duarte
 
Internationalizing CakePHP Applications
Internationalizing CakePHP ApplicationsInternationalizing CakePHP Applications
Internationalizing CakePHP ApplicationsPierre MARTIN
 
PHPSpec - the only Design Tool you need - 4Developers
PHPSpec - the only Design Tool you need - 4DevelopersPHPSpec - the only Design Tool you need - 4Developers
PHPSpec - the only Design Tool you need - 4DevelopersKacper Gunia
 
Система рендеринга в Magento
Система рендеринга в MagentoСистема рендеринга в Magento
Система рендеринга в MagentoMagecom Ukraine
 
Class 8 - Database Programming
Class 8 - Database ProgrammingClass 8 - Database Programming
Class 8 - Database ProgrammingAhmed Swilam
 
Data::FormValidator Simplified
Data::FormValidator SimplifiedData::FormValidator Simplified
Data::FormValidator SimplifiedFred Moyer
 
You code sucks, let's fix it
You code sucks, let's fix itYou code sucks, let's fix it
You code sucks, let's fix itRafael Dohms
 
Symfony2 Building on Alpha / Beta technology
Symfony2 Building on Alpha / Beta technologySymfony2 Building on Alpha / Beta technology
Symfony2 Building on Alpha / Beta technologyDaniel Knell
 
購物車程式架構簡介
購物車程式架構簡介購物車程式架構簡介
購物車程式架構簡介Jace Ju
 
Mocking Dependencies in PHPUnit
Mocking Dependencies in PHPUnitMocking Dependencies in PHPUnit
Mocking Dependencies in PHPUnitmfrost503
 
PHP Traits
PHP TraitsPHP Traits
PHP Traitsmattbuzz
 
Creating "Secure" PHP Applications, Part 1, Explicit Code & QA
Creating "Secure" PHP Applications, Part 1, Explicit Code & QACreating "Secure" PHP Applications, Part 1, Explicit Code & QA
Creating "Secure" PHP Applications, Part 1, Explicit Code & QAarchwisp
 
PhpSpec 2.0 ilustrated by examples
PhpSpec 2.0 ilustrated by examplesPhpSpec 2.0 ilustrated by examples
PhpSpec 2.0 ilustrated by examplesMarcello Duarte
 
PHP for Adults: Clean Code and Object Calisthenics
PHP for Adults: Clean Code and Object CalisthenicsPHP for Adults: Clean Code and Object Calisthenics
PHP for Adults: Clean Code and Object CalisthenicsGuilherme Blanco
 
"How was it to switch from beautiful Perl to horrible JavaScript", Viktor Tur...
"How was it to switch from beautiful Perl to horrible JavaScript", Viktor Tur..."How was it to switch from beautiful Perl to horrible JavaScript", Viktor Tur...
"How was it to switch from beautiful Perl to horrible JavaScript", Viktor Tur...Fwdays
 
Object Calisthenics Applied to PHP
Object Calisthenics Applied to PHPObject Calisthenics Applied to PHP
Object Calisthenics Applied to PHPGuilherme Blanco
 

Was ist angesagt? (20)

PHPCon 2016: PHP7 by Witek Adamus / XSolve
PHPCon 2016: PHP7 by Witek Adamus / XSolvePHPCon 2016: PHP7 by Witek Adamus / XSolve
PHPCon 2016: PHP7 by Witek Adamus / XSolve
 
Design Patterns in PHP5
Design Patterns in PHP5 Design Patterns in PHP5
Design Patterns in PHP5
 
Advanced php testing in action
Advanced php testing in actionAdvanced php testing in action
Advanced php testing in action
 
Functional Structures in PHP
Functional Structures in PHPFunctional Structures in PHP
Functional Structures in PHP
 
Php & my sql
Php & my sqlPhp & my sql
Php & my sql
 
Internationalizing CakePHP Applications
Internationalizing CakePHP ApplicationsInternationalizing CakePHP Applications
Internationalizing CakePHP Applications
 
PHPSpec - the only Design Tool you need - 4Developers
PHPSpec - the only Design Tool you need - 4DevelopersPHPSpec - the only Design Tool you need - 4Developers
PHPSpec - the only Design Tool you need - 4Developers
 
Система рендеринга в Magento
Система рендеринга в MagentoСистема рендеринга в Magento
Система рендеринга в Magento
 
Class 8 - Database Programming
Class 8 - Database ProgrammingClass 8 - Database Programming
Class 8 - Database Programming
 
Data::FormValidator Simplified
Data::FormValidator SimplifiedData::FormValidator Simplified
Data::FormValidator Simplified
 
You code sucks, let's fix it
You code sucks, let's fix itYou code sucks, let's fix it
You code sucks, let's fix it
 
Symfony2 Building on Alpha / Beta technology
Symfony2 Building on Alpha / Beta technologySymfony2 Building on Alpha / Beta technology
Symfony2 Building on Alpha / Beta technology
 
購物車程式架構簡介
購物車程式架構簡介購物車程式架構簡介
購物車程式架構簡介
 
Mocking Dependencies in PHPUnit
Mocking Dependencies in PHPUnitMocking Dependencies in PHPUnit
Mocking Dependencies in PHPUnit
 
PHP Traits
PHP TraitsPHP Traits
PHP Traits
 
Creating "Secure" PHP Applications, Part 1, Explicit Code & QA
Creating "Secure" PHP Applications, Part 1, Explicit Code & QACreating "Secure" PHP Applications, Part 1, Explicit Code & QA
Creating "Secure" PHP Applications, Part 1, Explicit Code & QA
 
PhpSpec 2.0 ilustrated by examples
PhpSpec 2.0 ilustrated by examplesPhpSpec 2.0 ilustrated by examples
PhpSpec 2.0 ilustrated by examples
 
PHP for Adults: Clean Code and Object Calisthenics
PHP for Adults: Clean Code and Object CalisthenicsPHP for Adults: Clean Code and Object Calisthenics
PHP for Adults: Clean Code and Object Calisthenics
 
"How was it to switch from beautiful Perl to horrible JavaScript", Viktor Tur...
"How was it to switch from beautiful Perl to horrible JavaScript", Viktor Tur..."How was it to switch from beautiful Perl to horrible JavaScript", Viktor Tur...
"How was it to switch from beautiful Perl to horrible JavaScript", Viktor Tur...
 
Object Calisthenics Applied to PHP
Object Calisthenics Applied to PHPObject Calisthenics Applied to PHP
Object Calisthenics Applied to PHP
 

Ähnlich wie Business Rules with Brick

Creating Domain Specific Languages in Python
Creating Domain Specific Languages in PythonCreating Domain Specific Languages in Python
Creating Domain Specific Languages in PythonSiddhi
 
Building Better Applications with Data::Manager
Building Better Applications with Data::ManagerBuilding Better Applications with Data::Manager
Building Better Applications with Data::ManagerJay Shirley
 
Zend Framework Study@Tokyo #2
Zend Framework Study@Tokyo #2Zend Framework Study@Tokyo #2
Zend Framework Study@Tokyo #2Shinya Ohyanagi
 
Zend_Form to the Rescue - A Brief Introduction to Zend_Form
Zend_Form to the Rescue - A Brief Introduction to Zend_FormZend_Form to the Rescue - A Brief Introduction to Zend_Form
Zend_Form to the Rescue - A Brief Introduction to Zend_FormJeremy Kendall
 
Quality assurance for php projects with PHPStorm
Quality assurance for php projects with PHPStormQuality assurance for php projects with PHPStorm
Quality assurance for php projects with PHPStormMichelangelo van Dam
 
Zend Certification PHP 5 Sample Questions
Zend Certification PHP 5 Sample QuestionsZend Certification PHP 5 Sample Questions
Zend Certification PHP 5 Sample QuestionsJagat Kothari
 
The worst Ruby codes I’ve seen in my life - RubyKaigi 2015
The worst Ruby codes I’ve seen in my life - RubyKaigi 2015The worst Ruby codes I’ve seen in my life - RubyKaigi 2015
The worst Ruby codes I’ve seen in my life - RubyKaigi 2015Fernando Hamasaki de Amorim
 
Error Reporting in ZF2: form messages, custom error pages, logging
Error Reporting in ZF2: form messages, custom error pages, loggingError Reporting in ZF2: form messages, custom error pages, logging
Error Reporting in ZF2: form messages, custom error pages, loggingSteve Maraspin
 
Use my code and modify it to do this taskdatabase.php php .pdf
Use my code and modify it to do this taskdatabase.php php  .pdfUse my code and modify it to do this taskdatabase.php php  .pdf
Use my code and modify it to do this taskdatabase.php php .pdfsaknizam
 
Tidy Up Your Code
Tidy Up Your CodeTidy Up Your Code
Tidy Up Your CodeAbbas Ali
 
Ruby on Rails For Java Programmers
Ruby on Rails For Java ProgrammersRuby on Rails For Java Programmers
Ruby on Rails For Java Programmerselliando dias
 
Unit testing with zend framework PHPBenelux
Unit testing with zend framework PHPBeneluxUnit testing with zend framework PHPBenelux
Unit testing with zend framework PHPBeneluxMichelangelo van Dam
 
Unit testing with zend framework tek11
Unit testing with zend framework tek11Unit testing with zend framework tek11
Unit testing with zend framework tek11Michelangelo van Dam
 
Meet Magento Belarus debug Pavel Novitsky (eng)
Meet Magento Belarus debug Pavel Novitsky (eng)Meet Magento Belarus debug Pavel Novitsky (eng)
Meet Magento Belarus debug Pavel Novitsky (eng)Pavel Novitsky
 

Ähnlich wie Business Rules with Brick (20)

Unit testing zend framework apps
Unit testing zend framework appsUnit testing zend framework apps
Unit testing zend framework apps
 
Creating Domain Specific Languages in Python
Creating Domain Specific Languages in PythonCreating Domain Specific Languages in Python
Creating Domain Specific Languages in Python
 
Building Better Applications with Data::Manager
Building Better Applications with Data::ManagerBuilding Better Applications with Data::Manager
Building Better Applications with Data::Manager
 
R Language
R LanguageR Language
R Language
 
Framework
FrameworkFramework
Framework
 
The new form framework
The new form frameworkThe new form framework
The new form framework
 
Zend Framework Study@Tokyo #2
Zend Framework Study@Tokyo #2Zend Framework Study@Tokyo #2
Zend Framework Study@Tokyo #2
 
Zend_Form to the Rescue - A Brief Introduction to Zend_Form
Zend_Form to the Rescue - A Brief Introduction to Zend_FormZend_Form to the Rescue - A Brief Introduction to Zend_Form
Zend_Form to the Rescue - A Brief Introduction to Zend_Form
 
Quality assurance for php projects with PHPStorm
Quality assurance for php projects with PHPStormQuality assurance for php projects with PHPStorm
Quality assurance for php projects with PHPStorm
 
Zend framework 04 - forms
Zend framework 04 - formsZend framework 04 - forms
Zend framework 04 - forms
 
D8 Form api
D8 Form apiD8 Form api
D8 Form api
 
Zend Certification PHP 5 Sample Questions
Zend Certification PHP 5 Sample QuestionsZend Certification PHP 5 Sample Questions
Zend Certification PHP 5 Sample Questions
 
The worst Ruby codes I’ve seen in my life - RubyKaigi 2015
The worst Ruby codes I’ve seen in my life - RubyKaigi 2015The worst Ruby codes I’ve seen in my life - RubyKaigi 2015
The worst Ruby codes I’ve seen in my life - RubyKaigi 2015
 
Error Reporting in ZF2: form messages, custom error pages, logging
Error Reporting in ZF2: form messages, custom error pages, loggingError Reporting in ZF2: form messages, custom error pages, logging
Error Reporting in ZF2: form messages, custom error pages, logging
 
Use my code and modify it to do this taskdatabase.php php .pdf
Use my code and modify it to do this taskdatabase.php php  .pdfUse my code and modify it to do this taskdatabase.php php  .pdf
Use my code and modify it to do this taskdatabase.php php .pdf
 
Tidy Up Your Code
Tidy Up Your CodeTidy Up Your Code
Tidy Up Your Code
 
Ruby on Rails For Java Programmers
Ruby on Rails For Java ProgrammersRuby on Rails For Java Programmers
Ruby on Rails For Java Programmers
 
Unit testing with zend framework PHPBenelux
Unit testing with zend framework PHPBeneluxUnit testing with zend framework PHPBenelux
Unit testing with zend framework PHPBenelux
 
Unit testing with zend framework tek11
Unit testing with zend framework tek11Unit testing with zend framework tek11
Unit testing with zend framework tek11
 
Meet Magento Belarus debug Pavel Novitsky (eng)
Meet Magento Belarus debug Pavel Novitsky (eng)Meet Magento Belarus debug Pavel Novitsky (eng)
Meet Magento Belarus debug Pavel Novitsky (eng)
 

Mehr von brian d foy

Conferences for Beginners presentation
Conferences for Beginners presentationConferences for Beginners presentation
Conferences for Beginners presentationbrian d foy
 
20 years in Perl
20 years in Perl20 years in Perl
20 years in Perlbrian d foy
 
PrettyDump Perl 6 (London.pm)
PrettyDump Perl 6 (London.pm)PrettyDump Perl 6 (London.pm)
PrettyDump Perl 6 (London.pm)brian d foy
 
Dumping Perl 6 (French Perl Workshop)
Dumping Perl 6 (French Perl Workshop)Dumping Perl 6 (French Perl Workshop)
Dumping Perl 6 (French Perl Workshop)brian d foy
 
Perl v5.26 Features (AmsterdamX.pm)
Perl v5.26 Features (AmsterdamX.pm)Perl v5.26 Features (AmsterdamX.pm)
Perl v5.26 Features (AmsterdamX.pm)brian d foy
 
Dumping Perl 6 (AmsterdamX.pm)
Dumping Perl 6 (AmsterdamX.pm)Dumping Perl 6 (AmsterdamX.pm)
Dumping Perl 6 (AmsterdamX.pm)brian d foy
 
6 more things about Perl 6
6 more things about Perl 66 more things about Perl 6
6 more things about Perl 6brian d foy
 
6 things about perl 6
6 things about perl 66 things about perl 6
6 things about perl 6brian d foy
 
Perl 5.28 new features
Perl 5.28 new featuresPerl 5.28 new features
Perl 5.28 new featuresbrian d foy
 
The Surprisingly Tense History of the Schwartzian Transform
The Surprisingly Tense History of the Schwartzian TransformThe Surprisingly Tense History of the Schwartzian Transform
The Surprisingly Tense History of the Schwartzian Transformbrian d foy
 
Perl Power Tools - Saint Perl 6
Perl Power Tools - Saint Perl 6Perl Power Tools - Saint Perl 6
Perl Power Tools - Saint Perl 6brian d foy
 
Perl Bag of Tricks - Baltimore Perl mongers
Perl Bag of Tricks  -  Baltimore Perl mongersPerl Bag of Tricks  -  Baltimore Perl mongers
Perl Bag of Tricks - Baltimore Perl mongersbrian d foy
 
The Whitespace in the Perl Community
The Whitespace in the Perl CommunityThe Whitespace in the Perl Community
The Whitespace in the Perl Communitybrian d foy
 
CPAN Workshop, Chicago 2014
CPAN Workshop, Chicago 2014CPAN Workshop, Chicago 2014
CPAN Workshop, Chicago 2014brian d foy
 
Parsing JSON with a single regex
Parsing JSON with a single regexParsing JSON with a single regex
Parsing JSON with a single regexbrian d foy
 
Reverse Installing CPAN
Reverse Installing CPANReverse Installing CPAN
Reverse Installing CPANbrian d foy
 
Advanced modulinos
Advanced modulinosAdvanced modulinos
Advanced modulinosbrian d foy
 
Advanced modulinos trial
Advanced modulinos trialAdvanced modulinos trial
Advanced modulinos trialbrian d foy
 

Mehr von brian d foy (20)

Conferences for Beginners presentation
Conferences for Beginners presentationConferences for Beginners presentation
Conferences for Beginners presentation
 
20 years in Perl
20 years in Perl20 years in Perl
20 years in Perl
 
PrettyDump Perl 6 (London.pm)
PrettyDump Perl 6 (London.pm)PrettyDump Perl 6 (London.pm)
PrettyDump Perl 6 (London.pm)
 
Dumping Perl 6 (French Perl Workshop)
Dumping Perl 6 (French Perl Workshop)Dumping Perl 6 (French Perl Workshop)
Dumping Perl 6 (French Perl Workshop)
 
Perl v5.26 Features (AmsterdamX.pm)
Perl v5.26 Features (AmsterdamX.pm)Perl v5.26 Features (AmsterdamX.pm)
Perl v5.26 Features (AmsterdamX.pm)
 
Dumping Perl 6 (AmsterdamX.pm)
Dumping Perl 6 (AmsterdamX.pm)Dumping Perl 6 (AmsterdamX.pm)
Dumping Perl 6 (AmsterdamX.pm)
 
6 more things about Perl 6
6 more things about Perl 66 more things about Perl 6
6 more things about Perl 6
 
6 things about perl 6
6 things about perl 66 things about perl 6
6 things about perl 6
 
Perl 5.28 new features
Perl 5.28 new featuresPerl 5.28 new features
Perl 5.28 new features
 
The Surprisingly Tense History of the Schwartzian Transform
The Surprisingly Tense History of the Schwartzian TransformThe Surprisingly Tense History of the Schwartzian Transform
The Surprisingly Tense History of the Schwartzian Transform
 
Perl Power Tools - Saint Perl 6
Perl Power Tools - Saint Perl 6Perl Power Tools - Saint Perl 6
Perl Power Tools - Saint Perl 6
 
Perl Bag of Tricks - Baltimore Perl mongers
Perl Bag of Tricks  -  Baltimore Perl mongersPerl Bag of Tricks  -  Baltimore Perl mongers
Perl Bag of Tricks - Baltimore Perl mongers
 
The Whitespace in the Perl Community
The Whitespace in the Perl CommunityThe Whitespace in the Perl Community
The Whitespace in the Perl Community
 
CPAN Workshop, Chicago 2014
CPAN Workshop, Chicago 2014CPAN Workshop, Chicago 2014
CPAN Workshop, Chicago 2014
 
Parsing JSON with a single regex
Parsing JSON with a single regexParsing JSON with a single regex
Parsing JSON with a single regex
 
Reverse Installing CPAN
Reverse Installing CPANReverse Installing CPAN
Reverse Installing CPAN
 
Advanced modulinos
Advanced modulinosAdvanced modulinos
Advanced modulinos
 
Advanced modulinos trial
Advanced modulinos trialAdvanced modulinos trial
Advanced modulinos trial
 
Bag of tricks
Bag of tricksBag of tricks
Bag of tricks
 
I ❤ CPAN
I ❤ CPANI ❤ CPAN
I ❤ CPAN
 

Kürzlich hochgeladen

Pharma Works Profile of Karan Communications
Pharma Works Profile of Karan CommunicationsPharma Works Profile of Karan Communications
Pharma Works Profile of Karan Communicationskarancommunications
 
Catalogue ONG NƯỚC uPVC - HDPE DE NHAT.pdf
Catalogue ONG NƯỚC uPVC - HDPE DE NHAT.pdfCatalogue ONG NƯỚC uPVC - HDPE DE NHAT.pdf
Catalogue ONG NƯỚC uPVC - HDPE DE NHAT.pdfOrient Homes
 
VIP Call Girls In Saharaganj ( Lucknow ) 🔝 8923113531 🔝 Cash Payment (COD) 👒
VIP Call Girls In Saharaganj ( Lucknow  ) 🔝 8923113531 🔝  Cash Payment (COD) 👒VIP Call Girls In Saharaganj ( Lucknow  ) 🔝 8923113531 🔝  Cash Payment (COD) 👒
VIP Call Girls In Saharaganj ( Lucknow ) 🔝 8923113531 🔝 Cash Payment (COD) 👒anilsa9823
 
It will be International Nurses' Day on 12 May
It will be International Nurses' Day on 12 MayIt will be International Nurses' Day on 12 May
It will be International Nurses' Day on 12 MayNZSG
 
RE Capital's Visionary Leadership under Newman Leech
RE Capital's Visionary Leadership under Newman LeechRE Capital's Visionary Leadership under Newman Leech
RE Capital's Visionary Leadership under Newman LeechNewman George Leech
 
Yaroslav Rozhankivskyy: Три складові і три передумови максимальної продуктивн...
Yaroslav Rozhankivskyy: Три складові і три передумови максимальної продуктивн...Yaroslav Rozhankivskyy: Три складові і три передумови максимальної продуктивн...
Yaroslav Rozhankivskyy: Три складові і три передумови максимальної продуктивн...Lviv Startup Club
 
Sales & Marketing Alignment: How to Synergize for Success
Sales & Marketing Alignment: How to Synergize for SuccessSales & Marketing Alignment: How to Synergize for Success
Sales & Marketing Alignment: How to Synergize for SuccessAggregage
 
MONA 98765-12871 CALL GIRLS IN LUDHIANA LUDHIANA CALL GIRL
MONA 98765-12871 CALL GIRLS IN LUDHIANA LUDHIANA CALL GIRLMONA 98765-12871 CALL GIRLS IN LUDHIANA LUDHIANA CALL GIRL
MONA 98765-12871 CALL GIRLS IN LUDHIANA LUDHIANA CALL GIRLSeo
 
VIP Kolkata Call Girl Howrah 👉 8250192130 Available With Room
VIP Kolkata Call Girl Howrah 👉 8250192130  Available With RoomVIP Kolkata Call Girl Howrah 👉 8250192130  Available With Room
VIP Kolkata Call Girl Howrah 👉 8250192130 Available With Roomdivyansh0kumar0
 
Catalogue ONG NUOC PPR DE NHAT .pdf
Catalogue ONG NUOC PPR DE NHAT      .pdfCatalogue ONG NUOC PPR DE NHAT      .pdf
Catalogue ONG NUOC PPR DE NHAT .pdfOrient Homes
 
Keppel Ltd. 1Q 2024 Business Update Presentation Slides
Keppel Ltd. 1Q 2024 Business Update  Presentation SlidesKeppel Ltd. 1Q 2024 Business Update  Presentation Slides
Keppel Ltd. 1Q 2024 Business Update Presentation SlidesKeppelCorporation
 
VIP Call Girl Jamshedpur Aashi 8250192130 Independent Escort Service Jamshedpur
VIP Call Girl Jamshedpur Aashi 8250192130 Independent Escort Service JamshedpurVIP Call Girl Jamshedpur Aashi 8250192130 Independent Escort Service Jamshedpur
VIP Call Girl Jamshedpur Aashi 8250192130 Independent Escort Service JamshedpurSuhani Kapoor
 
The Coffee Bean & Tea Leaf(CBTL), Business strategy case study
The Coffee Bean & Tea Leaf(CBTL), Business strategy case studyThe Coffee Bean & Tea Leaf(CBTL), Business strategy case study
The Coffee Bean & Tea Leaf(CBTL), Business strategy case studyEthan lee
 
Monte Carlo simulation : Simulation using MCSM
Monte Carlo simulation : Simulation using MCSMMonte Carlo simulation : Simulation using MCSM
Monte Carlo simulation : Simulation using MCSMRavindra Nath Shukla
 
Call Girls in Gomti Nagar - 7388211116 - With room Service
Call Girls in Gomti Nagar - 7388211116  - With room ServiceCall Girls in Gomti Nagar - 7388211116  - With room Service
Call Girls in Gomti Nagar - 7388211116 - With room Servicediscovermytutordmt
 
Call Girls Navi Mumbai Just Call 9907093804 Top Class Call Girl Service Avail...
Call Girls Navi Mumbai Just Call 9907093804 Top Class Call Girl Service Avail...Call Girls Navi Mumbai Just Call 9907093804 Top Class Call Girl Service Avail...
Call Girls Navi Mumbai Just Call 9907093804 Top Class Call Girl Service Avail...Dipal Arora
 
Call Girls Pune Just Call 9907093804 Top Class Call Girl Service Available
Call Girls Pune Just Call 9907093804 Top Class Call Girl Service AvailableCall Girls Pune Just Call 9907093804 Top Class Call Girl Service Available
Call Girls Pune Just Call 9907093804 Top Class Call Girl Service AvailableDipal Arora
 

Kürzlich hochgeladen (20)

Best Practices for Implementing an External Recruiting Partnership
Best Practices for Implementing an External Recruiting PartnershipBest Practices for Implementing an External Recruiting Partnership
Best Practices for Implementing an External Recruiting Partnership
 
Pharma Works Profile of Karan Communications
Pharma Works Profile of Karan CommunicationsPharma Works Profile of Karan Communications
Pharma Works Profile of Karan Communications
 
Forklift Operations: Safety through Cartoons
Forklift Operations: Safety through CartoonsForklift Operations: Safety through Cartoons
Forklift Operations: Safety through Cartoons
 
Catalogue ONG NƯỚC uPVC - HDPE DE NHAT.pdf
Catalogue ONG NƯỚC uPVC - HDPE DE NHAT.pdfCatalogue ONG NƯỚC uPVC - HDPE DE NHAT.pdf
Catalogue ONG NƯỚC uPVC - HDPE DE NHAT.pdf
 
VIP Call Girls In Saharaganj ( Lucknow ) 🔝 8923113531 🔝 Cash Payment (COD) 👒
VIP Call Girls In Saharaganj ( Lucknow  ) 🔝 8923113531 🔝  Cash Payment (COD) 👒VIP Call Girls In Saharaganj ( Lucknow  ) 🔝 8923113531 🔝  Cash Payment (COD) 👒
VIP Call Girls In Saharaganj ( Lucknow ) 🔝 8923113531 🔝 Cash Payment (COD) 👒
 
It will be International Nurses' Day on 12 May
It will be International Nurses' Day on 12 MayIt will be International Nurses' Day on 12 May
It will be International Nurses' Day on 12 May
 
RE Capital's Visionary Leadership under Newman Leech
RE Capital's Visionary Leadership under Newman LeechRE Capital's Visionary Leadership under Newman Leech
RE Capital's Visionary Leadership under Newman Leech
 
Yaroslav Rozhankivskyy: Три складові і три передумови максимальної продуктивн...
Yaroslav Rozhankivskyy: Три складові і три передумови максимальної продуктивн...Yaroslav Rozhankivskyy: Три складові і три передумови максимальної продуктивн...
Yaroslav Rozhankivskyy: Три складові і три передумови максимальної продуктивн...
 
KestrelPro Flyer Japan IT Week 2024 (English)
KestrelPro Flyer Japan IT Week 2024 (English)KestrelPro Flyer Japan IT Week 2024 (English)
KestrelPro Flyer Japan IT Week 2024 (English)
 
Sales & Marketing Alignment: How to Synergize for Success
Sales & Marketing Alignment: How to Synergize for SuccessSales & Marketing Alignment: How to Synergize for Success
Sales & Marketing Alignment: How to Synergize for Success
 
MONA 98765-12871 CALL GIRLS IN LUDHIANA LUDHIANA CALL GIRL
MONA 98765-12871 CALL GIRLS IN LUDHIANA LUDHIANA CALL GIRLMONA 98765-12871 CALL GIRLS IN LUDHIANA LUDHIANA CALL GIRL
MONA 98765-12871 CALL GIRLS IN LUDHIANA LUDHIANA CALL GIRL
 
VIP Kolkata Call Girl Howrah 👉 8250192130 Available With Room
VIP Kolkata Call Girl Howrah 👉 8250192130  Available With RoomVIP Kolkata Call Girl Howrah 👉 8250192130  Available With Room
VIP Kolkata Call Girl Howrah 👉 8250192130 Available With Room
 
Catalogue ONG NUOC PPR DE NHAT .pdf
Catalogue ONG NUOC PPR DE NHAT      .pdfCatalogue ONG NUOC PPR DE NHAT      .pdf
Catalogue ONG NUOC PPR DE NHAT .pdf
 
Keppel Ltd. 1Q 2024 Business Update Presentation Slides
Keppel Ltd. 1Q 2024 Business Update  Presentation SlidesKeppel Ltd. 1Q 2024 Business Update  Presentation Slides
Keppel Ltd. 1Q 2024 Business Update Presentation Slides
 
VIP Call Girl Jamshedpur Aashi 8250192130 Independent Escort Service Jamshedpur
VIP Call Girl Jamshedpur Aashi 8250192130 Independent Escort Service JamshedpurVIP Call Girl Jamshedpur Aashi 8250192130 Independent Escort Service Jamshedpur
VIP Call Girl Jamshedpur Aashi 8250192130 Independent Escort Service Jamshedpur
 
The Coffee Bean & Tea Leaf(CBTL), Business strategy case study
The Coffee Bean & Tea Leaf(CBTL), Business strategy case studyThe Coffee Bean & Tea Leaf(CBTL), Business strategy case study
The Coffee Bean & Tea Leaf(CBTL), Business strategy case study
 
Monte Carlo simulation : Simulation using MCSM
Monte Carlo simulation : Simulation using MCSMMonte Carlo simulation : Simulation using MCSM
Monte Carlo simulation : Simulation using MCSM
 
Call Girls in Gomti Nagar - 7388211116 - With room Service
Call Girls in Gomti Nagar - 7388211116  - With room ServiceCall Girls in Gomti Nagar - 7388211116  - With room Service
Call Girls in Gomti Nagar - 7388211116 - With room Service
 
Call Girls Navi Mumbai Just Call 9907093804 Top Class Call Girl Service Avail...
Call Girls Navi Mumbai Just Call 9907093804 Top Class Call Girl Service Avail...Call Girls Navi Mumbai Just Call 9907093804 Top Class Call Girl Service Avail...
Call Girls Navi Mumbai Just Call 9907093804 Top Class Call Girl Service Avail...
 
Call Girls Pune Just Call 9907093804 Top Class Call Girl Service Available
Call Girls Pune Just Call 9907093804 Top Class Call Girl Service AvailableCall Girls Pune Just Call 9907093804 Top Class Call Girl Service Available
Call Girls Pune Just Call 9907093804 Top Class Call Girl Service Available
 

Business Rules with Brick

  • 1. Business Rules with Brick brian d foy Nordic Perl Workshop 2007
  • 2. Field validation is too low-level Business rules are high-level Code is for programmers Connect coders and business
  • 3. Field validation is too simple is_number( $age ); cookie_expired( $cookie ); amount_ok( $n + $m + $o ); required( @fields );
  • 4. Errors too vague “Number is out of range” “Password has invalid characters” “Field foo is missing”
  • 5. Helpful messages “Number was %s but needs to be %s” “Password can only be alphabetic, but I found %s” “Field bar requires field foo, which was blank”
  • 6. Loose coupling Remove business logic from code Avoid lock-in to technology Separate architecture
  • 7. Data::FormValidator Perfectly fine for simple things Based on fields Relationships tough to specify Poor error reporting Tried to subclass Tried to refactor
  • 8. Easy for programmers presence right format allowed value one-to-one ignore business
  • 9. Hard for business Many-to-many relationships Out-of-band information Legacy rules Exceptions Don’t know Perl
  • 12. Full validation Presence Format Valid Value Relationships Right Value
  • 14. Programmers read code No one else does
  • 15. Business people know the rules No one else does
  • 17. Describe the validation Turn it into code Explain the validation Apply it to input data Explain the results
  • 18. Brick
  • 20. A rule is simple Complex rules compose simple rules Rules divorced from input fields Re-useable rules close over setup
  • 21. Still alpha In active use at a major client Detailed, user-defined error messages
  • 22. Describe the situation Make it look less like code @Description = ( [ label => method_name => %setup ], ); Might come from a config file
  • 23. Explain profile some_label __compose_AND __compose_ONE_OF __fields_are_something __compose_AND __compose_AND _value_length_is_equal_to_greater_than _value_length_is_equal_to_less_than _is_only_decimal_digits _is_only_decimal_digits __compose_ONE_OF __fields_are_something __compose_AND _is_YYYYMMDD_date_format _is_valid_date __compose_ONE_OF __fields_are_something __compose_AND _is_YYYYMMDD_date_format _is_valid_date
  • 24. Putting it together @Description = ( [ label => constraint_name => %setup ], ); my $Brick = Brick->new(); my $profile = $Brick->profile_class->new( @Description ); my $result = $Brick->apply( $profile, %Input );
  • 25. Results object Tree data structure Brick::Result can play with it @Results = ( [ label => [ 1 | 0 ] => %errors ], );
  • 26. Error Hash $errors = [ { handler => $method1, message => ..., errors => [ ... ] }, { handler => $method2, message => ..., errors => [ ... ] }, ... ];
  • 27. Describe what happened just_right: passed three_digit_odd_number too_long: failed three_digit_odd_number long_number: _value_length: [12345] isn't 3 or fewer characters too_short: failed three_digit_odd_number short_number: _value_length: [13] isn't 3 or more characters even_number: failed three_digit_odd_number even_number: _matches_regex: [24] did not match the pattern even_number: _value_length: [24] isn't 3 or more characters two_fields: failed twofer even_number: _matches_regex: [24] did not match the pattern short_number: _value_length: [13] isn't 3 or more characters
  • 28. The brick interface Closes over setup data Has access to all input True if everything is okay die with a reference if it isn’t
  • 29. A validation routine my $sub = sub { my $input = shift; return 1 if exists $input->{cat}; die { # result error message handler => 'Cat key check', failed_field => 'cat' message => quot;No field named 'cat'quot;, }; }
  • 30. Add to bucket Put it in the communal bucket Use the brick in different relationships $brick = $bucket->add_to_bucket( { name => 'cat key checker', description => quot;Has field named 'cat'quot;, code => $sub } );
  • 31. Compose bricks sub _us_postal_code_format { my( $bucket, $setup ) = @_; $setup->{exact_length} = 5; my $composed = $bucket->__compose_satisfy_all( $bucket->_value_length_is_exactly( $setup ), $bucket->_is_only_decimal_digits( $setup ), ); }
  • 32. Make trees my $postal = $brick->_postal_code_format( { ... } ); my $street = $brick->_address_format( { ... } ); my $usps = $brick->_usps_check( { ... } ); my $address = $brick->__compose_satisfy_all( $postal, $street, $usps ); my $basket = $brick->__compose_satisfy_all( ... ); my $order = $brick->__compose_satisfy_all( $address, $basket, ... );
  • 33. Validation profile some_label __compose_AND __compose_ONE_OF __fields_are_something __compose_AND __compose_AND _value_length_is_equal_to_greater_than _value_length_is_equal_to_less_than _is_only_decimal_digits _is_only_decimal_digits __compose_ONE_OF __fields_are_something __compose_AND _is_YYYYMMDD_date_format _is_valid_date __compose_ONE_OF __fields_are_something __compose_AND _is_YYYYMMDD_date_format _is_valid_date
  • 34. Get the results foreach my $item ( @profile ) { my $label = $item->[0]; my $method = $item->[1]; my $result = eval{ $brick->$method->( $input ) } my $eval_error = $@; $result = 0 if ref $eval_error; push @results, [ $label, $method, $result, $@ ]; }
  • 35. How to use Brick Plug-in validation (MVC) Subclass to adapt Store all business logic separately
  • 36. Didn’t cover... Filters Selectors Subclasses Configuration as code