Preview only show first 10 pages with watermark. For full document please download

Uni

   EMBED

  • Rating

  • Date

    December 1969
  • Size

    380.9KB
  • Views

    187
  • Categories


Share

Transcript

04IN1011: Progr Programming amming techniques and technologie technologiess (6 ECTS) INJE02: Programming (8 ECTS) Final—SS 2013 Universit¨ at Koblenz-Landau, FB4 at Prof. Dr. Ralf L¨ammel, ammel, Dr. Manfred Jackel 16 July 2013 Name, Vorname Matrikel-Nr. Email Studiengang ECTS Pr¨ ufungsversuch ufungsversuch [email protected] 2 BSc Inf  2 BSc CV 2 ........................ 2 6 2 8 2 1 2 2 2 3 Hiermit best¨ atige ich, dass ich zur Klausur angemeldet und zugelassen bin. atige Eine falsche Angabe wird als T¨ auschungsversuc auschungsversuch h gewertet. Unterschrift: ————————————————————————————— Aufga Aufgabe be 1 2 3 4 5 6 7 8 9 10 Total Korrekturabschnitt In der der 8 ECTS ECTS-V -Ver ersi sion on werd werden en 20 Punk Punkte te als als 10 1000 % ange angese setz tzt. t. Es werden also die Antworten zu allen 10 Fragen gez¨ ahlt. ahlt. In der 6 ECTS-Version werden 16 Punk Punkte te als als 100 % anges angeset etzt zt.. Es werde werden n die Antw Antwort orten en zu 8 Fragen gez¨ ahlt bei Maximierung der ahlt Gesamtpunktzahl. 1 Punkt Punkte e (0-2 (0-2)) Exam Manual 1. If you have any questions regarding the following items, please ask them them ahead ahead of the final. final. You can ask ask them them durin duringg the the final final or the the re-sit as well, but this may be less helpful to you. 2. There There are 10 exam assignments assignments with 0-2 points each. each. 0 means ‘missing’ or ‘wrong’; 1 means ‘arguably appropriate, but significantly incomplete or incorrect’; 2 means ‘appropriate and essentially complete and correct’. correct’. You might get an extra point for each exam assignmen assignment, t, if you manage to come up with an exceptionally insightful solution. The The exam exam lasts lasts 1 hour hour.. Thus Thus,, one one can can spend spend more more than than 5 min per exam assignment. 3. All exam assignme assignments nts focus focus on ‘program ‘program comprehension’. comprehension’. That is, you need to understand and comment on some given code fragment. A 140 chars limit applies to each answer if text is required. Longer answers will receive a reduced score (≥ 0). In some cases, if any, any, you may need to write down some piece of code, grammar, XML, schema, SQL, or alike. 4. The overall overall topics for the exam are defined with the dry-run; dry-run; see the section headers and the per-section footnotes for extra explanations. These topics are maintained for the actual final and the re-sit of the given given course edition. edition. The topics may be different different in the next edition of this course. 5. One should be prepared— prepared—syste systematical matically—th ly—that at the text of the exam assignments relates to the (software) concepts  that are listed on the wiki pages for the individual individual lectures. lectures. Definitions Definitions of the concepts concepts are never inquired, but basic understanding of the concepts is assumed and crucial for passing the exam. 6. The code fragments fragments of the exam assignments assignments may be drawn from the illustrations  given for all concepts on the wiki pages, the contributions  (i.e., implementations of the 101system ) practiced in the lectures, and the overall scenarios of the homework assignments. 7. Detailed Detailed knowledge knowledge of libraries, technologies technologies,, and language extensions extensions (such as specific details of java.lang.reflect, Hibernate mapping files, or AspectJ AspectJ langua language ge constr construct ucts) s) is never never assumed. assumed. As the exam exam assignments require understanding of code, one needs to remember a fair amount of details though. 2 “The “T he Expr Expres essi sion on prob proble lem” m”1 1 Consider the following Java-based object model for expression forms and an extra class for an evaluator with an incomplete definition of a static evaluation method: publ public ic abstr abstrac act t class class Expr Expr { } publ public ic class class Liter Literal al exten extends ds Expr Expr { publi public c int info; info; // a consta constant nt } publ public ic class class Add exten extends ds Expr Expr { publi public c Expr Expr left, left, righ right; t; // opera operand nds s of addit addition ion } public public class class Evaluato Evaluator r { publi public c int evalu evaluate ate(E (Expr xpr e) { ... // metho method d body body omitt omitted ed } } By placing methods such as evaluate  outside the underlying classes for data variants, we seem to be achieving ‘operation extensibility’, i.e., the ability to add operations without the need to revise code for existing data variants. However, what is the drawback of such an approach in Java? Reference solution As the evaluate  method would need to dispatch on the different expression forms, it would also involve involve weakly weakly typed typed casts. casts. Data extensibilit extensibility y may also be b e limited. limited. 1 This topic concerns concerns the lecture with the same name. One should understand understand,, for example, example, data and operation operation extensibi extensibilit lity y, the relationship relationship to class inheritance, inheritance, object composition, composition, and the use of static static versus versus instance methods. methods. The problem also resurfaces resurfaces in the contexts of AOP and the Visitor  design pattern. 3 “XML “XML data data bind bindin ing” g”2 2 Consider the following XSD fragment which models lines as consisting of two points: Why is it difficult to map this element declaration automatically to a Java class? Reference solution We would prefer a Line  class with two fields, but reasonable names of those fields are not suggested by the element declaration. 2 This topic concerns concerns the lecture with the same name. One should understand understand,, for example, some basics of XML schemas, the differences between object graphs and XML data, the overall utility of annotations in the mapping processing, the notions of marshaling and unmarshaling, and the implications on OO programming. 4 “Object/re “Object/relati lationa onall mappin mapping” g”3 3 Consider the following Java code which persists a new cat in a Hibernate session: Transaction tx = session.beginTransaction( session.beginTransaction(); ); Cat princess princess = new Cat(); Cat(); princess.setName("Princess"); princess.setSex(’F’); princess.setWeight(7.4f); session.save(princess); tx.commit(); Why is it necessary to explicitly ‘save’ the new cat, if you want Hibernate to persist the cat? Reference solution Assuming that Cat  is a POJO class, Hibernate would not know about the new instance instance unless told explicitly, explicitly, as done with save . 3 This topic concerns concerns the lecture lecture ‘Database ‘Database programming’ programming’,, specifically specifically the part on object/relati object/relational onal mapping. One should understand understand,, for example, the motivation motivation for the use of O/R mapping, basic mapping rules from object models to relational tables, the notion of transactions on the OO program side, the mechanics of persisting objects and retrieving them later again. 5 “Refl “Reflec ecti tion on” ”4 4 Consid Consider er the follo followin wingg reflect reflection ion code which which perform performss object object constr construct uction ion and method invocation: 01 02 03 04 05 Class Class clss clss = Class.f Class.forNa orName(" me("mypac mypackage kage.MyCl .MyClass" ass"); ); Constr Construct uctor or cons cons = clss.g clss.getC etCons onstru tructo ctor() r(); ; Obje Object ct obj obj = cons cons.n .new ewIn Inst stan ance ce() (); ; Method Method meth meth = clss.ge clss.getMe tMetho thod(" d("myM myMeth ethod" od"); ); meth.i meth.invo nvoke( ke(obj obj); ); Extract a Java class from the code which would be suitable for this reflection code to succeed. Reference solution package mypackage public public class class MyClas MyClass s { public public void void myMeth myMethod( od() ) { } } 4 This topic concerns the lecture ‘Metaprograms and metadata’, specifically the part on Java’s introspection. introspection. One should understand, for example, the basics of the reflection API, its fundamental limitations, simple use cases such as object dumping, and the role of exceptions in the use of reflection. 6 “Aspect“Aspect-ori orien ented ted progra programmi mming” ng”5 5 Consider the following aspect that should be applied to a simple Account  class with methods for withdrawal, deposit, etc. before(A before(Accou ccount nt a, double double value): value): call(voi call(void d Account. Account.withd withdraw( raw(doub double)) le)) && target(a target(a) ) && args(val args(value) ue) { assert assert value value >= 0 && a.getB a.getBala alance nce() () >= value; value; } Explain Explain the aspect. Reference solution The poincut identifies the withdraw  method and binds receiver and argument; the advice asserts that there is sufficient balance. 5 This topic concerns concerns the lecture with the same name. One should understand understand,, for example, the key notions of crosscutting, join point, pointcut, before/after/around advice, and inter-type declarations as well as basic application scenarios such as logging, contract checking, and update handling. 7 “Fun “F unct ctor orss in in OO prog progra rams ms” ”6 6 Consider the following functor interface: interfac interface e Function Function Z> { Z appl apply( y(X X x, Y y); y); } Write down a Java expression which instantiates an anonymous class that implements the Function  interface such that apply  implements string concatenation. Reference solution new Function ring> { String String apply( apply(Str String ing x, String String y) { return return x+y; }; } 6 This topic concerns concerns the lecture lecture ‘Functi ‘Functional onal OO programmin programming’. g’. The lecture lecture dealt with parsing and traversal combinators, but these relatively advanced scenarios are not exercised in the exam. Instead, one should understand the notion of functors as such and manage simple scenarios such as list processing, as exercised by the homework assignment on FOOP. 8 “Mul “M ultit tithr hread eadin ing” g”7 7 Consider the following code that could be part of an application for searching and booking flight connections: fina final l Date Date date date = ...; ...; // the the date date for for the the flig flight ht final final Airpor Airport t from from = ...; ...; // aiport aiport for depart departure ure final final Airpor Airport t to = ...; ...; // airpor airport t for arrival arrival Callable> on>> searchCallable searchCallable = new Callable>() on>>() { public public List on> call() call() { List List options = new LinkedList(); LinkedList(); ... // actual actual search search omitte omitted d return options; } }; Future> >> searchFuture = pool.submit(searchCallable); That is, a ‘callable’ for seaching booking options is instantiated and ‘submitted’ to a ‘thread pool’ to receive a ‘future’ in return so that the determined booking options could be retrieved eventually. What is the advantage of delegating the search to a thread? Reference solution The main thread thread of the applic applicati ation on remain remainss respons responsiv ive. e. The future future could could be checked later for the availability of the result. 7 This topic concerns concerns the lecture with the same name. One should understand understand,, for example, example, the use of ‘callables’ ‘callables’,, ‘runnables ‘runnables’, ’, functors, functors, and thread thread po ols in scenarios scenarios of  programming with threads as well as simple means of synchronization for use of shared resources. 9 “Rem “Remot ote e meth method od in invocati ocation on” ”8 8 Consider the following server-side RMI code which binds a product catalog so that a client may access the catalog: ProductC ProductCatal atalog og amazon amazon = ...; // InetAddress addr = InetAddress.getLocalHost( InetAddress.getLocalHost(); ); hostname = addr.getHostName(); addr.getHostName(); Naming.r Naming.rebin ebind("/ d("//" /" + hostname hostname + "/Amazon "/Amazon", ", amazon); amazon); Why is it sufficient to bind only the catalog as such, but not the individual sections, entries, and other components of the catalog? Reference solution All the catalog’s components can be retrieved on the client side via regular getters; only the root object, i.e., the catalog, must be looked up. 8 This topic concerns concerns the lecture with the same name. One should understand understand,, for example, the role of interfaces for services, the need for client-side stubs (proxies) and server-side skeletons, and the use of a name-binding service. 10 “Recur “Recursiv sive e descen descentt parsin parsing” g”9 9 Consider the following grammar production: compan company y : ’compa ’company’ ny’ STRING STRING ’{’ ceo departm department ent* * ’}’ Please sketch the code that would implement the production in a recursive descent parser. Reference solution privat private e final final void void compan company() y() {  match("company");  match("company");  match(STRING);  match(STRING);  match("{"); ceo(); while (test("department")) (test("department")) department();  match("}"); } 9 This topic concerns the lecture ‘Language processing patterns’, specifically the Acpatterns. One should understand, understand, for example, example, the corresponde correspondence nce ceptor  and Parser  patterns. between grammars and ‘procedures’ (methods) that perform recursive descent parsing. 11 10 “Par “Parse serr gener generat atio ion” n”10 Consider the following ANTLR grammar fragment which is concerned with totaling salaries of employees. employee employee : STRING STRING ’{’ ’address’ STRING ’salary’ ’salary’ FLOAT FLOAT { total total += Double.p Double.parse arseDoub Double($F le($FLOAT LOAT.tex .text); t); } ’}’; The semantic action accesses a variable total . What What is the declar declaring ing scope scope of the variable? Reference solution The variable total  is an instance field of the class that is generated from the ANTLR grammar. 10 This topic concerns concerns the lecture lecture ‘Generati ‘Generative ve programmin programming’, g’, specifically specifically the Parser  patterns. One should understand, understand, for example, the repGeneration  and Text-to-object  patterns. resentation of context-free grammars with ANTLR, the overall mechanics of generating, building, and running an ANTLR-based parser, the role and expressiveness of semantic actions in ANTLR, and the possibility to parse text into ANTLR-unaware objects, in fact, POJOs. 12