Skip to content
Minsing Log
Go back

English Edition

When should you use static methods?

Programming & CS

Conclusion

Static methods are mainly used when implementing utility methods.

Instance variables cannot be accessed from static methods, and static methods cannot be used through instances.

cf) What is a utility function?: General functions that perform various calculations and processing on behalf of the user. Since they are used repeatedly, setting them up well makes subsequent work easier.

Characteristics

  1. They can be called without a class instance, but cannot be called from an instance. 
  2. They are useful for creating utility functions. Source: https://mygumi.tistory.com/253 [Maigumi’s HelloWorld: Tistory]

By what criteria should static methods be chosen?

In one sentence, it is as follows.

“Would this method be called even if no instance had been created?”  => “Yes.”

If the above is true, you can consider it static. To explain in a little more detail, let’s look at the following five points.

  1. If it is written as a utility class and does not assume change.
  2. If the method does not use instance variables.
  3. It does not depend on instance creation.
  4. If a method is shared, it can be extracted as a static method.
  5. Generally, they are said not to be overridden, but the example below shows that it is totally possible.
class Parent:
  @staticmethod
  def static_method():
      print("부모 클래스의 정적 메소드")

class Child(Parent):
  @staticmethod
  def static_method():
      print("자식 클래스의 정적 메소드")

Source: https://mygumi.tistory.com/253 [Maigumi’s HelloWorld: Tistory]

Advantages and disadvantages of static methods

Advantage: Since they are used repeatedly like utility classes, they make tasks easier and improve code readability. Disadvantage: Since they are a structure that simply contains methods without state, they are a concept that deviates from object-oriented programming.

cf) What is a utility method? General functions that perform various calculations and processing on behalf of the user. Since they are used repeatedly, setting them up well makes subsequent work easier.

Reference links When should static methods be used? Nice explanation

공개 여정 구독

글이 올라오면 이메일로 보내드릴게요.

개발, 창업, 배움, 실패와 회고를 짧고 솔직하게 기록합니다. 검색으로 스쳐가는 독자가 아니라 여정을 따라오는 팬을 만들기 위한 뉴스레터입니다.

뉴스레터는 준비 중입니다. 그동안 RSS 로 구독하거나 이메일 로 알림을 요청해 주세요.


Share this post:

Comments

Sign in with GitHub to leave a comment.


Previous Post
list comprehension in functional style
Next Post
Calling a static method from a method of the same class or a different class