In my design i have a lot of objects which have a single Run() method, which when called performs what the object should do. Is that a valid interface design? It seems as though most objects I normally use have more than 1 method.
Asked
Active
Viewed 125 times
-1
-
4This is hard to judge without an example. – Flater Feb 19 '22 at 16:05
-
3Could be overkill to use a class for that, but there's no OO police, so you're probably ok. You don't give an example, so hard to say more. Some objects, like thread objects work like that so that they can separate their construction (on one thread) from their execution (on another thread). But if you're doing `new Foo(a,b).Run();` that might be better simply doing a function as in `fooRun(a,b);` – Erik Eidt Feb 19 '22 at 16:05
-
There could be scenarios. Like an object you use to collect data that is not all available at the same time. You add data to it by setting properties until it is complete. You then call Run() to process the data. Monitor or timer objects could be usages although for those I would at least expect a Stop and/or Dispose method as well. – Martin Maat Feb 20 '22 at 08:52
-
Does this answer your question: [Are classes with only a single (public) method a problem?](https://softwareengineering.stackexchange.com/questions/225893/are-classes-with-only-a-single-public-method-a-problem) – Doc Brown Feb 24 '22 at 13:26
-
Moreover: a single `Run` method is not a problem on its own. The interesting question is how your object processes inputs and output. If this is all processed by side effects to other objects (or to external datasources like a database), then I bet your code is pretty procedural and hard to test. – Doc Brown Feb 24 '22 at 13:29
1 Answers
3
An object with a single method is just a (first-class) procedure / function. An object with a single method and some instance variables is just a (first-class) closure ("lambda").
This is how Java programers did lambdas before Java had lambdas, and is in fact how Java itself does lambdas.
There is nothing wrong with lambdas. The only thing I would say is that if your language has lambdas, then for reasons of readability, maintainability, and clarity, you should use those instead of using something that is the same as a lambda but isn't a lambda.
The Strategy Software Design Pattern is based around a protocol with a single method, for example.

Jörg W Mittag
- 101,921
- 24
- 218
- 318