Parameters And Prototypes - Scott Klement

3y ago
44 Views
2 Downloads
1.92 MB
19 Pages
Last View : 19d ago
Last Download : 3m ago
Upload by : Jacoby Zeller
Transcription

Parameters and PrototypesPresented byScott Klementhttp://www.scottklement.com 2006-2007, Scott Klement“There are 10 types of people in the world.Those who understand binary, and those who don’t.”1Who are you?Scott Klement’s qualifications: Klement Sausage Co, Inc.IT Manager and Senior Programmerhttp://www.klements.com System iNEWS magazineTechnical Editor (also, author)http://www.iseriesnetwork.com System iNetwork Programming Tipse-Newsletter Editorhttp://www.iseriesnetwork.com/provipcenter/ SpeakerUser Groups, COMMON, and RPG Summit Award WinnerRecipient of a 2005 iSeries Innovation Award (by IBM and COMMON)Recipient of the 2005 Gary Guthrie Award for Excellence in Technical Writing (by System iNEWS)ASBPE Awards 2006 Western Region Silver Medalist for Feature Series (RPG and the IFS)COMMON Speaker of Merit2

Why talk about parameters?There are many reasons that parameters are animportant tool for today’s programmer. Parameters are the cornerstone of modern programming! Without parameters, ILE is nothing. Without parameters, Object-Oriented code doesn’t work. They are much more versatile than older techniques like theLDA. Parameters are more important today than everbefore! Too many System i programmers don’tunderstand how parameters work! There are some recent features that are worth learning.3Two Way Parameters (1 of 2)Parameters between programs are more valuable in i5/OS than they are on aWindows or Unix system because they let you pass data both ways. You canuse them to supply input values, but you can also use them to return information.On other systems, they're input-only.The two-way parameter is achieved using "shared memory".When one program calls another, the only thing that’s passed between them isan address in the computer’s memory where the parameter starts. Nothing elseis passed. Allows two-way. Is very efficient (only 16 bytes have to be passed)4

Two Way Parameters (2 of 2)Your computer’s memory is shared by everything running on it, so the operating system hasto keep track of which spaces are in use, and which ones are available.PGMDCL VAR(&MYNBR) TYPE(*DEC) LEN(5 0)CHGVAR VAR(&MYNBR) VALUE(54321)CALL PGM(TESTPGM) PARM(&MYNBR)ENDPGMThe DCL statement asksthe OS for 3 bytes ofmemory. The OS replieswith an "address 1000".The PARM statement tellsTESTPGM that there’s oneparameter, and that it’s inlocation 1000.PGM PARM(&COOLNUM)DCL VAR(&COOLNUM) TYPE(*DEC) LEN(5 0)CHGVAR VAR(&COOLNUM) VALUE(1234)ENDPGMThe &COOLNUM variableis put in address 1000because it's in the spaceprovided for parameter one.Since the first program is still referencing area 1000, it sees the new value.5What about the command line?If parameters are passed by sharing the address of the variables, what happensWhen you call from a command line, where there aren't variables?When you pass a literal on the CALL statement?When you use an API like QCMDEXC where all the parameters are together inone variable?CALL PGM(TESTPGM) PARM(18)CALL PGM(TESTPGM) PARM('WONKAVISION')The operating system creates temporary variables for your parameters.It passes the addresses of those temporary variables.Since you didn't specify any variable size, it makes one up according tothese rules:1.2.3.Numeric variables are always "packed" (*DEC) and 15,5Character variables are 32 chars long, and padded with blanksIf a character variable is more than 32 bytes, the exact length of the parameter value isused.6

