This week's book giveaway is in the Design forum.
We're giving away four copies of Design for the Mind and have Victor S. Yocco on-line!
See this thread for details.
Win a copy of Design for the Mind this week in the Design forum!
  • Post Reply
  • Bookmark Topic Watch Topic
  • New Topic

design patter to build an object

 
andy kumar
Ranch Hand
Posts: 64
  • Mark post as helpful
  • send pies
  • Quote
  • Report post to moderator
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
Posts: 64
  • Mark post as helpful
  • send pies
  • Quote
  • Report post to moderator
any suggestions....?
 
Paul Clapham
Sheriff
Pie
Posts: 20955
31
Eclipse IDE Firefox Browser MySQL Database
  • Mark post as helpful
  • send pies
  • Quote
  • Report post to moderator
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
Posts: 64
  • Mark post as helpful
  • send pies
  • Quote
  • Report post to moderator
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
Posts: 64
  • Mark post as helpful
  • send pies
  • Quote
  • Report post to moderator
so i guess...there is no way i can improve the for loop right?....any suggestions will be appreciated
 
  • Post Reply
  • Bookmark Topic Watch Topic
  • New Topic