In OOP such as C# and Java if I were to create a class to do all string manipulation, I know it is better to make all the function static. However when I need to call those functions multiple times, which one will be a better option (in the context of using less resources):
Creating an object one time only and call the function using that object.
StringManipulation sm = new StringManipulation();
sm.reverse("something");
sm.addPadding("something");
sm.addPeriod("something");
or
Calling the class directly everytime
StringManipulation.reverse("something");
StringManipulation.addPadding("something");
StringManipulation.addPeriod("something");
the performance differences of the give two options is negligible. but the main difference is in the usage of the methods.
if you need a method to do any general tasks independant of class objects then you will consider static methods in your design. else for object dependant tasks you should consider the instance methods.
You should create an object if you need some initialisation, like maybe getting values or parameters from a datasource.
The static is the way to go in your exemple as they are atomic function which return always the same result, whatever the context (stateless)
However, in C# (I don't know in java), there is a better way : Extention methods. Basicly, you will add method to the string object which will allow to call them directly on the string object, and, if yor return object is also a string, chain them if you need to :
public static string reverse(this string str)
{
// Code to reverse your string
return result;
}
.........
"something".reverse().addPadding()
For more info : https://msdn.microsoft.com/en-us/library/bb383977.aspx
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