Command Line Examples (1/2)Remember, it will ask the operating system for memory, just as a variable did.Numbers will be 15,5CALL PGM(TESTPGM) PARM(18)CALL PGM(TESTPGM) PARM('HELLO')(Positions 1000-1007)This string is 5 chars long,so QCMD will ask for 32characters, the first 5 willbe HELLO, the remaining27 will be blank.(Pos 1000-1031)CALL PGM(TESTPGM) PARM('A VERY VERY VERY VERYVERY LONG STRING')This string is 38 chars long,and so will be a 38character parameter with nopadding.(Pos 1000-1037)7Command Line Examples (2/2)PGM PARM(&MSG)DCL VAR(&MSG) TYPE(*CHAR) LEN(30)SNDMSG MSG(&MSG) TOUSR(QSYSOPR)ENDPGMPGM PARM(&MSG)DCL VAR(&MSG) TYPE(*CHAR) LEN(80)SNDPGMMSG MSGID(CPF9897) TOMSGQ(*EXT) MSGTYPE(*STATUS) MSGDTA(&MSG)ENDPGMThis’ll work from thecommand line, since 30 isless than 32.This might be a problem,since 80 is more than 32.You have to type at least 80characters (not includingtrailing spaces) or you’ll beviewing memory that’s notpart of what was passedfrom the command line.8

Look Out, It’s a Trick!FQSYSPRTOD ceptevalOQSYSPRTOOOOPosition 1010-1039'GETNAME'Name*inlr *onE'Name 'Name 3 'Address 'AddressName Scott C KlD NameCCPosition 1000-1009s*ENTRYCcAddress ement15APLISTPARMNameevalreturnPosition 1000-1014Name 'Scott C Klement'9Like a Data Structure?A data structure isn’t actually used by the operating system. However,thinking of it this way might make it easier to understand. Think of yourcomputer’s memory as one big data structure (billions of bytes long!)D MainStorageds. lots of other stuff here.Dpgm1 data10001039Dpgm1 name10001009Dpgm1 address10101039Dpgm2 name10001014. lots of other stuff here.10

The ProblemI deliberately used a data structure for name and address so I could controlthe memory that followed the name parameter. What if I hadn’t done that?What would’ve been in positions 1010-1014? Maybe unused memory (problem goes unnoticed!)Maybe another variable in my program.Maybe a variable in another program!Maybe a variable used by the operating system!Maybe memory that I’m not allowed to use!WHY DIDN’T IT WARN ME?How could it? Each program doesn’t know how the other programworks! They can’t read each other’s code Remember, the onlything they pass to one another is an address!11The SolutionThe solution is to code the “GETNAME” program with aprogram interface and prototype.A Program/Procedure Interface (PI) is: Like an *ENTRY PLIST (but better!) Requires a matching prototype to work. The replacement for *ENTRY PLIST in free-format.A Prototype (PR) is: A “blueprint” for making a call.It contains the name of the program to be called.It tells the compiler which parameters that program needs.The compiler can then make sure that the parms match.The prototype helps make the calling of a program self-documenting.A prototype also adds a lot of “convienience” functionality, as I’ll demonstrate in a bit.All of IBM’s new functionality related to parms since V3R2 has gone into prototypes!12

Saved by the PrototypeOne member for the prototype (SOURCELIB/PROTOTYPE,GETNAME)D GetNameDnamePRExtPgm(‘GETNAME’)15AThe prototype must match the Program Interface (PI) in the program:/copy sourcelib/prototypes,getnameD GetNamePIDName15ACcevalreturnName 'Scott C Klement'If the caller uses the prototype, it’ll protect him from mistakes:/copy sourcelib/prototypes,getnameD DatadsDName10ARNF7535The type and attributesDAddress30A of parameter 1 do not.match those of the prototype.ccallpGetName( Name )13Prototypes for ProgramsA prototype is very much like a parameter list (PLIST), but is newer andhas a lot of additional features. You can use a prototype to call aprogram, a subprocedure, or a Java class.D CalcTaxDStateDAmountPrototype Name PREXTPGM(‘CALCTAX’)2A9P 2First ParameterSecond ParameterProgram NamePrototype nameThis is the name you’ll use when using the prototype to make a call. By default, it’s also thename of the subprocedure that it calls. Add EXTPGM to make it call a program. First ParameterThe first parameter to the procedure (name is for documentation, no variable is declared.) Second ParameterYou can have as many parameters as you like, from 0-255 to a program, or 0-399 to aprocedure. External Program Name14

