Results 1 to 5 of 5
  1. #1
    Join Date
    May 2012
    Posts
    10
    Rep Power
    0

    Default constructor with conditions

    Hi,

    Is
    it acceptable to put a condition inside a constructor: for example, i want to create an instance of a client with these properties

    id_client, client_last_name, client_first_name ,client_adress if the client type is a particualar;
    If the client type is a company_name , i want to create a client instance with theses properties : id_client, company_name, client_adress.
    Can i insert inside the constructor a condition like this

    Java Code:
    public class Client {
    	
    	private static JTextPane jTextPane1;
    	private static JFrame  fenetre_affichage_clients; 
    	private static String texte_final; 
    	private String texte;   
    	private String id_client; 
    	private String last_name_client;
    	private String first_name_client;
    	private String client_adress;
    	private String company_name; 
    		private static String client_type;
    	
    	
    	
    	public Client(ResultSet res_set)throws SQLException{
    if (client_type.equals("particular"){
    		id_client=res_set.getString(1); 
    		
    		client_first_name=res_set.getString(2);
    		
    		client_first_name=res_set.getString(3);
    		
    		client_adress=res_set.getString(4);
    				
    		client_type=res_set.getString(5);
    }end if 
    
    else if client_type.equals("company") {
    		
    		id_client=res_set.getString(1); 
    		
    		company_name=res_set.getString(2);
    		
    			
    		client_adress=res_set.getString(3);
    				
    		client_type=res_set.getString(4);
    		
    		}// end of else 
    				
    		
    		}// end of constructor
    Do you think it is better and recommanded to create two different classes .

    Thanks a lot for your answer.
    Best regards.
    curious_programmer

  2. #2
    DarrylBurke's Avatar
    DarrylBurke is offline Forum Police
    Join Date
    Sep 2008
    Location
    Madgaon, Goa, India
    Posts
    11,458
    Rep Power
    20

    Default Re: constructor with conditions

    Where does the value of client_type come from? It's a private static String that's never initialized. (And why it should be static is another question altogether.)

    When asking a design related question, at least post reasonable code.

    db
    If you're forever cleaning cobwebs, it's time to get rid of the spiders.

  3. #3
    Join Date
    May 2012
    Posts
    10
    Rep Power
    0

    Default Re: constructor with conditions

    Quote Originally Posted by DarrylBurke View Post
    Where does the value of client_type come from? It's a private static String that's never initialized. (And why it should be static is another question altogether.)

    When asking a design related question, at least post reasonable code.

    db

    Hi,
    You are right , it is not justiied to put the cleint_type varaible as a static one.

    The client_type value is recovered from another class:connexion_BDD : in this class, you can find a variable called choix_type_client which is a static variable .
    In fact, this variable is created in the fenetre_selection_client class( another class which is a Jframe and displays JRadioButtons to permit the user to choose the client type he wants to display).

    Here is that code

    Java Code:
    package package_selection_clients;
    import java.util.*; 
    
    
    import java.sql.Connection;
    import java.sql.DriverManager;
    import java.sql.ResultSet;
    import java.sql.Statement;
    
    
    public class Connexion_BDD {
    	private String id_connexion;
    	// declaration de la variable ConnexionSQL qui va contenir l'adresse d' une instance de la classe Connection 
    	// pour l'instant elle est initiallisée à null
    	
    	private Connection ConnexionSQL = null;
    	 // declaration de la variable de type Statement
    	 //L'exécution d'une requête SQL s'effectue via un objet de la classe java.sql.Statement .
    	 // objet Statement => instruction SQL . C'est cet objet qui exécute les requêtes SQL et qui retourne les résultats.
    	private Statement  stmt  = null;
    	//declarationde la variable qui va contenir la requête de selection des clients particuliers 
    	ResultSet  rs  = null;
    	//declaration de la variable requete_1 qui va contenir le texte de la requête vers la base de données (BDD)
    	private String    requete_1  = "";
    	//declaration de la variable statique listeclients  de type ArrayList.
    	//Cette ArrayList est destinée à contenir des éléments de type Clients qui sont soit particuliers soit des entreprises 
       static  ArrayList<Client> listeClients;  
       
    	
    	
    	
    	// création du getter qui va récupéret l'adresse de l'instance de la classe Connection créée
    	
    	public Connection getConnexionSQL(){
    	
    		return ConnexionSQL;
    	}
    	
    	
    	
    	public Connexion_BDD(){
    		
    			
    		
    	}// constructeur par défaut 
    	
    	public void Connecter_BDD(){
    
    		try {
    			
    			Class.forName(driverOdbc).newInstance();
    			System.out.println("drivers chargés");
    			
    			
    			ConnexionSQL = DriverManager.getConnection("jdbc:odbc:bdd_clients","","");
    			System.out.println("connection établie:" + ConnexionSQL);
    			
    			
    			  stmt = ConnexionSQL.createStatement();
    
    			  if(fenetre_selection_clients.choix_type_client.equals("particuliers")){
    
    			  requete_1 = "select ID_CLI,NOM_CLI,PRENOM_CLI,AD1_CLI,AD2_CLI, AD3_CLI, TYPE_CLI from  
                             CLIENTS_PARTICULIERS where TYPE_CLI = '"  +fenetre_selection_clients.choix_type_client+ "' ";
    			  }// fin if 
    
    			  else if (fenetre_selection_clients.choix_type_client.equals("entreprises")){
    
    			  requete_1 = "select ID_CLI, RAISON_SOC_CLI, AD1_CLI, AD2_CLI, AD3_CLI, TYPE_CLI from 
                              CLIENTS_ENTREPRISES where TYPE_CLI = '"  +fenetre_selection_clients.choix_type_client+ "' ";
    			  }// fin de else if 
    
    			  System.out.println(requete_1); 
    			  
    			  rs = stmt.executeQuery(requete_1);
    			 
    						 
    			 listeClients = new ArrayList<Client>();
    			   while(rs.next())
    			    {
    			      listeClients.add(new Client(rs));
    			    }// fin de while
    
    			   System.out.println("le nombre d elements de listeClients est "+listeClients.size());
    			
    			
    		}//fin de try
    		
    		catch(Exception sqle){
    			
    			System.out.println("le message d'erreur est le suivant "+ sqle.getMessage());
    			
    		}// fin de catch
    		
    	}// fin de fonction Connecter_BDD
    //	---------------------------	
    	
    }// fin de classe Connexion_BDD
    You can see i did not yet written the close instruction to close the connection and the statement.

    Thanks a lot for your help.
    Best regards.

    Nathalie
    Last edited by curious_programmer; 05-16-2012 at 12:44 PM. Reason: additional code

  4. #4
    Join Date
    May 2012
    Posts
    10
    Rep Power
    0

    Default Re: constructor with conditions

    [QUOTE=curious_programmer;286239]Hi,
    You are right , it is not justified to put the client_type varaible as a static one.

    The client_type value is recovered from another class:connexion_BDD : in this class, you can find a variable called choix_type_client which is a static variable .
    In fact, this variable is created in the fenetre_selection_client class( another class which is a Jframe and displays JRadioButtons to permit the user to choose the client type he wants to display).

    Here is that code

    Java Code:
    package package_selection_clients;
    import java.util.*; 
    
    
    import java.sql.Connection;
    import java.sql.DriverManager;
    import java.sql.ResultSet;
    import java.sql.Statement;
    
    
    public class Connexion_BDD {
    	private String id_connexion;
    	// declaration de la variable ConnexionSQL qui va contenir l'adresse d' une instance de la classe Connection 
    	// pour l'instant elle est initiallisée à null
    	
    	private Connection ConnexionSQL = null;
    	 // declaration de la variable de type Statement
    	 //L'exécution d'une requête SQL s'effectue via un objet de la classe java.sql.Statement .
    	 // objet Statement => instruction SQL . C'est cet objet qui exécute les requêtes SQL et qui retourne les résultats.
    	private Statement  stmt  = null;
    	//declarationde la variable qui va contenir la requête de selection des clients particuliers 
    	ResultSet  rs  = null;
    	//declaration de la variable requete_1 qui va contenir le texte de la requête vers la base de données (BDD)
    	private String    requete_1  = "";
    	//declaration de la variable statique listeclients  de type ArrayList.
    	//Cette ArrayList est destinée à contenir des éléments de type Clients qui sont soit particuliers soit des entreprises 
       static  ArrayList<Client> listeClients;  
       
    	
    	
    	
    	// création du getter qui va récupéret l'adresse de l'instance de la classe Connection créée
    	
    	public Connection getConnexionSQL(){
    	
    		return ConnexionSQL;
    	}
    	
    	
    	
    	public Connexion_BDD(){
    		
    			
    		
    	}// constructeur par défaut 
    	
    	public void Connecter_BDD(){
    
    		try {
    			
    			Class.forName(driverOdbc).newInstance();
    			System.out.println("drivers chargés");
    			
    			
    			ConnexionSQL = DriverManager.getConnection("jdbc:odbc:bdd_clients","","");
    			System.out.println("connection établie:" + ConnexionSQL);
    			
    			
    			  stmt = ConnexionSQL.createStatement();
    
    			  if(fenetre_selection_clients.choix_type_client.equals("particuliers")){
    
    			  requete_1 = "select ID_CLI,CLI_LN,CLI_FN,AD1_CLI,AD2_CLI, AD3_CLI, CLI_TYPE from  
                             CLIENTS_PARTICULIERS where CLI_TYPE = '"  +fenetre_selection_clients.choix_type_client+ "' ";
    			  }// fin if 
    
    			  else if (fenetre_selection_clients.choix_type_client.equals("entreprises")){
    
    			  requete_1 = "select ID_CLI, COMPANY_NAME, AD1_CLI, AD2_CLI, AD3_CLI, CLI_TYPE from 
                              CLIENTS_ENTREPRISES where CLI_TYPE = '"  +fenetre_selection_clients.choix_type_client+ "' ";
    			  }// fin de else if 
    
    			  System.out.println(requete_1); 
    			  
    			  rs = stmt.executeQuery(requete_1);
    			 
    						 
    			 listeClients = new ArrayList<Client>();
    			   while(rs.next())
    			    {
    			      listeClients.add(new Client(rs));
    			    }// fin de while
    
    			   System.out.println("le nombre d elements de listeClients est "+listeClients.size());
    			
    			
    		}//fin de try
    		
    		catch(Exception sqle){
    			
    			System.out.println("le message d'erreur est le suivant "+ sqle.getMessage());
    			
    		}// fin de catch
    		
    	}// fin de fonction Connecter_BDD
    //	---------------------------	
    	
    }// fin de classe Connexion_BDD
    You can see i did not yet have written the close instruction to close the connection and the statement.

    Thanks a lot for your help.
    Best regards.

    Nathalie

  5. #5
    Tolls is offline Moderator
    Join Date
    Apr 2009
    Posts
    12,225
    Rep Power
    20

    Default Re: constructor with conditions

    I wouldn't pass a ResultSet into a constructor.
    That ties your model directly with the database, which is not great design as you may not always want to build your Client objects from the database.
    So, in your DAO you would extract the relevant data and pass that to the Client constructor.

    Which brings me to part two. You have two Clients there, at least as currently written. So make them two classes that share a common interface, and possibly extend an AbstractClient if there is some commonality between them in data and code. Then the DAO could contain a Factory method to generate the correct type of Client.
    Please do not ask for code as refusal often offends.

    ** This space for rent **

Similar Threads

  1. How to avoid many if else conditions
    By Addymails in forum New To Java
    Replies: 9
    Last Post: 03-22-2012, 01:39 PM
  2. Problem in while conditions
    By davie89 in forum New To Java
    Replies: 2
    Last Post: 03-20-2012, 01:37 AM
  3. while and proper conditions for if
    By Saletra in forum New To Java
    Replies: 11
    Last Post: 08-25-2010, 11:37 AM
  4. Asking for a username with conditions
    By ScentOfAWookie in forum New To Java
    Replies: 2
    Last Post: 03-20-2009, 06:53 AM

Posting Permissions

  • You may not post new threads
  • You may not post replies
  • You may not post attachments
  • You may not edit your posts
  •