I'm very new to OOP and am trying my hardest to keep things strictly class based, while using good coding principles.
I'm a fair ways into my project now and I have a lot of general use methods I want to put into an utilities class. Is there a best way to create a utilities class?
public class Utilities { int test; public Utilities() { } public int sum(int number1, int number2) { test = number1 + number2; } return test; }
After creating this Utilities class, do I just create an Utilities object, and run the methods of my choosing? Do I have this Utilities class idea correct?
Methods in the class should have appropriate names. Methods only used by the class itself should be private. The class should not have any non-final/non-static class fields. The class can also be statically imported by other classes to improve code readability (this depends on the complexity of the project however).
A utility class is a class that is just a namespace for functions. No instances of it can exist, and all its members are static. For example, java. lang. Math and java.
Whenever a common block of code needs to be used from multiple places, we can create utils class. Example: I want to verify whether a text is null or empty. This will be used in several places in my project.
utility class is a class that defines a set of methods that perform common, often re-used functions. Most utility classes define these common methods under static (see Static variable) scope. Examples of utility classes include java. util.
You should make it a static
class, like this:
public static class Utilities { public static int Sum(int number1, int number2) { return number1 + number2; } } int three = Utilities.Sum(1, 2);
The class should (usually) not have any fields or properties. (Unless you want to share a single instance of some object across your code, in which case you can make a static
read-only property.
If you are working with .NET 3.0 or above, you should look into extension methods. They allow you to write a static
function that will act against a particular type, like Int32
, while seeming to be a method on that object. So then you could have: int result = 1.Add(2);
.
Try this out; it might just show you another way. ;)
C# Tutorial - Extension Methods
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With