Calling Older ProgramsYou can use prototypes to call RPG III programs, RPG IV programs that still use*ENTRY PLIST, or even programs written in other languages (CL, COBOL, C).D GetIpDDeviceDAddressPRD MyDevD MyAddrssExtPgm(‘GETIP’)10A15AYou only need a PIfor input (*ENTRYPLIST) parameters,not when callingsomething else.10A15A/freeMyDev ‘DSP01’;callp GetIp( MyDev : MyAddr );/end-freeThat’ll work even though GETIP is a CL program. It would also work if GETIPwas an RPG program that used *ENTRY PLIST (in RPG III or RPG IV).15Introducing CONSTWhen you specify CONST, the compiler won’t let you change the value of theparameter during the call.FPRICELIST IFEK DISK/copy prototypes,getPriceD GetPriceDItemNoDZoneDPricePI5P 0 const1Aconst9P 2Make sure you addCONST to the codein the /COPY as well./freechain (ItemNo:Zone) PRICELIST;if %found;Price plPrice;else;ItemNo -1;endif;return;/end-freeOops, I typedItemNo instead ofPrice. But, becauseof CONST this won’tcompile!CONST also helps make it self-documenting. You can see which are input and which are16output, since the input-only parameters have CONST.

CONST Convienience (1/2)When the compiler knows that a parameter is input-only, it’s able to do someextra work for you.D 5P 0 const1Aconst9P 2D TempItemD TempZoneD myPricesss5P 01A9P 2Without CONST:TempItem 1234;TempZone ‘A’;GetPrice( TempItem: TempZone: myPrice );With CONST:GetPrice ( 1234 : ‘A’: myPrice );You can pass a literal value instead of a variable when you use CONST. The compiler willautomatically create a temporary variable, store your literal in it, and pass the temporaryvariable.17CONST Convienience (2/2)You can even pass an expression. It will be calculated, stored in atemporary variable, and that temporary variable will be passed:D �)11P 2 const3Aconst11P 2D TempVar.s11P 2Without CONST:TempVar TotalCost – Discounts;CalcTax( TempVar : Region: Total);With CONST:CalcTax( TotalCost - Discounts : Region: Total );Or the output of a BIF or subprocedure:BIF Example:OpenFile( %trim(Library) ‘/’ %trim(File) );Subprocedure Example:LogError( getErrorMsg (errorNo) );18

