Helper class
This article needs additional citations for verification. (October 2023) |
In object-oriented programming, a helper class is used to assist in providing some functionality, which isn't the main goal of the application or class in which it is used.[1][2] An instance of a helper class is called a helper object (for example, in the delegation pattern).
Helper classes are often created in introductory programming lessons, after the novice programmer has moved beyond creating one or two classes.
A utility class is a special case of a helper class in which the methods are all static.[3] In general, helper classes do not have to have all static methods, but may have instance variables. Multiple instances of the helper class may exist as well.
Example
[edit | edit source]This is also an example of a utility class. Below are extension methods on the string object.
public static class PrependHelper
{
// static functions
public static string MeowPrepend(this string text)
{
return $"Meow meow {text}!";
}
public static string WoofPrepend(this string text)
{
return $"Woof woof {text}!";
}
public static string WoohPrepend(this string text)
{
return $"Wooh {text}!";
}
}
Alternative to helper class
[edit | edit source]Functions which are going to be helper classes could be placed close to where they are used. The other alternative is wrapping helper class parameters into a class as a field. That class can have a name from the business domain connected to the fields it has. The example below shows how to convert helper methods to methods on domain types:
public class Text
{
string text;
public string MeowPrepend()
{
return $"Meow meow {text}!";
}
public string WoofPrepend()
{
return $"Woof woof {text}!";
}
public string WoohPrepend()
{
return $"Wooh {text}!";
}
}
References
[edit | edit source]- ^ Lua error in Module:Citation/CS1/Configuration at line 2172: attempt to index field '?' (a nil value).
- ^ Lua error in Module:Citation/CS1/Configuration at line 2172: attempt to index field '?' (a nil value).
- ^ Lua error in Module:Citation/CS1/Configuration at line 2172: attempt to index field '?' (a nil value).