Pergunta

Given the code below, the spaceship (only ever one in the program) checks to see if it can pay for a new part, and 'if (so)', builds it. When the payFor: message is sent, should the iVars be dealt with like below, or should the each transaction be a method like +(void)deduct: (ShipObject *) cost;, or should I use struct and use structure arithmetic?

@ implementation Spaceship
+(void) payFor: (ShipObject) *shipObject
{
    totalEnergy     -= [shipObject energy];     
    totalCredits    -= [shipObject credits];
    totalSamples    -= [shipObject samples];
}

+(void) buildShipObject: (ShipObject) *shipObject
{
    if ([self canBuild: shipObject]) {
        [self payFor: shipObject];
...
}

Thanks for any insights!

Foi útil?

Solução

First, since the methods are class methods, not instance methods, I assume that variables not ivars, but static variables of some sort.

If payments with some, not all, forms of payment are to be allowed (say, only with energy and samples, but not credits) then you should use three different methods. Otherwise, your payFor method is very idiomatic to Objective C. Using C struct should be reserved for the rare situations where Objective C classes no longer provide adequate performance.

Consider making the spaceship a singleton, and use ivars: this may become handy if you decide to introduce more ships in the game, or do something that's easier done with objects (e.g. externalization of object's state).

Licenciado em: CC-BY-SA com atribuição
Não afiliado a StackOverflow
scroll top