What if I don’t want a fixed-size?Occasionally you want to write a program that will work with any size stringthat RPG supports. For example, what if you want to write a program that’llcenter text in a string, no matter how long?D CenterDStringDLength/copy prototypes,centerD ons(*varsize)15P 5 constOPTIONS(*VARSIZE) disables thecompiler’s check that you’vepassed a long enough string.65535Aoptions(*varsize)15P 5 constDDDD10I 010I 010I 065535AvaryinglentrimlenstartSavePRssss/freelen Length;Save %trim(%subst(String:1:Len));trimlen %len(Save);start len/2 - trimlen/2 1;%subst(String:1:len) *blanks;%subst(String:start:trimlen) Save;return;/end-freeWith options(*VARSIZE), it’sup to you to ensure that youdon’t access memory that youaren’t allowed to access. So, beextra careful when you use this!Tip: ExtPgm can help whenyou’re stuck with an19uglynaming convention!Calling *VARSIZE from CLAs mentioned earlier, you can call programs with PR/PI from older programsor other languages. The prototype is nice to have, but it’s not required whenmaking a call.PGMDCL VAR(&TEST) TYPE(*CHAR) LEN(80)CHGVAR VAR(&TEST) VALUE(‘CENTER THIS')CALL PGM(CTR001R4) PARM(&TEST 80)SNDPGMMSG MSGID(CPF9897) MSGF(QCPFMSG) MSGTYPE(*COMP) MSGDTA(&TEST)ENDPGMSince there aren’tprototypes in CL, youhave to use theexternal name.Since there’s no variabledeclared, CL’s literals usethe same rules fordetermining the variablesize as the command linedoes. Numbers are 15,5,characters are 32 long.20

Calling *VARSIZE from RPGUsing the prototype makes it easier to read, and lets you use BIFs,expressions and other tools to make the code easier to write and maintain.D ons(*varsize)15P 5 const/copy prototypes,centerD ErrMsgs50A/freeErrMsg 'Invalid Account Number';center(ErrMsg: %size(ErrMsg));exfmt Screen7;*inlr *on;/end-freeBecause the 2nd parm isCONST, a BIF can be usedto calculate the variable size.Always use the prototypename when usingCALLP.21What about optional parms?It’s common to use optional parameters in RPG. They’re especially usefulwhen functionality needs to be added to a program without breakingbackward-compatibility.What if you start doing business internationally, and need the GETPRICEprogram to return the prices in different currencies? Existing programs arefine, but new ones might pass a parameter for the currency type.This is how that was done with *ENTRY lseevalendifItemNoZonePriceoCurrency%parms 4Currency oCurrencyCurrency 'us'22

Options(*nopass)Making a parameter optional in a prototype can be done the same way youdid it before, if you use options(*nopass)/copy prototypes,getpriceD GetPriceDItemNoDZoneDPriceDoCurrencyPID CurrencysRemember to add this parm in the5P 0 const/COPY member as well!1Aconst9P 232Aconst options(*nopass)like(oCurrency)/freeif %parms 4;Currency oCurrency;else;Currency 'us';endif;Tip: You can include more than one “options” value on aparameter by separating them with colons.OPTIONS(*NOPASS) means thatthe caller doesn’t have to add thisparm in order to call this program.*NOPASS parameters must be atthe end of the parameter list.Once you’ve declared one, anyparameters after it must also )A parameter can be declared as “omissible” with options(*omit). Strange asit may sound, this doesn’t mean that you don’t have to pass the parameter!What it means is that you can pass a special value of *OMIT instead of avariable./copy prototypes,getpriceD GetPriceDItemNoDoZoneDPriceDoCurrencyDPID CurrencyD Zoness5P 0 const1Aconst options(*omit)9P (oZone)/freeif %addr(oZone) *NULL;Zone 'A';else;Zone oZone;endif;if %parms 4 or %addr(oCurrency) *NULL;Currency 'US';else;Currency oCurrency;endif;When a caller passes *OMIT, theaddress passed for the parameteris set to *NULL.When both *NOPASS and *OMITare specified, you must first checkfor *NOPASS, and only check*OMIT if the parm was passed.24

