Program Tip

왜 "메서드 오버로딩을 피해야합니까?"

programtip 2020. 10. 19. 12:37
반응형

왜 "메서드 오버로딩을 피해야합니까?"


Jorge Ortiz메서드 오버로딩을 피하라고 조언하는 이유는 무엇 입니까?


오버로딩은 메서드를 함수로 들어 올리는 것을 조금 더 어렵게 만듭니다.

object A {
   def foo(a: Int) = 0
   def foo(b: Boolean) = 0
   def foo(a: Int, b: Int) = 0

   val function = foo _ // fails, must use = foo(_, _) or (a: Int) => foo(a)
}

오버로드 된 메서드 집합 중 하나를 선택적으로 가져올 수 없습니다.

매개 변수 유형에 인수를 적용하기 위해 암시 적 뷰를 적용하려고 할 때 모호성이 발생할 가능성이 더 큽니다.

scala> implicit def S2B(s: String) = !s.isEmpty                             
S2B: (s: String)Boolean

scala> implicit def S2I(s: String) = s.length                               
S2I: (s: String)Int

scala> object test { def foo(a: Int) = 0; def foo(b: Boolean) = 1; foo("") }
<console>:15: error: ambiguous reference to overloaded definition,
both method foo in object test of type (b: Boolean)Int
and  method foo in object test of type (a: Int)Int
match argument types (java.lang.String)
       object test { def foo(a: Int) = 0; def foo(b: Boolean) = 1; foo("") }

기본 매개 변수를 사용할 수 없게 조용히 렌더링 할 수 있습니다.

object test { 
    def foo(a: Int) = 0; 
    def foo(a: Int, b: Int = 0) = 1 
}

개별적으로 이러한 이유 때문에 과부하를 완전히 피해야하는 것은 아닙니다. 더 큰 문제를 놓치고있는 것 같습니다.

최신 정보

증거가 쌓이고 있습니다.

업데이트 2

  • (현재) 패키지 객체에서 오버로드 된 메서드를 사용할 수 없습니다.
  • API 호출자에 대해 적용 성 오류 를 진단 하기 더 어렵습니다 .

업데이트 3

  • 정적 과부하 해결은 API의 모든 유형 안전을 약화시킬 수 있습니다.
scala> object O { def apply[T](ts: T*) = (); def apply(f: (String => Int)) = () }
defined object O

scala> O((i: String) => f(i)) // oops, I meant to call the second overload but someone changed the return type of `f` when I wasn't looking...

Gilad와 Jason (retronym)이 제공하는 이유는 모두 가능하면 과부하를 피하는 매우 좋은 이유입니다. Gilad의 이유는 오버로딩이 일반적으로 문제가되는 이유에 초점을 맞추고, Jason의 이유는 다른 Scala 기능의 맥락에서 문제가되는 이유에 초점을 맞 춥니 다.

Jason의 목록에 오버로딩이 유형 추론과 제대로 상호 작용하지 않는다고 추가합니다. 중히 여기다:

val x = ...
foo(x)

추론 된 유형 x이 변경 foo되면 호출 되는 메소드가 변경 될 수 있습니다 . x변경 될 필요가 없습니다. 유추 된 유형의 x. 모든 종류의 이유로 발생할 수 있습니다.

주어진 모든 이유 (그리고 몇 가지 더 잊고 있다고 확신합니다) 때문에 메서드 오버로딩은 가능한 한 적게 사용해야한다고 생각합니다.


나는 조언이 특히 스칼라를위한 것이 아니라 일반적으로 OO를위한 것이라고 생각한다 (지금까지 나는 스칼라가 OO와 기능 사이의 동종 최고라고 생각한다).

재정의 는 괜찮으며 다형성의 핵심이며 OO 디자인의 핵심입니다.

Overloading on the other hand is more problematic. With method overloading it's hard to discern which method will be really invoked and it's indeed a frequently a source of confusion. There is also rarely a justification why overloading is really necessary. The problem can most of the time be solved another way and I agree that overloading is a smell.

Here is an article that explain nicely what I mean with "overloading is a source of confusion", which I think is the prime reason why it's discouraged. It's for java but I think it applies to scala as well.

참고URL : https://stackoverflow.com/questions/2510108/why-avoid-method-overloading

반응형