Is there a difference of this two ways?

  • Thread starter Thread starter Guest
  • Start date Start date
G

Guest

I believe each ways below will produce the same results. But may i know which one will be better and encourage to be used.

Sample1:

class Animal
{
public void GetWeight()
{

}
}

class ClientApp
{
Animal anim = new Animal();
anim.GetWeight();
}

Sample2:

class Animal
{
private static Animal weight;

public static Animal GetWeight()
{
if (weight == null)
{
weight = new Animal();
}

return weight;
}
}

class ClientApp
{
Animal anim = Animal.GetLength();
}

Any help? Thanks.
 
I believe the GetWeight() method is supposed to return weight of an animal object. (The return type void is a little confusing -- should it be float ?). Basically the concept of static variables in a class is that if one has any piece of information which is common to all objects of a class, it should be stored as a static data member. Now, if weight has common meaning of weight of an animal, it will be different for different animal objects, so it should be stored in an instance variable rather than a static variable, with a property defined to get and set its value.
So the first approach is a better one, even though it's not clear what will be the logic of GetWeight() method.

You can try something like this
class Animal
{
float m_weight;
public float Weight
{
get { return m_weight; }
set { if (value > 0) m_weight = value; }
}
//other code
}

class Client
{
Animal first;
Client() { first = new Animal(); }
public void SetWeight(float w) { first.Weight = w; }
public float GetWeight() { return first.Weight; }
//other methods and properties
}

Hope this helps.
 
Back
Top