java - Accesing field's methods in composition -


i have class player contains few private fields of other classes ( believe called composition ).

public class player {     private string name;     private statistics statistics;     private experience experience;     private effort effort; } 

i post 1 of them called statistics

public final class statistics {     pool pool;     edge edge;      class pool     {         private map<stats, limitedint> map = new hashmap<>();         private int freepoints = 0;          void setavailable(stats stat, int value){}         int getavailable(stats stat){ return 0; }         void setmax(stats stat, int value){}         int getmax(stats stat, int value){ return 0; }         void setfreepoints(int value){}         int getfreepoints(){ return 0; }         void spendfreepoints(stats stat, int amount){}     }      class edge     {         private map<stats, integer> map = new hashmap<>();         private int freepoints = 0;          void setmax(stats stat, int value){}         int getmax(stats stat, int value){ return 0; }         void setfreepoints(int value){}         int getfreepoints(){ return 0; }         void spendfreepoints(stats stat, int amount){}     } } 

it not implemented yet of course, want know correct version of changing example player's pool. can imagine following scenarios:

  1. player has same methods pool class like

    public class player {     // above     void setavailablepool(stats stat, int value){ statistics.pool.setavailable(stat, value); } } 

this solution seems ok in player class have lot of 1-line methods redirect orders composed fields.

  1. i transfer pool , edge player class , make them public final read mutable objects should rather private.

those 2 first thoughts, wanted ask how create interface in class when use composition.

one-line methods not problem, makes solution #1 unsatisfying violation of law of demeter (statistics.pool.setxxxx). might better have statistics.setavailableinpool() method (or use idea #2). can' t offer more specific implementation because it's not clear pool , edge classes supposed (or why they're similar each other not implement common interface).

in answer general question creating interfaces composition, take @ solid principles. basically, should think behaviors need dependencies, name behaviors clearly, , depend on interface rather concrete class. makes code easier understand , easier change in 1 place without having change everywhere.


Comments

Popular posts from this blog

qt - Using float or double for own QML classes -

Create Outlook appointment via C# .Net -

ios - Swift Array Resetting Itself -