Say I have a class that's meant to perform a single function. After performing the function, it can be destroyed. Is there any reason to prefer one of these approaches?
// Initialize arguments in constructor
MyClass myObject = new MyClass(arg1, arg2, arg3);
myObject.myMethod();
// Pass arguments to method
MyClass myObject = new MyClass();
myObject.myMethod(arg1, arg2, arg3);
// Pass arguments to static method
MyClass.myMethod(arg1, arg2, arg3);
I was being intentionally vague about the details, to try to get guidelines for different situations. But I didn't really have in mind simple library functions like Math.random(). I'm thinking more of classes that perform some specific, complex task, but only require one (public) method to do it.
i think, if properties of your class or the instance of class will not be used in constructors or in your methods, methods are not suggested to be designed like 'static' pattern. static method should be always thinked in 'help' way.
I'd suggest that its hard to answer based on the information provided.
My gut is that if you are just going to have one method, and that you are going to throw the class away immediately, then make it a static class that takes all the parameters.
Of course, its hard to tell exactly why you need to create a single class just for this one method. Is it the typical "Utilities class" situation as most are assuming? Or are you implementing some sort of rule class, of which there might be more in the future.
For instance, have that class be plugable. Then you'd want to create an Interface for your one method, and then you'd want to have all the parameters passed into the interface, rather than into the constructor, but you wouldn't want it to be static.
If there is no reason to have an instance of the class created in order to execute the function then use the static implementation. Why make the consumers of this class create an instance when one is not needed.
I prefer the static way. Since the Class is not representing an object it doesn't make sense to make an instance of it.
Classes that only exist for their methods should be left static.
I would just do everything in the constructor. like so:
or
You might be able to avoid the situation all together. Try to refactor so that you get
arg1.myMethod1(arg2, arg3)
. Swap arg1 with either arg2 or arg3 if it makes more sense.If you do not have control over the class of arg1, then decorate it :
The reasoning is that, in OOP, data and methods processing that data belong together. Plus you get all the advantages that Mark mentionned.