Calling *NOPASS and *OMITCalling a program that uses *NOPASS and *OMIT is easy when you use aprototype./copy prototypes,getprice/freeGetPrice( 54321 : ‘B’: myPrice );GetPrice( 54321 : *omit: myPrice );GetPrice( 54321 : ‘A’: myPrice: ‘Canada’);GetPrice( 12345 : *omit: myPrice: ‘UK’);GetPrice( 12345 : *omit: myPrice: *omit );Without a prototype, you can’t use *OMIT (unless you’re calling asubprocedure), but you can still use *NOPASS simply by passing ADJ) can be used to tell the compiler to right-adjust aCONST parameter value. (Requires V4R4 or later.)D MyProgramDParm1PR20AExtPgm(‘MYPGM')const options(*RightAdj)20Aconst options(*RightAdj)/copy prototypes,MyProgram/freeMyProgram(‘Patio Daddio’);/copy prototypes,MyProgramD MyProgramDParm1PI/free. . . Parm1 now contains “Patio Daddio” . . .Sadly, I haven’t found a practical use for this feature.26

Options(*TRIM)Options(*TRIM) can be used to tell the compiler to remove leading andtrailing blanks for a CONST parameter value. (Requires V5R3 or later)D JoinNameDFirstDLastDWholeNamePR30A30A50A/copy prototypes,joinnameD Scotts20AD Klements20AD Wholes50A/freeJoinName(Scott: Klement: Whole);// result is: “Klement, ScottExtPgm('JOINNAME')varying const options(*trim)varying const options(*trim)inz('inz('Scott ')Klement ')“/copy prototypes,joinnameD JoinNamePIDFirst30Avarying const options(*trim)DLast30Avarying const options(*trim)DWholeName50A/free// It's not necessary to trim blanks, because the// compiler has done it for us.Wholename Last ', ' NULLIND) tells the system that you want to pass nullindicators with a database field. (Requires V5R4 or later)Without *NULLIND, if a null-capable database field is passed, the calledprogram (or procedure) doesn’t know if is set to null or not, and can’tchange whether it’s null or not.D SomeProgramDInvDatePR/copy prototypes,SomePgmD SomeProgramPIDInvDate/freeif %nullind(InvDate);%nullind(InvDate) *OFF;InvDate %date();else;// Already ')options(*nullind)options(*nullind)Warning: This is how I expect *NULLIND to work, but I haven’t had a chance to28test a V5R4 system yet, so I may be wrong!

Prototypes & External DefinitionsQ: I prefer to use an externally defined file as a “data dictionary”. How can Iuse an external field definition on a prototype?A: Use LIKE to define the fields in the prototype. Put an externally defineddata structure into your /COPY member so you have an external definitionto reference.** Pull in the external definitions for the CUSTMAS fileD CUSTMAS tE DSExtName(‘CUSTMAS’)DqualifiedDbased(Template Only)D tStateDCustZipPRExtPgm(‘CUSTADDR’)like(CUSTMAS t.custno)constlike(CUSTMAS t.name)like(CUSTMAS t.addr)like(CUSTMAS t.city)like(CUSTMAS t.state)like(CUSTMAS t.zipCode)29Data Structures (V5R1 )Q: Can I pass a data structure using a prototype?A: You can use LIKEDS to pass a data structure in V5R1 or later.D MyDataDField1DField2DSD ExampleDDataStructPR10A7P 4ExtPgm(‘EXAMPLE’)likeds(MyData)/freecallp Example(MyData);Inside the EXAMPLE program:/copy prototypes,exampleD Field1 ‘PARM 1 DATA’;DataStruct.Field2 19.3412;30

Data Structures (pre-V5R1)A: If you don’t have V5R1, you have to use LIKE with pointer logic. (sorry!)D MyDataDField1DField2DSD ExampleDDataStructPR10A7P 4ExtPgm(‘EXAMPLE’)like(MyData)/freecallp Example(MyData);Inside the EXAMPLE program:/copy prototypes,exampleD ExampleDDataStructPID LocalVersionDField1DField2DSlike(MyData)based(p data)10A7P 4/freep data %addr(DataStruct);Field1 ‘PARM 1 DATA’;Field2 19.3412;31Multiple Occurrence DSThis also must be done with pointer logic. Make sure you always pass thefirst occurrence if you want the whole DS to be passed.D MyDataDField1DField2DSD ExampleDDataStructPRoccurs(10)10A7P ta) 1;callp Example(MyData);Inside the EXAMPLE program:/copy prototypes,exampleD ExampleDDataStructPIlike(MyData)D LocalVersionDSbased(p data)Doccurs(10)DField110ADField27P 4/freep data %addr(DataStruct);for x 1 to 10;%occur(LocalVersion) x;Field1 ‘PARM 1 DATA’;Field2 19.3412;endfor;32

