sas® macro design patterns
DESCRIPTION
The qualities which SAS® macros share with object-oriented languages account for the power of macro programming. This paper illustrates some examples of specific design patterns which can be partially or fully implemented with the SAS macro language. The material is intermediate to advanced, and assumes knowledge of macros and macro variables. The goal is to illustrate best practices for SAS macro programming.TRANSCRIPT
SAS® Macro Design SAS® Macro Design ggPatternsPatterns
Mark Tabladillo Ph DMark Tabladillo Ph DMark Tabladillo Ph.D.Mark Tabladillo Ph.D.Software Developer, MarkTab ConsultingSoftware Developer, MarkTab ConsultingAssociate Faculty, University of PhoenixAssociate Faculty, University of Phoenix
Atlanta, GAAtlanta, GA,,
IntroductionIntroductionIntroductionIntroduction
Experienced SAS programmers use Experienced SAS programmers use macros regularlymacros regularlymacros regularlymacros regularlyThe Macro Facility has two componentsThe Macro Facility has two components
The macro processor (engine or mechanism)The macro processor (engine or mechanism)The macro language (syntax)The macro language (syntax)
Power of SAS MacrosPower of SAS MacrosPower of SAS MacrosPower of SAS Macros
Power SourcePower Source DefinitionDefinition ExamplesExamples
FunctionFunction The SAS System has added specific The SAS System has added specific macro functions.macro functions.
•• %LENGTH%LENGTH•• %EVAL%EVAL
%SYSFUNC%SYSFUNC•• %SYSFUNC%SYSFUNCSee SAS Institute (2005)See SAS Institute (2005)
ImplementationImplementation The SAS System defines specific ways The SAS System defines specific ways that macro variables and macros that macro variables and macros
•• Global versus local macro Global versus local macro variablesvariables
resolve.resolve. •• %DO inside macros%DO inside macrosSee SAS Institute (2005)See SAS Institute (2005)
StructureStructure The SAS Macro language has some The SAS Macro language has some characteristics of objectcharacteristics of object--orientedoriented
To some extent:To some extent:•• EncapsulationEncapsulationcharacteristics of objectcharacteristics of object--oriented oriented
languages.languages.•• EncapsulationEncapsulation•• PolymorphismPolymorphism•• InheritanceInheritanceSee Tabladillo (2005)See Tabladillo (2005)
SAS Macro Design PatternsSAS Macro Design PatternsSAS Macro Design PatternsSAS Macro Design Patterns
FocusFocus: structural power: structural powerA hA h id l hid l hApproachApproach: provide examples on how : provide examples on how macros can implement some aspects of macros can implement some aspects of
bjbj i d d ii d d iobjectobject--oriented design patternsoriented design patternsMissionMission: to provide specific design ideas : to provide specific design ideas for structuring macros in the most for structuring macros in the most powerful way possible powerful way possible
OutlineOutlineOutlineOutline
FirstFirst: Illustrate three specific ways to trick the: Illustrate three specific ways to trick theFirstFirst: Illustrate three specific ways to trick the : Illustrate three specific ways to trick the SAS macro language to emulate some SAS macro language to emulate some properties of objectproperties of object--oriented languages. oriented languages. SecondSecond: Answer what a : Answer what a design patterndesign pattern is and why is and why design patterns are useful.design patterns are useful.Third: Third: List seven specific design patterns and List seven specific design patterns and provide SAS macro language examples.provide SAS macro language examples.Finally: Finally: Provide some general application Provide some general application advice.advice.
OverviewOverviewOverviewOverview
How to trick the SAS Macro How to trick the SAS Macro LanguageLanguageLanguageLanguage
Why design patterns are usefulWhy design patterns are usefulSix specific design patternsSix specific design patternsGeneral application development adviceGeneral application development advicepp ppp p
How to Trick the SAS Macro How to Trick the SAS Macro LanguageLanguage
Trick One Trick One –– emulate inheritance by emulate inheritance by cutting and pasting textcutting and pasting textcutting and pasting textcutting and pasting textThere is no %INHERITThere is no %INHERIT
How to Trick the SAS Macro How to Trick the SAS Macro LanguageLanguage
Trick Two Trick Two –– emulate all types of variables emulate all types of variables with macro variableswith macro variableswith macro variableswith macro variablesMacro variables are inherently characterMacro variables are inherently character
How to Trick the SAS Macro How to Trick the SAS Macro LanguageLanguage
%macro interface(char, num, array, macro);( , , y, );%local major;%macro breakarray(m, n, p, q);data _null_;
call symput('major',&m);run;
%put &m &n &p &q;%mend breakarray;%macro submacro(a, b);%put &a &b;%mend submacro;%put &char &num &array ¯o;* Break up the array;%breakarray&array.;%put &major;%put &major;* Call the named macro;%¯o.;%mend interface;%interface (char=character, num=2005, array=(1,2,3,4), macro=submacro(a=5,b=c));
How to Trick the SAS Macro How to Trick the SAS Macro LanguageLanguage
Trick Three Trick Three –– emulate public functions emulate public functions (or methods) by applying nested macros(or methods) by applying nested macros(or methods) by applying nested macros(or methods) by applying nested macrosMacros do not expose internal functionsMacros do not expose internal functionsHowever, developers can write nested However, developers can write nested macrosmacros
OverviewOverviewOverviewOverview
How to trick the SAS Macro LanguageHow to trick the SAS Macro LanguageWh d i f lWh d i f lWhy design patterns are usefulWhy design patterns are useful
Six specific design patternsSix specific design patternsGeneral application development adviceGeneral application development advice
Design Pattern FundamentalsDesign Pattern FundamentalsDesign Pattern FundamentalsDesign Pattern Fundamentals
Pattern Pattern –– a solution to a problem in a solution to a problem in contextcontextcontextcontextPatterns provide a way to solve Patterns provide a way to solve
l i bl i hl i bl i hcommonly recurring problems with two commonly recurring problems with two goals:goals:
Reuse SolutionsReuse SolutionsEstablish Common TerminologyEstablish Common Terminology
OverviewOverviewOverviewOverview
How to trick the SAS Macro LanguageHow to trick the SAS Macro LanguageWh d i f lWh d i f lWhy design patterns are usefulWhy design patterns are usefulSix specific design patternsSix specific design patterns
General application development adviceGeneral application development advice
FACADE: SIMPLIFY A FACADE: SIMPLIFY A COMPLEX SYSTEMCOMPLEX SYSTEM
Façade Pattern Key FeaturesFaçade Pattern Key Features
IntentIntent You want to simplify how to use an existing system. You need to You want to simplify how to use an existing system. You need to define your own interfacedefine your own interfacedefine your own interface.define your own interface.
ProblemProblem You need to use only a subset of a complex system. Or you need to You need to use only a subset of a complex system. Or you need to interact with the system in a particular way.interact with the system in a particular way.
SolutionSolution The Facade presents a new interface for the client of the existingThe Facade presents a new interface for the client of the existingSolutionSolution The Facade presents a new interface for the client of the existing The Facade presents a new interface for the client of the existing system to use.system to use.
ConsequencesConsequences The Façade simplifies the use of the required subsystem. However, The Façade simplifies the use of the required subsystem. However, since the Façade is not complete, certain functionality may be since the Façade is not complete, certain functionality may be
il bl h liil bl h liunavailable to the client.unavailable to the client.
FACADE: SIMPLIFY A FACADE: SIMPLIFY A COMPLEX SYSTEMCOMPLEX SYSTEM
FULLY IMPLEMENTED EXAMPLE%macro facade(dataset);proc freq data=&dataset.;
tables year*sales/list missing;run;
proc means data=&dataset.;var annualSales totalEmployees sumTurnover;run;
%mend facade;%facade(dataset=sales.ca200503);%facade(dataset=sales.ca200510);%facade(dataset=sales ca200511);%facade(dataset=sales.ca200511);
STRATEGY: USE DIFFERENT BUSINESS STRATEGY: USE DIFFERENT BUSINESS RULES DEPENDING ON CONTEXTRULES DEPENDING ON CONTEXTRULES DEPENDING ON CONTEXTRULES DEPENDING ON CONTEXT
Strategy Pattern Key FeaturesStrategy Pattern Key Features
IntentIntent Allows you to use different business rules or algorithms depending on the Allows you to use different business rules or algorithms depending on the context in which they occur.context in which they occur.
ProblemProblem The selection of an algorithm that needs to be applied depends upon the The selection of an algorithm that needs to be applied depends upon the client making the request or the data being acted upon. If you simply client making the request or the data being acted upon. If you simply have a rule in place that does not change, you do not need a Strategy have a rule in place that does not change, you do not need a Strategy pattern.pattern.
SolutionSolution Separates the selection of the algorithm from the implementation of the Separates the selection of the algorithm from the implementation of the algorithm. Allows for the selection to be made based upon context.algorithm. Allows for the selection to be made based upon context.
ConsequencesConsequences •• The Strategy pattern defines a family of algorithms.The Strategy pattern defines a family of algorithms.•• Switches and/or conditionals can be eliminated.Switches and/or conditionals can be eliminated.•• You must invoke all algorithms in the same way (they must all have the You must invoke all algorithms in the same way (they must all have the
same interface)same interface)same interface).same interface).
STRATEGY: USE DIFFERENT BUSINESS STRATEGY: USE DIFFERENT BUSINESS RULES DEPENDING ON CONTEXTRULES DEPENDING ON CONTEXTRULES DEPENDING ON CONTEXTRULES DEPENDING ON CONTEXT
FULLY IMPLEMENTED EXAMPLEdata work.taxExample;
length grossAmount totalTax 8;grossAmount = 34000;run;
%macro calculateTaxes(dataset,county);% ( )%macro taxStrategy(county);%macro DeKalb;
totalTax = grossAmount * 0.06;%mend deKalb;%macro Fulton;
totalTax = grossAmount * 0 075;totalTax grossAmount 0.075;%mend Fulton;%macro Gwinnett;
totalTax = grossAmount * 0.06;%mend Gwinnett;%if &county. = DeKalb or &county. = Fulton or &county. = Gwinnett %then %&county.;%mend taxStrategy;data &dataset.;
set &dataset.;%taxStrategy(&county.);run;
i t d t d t tproc print data=&dataset.;run;
%mend calculateTaxes;%calculateTaxes(dataset=work.taxExample, county=Fulton);
SINGLETON: HAVE ONLY SINGLETON: HAVE ONLY ONE OBJECT AVAILABLEONE OBJECT AVAILABLE
Decorator Pattern Key FeaturesDecorator Pattern Key Features
IntentIntent You want to have only one of an object but there is no global object You want to have only one of an object but there is no global object that controls the instantiation of the object.that controls the instantiation of the object.
ProblemProblem Several different client objects need to refer to the same thing and Several different client objects need to refer to the same thing and you want to ensure that you do not have more than one of them.you want to ensure that you do not have more than one of them.
SolutionSolution Guarantees one instance.Guarantees one instance.
ConsequencesConsequences Clients need not concern themselves whether an instance of the Clients need not concern themselves whether an instance of the singleton object exists. singleton object exists. g jg j
SINGLETON: HAVE ONLY ONE SINGLETON: HAVE ONLY ONE OBJECT AVAIABLEOBJECT AVAIABLE
Fully Implemented Singleton Pattern: Fully Implemented Singleton Pattern: Only one SAS Macro is allowedOnly one SAS Macro is allowedOnly one SAS Macro is allowedOnly one SAS Macro is allowed
Only one SAS local named variableOnly one SAS local named variableOnly one SAS global named variableOnly one SAS global named variableOnly one instance of a base SAS sessionOnly one instance of a base SAS sessionyy
DECORATOR: ATTACH ADDITIONAL DECORATOR: ATTACH ADDITIONAL RESPONSIBILITIES DYNAMICALLYRESPONSIBILITIES DYNAMICALLYRESPONSIBILITIES DYNAMICALLYRESPONSIBILITIES DYNAMICALLY
Decorator Pattern Key FeaturesDecorator Pattern Key Features
IntentIntent Attach additional responsibilities to an object dynamically.Attach additional responsibilities to an object dynamically.
ProblemProblem The object that you want to use does the basic functions you require. The object that you want to use does the basic functions you require. However, you may need to add some additional functionality to However, you may need to add some additional functionality to the object occurring before or after the object’s base the object occurring before or after the object’s base functionality.functionality.yy
SolutionSolution Allows for extending the functionality of an object without resorting Allows for extending the functionality of an object without resorting to subclassing.to subclassing.
ConsequencesConsequences Functionality that is to be added resides in small objects. The Functionality that is to be added resides in small objects. The advantage is the ability to dynamically add this function before or advantage is the ability to dynamically add this function before or after the core functionality. after the core functionality.
DECORATOR: ATTACH ADDITIONAL DECORATOR: ATTACH ADDITIONAL RESPONSIBILITIES DYNAMICALLYRESPONSIBILITIES DYNAMICALLYRESPONSIBILITIES DYNAMICALLYRESPONSIBILITIES DYNAMICALLY
PARTIALLY IMPLEMENTED DECORATOR PATTERNPARTIALLY IMPLEMENTED DECORATOR PATTERN%macro messyMacro(num,char);
* Messy Macro;%put MessyMacro &num. &char.;
%mend messyMacro;
%macro decoratorBefore(parameters);%put Before;%messyMacro¶meters.;
%mend decoratorBefore;
% d t B f A dAft ( t )%macro decoratorBeforeAndAfter(parameters);%put Before;%messyMacro¶meters.;%put After;
%mend decoratorBeforeAndAfter;
%macro decoratorAfter(parameters);%messyMacro¶meters.;%put After;
%mend decoratorAfter;
%decoratorBeforeAndAfter(parameters=(num=1,char=SAS));
TEMPLATE METHOD: APPLY DISCIPLINE TO TEMPLATE METHOD: APPLY DISCIPLINE TO THE FUNCTIONS AVAILABLE INSIDE MACROSTHE FUNCTIONS AVAILABLE INSIDE MACROSTHE FUNCTIONS AVAILABLE INSIDE MACROSTHE FUNCTIONS AVAILABLE INSIDE MACROS
Template Method Pattern Key FeaturesTemplate Method Pattern Key Features
IntentIntent Define the skeleton of an algorithm in an operation, deferring Define the skeleton of an algorithm in an operation, deferring some steps to subclasses. Redefine the steps in an algorithm some steps to subclasses. Redefine the steps in an algorithm without changing the algorithm’s structurewithout changing the algorithm’s structure
ProblemProblem There is a procedure or set of steps to follow that is consistent There is a procedure or set of steps to follow that is consistent at one level of detail, but individual steps may have differentat one level of detail, but individual steps may have differentat one level of detail, but individual steps may have different at one level of detail, but individual steps may have different implementations at a lower level of detail.implementations at a lower level of detail.
SolutionSolution Allows for definition of substeps that vary while maintaining a Allows for definition of substeps that vary while maintaining a consistent basic process.consistent basic process.
ConsequencesConsequences Templates provide a good platform for code reuse. They are Templates provide a good platform for code reuse. They are also helpful in ensuring the required steps are implemented.also helpful in ensuring the required steps are implemented.
TEMPLATE METHOD: APPLY DISCIPLINE TO TEMPLATE METHOD: APPLY DISCIPLINE TO THE FUNCTIONS AVAILABLE INSIDE MACROSTHE FUNCTIONS AVAILABLE INSIDE MACROSTHE FUNCTIONS AVAILABLE INSIDE MACROSTHE FUNCTIONS AVAILABLE INSIDE MACROS
%macro accessSAS(connectParameters,selectRecordParameters);%macro connectDB(num,char);%put SAS ConnectDB;%mend connectDB;%macro selectRecords(num,char);%put SAS Record Selection;%mend selectRecords;
%macro accessSQLServer(connectParameters,selectRecordParameters);%macro connectDB(num,char);%put SQL Server ConnectDB;%mend connectDB;%macro selectRecords(num,char);%put SQL Server Record Selection;%mend selectRecords;
%macro doQuery;* doQuery is the same for all macros;%connectDB&connectparameters.;%selectRecords&selectRecordParameters.;%mend doQuery;%doQuery;%mend accessSAS;
%macro doQuery;* doQuery is the same for all macros;%connectDB&connectparameters.;%selectRecords&selectRecordParameters.;%mend doQuery;%doQuery;%mend accessSQLServer;
PARTIALLY IMPLEMENTED TEMPLATE METHOD: Two different macros, same nested macros
%accessSAS(connectParameters=(num=1,char=SAS), selectRecordParameters=(num=2,char=SAS));%accessSQLServer(connectParameters=(num=1,char=SQLServer), selectRecordParameters=(num=2,char=SQLServer));
ANALYSIS MATRIX: HIGHANALYSIS MATRIX: HIGH--VOLUME MACRO PROCESSINGVOLUME MACRO PROCESSING
Analysis Matrix Method Pattern Key FeaturesAnalysis Matrix Method Pattern Key Features
IntentIntent Provide a systematic way to surface varying dimensions of change.Provide a systematic way to surface varying dimensions of change.
ProblemProblem Variations in the system need to be made explicit so that applying Variations in the system need to be made explicit so that applying design patterns becomes easier.design patterns becomes easier.
SolutionSolution Create a matrix which documents the concepts which are varying. Create a matrix which documents the concepts which are varying. p y gp y gMatrix creation can help the developer discover the concepts that Matrix creation can help the developer discover the concepts that are varying, find points of commonality, and uncover missing are varying, find points of commonality, and uncover missing requirements.requirements.
ConsequencesConsequences The final design is optimized for the surfaced dimensions andThe final design is optimized for the surfaced dimensions andConsequencesConsequences The final design is optimized for the surfaced dimensions, and The final design is optimized for the surfaced dimensions, and refactoring may be required if dimensions are added or removed.refactoring may be required if dimensions are added or removed.
ANALYSIS MATRIX: HIGHANALYSIS MATRIX: HIGH--VOLUME MACRO PROCESSINGVOLUME MACRO PROCESSING
U.S. SalesU.S. Sales Canadian SalesCanadian Sales German SalesGerman Sales
Calculate freightCalculate freight CombinationCombination CombinationCombination CombinationCombination
Verify addressVerify address CombinationCombination CombinationCombination CombinationCombination
Calculate taxCalculate tax CombinationCombination CombinationCombination CombinationCombination
MoneyMoney CombinationCombination CombinationCombination CombinationCombination
DatesDates CombinationCombination CombinationCombination CombinationCombination
Maximum Maximum CombinationCombination CombinationCombination CombinationCombinationweightweightAnalysis Matrix Example (Shalloway and Trott, 2005, p. 286)
OverviewOverviewOverviewOverview
How to trick the SAS Macro LanguageHow to trick the SAS Macro LanguageWh d i f lWh d i f lWhy design patterns are usefulWhy design patterns are usefulSix specific design patternsSix specific design patternsGeneral application development General application development adviceadvice
General Application AdviceGeneral Application AdviceGeneral Application AdviceGeneral Application Advice
Th l ill l d iTh l ill l d iThe examples illustrate conceptual design The examples illustrate conceptual design patternspatternsThe examples could be used as is, or The examples could be used as is, or combined with one anothercombined with one anotherConsider upgrading to SAS/AFConsider upgrading to SAS/AFMost optionally licensed products representMost optionally licensed products representMost optionally licensed products represent Most optionally licensed products represent procedures which extend base SASprocedures which extend base SAS
ConclusionConclusionConclusionConclusion
This presentation: This presentation: ppProvided tricks for objectProvided tricks for object--oriented emulationoriented emulationDefined and defended design patternsDefined and defended design patternsDefined and defended design patternsDefined and defended design patternsDemonstrated fully or partially implemented Demonstrated fully or partially implemented design patternsdesign patternsdesign patternsdesign patternsProvided application adviceProvided application advice
Read more (books or web) onRead more (books or web) on design patternsdesign patternsRead more (books or web) on Read more (books or web) on design patternsdesign patternsto deepen your topical understandingto deepen your topical understanding
ReferencesReferencesReferencesReferences
Fowler, Martin (1999), Fowler, Martin (1999), Refactoring: Improving the Design of Existing Refactoring: Improving the Design of Existing CodeCode, Reading, MA: Addison Wesley Longman, Inc., Reading, MA: Addison Wesley Longman, Inc.Gamma, E., Helm, R., Johnson, R., Vlissides, J. (1995), Gamma, E., Helm, R., Johnson, R., Vlissides, J. (1995), Design Design Patterns: Elements of Reusable ObjectPatterns: Elements of Reusable Object Oriented SoftwareOriented Software Reading MA:Reading MA:Patterns: Elements of Reusable ObjectPatterns: Elements of Reusable Object--Oriented SoftwareOriented Software, Reading, MA: , Reading, MA: Addison Wesley Longman, Inc.Addison Wesley Longman, Inc.SAS Institute Inc. (2005), SAS Institute Inc. (2005), SAS OnlineDoc® 9.1.3SAS OnlineDoc® 9.1.3, Cary, NC: SAS , Cary, NC: SAS Institute, Inc.Institute, Inc.Shalloway, A., and Trott, J. (2005), Shalloway, A., and Trott, J. (2005), DesignDesign Patterns Explained: a New Patterns Explained: a New Perspective on ObjectPerspective on Object Oriented Design (Second Edition)Oriented Design (Second Edition) Boston MA:Boston MA:Perspective on ObjectPerspective on Object--Oriented Design (Second Edition)Oriented Design (Second Edition), Boston, MA: , Boston, MA: AddisonAddison--Wesley, Inc.Wesley, Inc.Tabladillo, M. (2005), “Macro Architecture in Pictures”, Tabladillo, M. (2005), “Macro Architecture in Pictures”, SUGI SUGI ((ProceedingsProceedings, 2005., 2005.
Contact InformationContact InformationContact InformationContact Information
Mark TabladilloMark TabladilloS f D l M kT bS f D l M kT b C l iC l iSoftware Developer, MarkTab Software Developer, MarkTab ConsultingConsulting
http://www.marktab.comhttp://www.marktab.com