Conception Orientée Objet. Romain Rouvoy Licence mention Informatique Université Lille 1

Similar documents
VLANs. Commutation LAN et Wireless Chapitre 3

Java et Mascopt. Jean-François Lalande, Michel Syska, Yann Verhoeven. Projet Mascotte, I3S-INRIA Sophia-Antipolis, France

Chapitre 6 Programmation orientée aspect (AOP)

SunVTS Quick Reference Card

Sun Control Station. Performance Module. Sun Microsystems, Inc. Part No September 2003, Revision A

Classes internes, Classes locales, Classes anonymes

Formation. Application Server Description du cours

<?php. file_get_contents( cours.txt ) /* Persistance côté serveur */ /* */

Sun Java System Connector for Microsoft Outlook Q4 Installation Guide

Héritage (2) Programmation Orientée Objet. Jean-Christophe Routier Licence mention Informatique Université Lille Sciences et Technologies

Concilier Gouvernance et DevOps? AWS vous permet de satisfaire l'équation!

(800) Toll Free (804) Fax Introduction to Java and Enterprise Java using Eclipse IDE Duration: 5 days

Solaris 8 6/00 Sun Hardware Roadmap

Solaris 9 9/04 Installation Roadmap

man pages section 6: Demos

SunVTS Quick Reference Card

Oracle ZFS Storage Appliance Cabling Guide. For ZS3-x, 7x20 Controllers, and DE2-24, Sun Disk Shelves

Oracle Dual Port QDR InfiniBand Adapter M3. Product Notes

Sun Management Center 3.6 Version 7 Add-On Software Release Notes

TP 3 des architectures logicielles Séance 3 : Architecture n-tiers distribuée à base d EJB. 1 Préparation de l environnement Eclipse

Read me carefully before making your connections!

Planning Premier Workshops de Septembre 2018 à Juin 2019 Microsoft Services Edition Juillet 2018

Traditional Chinese Solaris Release Overview

Sun Ultra TM. 5 and Ultra 10 Product Notes. Sun Microsystems, Inc. 901 San Antonio Road Palo Alto, CA U.S.A.

Lecture Notes CPSC 224 (Spring 2012) Today... Java basics. S. Bowers 1 of 8

Font Administrator User s Guide

Guide Share France Groupe de Travail MQ septembre 2017

Utilisez Mutant / Mutest pour améliorer vos tests, votre code Sigilium

Test, beauty, cleanness. d après le cours de Alexandre Bergel

UE 2I002 (ex LI230) : éléments de programmation par objets avec Java TD10 - Exceptions

Font Administrator User s Guide. Sun Microsystems, Inc. 901 San Antonio Road Palo Alto, CA U.S.A.

Object Oriented Programming. Week 1 Part 3 Writing Java with Eclipse and JUnit

Java Persistence API (JPA) Entities

Solaris 8 User Supplement. Sun Microsystems, Inc. 901 San Antonio Road Palo Alto, CA U.S.A.

ILLUSTRATION DES EXCEPTIONS

Binghamton University. CS-140 Fall Problem Solving. Creating a class from scratch

Tutorial :.Net Micro Framework et.net Gadgeteer

Sun Ethernet Fabric Operating System. LLA Administration Guide

Memory Hole in Large Memory X86 Based Systems

8.4. Mobile Platform Release Notes

Atelier Java - J1. Marwan Burelle. EPITA Première Année Cycle Ingénieur.

Sun Java System Directory Server Release Notes for HP-UX

Sun Fire V100 Server Product Notes

TD : Compilateur ml2java semaine 3

Canada s Energy Future:

Java Desktop System Release 2 Installation Guide

Préparation au concours ACM TP 2

VHDL par Ahcène Bounceur VHDL

Solaris 8 User Supplement. Sun Microsystems, Inc. 901 San Antonio Road Palo Alto, CA U.S.A.

Dominique Blouin Etienne Borde

Java Desktop System Release 3 Troubleshooting Guide

Ultra Enterprise 6000/5000/4000 Systems Power Cord Installation

About Transferring License Rights for. PL7 V4.5 and Unity Pro V2.3 SP1 Software

Solaris 8 Desktop User Supplement. Sun Microsystems, Inc. 901 San Antonio Road Palo Alto, CA U.S.A.

