I'm using Java in eclipse, and I read a thread
I really liked home's answer, because I never really thought about it before. The whole idea that subclasses should really not have access to members that is. However, I have an interesting edge case if someone wants to give it a go.
Suppose I have an interface Buildable
and an Enum CatanPiece
:
public interface Buildable
{
HashMap<Resource, Integer> getCost();
Buildable build( final PlayerHand payment );
}
public enum CatanPiece implements Buildable
{
ROAD
{
@Override
public HashMap<Resource, Integer> getCost()
{
if ( cost.isEmpty() )
{
cost.put( BRICK, 1 );
cost.put( LUMBER, 1 );
}
return cost;
}
},
SETTLEMENT
{
@Override
public HashMap<Resource, Integer> getCost()
{
if ( cost.isEmpty() )
{
cost.put( BRICK, 1 );
cost.put( LUMBER, 1 );
cost.put( SHEEP, 1 );
cost.put( WHEAT, 1 );
}
return cost;
}
},
CITY
{
@Override
public HashMap<Resource, Integer> getCost()
{
if ( cost.isEmpty() )
{
cost.put( WHEAT, 2 );
cost.put( ORE, 3 );
}
return cost;
}
};
protected final HashMap<Resource, Integer> cost;
private CatanPiece()
{
cost = getCost();
}
@Override
public abstract HashMap<Resource, Integer> getCost();
@Override
public Buildable build( final PlayerHand payment )
{
return ( payment.remove( cost ) ? null : this );
}
}
So Checkstyle is giving me crap about the protected HashMap I'm using, but for those looking at this question that understand it, you can see I don't have the problem of someone misusing that variable. AND I would in fact make it private and use a protected get method, however the return on that method is different per instance.
Potential answers: Ignore the checkstyle warning, or perhaps include an abstract init() method to initialize the HashMap then simply implement the getCost() method generically for all memebers of the enum.
What do you think?