IdentifiantMot de passe
Loading...
Mot de passe oublié ?Je m'inscris ! (gratuit)
Navigation

Inscrivez-vous gratuitement
pour pouvoir participer, suivre les réponses en temps réel, voter pour les messages, poser vos propres questions et recevoir la newsletter

avec Java Discussion :

Mieux organiser mon code, demande de conseil.


Sujet :

avec Java

  1. #1
    Membre averti
    Homme Profil pro
    Inscrit en
    Janvier 2014
    Messages
    18
    Détails du profil
    Informations personnelles :
    Sexe : Homme
    Localisation : Japon

    Informations forums :
    Inscription : Janvier 2014
    Messages : 18
    Par défaut Mieux organiser mon code, demande de conseil.
    Bonjour à tou(te)s,

    Je me suis mis à Java il y a un an, la programmation pareil.
    Bon, j'ai quelques bases en Python.

    Donc je commence à avoir un code assez long, dans lequel je mets les différentes choses que je dois faire.
    Je ne sais pas comment faire pour mieux organiser la disposition des méthodes, il n'y a qu'une classe.

    Bon, tous les conseils sont les bienvenus.

    Code : Sélectionner tout - Visualiser dans une fenêtre à part
    1
    2
    3
    4
    5
    6
    7
    8
    9
    10
    11
    12
    13
    14
    15
    16
    17
    18
    19
    20
    21
    22
    23
    24
    25
    26
    27
    28
    29
    30
    31
    32
    33
    34
    35
    36
    37
    38
    39
    40
    41
    42
    43
    44
    45
    46
    47
    48
    49
    50
    51
    52
    53
    54
    55
    56
    57
    58
    59
    60
    61
    62
    63
    64
    65
    66
    67
    68
    69
    70
    71
    72
    73
    74
    75
    76
    77
    78
    79
    80
    81
    82
    83
    84
    85
    86
    87
    88
    89
    90
    91
    92
    93
    94
    95
    96
    97
    98
    99
    100
    101
    102
    103
    104
    105
    106
    107
    108
    109
    110
    111
    112
    113
    114
    115
    116
    117
    118
    119
    120
    121
    122
    123
    124
    125
    126
    127
    128
    129
    130
    131
    132
    133
    134
    135
    136
    137
    138
    139
    140
    141
    142
    143
    144
    145
    146
    147
    148
    149
    150
    151
    152
    153
    154
    155
    156
    157
    158
    159
    160
    161
    162
    163
    164
    165
    166
    167
    168
    169
    170
    171
    172
    173
    174
    175
    176
    177
    178
    179
    180
    181
    182
    183
    184
    185
    186
    187
    188
    189
    190
    191
    192
    193
    194
    195
    196
    197
    198
    199
    200
    201
    202
    203
    204
    205
    206
    207
    208
    209
    210
    211
    212
    213
    214
    215
    216
    217
    218
    219
    220
    221
    222
    223
    224
    225
    226
    227
    228
    229
    230
    231
    232
    233
    234
    235
    236
    237
    238
    239
    240
    241
    242
    243
    244
    245
    246
    247
    248
    249
    250
    251
    252
    253
    254
    255
    256
    257
    258
    259
    260
    261
    262
    263
    264
    265
    266
    267
    268
    269
    270
    271
    272
    273
    274
    275
    276
    277
    278
    279
    280
    281
    282
    283
    284
    285
    286
    287
    288
    289
    290
    291
    292
    293
    294
    295
    296
    297
    298
    299
    300
    301
     
    package com.company;
     
    import tech.tablesaw.api.DoubleColumn;
    import tech.tablesaw.api.StringColumn;
    import tech.tablesaw.api.Table;
     
    import java.awt.*;
    import java.io.*;
    import java.io.File;
    import java.nio.file.*;
    import java.nio.file.Files;
    import java.util.ArrayList;
    import java.util.List;
    import java.util.Scanner;
     
     
    public class Main {
     
        public void Create1Directory(String Path33, String nomFile) throws Exception {
            //Pour creer un seul dossier
     
            File file = new File(Path33 + "Selection "+ nomFile);
            if (!file.exists()) {
                if (file.mkdir()) {
                    System.out.println("Directory is created!");
                } else {
                    System.out.println("Failed to create directory!");
                }
            }
        }
     
        public Table CreateMDirectory(String nomDossier2) throws Exception {
    //Pour creer plusieurs dossiers en se basant sur un Tableau
            String ND2 = nomDossier2;
            Table t2 = listDirectoryInFolder(ND2);
            for (int i = 0; i <t2.rowCount() ; i++) { //
                System.out.println(t2.get(i, 0).toString()); //
                File file = new File(ND2 + "\\" + "Selection " + t2.get(i, 0).toString());
                File filep = new File(ND2 + "\\" + "Kokaizumi " + t2.get(i, 0).toString());
                if (file.exists()) {
                   // System.out.println("Directory exists already!"); //
                } else {
                    file.mkdir();
                   // System.out.println("Directory is created!"); //
                }
                if (filep.exists()) {
                    System.out.println("Directory exists already!"); //
                } else {
                    filep.mkdir();
                    System.out.println("Directory is created!"); //
                }
     
            }
            Table t3 = listDirectoryInFolder(ND2);
            return t3;
     
        }
     
        public Table listDirectoryInFolder(String nomDossier) throws Exception {
            String ND = nomDossier;
            File file = new File(ND);
            File[] listOfFiles = file.listFiles();
            Table t = Table.create();
            List<String> noma = new ArrayList<>();
            List<String> patha = new ArrayList<>();
            List<String> nomb = new ArrayList<>();
            List<String> pathb = new ArrayList<>();
            List<String> nomc = new ArrayList<>();
            List<String> pathc = new ArrayList<>();
            //Nombre de fichiers dans le dossier
            System.out.println("Nombres de Files/Directory dans le dossier: "+listOfFiles.length);
     
     
            for (int i = 0; i < listOfFiles.length; i++) {
                if (listOfFiles[i].isFile()) {
                    //System.out.println("File Name: " + listOfFiles[i].getName());
                    noma.add(listOfFiles[i].getName());
                    //System.out.println("File Path: " + listOfFiles[i].getAbsolutePath());
                    patha.add(listOfFiles[i].getAbsolutePath()); }
                else if (listOfFiles[i].isDirectory()) {
                    if (listOfFiles[i].getName().startsWith("Selection")){
                        //System.out.println("Directory Name: " + listOfFiles[i].getName());
                        nomb.add(listOfFiles[i].getName());
                        //System.out.println("Directory Path: " + listOfFiles[i].getAbsolutePath());
                        pathb.add(listOfFiles[i].getAbsolutePath());
                    }
                    else if (listOfFiles[i].getName().startsWith("Kokaizumi")){
                        //System.out.println("Directory Name: " + listOfFiles[i].getName());
                        nomc.add(listOfFiles[i].getName());
                        //System.out.println("Directory Path: " + listOfFiles[i].getAbsolutePath());
                        pathc.add(listOfFiles[i].getAbsolutePath());
                    }
                    else
                        {//System.out.println("Directory Name: " + listOfFiles[i].getName());
                            noma.add(listOfFiles[i].getName());
                    //System.out.println("Directory Path: " + listOfFiles[i].getAbsolutePath());
                    patha.add(listOfFiles[i].getAbsolutePath());}
     
     
                }
            }
     
            String[] nom2 = new String[noma.size()];
            String[] path2 = new String[patha.size()];
            String[] nom3 = new String[nomb.size()];
            String[] path3 = new String[pathb.size()];
            String[] nom4 = new String[nomc.size()];
            String[] path4 = new String[pathc.size()];
     
            nom2 = noma.toArray(nom2);
            path2 = patha.toArray(path2);
            nom3 = nomb.toArray(nom3);
            path3 = pathb.toArray(path3);
            nom4 = nomc.toArray(nom4);
            path4 = pathc.toArray(path4);
     
            StringColumn column0 = StringColumn.create("Nom fichier", nom2 );
            StringColumn column1 = StringColumn.create("Path1", path2 );
            StringColumn column2 = StringColumn.create("Nom dossier selection", nom3 );
            StringColumn column3 = StringColumn.create("Path2", path3 );
            StringColumn column4 = StringColumn.create("Nom dossier Kokaizumi", nom4 );
            StringColumn column5 = StringColumn.create("Path3", path4 );
     
            t.addColumns(column0);
            t.addColumns(column1);
            t.addColumns(column2);
            t.addColumns(column3);
            t.addColumns(column4);
            t.addColumns(column5);
     
     
     
            //System.out.println(t);
            t.write().csv("test.csv");
            return t;
     
     
        }
     
        public static void  checkIfEnoughFilesfor1(String PathOriginFolder,String pathDestinationFolder, int selectParDossier) throws IOException {
     
            String Lepatha = PathOriginFolder;
            String Lepath2a =  pathDestinationFolder;
            System.out.println("le dossier d'origine: "+ Lepatha);
            System.out.println("le dossier de destination: "+ Lepath2a);
     
     
            File dir = new File(Lepath2a);
            File dirOrig = new File(Lepatha);
     
     
     
            int nbrSelecionesa = selectParDossier;
     
            System.out.println("nombre de photos necessaires: "+ nbrSelecionesa);
     
            String[] files = dir.list();
            String[] filesOrig = dirOrig.list();
     
            System.out.println( "Nombres d'images dans le dossier Selection : "+files.length);
     
     
            List<Integer> hazardNumbers = new ArrayList<>();
     
            int nbrrestant= nbrSelecionesa-files.length;
            System.out.println("le nombre de files necessaire est "+nbrrestant);
            int iab=0;
            while (iab<nbrrestant){
                int idz=(int)(Math.random()*filesOrig.length);
                if (filesOrig[idz].endsWith(".JPG")) {
                    if (!hazardNumbers.contains(idz)) {
                        hazardNumbers.add(idz);
                    }
                }
                iab++;
            }
     
            System.out.println("les photos choisies au Hasard: "+ hazardNumbers);
     
            Desktop.getDesktop().open(dir);
            Desktop.getDesktop().open(dirOrig);
     
     
            for (int i = 0; i < nbrrestant;i++ ) {
                Path temp = Files.move (Paths.get(PathOriginFolder+"\\"+filesOrig[hazardNumbers.get(i)]),
                        Paths.get(pathDestinationFolder+"\\"+filesOrig[hazardNumbers.get(i)]));
            }
     
     
     
     
     
        }
     
        public  void  checkIfEnoughFilesForM(String nomDossier3) throws Exception {
            String ND3=nomDossier3;
            Table t3 = CreateMDirectory(ND3);
            //System.out.println(t3.columnNames());
            t3.sortAscendingOn("Nom fichier");
            //System.out.println(t3);
            DoubleColumn nc = DoubleColumn.create("nombreDePhotos",t3.rowCount());
            t3.addColumns(nc);
            String input;
            double selectParDossier=0;
            for (int i = 13; i <t3.rowCount(); ) { //t3.rowCount()
            String Lepatha = t3.get(i, 1).toString();
            String Lepath2a =  t3.get(i, 3).toString();
            System.out.println("le dossier d'origine: "+ Lepatha);
            System.out.println("le dossier de destination: "+ Lepath2a);
            Scanner myObj = new Scanner(System.in);
            System.out.println("Entre le nombre necessaire de photos:");
            double nbrphnec = myObj.nextDouble();
            nc.set(i,nbrphnec);
            File dir = new File(Lepath2a);
            File dirOrig = new File(Lepatha);
            double nbrSelecionesa = nbrphnec;
            System.out.println("nombre de photos necessaires: "+ nbrSelecionesa);
            String[] files = dir.list();
            String[] filesOrig = dirOrig.list();
            System.out.println( "Nombres d'images dans le dossier Selection: "+files.length);
            List<Integer> hazardNumbers = new ArrayList<>();
            int nbrrestant= (int) (nbrSelecionesa-files.length);
            System.out.println("le nombre de files necessaire est "+nbrrestant);
                while (hazardNumbers.size()<nbrrestant){
                int idz=(int)(Math.random()*filesOrig.length);
                    if (filesOrig[idz].endsWith(".JPG")) {
                        if (!hazardNumbers.contains(idz)) {
                            hazardNumbers.add(idz);
                        }
                    }
     
                }
     
                System.out.println("les photos choisies au Hasard: "+ hazardNumbers);
                //System.out.println(hazardNumbers.get(0));
                int ia = 0;
                while (ia<hazardNumbers.size()) {
     
                   Path temp = Files.move (Paths.get(Lepatha+"\\"+filesOrig[hazardNumbers.get(ia)]),
                            Paths.get(Lepath2a+"\\"+filesOrig[hazardNumbers.get(ia)]));
                    ia++;
                }
                Desktop.getDesktop().open(dir);
                Desktop.getDesktop().open(dirOrig);
                Scanner myObj3 = new Scanner(System.in);
                System.out.println("On augmente de combien la boucle?:");
                int boucleavance = myObj3.nextInt();
                i=i+boucleavance;
                System.out.println("Bon, maintenant i est egal a: "+i);
                //System.out.println(t3);
            }
     
        }
     
        public  void  moveFromSelectionToKokaizumi(String nomDossier4) throws Exception {
            String ND4=nomDossier4;
            Table t4 = CreateMDirectory(ND4);
            //System.out.println(t4.columnNames());
            t4.sortAscendingOn("Nom fichier");
            //System.out.println(t4);
     
     
            for (int iz = 0; iz <t4.rowCount(); ) { //t3.rowCount()
                String Lepathz = t4.get(iz, 3).toString();
                String Lepath2z =  t4.get(iz, 5).toString();
                System.out.println("le dossier d'origine: "+ Lepathz);
                System.out.println("le dossier de destination: "+ Lepath2z);
                File dirOrigz = new File(Lepathz);
                File dirz = new File(Lepath2z);
                String[] filesOrigz = dirOrigz.list();
                int iaz = 0;
                //System.out.println(Lepathz+"\\"+filesOrigz[iaz]);
                while (iaz<filesOrigz.length) {
     
                    Path temp = Files.move (Paths.get(Lepathz+"\\"+filesOrigz[iaz]), Paths.get(Lepath2z+"\\"+filesOrigz[iaz]));
                    iaz++;
                                                }
                Desktop.getDesktop().open(dirz);
                Desktop.getDesktop().open(dirOrigz);
                Scanner myObj3 = new Scanner(System.in);
                System.out.println("On augmente de combien la boucle?:");
                int boucleavance = myObj3.nextInt();
                iz=iz+boucleavance;
                System.out.println("Bon, maintenant i est egal a: "+iz);
                //System.out.println(t3);
            }
     
        }
     
        public static void main (String[]args) throws Exception
        {
            Main client = new Main();
            //client.Create1Directory("G:\\Stock\\Arima\\","22.  MEO");
            //client.CreateMDirectory("G:\\Stock\\Kinoshita");
            //client.listDirectoryInFolder("G:\\Stock\\Kinoshita");
           // client.checkIfEnoughFilesForM("G:\\Stock\\Kinoshita");
           // client.checkIfEnoughFilesfor1("G:\\Stock\\Kinoshita\\9.  MEO","G:\\Stock\\Kinoshita\\Selection 9.  MEO", 10);
              //  client.moveFromSelectionToKokaizumi("G:\\Stock\\Kinoshita");
        }
    }
    Merci.

  2. #2
    Membre très actif

    Profil pro
    Inscrit en
    Janvier 2009
    Messages
    486
    Détails du profil
    Informations personnelles :
    Localisation : France

    Informations forums :
    Inscription : Janvier 2009
    Messages : 486
    Billets dans le blog
    5
    Par défaut
    Bon, pour commencer, il faut savoir que notre cerveau humain n'est pas capable de concevoir un problème "complexe".

    Mais ce n'est pas grave.
    Car un problème complexe, c'est la somme de problème "simple", problème simple que l'on sera résoudre.
    D'une certaine façon, c'est le rasoir d'Ockham ( https://fr.wikipedia.org/wiki/Rasoir_d%27Ockham ).

    En résumé, il faut décomposer le problème.

    En informatique, ça se retrouve dans SOLID ( https://fr.wikipedia.org/wiki/SOLID_(informatique) ).
    C'est le S (pour Single responsibility principle ou principe de responsabilité).

    En résumé, une classe ne fait qu'une seule chose, a la responsabilité d'une seule chose, et le fait bien.

    De fait, le code devient plus lisible, plus compréhensible et il est surtout testable (via des tests unitaires).

  3. #3
    Membre très actif

    Profil pro
    Inscrit en
    Janvier 2009
    Messages
    486
    Détails du profil
    Informations personnelles :
    Localisation : France

    Informations forums :
    Inscription : Janvier 2009
    Messages : 486
    Billets dans le blog
    5
    Par défaut
    Un dernier point: Attention à l'encapsulation des méthodes. Peuvent-elles être appelées partout?

  4. #4
    Membre averti
    Homme Profil pro
    Inscrit en
    Janvier 2014
    Messages
    18
    Détails du profil
    Informations personnelles :
    Sexe : Homme
    Localisation : Japon

    Informations forums :
    Inscription : Janvier 2014
    Messages : 18
    Par défaut
    Merci @PhilippeGibault pour tes réponses,
    et pour le point de vu méthodologique.

    Si je comprends bien je devrais plutôt utiliser des class plutôt que des methodes. Je devrais isoler la fonction de chaque class afin de pouvoir les imaginer comme les pièces de lego, interchangeable et facilement utilisables.

    Logique effectivement.

    merci des ces conseils.

    Edit:

    J'ajoute ici ce que je trouve au fur et à mesure que je potasse sur le sujet.
    https://jetbrains.org/intellij/sdk/d...structure.html

  5. #5
    Membre émérite Avatar de Cincinnatus
    Homme Profil pro
    Développeur d'applications métier
    Inscrit en
    Mars 2007
    Messages
    593
    Détails du profil
    Informations personnelles :
    Sexe : Homme
    Localisation : France, Nord (Nord Pas de Calais)

    Informations professionnelles :
    Activité : Développeur d'applications métier
    Secteur : Service public

    Informations forums :
    Inscription : Mars 2007
    Messages : 593
    Par défaut
    Bonjour,

    Citation Envoyé par Tsurubaso Voir le message
    Si je comprends bien je devrais plutôt utiliser des class plutôt que des methodes. Je devrais isoler la fonction de chaque class afin de pouvoir les imaginer comme les pièces de lego, interchangeable et facilement utilisables.
    Une piste pour réorganiser le code : le site de Martin Fowler (extrait de son livre) :
    https://refactoring.com/catalog/

    Ou tiré du livre "Working effectively with Legacy code" :
    https://understandlegacycode.com/blo...h-legacy-code/

    Il faut bien étudier le code pour voir comment le scinder en méthodes d'une même classe ou dans plusieurs classes. Comme dit plus haut, une classe doit avoir une responsabilité et une seule. Chaque méthode doit avoir une action précise à mener.

    Bon courage !

Discussions similaires

  1. Demande d'aide sur mon code
    Par b.soufiane dans le forum C++
    Réponses: 6
    Dernier message: 07/12/2007, 16h36
  2. Conseil sur l'organisation du code
    Par Fly3R dans le forum Windows Forms
    Réponses: 7
    Dernier message: 07/11/2007, 16h39
  3. Conseil pour réduire mon code
    Par Triwis dans le forum Windows Forms
    Réponses: 7
    Dernier message: 17/08/2007, 16h17
  4. Optimisation de code - demande de conseils
    Par ploukinet dans le forum MATLAB
    Réponses: 11
    Dernier message: 14/06/2007, 12h58
  5. Comment mieux sécuriser mon code ?
    Par bolo dans le forum ASP.NET
    Réponses: 17
    Dernier message: 11/05/2007, 07h05

Partager

Partager
  • Envoyer la discussion sur Viadeo
  • Envoyer la discussion sur Twitter
  • Envoyer la discussion sur Google
  • Envoyer la discussion sur Facebook
  • Envoyer la discussion sur Digg
  • Envoyer la discussion sur Delicious
  • Envoyer la discussion sur MySpace
  • Envoyer la discussion sur Yahoo