Why make a class with only 1 static function?

delphi

Solution

It largely comes down to personal choice.

However, one benefit that the class function provides is a means to fake namespaces. Suppose that the function name that you wanted to use was quite short and general. In that situation it might collide with another symbol having the same name, defined in a different unit. At which point you might be subject to the vagaries of unit use order, and may need to fully qualify the name. By using a class function, you force the user to qualify the function name with its class.

Another point to make here is that the two alternatives that you present have a potentially significant difference. The class function in your question has a `Self` pointer. Unlike for an instance method, this refers to the class rather than an instance. To make the two functions completely equivalent you would declare the class function to be `static`.

class function SomeFunction(sMyString: string): ISomeInterface; static;

Of course, one thing that can be done with a non-static class function, is that it can be used where an `of object` method type is required.

Problem

Recently I ran into the following code: ``` interface TSomeClass=Class public class function SomeFunction(sMyString: string) : ISomeInterface; end; implementation TSomeClass.SomeFunction(sMyString: string) : ISomeInterface; begin ...Get some dependency. end; ``` Basically a class with 1 class function in it. What's the benefit of this construct over just having the function in a unit without it being part of a class? like: ``` interface function SomeFunction(sMyString: string) : ISomeInterface; implementation SomeFunction(sMyString: string) : ISomeInterface; begin ...Get some dependency. end; ```

Original source