Question on Decouple

1 reply [Last post]
Offline
Joined: 01/06/2011

i was wondering how does the coupling work in this example: 
part of method in my game class, hero is a instance of mainCharacter
data += hero.getX()+":"+hero.getY()+":"+hero.getZ()+":"+hero.getMoney();
            for (String s : hero.getBadge()) {
                data += ":"+s;
            }
            for (Creature c : hero.getPMon()) {
                String info = c.getName()+":"+c.getHp()+":"+c.getCurHp()+":"+c.getMp()+":"+c.getCurMp()
                    +":"+c.getLvl()+":"+c.getExp()+":"+c.getAtt()+":"+c.getDef();
                for(Skill s: c.getAllSkill()){
                    info += ":"+s.getName();
                }
                data += ":"+info;
            }
            for (Item i : hero.getBag().getItemList()) {
                String info = i.getName()+":"+i.getNum();
                data += ":"+info;
            }
with the above code it said my class is couple to item and creature class, but i only want to couple(uses) to a MainCharacter class.
My mainCharacter class contain Bag class instances which contain a ArrayList of item, and mainCharacter contain a ArrayList of Creature. I am just wondering how can i decouple / get rid of the has a arrow from the item and creature class from the game class.

Offline
Joined: 12/13/2010
You can't decouple the Item

You can't decouple the Item class from your Game class, because of this line:
           for (Item i : hero.getBag().getItemList()) {
You are indeed using the Item class in your Game code.
 
One way to get around it is to have a getItemInfo() method in your Bag class, which returns an array of strings, then you can do this:
           for (String info : hero.getBag().getItemInfo()) {
                 data += info;
            }
 Let me know if this works for you.