简体   繁体   中英

Putting function in appropriate class

public static FirstObjectType GetObject(SecondObjectType secondobjectType) 
{
         do something
}

Where should I put this function? Should I put it in SecondObjectType class or FirstObjectType class in terms of code readability, customs and traditions? Should the function be included in the return class or the parameter class from your experience?

Thanks for your answer.

I usually put the method in the class that has the same type as the return type of the method.

eg:

public static FirstObjectType GetObject(SecondObjectType secondobjectType) 
{
         do something
}

would go in the FirstObjectType class.

Alternatively you can use the Factory Pattern and have a factory for getting the objects you need. Which could give you code simliar to the following:

FirstObjectTypeFactory.GetObject(SecondObjectType secondObjectType)

Then you always know which factory to get the object from based on its return type.

This is way to vague to answer, but I'll give a few general tips

If you have a collection of FirstObjectTypes and are trying to find the one that matches SecondObjectType , then it belongs to the class that owns the collection. This could be a factory pattern.

If you are always creating a new FirstObjectType , it could just be a constructor for FirstObjectType .

Does SecondObjectType have to have knowledge of FirstObjectType ? If so, then it I would consider making it a method on SecondObjectType .

There are a million other scenarios and there is no one size fits all.

I'll create an Extension Method for that.

Just add this in the signature

public static FirstObjectType GetObject(this SecondObjectType secondobjectType) 
{
    //do something
}

After that you can do:

SecondObjectType sobj = new SecondObjectType()
//code
FirstObjectType  fobj = sobj.GetObject();

And put it with my other extension method file like ExtensionMethods.cs. Or if the class containing the GetObject method is static too, put it in the same class (In this case in the SecondObjectType's class)

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM