Advantages to Using Private Static Methods

后端 未结 8 2204
南笙
南笙 2020-11-27 09:52

When creating a class that has internal private methods, usually to reduce code duplication, that don\'t require the use of any instance fields, are there performance or mem

相关标签:
8条回答
  • 2020-11-27 10:25

    A call to a static method generates a call instruction in Microsoft intermediate language (MSIL), whereas a call to an instance method generates a callvirt instruction, which also checks for a null object references. However, most of the time the performance difference between the two is not significant.

    src: MSDN - http://msdn.microsoft.com/en-us/library/79b3xss3(v=vs.110).aspx

    0 讨论(0)
  • 2020-11-27 10:29

    I very much prefer all private methods to be static unless they really can't be. I would much prefer the following:

    public class MyClass
    {
        private readonly MyDependency _dependency;
    
        public MyClass(MyDependency dependency)
        {
            _dependency = dependency;
        }
    
        public int CalculateHardStuff()
        {
            var intermediate = StepOne(_dependency);
            return StepTwo(intermediate);
        }
    
        private static int StepOne(MyDependency dependency)
        {
            return dependency.GetFirst3Primes().Sum();
        }
    
        private static int StepTwo(int intermediate)
        {
            return (intermediate + 5)/4;
        }
    }
    
    public class MyDependency
    {
        public IEnumerable<int> GetFirst3Primes()
        {
            yield return 2;
            yield return 3;
            yield return 5;
        }
    }
    

    over every method accessing the instance field. Why is this? Because as this process of calculating becomes more complex and the class ends up with 15 private helper methods, then I REALLY want to be able to pull them out into a new class that encapsulates a subset of the steps in a semantically meaningful way.

    When MyClass gets more dependencies because we need logging and also need to notify a web service (please excuse the cliche examples), then it's really helpful to easily see what methods have which dependencies.

    Tools like R# lets you extract a class from a set of private static methods in a few keystrokes. Try doing it when all private helper methods are tightly coupled to the instance field and you'll see it can be quite a headache.

    0 讨论(0)
提交回复
热议问题