Best way to call a function multiple times

In OOP, such as C # and Java, if I had to create a class to do all the string manipulation, I know that it’s better to make the whole static function. However, when I need to call these functions several times, which one will be the best option (in the context of using less resources):

  • Create an object only once and call a function using this object.

    StringManipulation sm = new StringManipulation(); sm.reverse("something"); sm.addPadding("something"); sm.addPeriod("something"); 

or

  1. Calling a class directly every time

     StringManipulation.reverse("something"); StringManipulation.addPadding("something"); StringManipulation.addPeriod("something"); 
+7
java function c # static class
source share
3 answers

performance differences for the two options are minor. but the main difference is the use of methods.

if you need a method to perform any general tasks that are independent of class objects, then you will consider static methods in your design. else for object-dependent tasks you should consider instance methods.

+1
source share

I believe it will be effective

 StringManipulation sm = new StringManipulation(); sm.reverse("something").addPadding("something").addPeriod("something"); 

Create one instance that will make it work.

+1
source share

You must create an object if you need initialization, for example, it is possible to get values ​​or parameters from a data source.

Staticity is the way to go in your example, since they are an atomic function that always returns the same result, regardless of context (idle)

However, in C # (I don't know in java), there is a better way: extension methods. Basically, you will add a method to the string object that will allow them to be called directly on the string object, and if the yor return object is also a string, bind them if you need:

 public static string reverse(this string str) { // Code to reverse your string return result; } ......... "something".reverse().addPadding() 

For more information: https://msdn.microsoft.com/en-us/library/bb383977.aspx

+1
source share

All Articles