my dog learned polymorphism*
The moose likes OO, Patterns, UML and Refactoring and the fly likes design patter to build an object Big Moose Saloon
  Search | Java FAQ | Recent Topics | Flagged Topics | Hot Topics | Zero Replies
Register / Login


Win a copy of Java 8 in Action this week in the Java 8 forum!
JavaRanch » Java Forums » Engineering » OO, Patterns, UML and Refactoring
Bookmark "design patter to build an object" Watch "design patter to build an object" New topic
Author

design patter to build an object

andy kumar
Ranch Hand

Joined: Jun 08, 2009
Posts: 54
I have a class like this:-

public class House {
int houseNo;
Room masterRoom;
Room room2;
Room room3;
public int getHouseNo() { return houseNo; }
public void setHouseNo(int houseNo) { this.houseNo = houseNo; }
public Room getMasterRoom() { return masterRoom; }
public void setMasterRoom(Room masterRoom) { this.masterRoom = masterRoom; }
public Room getRoom2() { return room2; }
public void setRoom2(Room room2) { this.room2 = room2; }
public Room getRoom3() { return room3; }
public void setRoom3(Room room3) { this.room3 = room3; }
}

public class Room { }

public class test {

public static void main(String[] args) {
List<Room> rooms = new ArrayList<Room>();
// make new rooms and add to the list
House house = makeHouse(1, rooms);
}

// i want to refactor make house method, bsically the for loop to look much better
public static House makeHouse(int houseNo, List<Room> rooms) {
House house = new House();
house.setHouseNo(houseNo);
for (int i = 0; i < rooms.size(); i++) {
if (i == 0) {
house.setMasterRoom(rooms.get(i));
} else if (i == 1) {
house.setRoom2(rooms.get(i));
} else {
house.setRoom3(rooms.get(i));
}
}
return house;
}
}

I have the above classes and I want to refactor the makehouse method because i do not like the way i have written the for loop. Note I cannot change the method signature or basically I cannot change how the House class is structured. The house class is given to me so i have no control over it.
andy kumar
Ranch Hand

Joined: Jun 08, 2009
Posts: 54
any suggestions....?
Paul Clapham
Bartender

Joined: Oct 14, 2005
Posts: 18154
    
    8

I don't see the point of using a for-loop at all. Since your design is hard-coded to have exactly three rooms, what's wrong with just having three lines of code which assign those three rooms to the House?
andy kumar
Ranch Hand

Joined: Jun 08, 2009
Posts: 54
it is not necessary that it will have 3 rooms....it will have a master room but the rest can be null
andy kumar
Ranch Hand

Joined: Jun 08, 2009
Posts: 54
so i guess...there is no way i can improve the for loop right?....any suggestions will be appreciated
 
I agree. Here's the link: http://aspose.com/file-tools
 
subject: design patter to build an object
 
Similar Threads
about lists
Object trouble.
ListCellRenderer!!!Help!!
JPA Multiple Foreign Key Join
Room Class