Sun Control Station. Software Installation. Sun Microsystems, Inc. Part No January 2004, Revision A

Scenario Planning - Part 1

Rackmount Placement Matrix

5. Enterprise JavaBeans 5.3 Entity Beans. Entity Beans

Sun Patch Manager 2.0 Administration Guide for the Solaris 8 Operating System

Oracle ZFS Storage Appliance Simulator Quick Start Guide

Sun Enterprise System 336-Mhz Processor Upgrade Instructions

Sun Ethernet Fabric Operating System RMON Administration Guide

Sun Ethernet Fabric Operating System. IGMP Administration Guide

Tutorial 1 : minimal example - simple variables replacements

Forte for Java (Community Edition) QuickStart Guide

Solaris PC NetLink 1.2 Installation Guide

Sun Fire V60x and V65x Servers ReadMe

GNOME 2.0 Desktop for the Solaris Operating Environment User Guide

New advances in large scale industrial DEM modeling towards energy efficient processes

Sun Management Center 4.0 Version 4 Add-On Software Release Notes

Internship Report. Point Cloud Renderer. By Thibaut Bernard. German tutor Ole Wendlandt. French tutor Thomas Diette

Simplified Chinese Solaris Release Overview

Sun Management Center 4.0 Version 3 Add-On Software Release Notes

Collections. Collections. USTL routier 1

Fortran 90 Browser. f90browse

The Solaris Security Toolkit - Quick Start

The Personal Information Canadians Give to Retailers

Cable Management Guide

CSCI 161 Introduction to Computer Science

Sun StorageTek 2500 Series Array Firmware Upgrade Guide

ECLIPSE JAVA DOCUMENTATION

Distance Transform. Etienne Folio. Technical Report n o 0806, JUNE 2008 revision 1748

Analyse statique de programmes avioniques

Accessible depuis une interface web, OCS va permettre de visualiser l'inventaire de votre parc.

UltraSPARC - IIs CPU Module Installation Guide

ControlLogix Redundant Power Supply Chassis Adapter Module

Sun Management Center 4.0 Version 2 Add-On Software Release Notes

Sun StorEdge T3 Disk Tray Cabinet Installation Guide

Feature-Based Facial Expression Recognition: Experiments With a Multi-Layer Perceptron

Ramassage Miette Garbage Collector

Sun Netra TM X4200 M2 Server Product Notes

Jini Network Technology

COURSE 80434: FIXED ASSETS IN MICROSOFT DYNAMICS NAV 2013

Sun StorEdge Network 2 Gb Brocade SilkWorm 3200 and 3800 Switches Release Notes

20-40 Gbyte 8mm Tape Drive Installation and User s Guide

Managing Boot EnvironmentsWith Oracle Solaris 11 Express

Netra Blade X3-2B (formerly Sun Netra X6270 M3 Blade) for VMware ESXi. Installation Guide

Programming overview

man pages section 9: DDI and DKI Overview

Getting started with Java

Transcription:

Conception Orientée Objet Romain Rouvoy Licence mention Informatique Université Lille 1 1

Menu du jour 1. Coder c est douter 2. De la génération 3. À l analyse 2

Mauvaise conception? Où est le problème? 3

Derrière le clavier! 4

Coder, c est douter? 5

Pourquoi ne pas générer? Beaucoup d erreurs proviennent de la routine Coder des parties répétitives Par exemple Générer des getters/setters 6

