Object-oriented Programming Laws for Annotated Java Programs

Object-oriented programming laws have been proposed in the context of languages that are not combined with a behavioral interface specification language (BISL). The strong dependence between source-code and interface specifications may cause a number…

Authors: Gabriel Falconieri Freitas, Marcio Cornelio, Tiago Massoni

I. Mackie and A. Martins Moreira (Eds.): T enth International W orksho p on Rule-Based Programming (RULE 2 009) EPTCS 21, 2010, pp. 65–76, doi:10.4204 / EPTCS.21.6 © Gabriel Falconieri Freitas et al. This work is licensed under the Creati ve Common s Attribution-Nonco mmercial-No Deriv ative W orks License. Object-o riented Pr ogrammi ng Laws f or Annota ted J av a Pr ograms Gabriel Falconieri Fr eitas Univ ersidade de Pernambuco (UPE), Brasil grff@dsc.u pe.br M ´ arcio Corn ´ elio Univ ersidade de Pernambuco (UPE), Brasil Univ ersidade Federal Rural de Pernambu co (UFRP E), Brasil marciocorn elio@acm.o rg T i ago Massoni Rohit Gheyi Univ ersidade Federal de Campina Grande (UFCG), Brasil { massoni, rohit } @dsc.uf cg.edu.br Object-orien ted programming laws ha ve been proposed in t he context of languages that are not com- bined with a behavioral interface specification language (BISL). The strong depen dence betwee n source-co de and interface specifica tions m ay ca use a number of d i ffi culties wh en transformin g pro- grams. I n this paper we introd uce a set of programming la ws for object-orien ted languages like Ja va combined with the Jav a Mod eling Languag e (JML). The set of laws deals with object-o riented fea- tures taking into accou nt their sp ecifications. Some laws deal on ly with fea tures of th e specifica tion languag e. Th ese laws constitute a set of small transform ations for the de velopment of more elaborate ones like refactorings. 1 Introd uction Software cha nges constant ly d ue to maintena nce that leads to correcti on of fails or just to impro ve func- tional ities. Howe ver , some chang es can take place to achie ve quality factors like reuse and legibi lity . In these cases, changes should not alter the software beha vior but only its internal structure. Impro ving the intern al software struct ure is an acti vity kno wn as refac toring [8]. T o av oid errors due to modificatio ns, e ver y change has to be done follo wing a discipline . This discipli ne can be achiev ed by programming laws, as guidelin es to informal programming prac- tices, est ablishi ng a basis for formal and rigo rous program de velop ment. They are large ly kno wn for imperati ve programming [12, 19]. Also, function al programming and logic programming hav e a set of laws describe d by Bird and de Moor [2] and S eres [20], respec ti vely . Laws of object-orien ted program- ming ha ve also bee n addressed in [3, 7, 6]. Design by Contract (D bC) [18] is a de velopment m ethodo logy that aims at the constructio n of reliab le object -orient ed systems. Its basic idea is that a contract is establish ed among classe s of a system. In this way , software de velo pers should formally specify what is require d and ensured by m ethods and types. The Ja va Modeling Language (JML) [16, 14] is a notati on for formally specify ing the beha vior of Ja v a classe s and methods. The set of progr amming laws for object- oriente d programming w e hav e nowad ays is designed for progra m transformatio n w ith n o rela tion to spec ifications langu ages designed for DbC. Changes in s pec- ification usually shoul d discha r ge code updates, maintaini ng the conforman ce between code and spec- ification. On the other hand, chang es in program code m ay require changes in spec ifications as the beha vior implemented by cod e may div erge from th e mean ing of the original speci fication. For in stance , movin g a redefined method to its supercl ass can be illegal if this transformati on causes weakeni ng of 66 Object-o riented P rogramming Laws fo r Annotated Ja v a Programs 1 p u b l i c c l a s s P o s i t i v e I n t e g e r D a t a { 2 / / @ p r i v a t e i n v a r i a n t v a l u e . i n t V a l u e ( ) > − 1 ; 3 p r i v a t e I n t e g e r v a l u e ; 4 p u b l i c P o s i t i v e I n t e g e r D a t a ( ) { v a l u e = ne w I n t e g e r ( 0 ) ; } 5 6 / * @ r e q u i r e s n e w V a l u e ! = n u l l & & n e w V a l u e . i n t V a l u e ( ) > − 1 ; 7 @ e n s u r e s g e t V a l u e ( ) . i n t V a l u e ( ) == n e w V a l u e . i n t V a l u e ( ) ; @ * / 8 p u b l i c v o i d r e g i s t e r V a l u e ( I n t e g e r n e w V a l u e ) { / * . . . * / } 9 10 / / @ e n s u r e s \ r e s u l t ! = n u l l ; 11 p u b l i c / * @ p u r e @ * / I n t e g e r g e t V a l u e ( ) { / * . . . * / } 12 13 / * @ r e q u i r e s g e t V a l u e ( ) ! = n u l l ; 14 @ e n s u r e s ! ( \ r e s u l t ) . e q u a l s ( ” ” ) ; @ * / 15 p u b l i c S t r i n g f o r m a t ( ) { / * . . . * / } 16 } Figure 1: Class Positiv eInte gerData pre-co nditio ns and strengt hening of post-cond itions . T ransfo rmation of object-orien ted prog rams w ith formal contra cts has already been addressed in a rather informal way [10]. A catalogue of laws (primiti ve transformat ions) to deal w ith Ja v a programs annotated with JML has been proposed in [9 ], which specifies about 80 laws. Here we present one law that deals only with JML specifica tions and two JML-aware Jav a laws that deals with attrib utes and methods, respec ti vely . A law that only deals w ith JML can impose conditions only on JML elements present in the progra m, w hereas JML-awa re Jav a laws in v olv e both JML and Jav a elemen ts for stating con dition s. The three la ws we presen t here are cat alogue d in [9]. In this paper , we define laws (Section 3) of object -orient ed programming for Ja va that are awa re of specifica tions w ritten in JML, w hich we describe in S ection 2. The laws we present here and other ones presen t in a more comprehens i ve catalogue [9] were applied to refactori ng a JML-specified versio n of a cor e modu le of a Manuf acturing Exe cution System (MES) [22]. In Section 4, we present proof of sound ness regardin g the JML parts of two laws. W e present an exa mple of program transformatio n by means of laws in Secti on 5. Final remarks appear in Section 6. 2 The Ja va Modeli ng Language The Ja va Modeli ng Language (JML) is a beha vioral interfa ce specification language (BISL) [16, 14] tailore d to Jav a [11]. Thus, JML serves to descr ibe names and static informat ion that appear in Ja va declar ations and how they act, how they behav e. JML specifica tions are written in the form of specia l annot ation comments that are in serted dire ctly in sour ce code of pro grams. These comment s must be gin with an at-sign ( @ ) and can be written in two ways: by using // @ ... or / *@ ... @* / . In Figure 1, w e presen t the class Posi tiveI ntege rData that repres ents positi ve integers . W e intro- duce an instanc e in v ariant (Line 2), which is a predicate that is true in all visible states of objects of a class [16]. The in varia nt in the example has priv ate vi sibilit y and establishe s that the a ttrib ute value must alw ays be greater than -1. JML uses the requires clause to specify the obligations of the caller of a method, w hat must be true Gabriel Falconi eri Freitas et al. 67 Law 1 h move in variant to sup er class i class B extends A { // @ in vari ant ψ 1 ; ad s cnt s md s } class C extends B { // @ in vari ant ψ ′ 1 && ψ 2 ; cnt s ′ md s ′ } = cd s , M ain class B extends A { // @ in var iant ψ 1 && ψ 2 ; ad s cnt s md s } class C extends B { // @ in var iant ψ ′ 1 ; cnt s ′ md s ′ } where ψ 2 ≡ this instanceof C == > ψ inv pro vided ( ↔ ) super does not appear in ψ 2 . ( → ) ψ 2 does not conta in occurrences of model fields declared in C , nor uncast occurrenc es of this .  to call a method. For instanc e, the preco ndition of the method r egiste rValu e requires the v alue of the Inte ger object to be registe red to be greater than -1. A postcondi tion specifies the implementor’ s obli gation , what must be true at the end of a method, just before it r eturns to the c aller . In J ML, the ensures cl ause introduces a postcon dition. For instance, the Line 7 in troduc es a normal postc onditi on that asse rts that the final v alue of th e Inte ger object we register is the same as the one the method recei ves as arg ument. The JML modifier pure (Line 11) indicat es that the m ethod doesn’ t ha ve any side e ff ects and hence can appear in specificati ons. In JML, the keyw ord also indicates that a method is extend ing the specification it inherits from its supertype . 3 Laws Our laws ex tend object-o riented progra mming laws from other work s [3, 6, 5, 7, 17]. The laws are written in an equationa l style. Each side of the equ ation corre sponds to a templat e of a well-for med progra m. Programming laws, in which left-hand and right -hand sides are related by equa lity , are a concis e presentatio n of a pair of laws. These laws precisely indicat e the modifications that can be done to a prog ram, stating their correspon ding side-co nditio ns. In f act, to apply a law , it is necessary to check (synta ctic or semantic) side-condi tions to ensure that the transformation is beha vior -preser ving and also maintain s its w ell-for medness. W e con sider that we are dealing with only one packa ge and working in a limited open system [7], in which classes of our system can depend on exter nal libraries. In Ja va and JML conte xt, we need to gua rantee that sou rce-cod e conti nues meeting its specifica- tions written in JML , taking into account the semantics of JML specificatio ns along with the notion of specifica tion inheri tance [13]. Here we prese nt a law for in varian ts written in JML. A JML-annota ted Jav a program has the format cd s M ain , where cd s is the set of all classes of the progra m and M ain corres ponds to the unique class in the program w hich has a static main method. W e use cnt s , ad s and m d s insid e a class to represent s the class constructors , attrib utes and metho ds, respec ti vel y . W e ha ve to emphasiz e that they may contain the specificat ions of each constr uctor or 68 Object-o riented P rogramming Laws fo r Annotated Ja v a Programs Law 2 h move r efer ence type attrib ute to super class i class B extends A { ad s cnt s md s } class C extends B { /*@ nullable @*/ T a ; ad s ′ cnt s ′ md s ′ } = cd s , M ain class B extends A { /*@ nullable @*/ T a ; ad s cnt s md s } class C extends B { ad s ′ cnt s ′ md s ′ } pro vided JML: ( ← ) D . a , for any D ≤ B and D  C does not occur inside specifications of cd s , M ain , cnt s , cnt s’ , md s nor md s ’ . J ava: ( ↔ ) T is not a primiti ve type. ( → ) (1) a is not declare d in ad s ; (2) T he attrib ute name a is not declared by the subclasse s of B in cd s . ( ← ) D . a , for an y D ≤ B e D  C does not occur in cd s , M ain , cnt s , cnt s’ , md s nor md s ’ .  method. It is not necess arily Jav a code only , w e can also ha ve the correspond ing JML specificati ons. In the laws, we use cd s 1 = cd s , M ain cd s 2 to denote the e qui valen ce of sets of class declarati ons cd s 1 and cd s 2 , wher e cd s is a co nte xt of c lass dec laratio ns for cd s 1 and c d s 2 . W e need to stress that thi s definit ion tak es into account only seq uentia l prog rams. W e write ‘ → ’ to indicate the condition that need to be satisfied to apply a law from left to ri ght. Like wise, we use ‘ ← ’ to indicate what has to be satis fied when applyi ng the law from right to left. W e use ‘ ↔ to indicate conditions that must hold in both directions. The first law we present ( La w 1 ) allows us to move an in varia nt ψ 2 from a subclass C to its superclass B . The in var iant we want to move only refers to in stance s of C as we require the in va riant to be applicabl e only to instances of class C . T o apply this law in any direction , we require that calls to super do not occur in ψ 2 , since after law applicatio n (in both direction s) these calls may refer di ff erent elements . T o apply this law from left to right, model fields cannot appear in ψ 2 and occur rences of this must be cast otherwis e the elements they refer may not be visible. Concerni ng the soundn ess of this law , we tak e in account the inheritan ce of specificatio ns in JML [13], in which inherit ed in varian ts are conjoined with locally added in v ariants . On the left-han d side, the in va riant ψ 2 , which is presen t in class C , is inherited by the subclasse s of C and holds for all subcla sses. On the right-ha nd side of the law , the in v ariant ψ 2 is inherite d by all subclasses of B beside s those that are not subcl asses of C . For those classes that are subcla sses of B , b ut not subclasses of C , the in v ariant holds becau se for objects of these classes the antecedent instanceof C fail s and the whole implicati on is true, not changing the meaning of any origin al local in varia nt that inherits ψ 2 . By using Law 2 , we can move an attrib ute to a superc lass if it is not already de clared in the superclass and i f it doe s not cause name con flicts. The applicatio n of Law 2 , from righ t to left, allo ws us to mo ve an attrib ute do wnward. In this case, w e prev ent access to the attrib ute by the exp ressio n this , and we allo w only accesses to a by C or subclasses of C , including accesses that appear in specifications . Gabriel Falconi eri Freitas et al. 69 In Law 2 , we consider only a ttrib utes whose type is a reference type. There is another law for moving an attrib ute of primiti ve type. T he reason for havin g two discti nct la ws for dealing with attrib utes of primiti ve and referenc e types comes from the nullable ke yword in Law 2 . In JML, any decla ration (ex cept for local variab les) whose type is a referenc e type is implicitly declared to be non-null, exc ept when one ad orns the dec laratio n with a nullable annotati on [16]. Thus, by default, JML alwa ys checks if a not n ullabl e attribu te is null in al l visi ble states of the class that declar es it. When we mo ve an attr ib ute to a supercla ss, this is not awa re about the newly m ov ed attrib ute and, therefore, this action can cause a undesira ble beha vior . In fact, if one instantiat es the superc lass, JML will raise an in v ariant exc eption report ing that the new attrib ute is null. T o a void this, we force attribu te nullabilit y to move it up. Then, if one wants to move a non-null a attrib ute, one needs to introduce nullable annotation before moving it. An attrib ute can become nullable applying a law named make attri b ute nullable , not presen ted here. Remember that in Ja va only reference types can be null. Law 3 allo ws us to mov e a redefine d method from a class to its superclass. The proviso concerning super is neede d because its semantics may be a ff ected when we mo ve it from a subclass to a supe rclass, or vice-vers a. W e can only m ov e the specification of a method if it does not refer to model fields of the class in which the method is origina lly declar ed. F urthermo re, this expr ession s may occur in the target method specificati ons only if they are cast. In fac t, as in the law the method has def ault visibility , only non-p ri v ate elements can be referenc ed in its pre- and postconditi ons. This is similar to Ja v a: the this exp ressio n m ay appear in mbod y’ if they hav e a cast and they mention only non-pri vate attribu tes or methods of cla ss C . T he rig ht-han d side of L aw 3 i ntrodu ces type tests in each one of the speci fications. In this way we assure that the original pre- and postco ndition s of the redefined method of C w ill only be applie d to calle rs that are instances of C or instanc es of any of C ’ s subcla sses. Law 3 h move r edefined method to super class: ov erriden method with non-defa ult specific ation case i class B extends A { ad s cnt s md s // @ r equ ir es ψ 1 ; // @ ensur es ψ 2 ; rt m ( pd s ) { mbody } } class C extends B { ad s ′ cnt s ′ md s ′ // @ also // @ r equ ir es ψ ′ 1 ; // @ ensur es ψ ′ 2 ; rt m ( pd s ) { mbody ′ } } = cd s , M ain class B extends A { ad s cnt s md s // @ requir es θ 1 && ψ 1 ; // @ ensures θ 1 && ψ 2 ; // @ also // @ requir es θ 2 && ψ ′ 1 ; // @ ensures θ 2 && ψ ′ 2 ; // @ also // @ requir es θ 2 && ψ 1 ; // @ ensures θ 2 && ψ 2 ; rt m ( pd s ) { if (!( this instance of C )) { mbody } else { mbody ′ } } } class C extends B { ad s ′ cnt s ′ md s ′ } where θ 1 ≡ !( this instanceo f C ) and θ 2 ≡ this instanceof C 70 Object-o riented P rogramming Laws fo r Annotated Ja v a Programs pro vided JML: ( ↔ ) super does not appear in ψ ′ 1 nor in ψ ′ 2 . ( → ) Both ψ 1 and ψ 2 do not contain occurrence s of model fields declare d in C , nor uncast occurrence s of this . J ava: ( ↔ ) (1) super and pri v ate attrib utes do not appear in mbody ′ ; (2) super . m does not appear in md s’ ( → ) mbody ′ does not contai n uncas t occurrenc es of this nor e xpress ions of the form (( C ) this ) . a and of the form (( C ) this ) . m ( e ) for any attrib ute a nor method m , in ad s ′ and md s ′ , respecti vely , with pri vate visib ility . ( ← ) m ( pd s ) is not declared in md s ′ .  4 Soundn ess The proofs we present here are only conce rned with the JML parts of the laws. Provin g the Jav a part is di ffi cult due to aliasin g, w hich can lead to representat ion e xposu re problems, for instan ce. In JML, specifica tions present in a class are inherited by its subcla sses, provid ed they are not priv ate. T his leads us to two con cepts: join of specifications and specification inheritance . 4.1 Join of spec ifications In a progra m written in Jav a and annotated with JML, classes inherit not only attrib utes and methods from supercla sses, they also inherit specificati ons of in varian ts, m ethods , history constraints , and initial- isation predi cates [13, 15]. Concer ning methods, a method speci fication may consi st of sev eral specifi- cation s cases, which are intro duced by th e use of cl auses such as requir es , assignable , ensur e s [16]. E ach specifica tion case has a precondit ion (the default predicate is true ) that states when the corresp onding specifica tion case appli es to a call. The ke yword a lso joins specificati ons cases. When a preconditi on of a specification cas e hol ds, the corres pondin g postcondit ion must ho ld also. defined e arlier in this section . The definitions we present here are taken from [15]. The notation T ⊲ ( pr e , po st ) is related to a specifi- cation case of an instan ce method that type checks when its recei ver ( this ) has static type T . It also type checks in conte xts w here t his has some subtyp e of T . In w hat follows, we introd uce the definition of joint JML method specificatio ns [15]. Definition 1 (J oin of JML method specificatio ns) L et T ′ ⊲ ( pr e ′ , po st ′ ) and T ⊲ ( pr e , po st ) be specifi ca- tions of an instance m ethod m . Let U be a subty pe of both T ′ and T . T hen the join of ( pre ′ , po st ′ ) and ( pre , po st ) for U , written ( pr e ′ , po st ′ ) ⊔ U ( pre , po st ) , is the specifi cation U ⊲ ( p , q ) with pr econdition p: pre || pre ′ and postco nditio n q: ( \ old (pr e’) == > post’) & & ( \ old (pr e) == > post)  In Definition 1, the precondit ion of joint m ethod specification s is their disjunction . The postcon di- tion of the join is a conjun ction of implicati ons (written == > in JML ’ s notatio n), stating that when a precon dition holds (in the pre-s tate), the correspon ding postcon dition must hold . Gabriel Falconi eri Freitas et al. 71 e xt inv B LH S = [by Definition 2 ] V { add ed inv U | U ∈ su per s ( B LH S ) } = [by set theory] V { add ed inv U | U ∈ (( su per s ( B LH S ) \ su per s ( A )) ∪ su per s ( A ) } = [by definition of conjunction ] ( V { add ed inv U | U ∈ (( su per s ( B LH S ) \ su per s ( A )) } ) ∧ ( V { add ed inv W | W ∈ su per s ( A ) } ) = [by definition of added in varian t in B LH S ] ψ 1 ∧ ( V { add ed inv W | W ∈ su per s ( A ) } ) = [by Propositiona l Logic] ψ 1 ∧ t r ue ∧ ( V { add ed inv W | W ∈ su per s ( A ) } ) = [by Propositiona l Logic] ψ 1 ∧ ( f al se ⇒ ψ inv ) ∧ ( V { add ed inv W | W ∈ su per s ( A ) } ) = [by type test for object of type B ] ψ 1 ∧ ( t hi s in st anceo f C ⇒ ψ inv ) ∧ ( V { add ed inv W | W ∈ su per s ( A ) } ) = [by definition of added in varian t in B R H S ] ( V { add ed inv U | U ∈ (( su per s ( B R H S ) \ su per s ( A )) } ) ∧ ( V { add ed inv W | W ∈ su per s ( A ) } ) = [by definition of conjunction ] V { add ed inv U | U ∈ (( su per s ( B R H S ) \ su per s ( A )) ∪ su per s ( A ) } = [by set theory] V { add ed inv U | U ∈ su per s ( B LH S ) } = [by Definition 2 ] e xt inv B R H S Figure 2: Proof of Law 1 - case of object of exact type B 4.2 Specification Inheritance Subtypes in JML inherit specification s, besides attrib utes an d methods. First, we introduce some n otatio n for type specification . For a type T , the in vari ant predicate declare d in the specification of T (without inheri tance) is denoted by ad ded inv T . For a meth od m dec lared in a ty pe T , the not ation added s pec T m = ( add ed pre T m , ad ded po st T m ) is the join of the specificatio n cases in type T for m . If m is declared in T with no specification and is not ove rriding any method, then ad d ed s pec T m = ( t rue , t rue ), which is the def ault spe cification in JML. W e use su per s ( T ) to deno te the set of all supe rtypes of T (incl uding T ) and method s ( T ) to denote the set of all instan ce method names declared in the specificatio ns of the types in a set T . Definition 2 (Extended specificatio n) Suppose T has supe rtypes su per s ( T ) , w hich includ es T itself . Then the ex tended specificat ion of T is a speci ficatio n such that : methods: for all m ethods m ∈ met hod s ( su per s ( T )) , the e xtende d specifica tion of m is the join of all added specifi cation s for m in T and all its pr oper supertypes e xt s pec T m = F T { add ed s pec U m | U ∈ su per s ( T ) } in variant: the exten ded in varian t of T is the conjunc tion of all added in varian ts in T and its pr oper supert ypes e xt int T = V T { add ed inv U | U ∈ su per s ( T ) }  The definitio ns w e presen t here w ere introdu ced in [15] and are the ones w e use in this pape r . 72 Object-o riented P rogramming Laws fo r Annotated Ja v a Programs e xt s pec B LH S m = [by Definition 2 ] F B LH S { add ed s pec U m | U ∈ su per s ( B ) } = [by set theory] F B LH S { add ed s pec U m | U ∈ ( su per s ( B ) \ su per s ( A )) ∪ su per s ( A ) } = [by definition of join with respect to B ] ( F B LH S { add ed s pec U m | U ∈ ( su per s ( B ) \ su per s ( A )) } ) ⊔ B ( F A { add ed s pec W m | W ∈ su per s ( A ) } ) = [by definition of join of specification cases for B LH S ] ( ψ 1 , \ old ( ψ 1 ) ⇒ ψ 2 ) ⊔ B ( F A { add ed s pec W m | W ∈ su per s ( A ) } ) = [by Propositiona l Logic] (( ψ 1 ∧ t r ue ) , \ old ( ψ 1 ∧ t r ue ) ⇒ ψ 2 ) ⊔ B ( F A { add ed s pec W m | W ∈ su per s ( A ) } ) = [by type test for object of type B ] (( ψ 1 ∧ ¬ ( t hi s in st anceo f C )) , \ old ( ψ 1 ∧ ¬ ( t hi s in st anceo f C )) ⇒ ψ 2 ) ⊔ B ( F A { add ed s pec W m | W ∈ su per s ( A ) } ) = [by Propositiona l Logic] (( ψ 1 ∧ ¬ ( t hi s in st anceo f C )) ∨ f al se ∨ f al se , \ old ( ψ 1 ∧ ¬ ( t hi s in st anceo f C )) ⇒ ψ 2 ) ∧ tr ue ∧ t r ue ) ⊔ B ( F A { add ed s pec W m | W ∈ su per s ( A ) } ) = [by type test for object of type B and Proposit ional L ogic] (( ψ 1 ∧ ¬ ( t hi s in st anceo f C )) ∨ (( t hi s in st anceo f C ) ∧ ψ 1 ) ∨ (( thi s in st anceo f C ) ∧ ψ ′ 1 ) , ( \ old ( ψ 1 ∧ ¬ ( t hi s in st anceo f C )) ⇒ ψ 2 ) ∧ ( \ old (( thi s in st anceo f C ) ∧ ψ 1 ) ⇒ ψ 2 )) ∧ ( \ old (( thi s in st anceo f C ) ∧ ψ ′ 1 ) ⇒ ψ ′ 2 )) ⊔ B ( F A { add ed s pec W m | W ∈ su per s ( A ) } ) = [by definition of join of specification cases for B R H S ] ( F B R H S { add ed s pec U m | U ∈ ( su per s ( B ) \ su per s ( A )) } ) ⊔ B ( F A { add ed s pec W m | W ∈ su per s ( A ) } ) = [by definition of join with respect to B ] F B R H S { add ed s pec U m | U ∈ ( su per s ( B ) \ su per s ( A )) ∪ su per s ( A ) } = [by set theory] F B R H S { add ed s pec U m | U ∈ su per s ( B ) } = [by Definition 2 ] e xt s pec B RH S m Figure 3: Proof of Law 3 - case of object of exact type B 4.3 Pr oofs Here we pre sent proofs for Laws 1 and 3 . Both proo fs in vo lve dealing with ca ses associa ted to the types of objects related to the classe s that are emphasize d in the laws. W e present the proof for just one case of these laws. The condit ions of the laws guarantee that both programs that appear in the laws are w ell- typed. Concerning L aw 2 , it is a law for attrib utes in w hich specification inheritance is not taken into consid eratio n. In F igure 2, we prese nt the proof for the case of Law 1 in which the we consider an object of exact type B . Notice that in L aw 1 , o n the left -hand side, an obj ect of exa ct type B has to e stablis h the (added) in v ariant ψ 1 . The added in varian t is giv en by ψ 1 ∧ ( thi s in st anceo f C ⇒ ψ inv ), on the right-hand side. For an object of type B , the type test is false and the w hole implication results true. The whole e ff ect is the same of the in v ariant of class B on the left-han d side. The proof for the case of L aw 3 in which we cons ider an object of ex act type B is presented in Fig- ure 3. On the left-hand side of this law , the specification c ase for method m in class B has pr econd ition ψ 1 Gabriel Falconi eri Freitas et al. 73 1 p u b l i c c l a s s E v e n I n t e g e r D a t a { 2 / / @ p r i v a t e i n v a r i a n t v a l u e . i n t V a l u e ( ) % 2 = = 0 ; 3 / / @ p r i v a t e i n v a r i a n t v a l u e . i n t V a l u e ( ) > − 1 ; 4 p r i v a t e I n t e g e r v a l u e ; 5 p u b l i c E v e n I n t e g e r D a t a ( ) { v a l u e = ne w I n t e g e r ( 0 ) ; } 6 / * @ r e q u i r e s n e w V a l u e ! = n u l l ; 7 @ r e q u i r e s n e w V a l u e . i n t V a l u e ( ) % 2 = = 0 & & n e w V a l u e . i n t V a l u e ( ) > − 1 ; 8 @ e n s u r e s g e t V a l u e ( ) . i n t V a l u e ( ) == n e w V a l u e . i n t V a l u e ( ) ; @ * / 9 p u b l i c v o i d r e g i s t e r V a l u e ( I n t e g e r n e w V a l u e ) { / * . . . * / } 10 / / @ e n s u r e s \ r e s u l t ! = n u l l ; 11 p u b l i c / * @ p u r e @ * / I n t e g e r g e t V a l u e ( ) { / * . . . * / } 12 / * @ r e q u i r e s g e t V a l u e ( ) ! = n u l l ; 13 @ e n s u r e s ! ( \ r e s u l t ) . e q u a l s ( ” ” ) ; @ * / 14 p u b l i c S t r i n g f o r m a t ( ) { / * . . . * / } 15 } Figure 4: Class EvenInt egerD ata and postcond ition ψ 2 . On the right- hand side, we enrich this specificatio n case with type tests in v olving the class name C , but with no impacts for object s with distinc t types from C . The other specification case for method m on the right-hand sid e a lso i n v olv es a type test, hav ing no e ff ects fo r c lasses other tha n class C . 5 A pplication In this section, we present an exa mple composed of excer pts of Ja v a classes annotate d with JML, as it is refactor ed by means of successi ve applicatio n of programming laws. C lasses Pos itive Integ erData (Figure 1) and Ev enInt egerD ata (Figure 4) represent positi ve and ev en integ ers, resp ecti vely . These classe s are part of a software that stores and manipulate s instan ces of positi ve and eve n intege rs. The class EvenI ntege rData (Figure 4) can only hold eve n posit i ve integers because of the in va riant written in Line 2. And, to reinforce the in vari ant, pr e-cond itions o f method regist erVal ue gua rantee that only e ven and p ositi ve v alues are all o wed. These cla sses share method s that ha ve the same functionali ty . Moreo ver , both h a ve an attribu te calle d value to sav e t he integer value of th e r espect i ve data. T o improve the d esign o f t his p rogram (e.g. by red ucing th e amou nt of duplicate d code) and to acce pt ne w data types (e.g. odd integ ers), we need to change the program in a disciplin ed way . In what follo w s, w e present a guidel ine that leads to the same structur e as obtaine d by apply ing the refactori ng Extract Superclas s [8]. W e do no t p resent a ll deriv ation step s, we omit mo st of them to sa ve space, b ut each step i s a ccomplis hed by the appli cation of a law . A detailed deriv ation, with all the steps and the ir correspo nding laws, can be found else where [9 ]. Our startin g point is composed by the classes presented in Figures 1 and 4. W e fi rst introduce a new class ( In teger Data ) to be the superclass of the existing clas ses, by applyi ng Law h class elim- inatio n i , from right to left. Then, we chang e the superclas s of classes P ositi veInte gerData and EvenIn teger Data to be Intege rData , by applying Law h chang e super class: fr om O bject to another class i , from left to right. W e prepare classes Posi tiveI ntege rData and EvenI ntege rData , for movin g attrib ute, in varian t, and methods. First, we move the common attrib ute va lue to the superc lass. This is accompli shed by the applicati on of a sequ ence of laws, be ginning with Law h chan ge attrib ute visibility: 74 Object-o riented P rogramming Laws fo r Annotated Ja v a Programs 1 p u b l i c c l a s s I n t e g e r D a t a { 2 / / @ p r o t e c t e d i n v a r i a n t v a l u e . i n t V a l u e ( ) > − 1 ; 3 p r o t e c t e d I n t e g e r v a l u e ; 4 5 / / @ e n s u r e s \ r e s u l t ! = n u l l ; @ * / 6 p u b l i c / * @ p u r e @ * / I n t e g e r g e t V a l u e ( ) { / * . . . * / } 7 } Figure 5: Class Integ erDat a fr om private to public i , which chan ges the visibility of the attrib ute v alue to public, then we change its visibility to def ault by the app licatio n of another la w . In the sequenc e, we appl y Law 2 to mo ve the attrib ute val ue from class Po sitive Integ erData to class In tegerD ata . T his is follo wed by the ap- plicati on of other laws to eliminat e the attrib ute va lue from class E venInt egerD ata . Then, we mov e common methods to the class Int egerD ata . First, we apply L aw h mo ve origina l method to super class i to mov e methods from class Posit iveIn teger Data to In tegerD ata ; then we apply Law 3 to move re- defined method s from Eve nInte gerDat a to Intege rData . A nother la w allo w s us to simpl ify condition al commands. After mo ving the attrib ute value and methods to the su percla ss Inte gerDat a , we change the in v ariant of class es Posi tiveI nteger Data and E venIn tegerD ata to be in the format requir ed by Law 1 . W e apply Law 1 twice, then we simplify the in varian t in class Intege rData and change its visibility . In Figure 5, w e present clas s an excer pt of class I ntege rData after the ap plicati on of the progra mming laws that lead to the ref actorin g E xtr act Super class [8]. The final ver sion of the Positi veInt egerD ata and EvenI ntege rData has no get Value method and does not hav e the common in v ariant (see Figure 5, Line 2) because, now , the y belong to In tegerD ata . In [9], we applied the laws propose d here along w ith othe rs to refactor a core module of a Manufac- turing Executio n S ystem (MES) [22] software, which formalizes m ethods and procedur es of productio n in an integr ated system and presents data in more useful and systematic way . T o control and m anipul ate data dynamically and in a high ly configu rable way , the MES so ftware i s built on top of a Meta Data API. W e ha ve refac tored a JML-specified ve rsion of the Meta Data API [9] by apply ing primitiv e transforma- tions exp ressed by m eans of our laws. W e applie d our laws to refact or code and to accommodate new feature s. For insta nce, we eliminate duplicate code by extractin g a supe rclass that abstracts the beha vior of other classes present in the system. This is described by the E xtra ct Super class ref actori ng [8]. Other refa ctorin gs present ed by Fowler [8] (for instan ce, R eplace Condition al with P olymorphism and Pull Up Method ) were also applied to the Meta Data A PI by means of the propo sed laws. 6 Conclusion Object-o riented p rogrammin g la w s were propo sed b y Borba et al. [3] for an object-ori ented langu age [4 ]. They proposed laws for classes and commands; they also define a normal form for object-ori ented pro- grams w ritten in their language along w ith a reduction strategy . They demonstra te that the set of laws is complete w ith respect to this normal form. Corn ´ elio [6, 5] prov es the laws with resp ect to a copy semantic s [4] and formally justifies, by using programming laws and data refinement, refa ctorin g prac- tices documente d by Fo wler [8]. Silva , Sampaio, and Liu consi der object-orie nted programming laws in a languag e with a reference semantics [21], applying such laws to code refa ctorin g. Duarte [7] adapts the progra mming laws in itially proposed in [3, 5] for the Jav a programming and proposes other laws for Gabriel Falconi eri Freitas et al. 75 langua ge features that are not present in the language used in [3, 5]. In this paper , we proposed laws for object -orient ed prog ramming in the presence of a beha vioral interf ace specificatio n language . In the laws that deal with source-d oce, we treat the transforma tion consid ering the restrictions imposed by the specificatio ns. These laws are based on programming laws from pre vious work [3, 5, 7] that does not c onsid er speci fications . W e hav e considered laws tha t address only a subset of the JML ’ s Le vel 0 constr ucts [16], spe cially for lightweight speci fications. Nev erthele ss, our preliminary focus is to cove r most of the JML constructs that form the core notation used in the design by contract methodolog y . W e ha ve also a pplied our s et of la ws for red ucing a JML-spec ified Ja va progra m to a normal form [9] to address the relati ve complet eness of the set of laws propo sed. W ith resp ect to the order of applic ation of programmin g laws in program tran sformatio n process, distin ct orders may lead to di ff erent results. The conditions for applicat ion of a pr ogramming law usually requir es the application of other pr ogramming la ws, defining that their ap plicat ions are n ot co mmutati ve. T o o btain the desired tar get progra m, a prope r law a pplica tion sequence must be establish ed. Commonly used sequenc es of application s of laws can be re gister ed as single transformation rules. Concerni ng the refactori ng process, we can vie w a ref actoring as a tar get transformat ion that can be reached by the applicati on of primiti ve transformatio ns expr essed by means of programming laws. The proces s of application of programming laws terminates when the desired structur e is reac hed. Corn ´ elio [6] presents ref actorings as rules constituted by a pair of programs, similar to a law , but the transfo rmation described is more complex than the one of a law . The prog ram on the left-hand side presen ts the clas s or classes before rule application ; the right-hand side presen ts the classes after rule applic ation. Refact oring rules capture complex transformat ions. Here we hav e not presented refactori ng rules as in [ 6], but the applicati on o f the programming laws we presente d he re and in [9 ] lead us to a result similar to that presen ted in [6], that is, a refac toring is deriv ed by the application of programming laws. Although at this moment our work does not p rov ide a way to transfo rm pro grams mechanically , it o ff ers a more re liable an d e xtensible alterna ti ve to addres s beha vior -preserving transfo rmations like r efac toring s. Moreo ver , since some condition s present in the laws are related to logic proofs, it is necessar y to use a theore m prover as an aux iliary tool. Di ff erently from laws that deal only with constructs of an ob ject-o riented progra mming la nguage , the presen ce of a behav ioral interf ace specification language requir es that we be aware of issues relate d, for instan ce, to the visibility of specification and code construc ts, in varian t preserv ation when introducing calls to super and changing a parameter type to a supertyp e requires introd ucing casts in occurre nces of the parameter in specificati ons. As future work, we intend to describ e laws to support other JML clauses like initially , constraint , r epr esents , and m odel fields. Also, we inten d to work on proof s for the Ja va parts of the laws based on a referen ce semantics [1]. Ackno wledgements W e are partially supporte d by the Brazilian Research Agency , CNPq, grant 484813 / 2007-2 , and by the National Institute of Science and T echnology for Software Engineering (INES 1 ), funded by CN Pq and F A CE PE, grant s 573964 / 2008 -4 and APQ -1037- 1.03 / 08. 1 http: // www .ines.org.br 76 Object-o riented P rogramming Laws fo r Annotated Ja v a Programs Refer ences [1] A. Baner jee & D. A. Naumann (2005) : Ownership confineme nt ensures r epr esen tation independ ence for object-orien ted pr ograms . Journal of the A CM 52(6) , p p. 894—960. [2] R. Bird & O. de Moor (1997): Algebra o f Pr ogramming . Prentice Hall. [3] P . Bor ba et al. (2 004) : Algebraic reasoning for ob ject-oriented pr ogramming . Science o f Comp uter Progr am- ming 52, pp. 53– 100. [4] A. L. C. Ca valcanti & D. A. Naumann (2000): A W eakes t Pr ec ondition Semantics for Refinement of Object-oriented Pr ograms . IEEE T ransactions on Software Engineering 26(8) , p p. 713– 728. [5] M . Cor n ´ elio ( 2004 ): Refa ctoring a s F ormal Refinemen ts . Ph.D. thesis, Universidade Federal de Pernam buco. [6] M . Corn ´ elio et al. (2009): Sou nd refactorings . Science of Com puter Programming A vailable at htt p://dx. doi.org/10.1016/j.scic o. 2009.10.001 . [7] R. Duarte (2 008) : P arallelizing Java P r ograms Using T ransformation Laws . Master’ s th esis, Un i versidade Federal de Pernambuco (UFPE). [8] M . Fowler (199 9): Refactoring: impr oving the design of e xisting code . Ad dison-W esley Longm an Pub lishing Co., Inc., Boston, MA, USA. [9] G. R. F . Freitas (2009 ): Re factoring Anno tated Java Pr ograms: A Ru le-Based Appr oa ch . Master’ s thesis, Departamen to de Sistemas e Computac ¸ ˜ ao, Uni versidad e d e Pernambuco. A vailable online. [10] M. Goldstein, Y . A. Feldman & S. T yszberowicz ( 2006) : Refa ctoring with Contracts . In: A GI LE ’0 6: Proceeding s of th e conf erence on A GI LE 2006 . I EEE Computer Society , W ashington, DC, USA, pp. 53–64. [11] J. Gosling et al. (200 5): J ava Language Specification . A ddison-W esley Professional, 3rd edition edition. [12] C. A. R. Hoare et al. (198 7): Laws of pr ogramming . Commun. A CM 30(8) , pp. 672–686. [13] G. T . Leavens ( 2006) : JML ’s Rich, Inh erited Specific ations for Beh avioral Subtyp es . In : Z. Liu & J. He, editors: ICFEM , Lecture Notes in Computer Science 4260. Springer, pp . 2–34. [14] G. T . Leavens & Y . Cheon (20 05): Design by Contract with JML . A vailable online . [15] G. T . Leavens & D. A. Naumann (200 6): Behav ioral Su btyping, Specification Inheritance, a nd Modular Reasoning . T echnical Repor t 06-20b, Department of Computer Science, Iow a State University , Ames, Iow a, 50011 . [16] G. T . Leavens et al. (2008): JML Refer ence Manual . A vailable online. [17] T . Masson i, R. Gh eyi & P . Borb a (2 008): F ormal Model-Driven Pr ogram Re factoring . In: J. L. Fiadeir o & P . In verardi, editors: F ASE , Lecture Notes in Com puter Science 4961. Spring er , pp. 362 –376 . A vailable at http:/ / dx.doi.org/10.1007/978- 3- 5 40- 787 43- 3_ 2 7 . [18] B. Meyer (1992): App lying design by contract . IEEE Computer 25, pp. 40–51 . [19] C. C. Morgan (1994 ): Pr ogramming fr o m Specifi cations . Prentice Hall, second edition. [20] S. Seres (2001): The Algebra of Lo gic Pr ogramming . Ph .D. thesis, Oxfor Uni versity Computing Laboratory . [21] L. S ilva, A. Sampaio & Z. L iu ( 2008) : Laws of Object-Orientation with Refer ence S emantics . I n: SEFM ’08: Proceeding s of the 2008 Sixth IEEE Internatio nal Con ference on S oftware En gineering and F o rmal Metho ds . IEEE Computer Society , W ashington, DC, USA, pp. 217–2 26. [22] R. R. Z agidullin & E. B. Frolov (200 8): Contr ol o f ma nufactu ring pr oduc tion by means of MES systems . Russian Engine ering Research 28(2) , pp. 166–168.

Original Paper

Loading high-quality paper...

Comments & Academic Discussion

Loading comments...

Leave a Comment