Advantages to Using Private Static Methods

后端 未结 8 2374
南笙
南笙 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:14

    When I'm writing a class, most methods fall into two categories:

    • Methods that use/change the current instance's state.
    • Helper methods that don't use/change the current object's state, but help me compute values I need elsewhere.

    Static methods are useful, because just by looking at its signature, you know that the calling it doesn't use or modify the current instance's state.

    Take this example:

    public class Library
    {
        private static Book findBook(List books, string title)
        {
            // code goes here
        }
    }

    If an instance of library's state ever gets screwed up, and I'm trying to figure out why, I can rule out findBook as the culprit, just from its signature.

    I try to communicate as much as I can with a method or function's signature, and this is an excellent way to do that.

提交回复
热议问题