Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Creating a Utilities Class?

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?

like image 830
sooprise Avatar asked May 18 '10 13:05

sooprise


People also ask

How do you write a utility class?

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).

What is a utility class?

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.

When should you create a utility class?

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.

How do you define a utility class in Java?

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.


2 Answers

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.

like image 200
SLaks Avatar answered Sep 22 '22 09:09

SLaks


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

like image 40
Lance Avatar answered Sep 22 '22 09:09

Lance