Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Better way to call Function multiple times [duplicate]

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

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

  1. Calling the class directly everytime

    StringManipulation.reverse("something");
    StringManipulation.addPadding("something");
    StringManipulation.addPeriod("something");
    
like image 545
Abraham Putra Prakasa Avatar asked Sep 30 '15 08:09

Abraham Putra Prakasa


2 Answers

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.

like image 137
stinepike Avatar answered Sep 23 '22 22:09

stinepike


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

like image 31
Remy Grandin Avatar answered Sep 23 '22 22:09

Remy Grandin