Best way to share a function between two class files

There are two files A.cs and B.cs There is a fn() method that is used in both classes.

The fn() method is used in both class files. This increases code complexity if I need this method in many class files (say 100 files).

I know that we can call this method by creating an object for the class in which this method is defined. How can I share this function between two or more classes without creating an object each time to access this method?

+4
source share
3 answers

Put the method in a static class:

 public static class Utils { public static string fn() { //code... } } 

You can then call this in A.cs and B.cs without creating a new instance of the class each time:

 A foo = new A(); foo.Property = Utils.fn(); 

Alternatively, you can create a BaseClass that inherits all classes:

 public class BaseClass { public BaseClass() { } public virtual string fn() { return "hello world"; } } public class A : BaseClass { public A() { } } 

Then you call fn() as follows:

 A foo = new A(); string x = foo.fn(); 
+7
source

Assuming this method is self-contained, you can create a static class and put this method as a static method in it, which is in the rotation called by other classes.

If is is not self-sufficient, you can try and declare it in some superclass and let the other 100 classes extend this class.

+1
source

Hopefully the function is not really called fn() , but it is actually named the way it works, like CalculateTotal() . Then you can extract this method into a class, say: TotalCalculator .

Now when you start the application, preferably using dependency injection, you create one instance of the class that is shared between objects that require it. For instance:

 class TotalCalculator { public int Calculate() { return 42; } } class NeedsCalculator1 { TotalCalculator _calculator; public NeedsCalculator1(TotalCalculator calculator) { _calculator = calculator; } public void Foo() { _calculator.Calculate(); } } class NeedsCalculatorToo { TotalCalculator _calculator; public NeedsCalculatorToo(TotalCalculator calculator) { _calculator = calculator; } public void Bar() { _calculator.Calculate(); } } 

Then you instantiate the calculator once and pass it to the constructor of the other classes:

 TotalCalculator calculator = new TotalCalculator(); NeedsCalculator1 dependency1 = new NeedsCalculator1(calculator); NeedsCalculatorToo dependency2 = new NeedsCalculatorToo(calculator); 

Now you can further distract the dependency of the calculator by creating, for example, a base class that contains the constructor and the protected field of the TotalCalculator instance.

+1
source

Source: https://habr.com/ru/post/1498341/


All Articles