Arrays (1 of 2)To pass an array, simply code a DIM keyword on the prototype definition:D Monthss15P 2 dim(12)D LoadSalesMonDDataPRExtPgm(‘MONSALES’)15P 2 dim(12)/freecallp LoadSalesMon(Months);Inside the MONSALES program:/copy prototypes,MonSalesD LoadSalesMonPIDData15P 2 dim(12)/freefor month 1 to 12;chain month MonthSales;if %found;Data(month) msTotal;else;Data(month) 0;endif;endfor;33Arrays (2 of 2)You can use options(*VARSIZE) if you want to write a program that canwork with different sizes of arrays:D ToDTotal/freefor x 1 to PageSize;4P 0 const2P 0 const5Adim(99)Ddim(99)25Adim(99)11P 2 varsize)options(*varsize)reade (CustNo) ORDERFIL;if l(x)endfor; ofOrder;ofDate;ofShipDs;ofTotal;Some programs may call this with a 5 element array. Others with a 20element. Web applications might want to read 80 or 90 at a time.34

Prototypes and SubproceduresPrototypes can also be used to call Java methods and ILE Subprocedures.There are additional keywords that you can use with those. OPDESCPass an operational descriptor (prototype-level) EXTPROCProvide a separate external name for the subprocedure. This also provides the ability toadjust calling conventions for C, CL or Java. (Prototype-level) VALUEPass a parameter by VALUE instead of passing it’s address (Parameter level)Return values:Subprocedures can return a value that can be used in an expression. This isalso part of the prototype.35Not Associated with PrototypesThe following are NOT prototype keyw

Requires a matching prototype to work. . The prototype helps make the calling of a program self-documenting. A prototype also adds a lot of “convienience” functionality, as I’ll demonstrate in a bit. All of IBM’s new functionality related to parms since V3R2 has gone into prototypes! 13

Related Documents:

Painter: Vera Klement, she describes Zoppot and the themes that appear repeatedly in her work drawn on her memories of this childhood paradise. Zoppot, my muse, my paradise lost, I remember you as in a dream—a luminou

2031849 3M Scott EPIC 3 LSM Motorola HT1000, XTS series 2031850 3M Scott EPIC 3 LSM Motorola HT750/1250/1550 series 2031851 3M Scott EPIC 3 LSM Motorola Mototrbo XPR series, APX series 2031852 3M Scott EPIC 3 LSM Kenwood TK280/290/380/390 series 2031854 3M Scott EPIC 3 LSM Harris P5400/7300, Unity series, XG series

Two types of prototypes: technical and executable 42 Technical Prototypes Technical prototypes are used assess feasibility of an architecture or to discover and quantify parameters ickly developed to serve their purpose, but not at product quality level This kind of prototype should be thrown away (should not make it into the final

Scott Aviation has contributed five audio-visual programs on the operation and maintenance of SCOTT SCBA and Breathing Devices. Users of these programs will need a carousel slide projector and a cassette tape player. Film Code Title SCOTT AV # 2 SCOTT Air Pak 4.5 Operation/ Maintenance SCOTT AV # 2a SCOTT Air

Dr. Danny Lanier Newton County Van Lucas Newton County Rebecca Farris Scott County Tommy Harrison Scott County Dr. Jimmy Hollingsworth, Chairman Scott County John Johnson Scott County Dr. Tony McGee Scott County Annie Stowers Scott County Patsy Clark Winston County Dr. R

and usability. The prototypes presented below can be classified on the basis of the interaction protocols described in Sect. 1.4. Now we briefly introduce an outline of each prototype based on the above-mentioned schema. 12.1.1 Passive, Left-to-Right Protocol The prototypes classified under this interaction protocol fulfill two requirements.

evaluation of technology prototypes by warfighters and other end users while the prototypes are still in development. DTRA's approach in evaluating prototypes is best exemplified through its annual Chemical and Biological Operational Analysis (CBOA) event, which provides a realistic venue for technology developers to observe

Artificial Intelligence (AI) is a science and a set of computational technologies that are inspired by—but typically operate quite differently from—the ways people use their nervous systems and bodies to sense, learn, reason, and take action. While the rate of progress in AI has been patchy and unpredictable, there have been significant advances since the field’s inception sixty years .