Should this just link to FunctorObjectExample? Or is a MethodObject that much different? I'm trying to write one, not sure what the "receiver" might be. Nor do I think I know the best way to return two or more variables. --TerryLorber
This is what I did:
class MethodObjectExample { public: MethodObjectExample(int size); void compute(std::vector<int>& values, int& response); protected: private: int _size; }; MethodObjectExample::MethodObjectExample(int size) : _size(size) { }// MethodObjectExample void MethodObjectExample::compute(std::vector<int>& values, int& response) { // does something that changes values and response based on _size. // ... 90 lines of code removed ... // done. }// compute
MethodObject is not a pattern, it is a target of RefactoringImprovingTheDesignOfExistingCode. Start with cruft, such as a very long 90-line method. Write a class called Cruft, and copy all the cruft inside it. Move all the local variables into member variables. Refactor the snot out of the remaining code. Voila: no more cruft.
If you don't start with cruft - if you Refactored early and often, with a very low disgust threshold, you don't get the cruft and don't need MethodObject. After you have MethodObject you are liberated to further split the object into healthier situations. --PhlIp
OK, I can see how it's not a pattern, instead a technique used in refactoring. Maybe my question is more of a style thing, What's the best way to return two or more variables from a method? --TerryLorber
Quite possibly this will need to be moved to a different page, but: A standard OO response might be that a method should never return more than one value, because a method should never do more than one thing. If you want to have a method return more than one value, there are a few things you can try:
To elaborate on Francis's first point, this is often a sign that you should create a new class. For example, I often have methods that are responsible for validating some other object according to a set of business rules. Usually, I want two things back from these kinds of methods, a boolean noting whether the item is valid or not, and a list of errors explaining why it is or is not valid. Usually I wrap these up in a simple class called ValidationResult?, which consists of a bool and a collection of strings.
One way to do the transfer in CeePlusPlus is to use a tuple, see for example BoostTupleLibrary. This allows an object which can contain a collection of items of different types e.g. a bool and a string. -- JohnFletcher
Contrast: GodClass