StringBuilder sourcebuilder = new StringBuilder(); sourcebuilder.append("package fil.coo;\n\n"); sourcebuilder.append("import java.util.*;\n\n"); sourcebuilder.append("public class MyBean {"); for (DBField dbfield:getfields) { // bean attribute sourcebuilder.append("\tprivate ").append(dbfield.gettype).append(tofieldname(dbfield.getname())).append(" = null;\n"); // setter method sourcebuilder.append("\tpublic void ").append(tosettername(dbfield.getname())).append("(");.append(dbfield.gettype).append(tofieldname(dbfield.getname())).append(") {\n").append("\t\tthis.").append(tofieldname(dbfield.getname())).append(" = ").append(tofieldname(dbfield.getname())).append(";\n\t}"); // getter method... sourcebuilder.append("\t}\n}\n"); 7

import fil.coo;import java.util.*; public class MyBean { #foreach( $field in getfields()) private $field.type $field.name = null; public void $field.setter()($field.type $field.name) { this.$field.name = $field.name ; } #end } public void #field.getter()() { return this.$field.name ; } 8

Template-based generation Forces Très «visuel» Facile à aborder Peut générer tout (et n importe quoi) Faiblesses Pas de typage Difficulté de réutilisation (donc copier/coller) Rapidement complexe (pré-processing) 9

$petlist.size() Pets on Sale! We are proud to offer these fine pets at these amazing prices. This month only, choose from: #foreach( $pet in $petlist ) $pet.name for only $pet.price #end Call Today! 10

Template-based generation Nombreux outils Apache Velocity Freemarker Eclipse JET Très utilisée Web frameworks (génération HTML) Persistence frameworks (génération POJO) Maven archetypes 11

API-based generation Forces Typage fort (correct par construction) Réutilisation aisée (comme tout programme) Faiblesses Potentiellement verbeux Pas très visuel 12

package com.example.helloworld; public final class HelloWorld { public static void main(string[] args) { System.out.println("Hello, World!"); } } 13

MethodSpec main = MethodSpec.methodBuilder("main").addModifiers(Modifier.PUBLIC, Modifier.STATIC).returns(void.class).addParameter(String[].class, "args").addstatement("$t.out.println($s)", System.class, "Hello, World!").build(); TypeSpec helloworld = TypeSpec.classBuilder("HelloWorld").addModifiers(Modifier.PUBLIC, Modifier.FINAL).addMethod(main).build(); JavaFile javafile = JavaFile.builder("fil.coo", helloworld).build(); javafile.writeto(system.out); 14

Et la qualité du code dans tout ça? 15

package fr.inria.gforge.spoon.processors; import org.apache.log4j.level; import spoon.processing.abstractprocessor; import spoon.reflect.code.ctcatch; /** * Reports warnings when empty catch blocks are found. */ public class CatchProcessor extends AbstractProcessor<CtCatch> { public void process(ctcatch element) { if (element.getbody().getstatements().size() == 0) { getfactory().getenvironment().report(this, Level.WARN, element, "empty catch clause"); } } } 16

Spoon Projet OSS développé par Inria depuis 2005 Couvre la génération, l analyse et la transformation Charge le code en un modèle Votre code devient une donnée manipulable Possibilité de lire/modifier/ajouter des éléments Correct par construction 17

18

19

<plugin> <groupid>fr.inria.gforge.spoon</groupid> <artifactid>spoon-maven-plugin</artifactid> <version>2.2</version> <executions> <execution> <phase>generate-sources</phase> <goals> <goal>generate</goal> </goals> </execution> </executions> <configuration> <processors> <processor>fr.inria.gforge.spoon.processors.catchprocessor</processor> </processors> </configuration> <!-- To be sure that you use the latest version of Spoon, specify it as dependency. --> <dependencies> <dependency> <groupid>fr.inria.gforge.spoon</groupid> <artifactid>spoon-core</artifactid> <version>5.4.0</version> </dependency> </dependencies> </plugin> 20

Factory Create new elements, fill their data and add them in an existing AST. The factory is the entry point to do that and each factory has them own responsibility. i.e., CoreFactory creates empty nodes and CodeFactory creates a node ready to be printed. if (message == "null") java.lang.system.out.println("message is null"); http://spoon.gforge.inria.fr/factories.html 21

if (message == "null") java.lang.system.out.println("message is null"); 22

if (message == "null") java.lang.system.out.println("message is null"); 23

if (message == "null") java.lang.system.out.println("message is null"); 24

if (message == "null") java.lang.system.out.println("message is null"); 25

if (message == "null") java.lang.system.out.println("message is null"); 26

if (message == "null") java.lang.system.out.println("message is null"); 27

if (message == "null") java.lang.system.out.println("message is null"); 28

if (message == "null") java.lang.system.out.println("message is null"); 29

if (message == "null") java.lang.system.out.println("message is null"); 30

if (message == "null") java.lang.system.out.println("message is null"); 31

if (message == "null") java.lang.system.out.println("message is null"); 32

@Override public void process(notnull annotation, CtParameter<?> element) { System.out.println("annotation found on " + element.getsimplename()); final CtVariableAccess<?> parameter = // getfactory().code().createvariableread(element.getreference(), false); final CtLiteral<?> nullaccess = getfactory().code().createliteral("null"); final CtBinaryOperator<Boolean> binaryoperator = // getfactory().code().createbinaryoperator(parameter, nullaccess, BinaryOperatorKind.EQ); final CtCodeSnippetStatement snippet = getfactory().code().createcodesnippetstatement( "System.out.println(\"" + element.getsimplename() + " is null\")"); // Creates condition. final CtIf anif = getfactory().core().createif(); anif.setcondition(binaryoperator); anif.setthenstatement(snippet.compile()); // Factory final CtExecutable ctexecutable = element.getparent(ctexecutable.class); ctexecutable.getbody().insertbegin(anif); } 33

@Override public void process(notnull annotation, CtParameter<?> element) { System.out.println("annotation found on " + element.getsimplename()); final CtVariableAccess<?> parameter = // getfactory().code().createvariableread(element.getreference(), false); final CtLiteral<?> nullaccess = getfactory().code().createliteral("null"); final CtBinaryOperator<Boolean> binaryoperator = // getfactory().code().createbinaryoperator(parameter, nullaccess, BinaryOperatorKind.EQ); final CtCodeSnippetStatement snippet = getfactory().code().createcodesnippetstatement( "System.out.println(\"" + element.getsimplename() + " is null\")"); // Creates condition. final CtIf anif = getfactory().core().createif(); anif.setcondition(binaryoperator); anif.setthenstatement(snippet.compile()); // Factory final CtExecutable ctexecutable = element.getparent(ctexecutable.class); ctexecutable.getbody().insertbegin(anif); } 34

@Override public void process(notnull annotation, CtParameter<?> element) { System.out.println("annotation found on " + element.getsimplename()); final CtVariableAccess<?> parameter = // getfactory().code().createvariableread(element.getreference(), false); final CtLiteral<?> nullaccess = getfactory().code().createliteral("null"); final CtBinaryOperator<Boolean> binaryoperator = // getfactory().code().createbinaryoperator(parameter, nullaccess, BinaryOperatorKind.EQ); final CtCodeSnippetStatement snippet = getfactory().code().createcodesnippetstatement( "System.out.println(\"" + element.getsimplename() + " is null\")"); // Creates condition. final CtIf anif = getfactory().core().createif(); anif.setcondition(binaryoperator); anif.setthenstatement(snippet.compile()); // Factory final CtExecutable ctexecutable = element.getparent(ctexecutable.class); ctexecutable.getbody().insertbegin(anif); } 35

@Override public void process(notnull annotation, CtParameter<?> element) { System.out.println("annotation found on " + element.getsimplename()); } final CtVariableAccess<?> parameter = // getfactory().code().createvariableread(element.getreference(), false); final CtLiteral<?> nullaccess = getfactory().code().createliteral("null"); final CtBinaryOperator<Boolean> binaryoperator = // getfactory().code().createbinaryoperator(parameter, nullaccess, BinaryOperatorKind.EQ); final CtCodeSnippetStatement snippet = getfactory().code().createcodesnippetstatement( "System.out.println(\"" + element.getsimplename() + " is null\")"); // Creates condition. final CtIf anif = getfactory().core().createif(); anif.setcondition(binaryoperator); anif.setthenstatement(snippet.compile()); // Factory final CtExecutable ctexecutable = element.getparent(ctexecutable.class); ctexecutable.getbody().insertbegin(anif); 36

@Override public void process(notnull annotation, CtParameter<?> element) { System.out.println("annotation found on " + element.getsimplename()); } final CtVariableAccess<?> parameter = // getfactory().code().createvariableread(element.getreference(), false); final CtLiteral<?> nullaccess = getfactory().code().createliteral("null"); final CtBinaryOperator<Boolean> binaryoperator = // getfactory().code().createbinaryoperator(parameter, nullaccess, BinaryOperatorKind.EQ); final CtCodeSnippetStatement snippet = getfactory().code().createcodesnippetstatement( "System.out.println(\"" + element.getsimplename() + " is null\")"); // Creates condition. final CtIf anif = getfactory().core().createif(); anif.setcondition(binaryoperator); anif.setthenstatement(snippet.compile()); // Factory final CtExecutable ctexecutable = element.getparent(ctexecutable.class); ctexecutable.getbody().insertbegin(anif); 37

@Override public void process(notnull annotation, CtParameter<?> element) { System.out.println("annotation found on " + element.getsimplename()); final CtVariableAccess<?> parameter = // getfactory().code().createvariableread(element.getreference(), false); final CtLiteral<?> nullaccess = getfactory().code().createliteral("null"); final CtBinaryOperator<Boolean> binaryoperator = // getfactory().code().createbinaryoperator(parameter, nullaccess, BinaryOperatorKind.EQ); final CtCodeSnippetStatement snippet = getfactory().code().createcodesnippetstatement( "System.out.println(\"" + element.getsimplename() + " is null\")"); // Creates condition. final CtIf anif = getfactory().core().createif(); anif.setcondition(binaryoperator); anif.setthenstatement(snippet.compile()); // Factory final CtExecutable ctexecutable = element.getparent(ctexecutable.class); ctexecutable.getbody().insertbegin(anif); } 38

@Override public void process(notnull annotation, CtParameter<?> element) { System.out.println("annotation found on " + element.getsimplename()); final CtVariableAccess<?> parameter = // getfactory().code().createvariableread(element.getreference(), false); final CtLiteral<?> nullaccess = getfactory().code().createliteral("null"); final CtBinaryOperator<Boolean> binaryoperator = // getfactory().code().createbinaryoperator(parameter, nullaccess, BinaryOperatorKind.EQ); final CtCodeSnippetStatement snippet = getfactory().code().createcodesnippetstatement( "System.out.println(\"" + element.getsimplename() + " is null\")"); // Creates condition. final CtIf anif = getfactory().core().createif(); anif.setcondition(binaryoperator); anif.setthenstatement(snippet.compile()); // Factory final CtExecutable ctexecutable = element.getparent(ctexecutable.class); ctexecutable.getbody().insertbegin(anif); } 39

Exemples d utilisation de Spoon Program Analysis The CatchProcessor detects empty catch blocks The ReferenceProcessor detects circular references between packages This Factory example detects wrong uses of the factory pattern Program Transformation The NotNullProcessor adds a not-null check for all method parameters The MutationProcessor randomly mutates some parts of the abstract syntax tree for mutation testing Annotation Processing The N-ton example introduces a N-ton design pattern (extension of singleton but for N instances) into a target class. It inserts static fields, methods, and initializer code into constructors The Database access example shows how to use annotation processing to add persistence into a POJO The Visitor example implements a visitor pattern by automatically introducing an accept method in a visited type hierarchy The Field Access example implements a refactoring that introduces setters and getters for the fields annotated with the Access annotation and that replaces all the direct accesses to these fields by calls to its new getters and setters 40

Et quoi d autre? void notreesetinspoon() throws Exception { // we don't use TreeSet, because they implicitly depend on Comparable SpoonAPI spoon = new Launcher(); spoon.addinputresource("src/main/java/"); spoon.buildmodel(); } assertequals(0, spoon.getfactory().package().getrootpackage().getelements(new AbstractFilter<CtConstructorCall>() { @Override public boolean matches(ctconstructorcall element) { return element.gettype().getactualclass().equals(treeset.class); }; }).size()); 41

Comment s assurer qu un générateur est correct? 42

Par le test! final SpoonAPI spoon = new Launcher(); spoon.addinputresource("path/of/my/file/foo.java"); spoon.run(); final CtType<Foo> type = spoon.getfactory().type().get(foo.class); assertthat(type.getfield("i")).withprocessor(new MyProcessor()).isEqualTo("public int j;"); 43

En résumé Génération de code pour limiter les erreurs «bêtes» (copier/coller) Analyse de code pour détecter les erreurs Transformation de code pour automatiser la production (lien Analyse => Génération) 44

C était le dernier épisode Ce que vous avez vu Quelques principes clés / méthodologies pour vous aider Notions d antipatrons à éviter et de métriques de code à comprendre Les apports de la génération et analyse de code Le tout supporté par un outillage (compatible Maven/Eclipse) Le tout valable pour tous vos développements (POJO, Android, Web, Go, Python ) Ce qu on attend de vous Approfondir chacun des points évoqués en cours Pratiquer, pratiquer, pratiquer! (en TP, en projet, en stage, en OSS, etc.) Est-ce que c est au programme du partiel? Bien évidemment! 45