4
\$\begingroup\$

I have figured out how to serialize multiple objects, however I am utterly convinced I can use some kind of loop for the if statements below, to avoid duplication. Please can someone advise how I would do this?

I have 20 objects in total, this code snippet shows the "if statements" for 4 of them.

import java.util.InputMismatchException;
import java.util.Scanner;
import java.io.*;
import java.util.Arrays;

public class Serializer extends WriteClub
{
   public void Serialize()
   {

    MainMenu pass_choice = new MainMenu();
    int passed_choice = pass_choice.chooseTeam();

    if(passed_choice==1){
    ClubInfo club = new ClubInfo("Arsneal" , "Emirates" , "Premier League" , 11122333 , 60000);
    tryWriteClub(club);
    } // end if 1

    if(passed_choice==2){
    ClubInfo club1 = new ClubInfo("Aston Villa" , "Villa Park" , "Premier League" , 111223334 , 40000);
    tryWriteClub(club1);
    } // end if 2    

    if(passed_choice==3){
    ClubInfo club2 = new ClubInfo("Bournemouth" , "Dean Court" , "Premier League" , 111223335 , 20000);
    tryWriteClub(club2);
    } // end if 3

    if(passed_choice==4){
    ClubInfo club3 = new ClubInfo("Chelsea" , "Stamford Bridge" , "Premier League" , 111223336 , 50000);
    tryWriteClub(club3);
    } // end if 2
   }
}
\$\endgroup\$

1 Answer 1

5
\$\begingroup\$

The solution I propose to you is to create an array or another ordered structure where you could create all the 20 club objects and just select the right one base on the index of the club.

ClubInfo [] clubs =  new ClubInfo[20];
clubs[0] = new ClubInfo("Arsneal" , "Emirates" , "Premier League" , 11122333 , 60000);

Then you can do :

ClubInfo club = clubs[passed_choice - 1];
tryWriteClub(club);

You could find a better way to deal with the index problem. Small problem is now the ClubInfo objects will either be created everytime the method is called or you could create it one time as a static array or something similar.


Naming

You do not follow the naming standard for the Java language. Method name should be nameLikeThis() and variable should be nameLikeThisToo. So your int passed_choice should be int passedChoice and the method public void Serialize() should be public void serialize().

Comments

I recommend that you get rid of comments like // end if 2. It is just noise that serve nothing. Comments should be use to explain why you have this particular piece of code.

\$\endgroup\$
1
  • 1
    \$\begingroup\$ On the comments, there's even a copy-paste error in the question, // end if 2 should be // end if 4 after 3. All the more to remove these. :) \$\endgroup\$
    – h.j.k.
    Commented Nov 26, 2015 at 15:45

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Not the answer you're looking for? Browse other questions tagged or ask your own question.