Month: September 2009

Java generic in return context

Posted by – 2009-09-25

아래 코드를 보시고 1, 2번 라인중에 어디서 에러가 날 지를 찾아보세요.

interface B {
  void doB();
}
class D implements B {
  public void doB() {}
}
interface H {
  B getB();
}
class HImpl implements H {
  public B getB() {
    return new D();  // 1)
  }
}
...
H h = new HImpl();
D d = h.getB(); // 2)

네, 2번 라인입니다.

그럼 다음 코드는?

interface B1 {
  void doB1();
}
interface B2 {
  void doB2();
}
class D implements B1, B2 {
  public void doB1() {}
  public void doB2() {}
}
interface H {
  <T extends B1 & B2> T getB();
}
class HImpl implements H {
  public <T extends B1 & B2> T getB() {
    return new D();  // 1)
  }
}
...
H h = new HImpl();
D d = h.getB(); // 2)

네, 1번입니다. 잘 이해가 되질 않아 사내 메일링 리스트에 물어보니

I think you're seeing and interpreting it as "this method can return anything that implements both interfaces". What it's actually saying is "the caller is going to tell you a specific class that implements both interfaces, and you must return one of those".

이랍니다. 즉 T 타입이 아직 결정되지 않은 상태라 D와 T는 compatible한 타입이 아닌거죠.

강제로 casting을 해서 컴파일이 되게 만들면 그 코드는 runtime error (ClassCastException)를 발생하게 됩니다. 다음 코드를 보세요. 즉 이런 방법으론 도저히 type-safe한 코드를 작성할 수 없습니다.

class D2 implements B1, B2 {
  public void doB1() {}
  public void doB2() {}
}
...
D2 d = h.getB(); // ClassCastException!!

이 같은 상황을 방지하기 위해 1번 라인에서 에러를 내 주는 것이죠.

코딩 가이드라인을 만들어 보자면 "method의 parameter로 사용되지 않는 type variable을 사용하면 안된다"입니다. 다음과 같은 경우는 parameter로도 사용되고 있으므로 문제가  없는 경우들입니다.

<T> T makeInstance(Class<T> cls) { return cls.newInstance(); }
...
<T extends Comparable<? super T>> T min(T a, T b) {
 return a.compareTo(b) < 1 ? a : b;
}

위의 예제 코드같은 경우 아래와 같은 방법으로 type-safe하게 작성될 수 있습니다.

interface B1 {
  void doB1();
}
interface B2 {
  void doB2();
}
class D implements B1, B2 {
  public void doB1() {}
  public void doB2() {}
}
interface H  <T extends B1, B2> {
  T getB();
}
class HImpl implements H<D> {
  public D getB() {
    return new D();  // 1)
  }
}
...
H<D> h = new HImpl();
D d = h.getB(); // 2)

사실... 아직도 잘 모르겠어요. Java generic. =(

Access level of methods in package-private class

Posted by – 2009-09-22

Java에서 (C++도 마찬가지지만) 권장되는 access level 사용법은 다음과 같습니다.

Use the most restrictive access level that makes sense for a particular member.

쉽게 얘기해서 private으로 충분하면 private을 쓰고 다음으로 package-private, protected, public 순으로 쓰라는 얘기.

그런데 C++와는 달리 Java는 class에도 public과 package-private 두 종류의 access level이 있습니다. 이 중 public class의 method들은 위의 권장 사항을 따르면 될 듯 한데 package-private class일 경우는 어떨까요?

Package-private class에서는 실제 사용될 수 있는 조건으로 봤을 때 method들이 public이건 protected건 모두 package-private과 같은 조건을 가집니다. 즉, 아무리 method의 access level을 public이나 protected로 해봐야 다른 package에선 이 method를 사용할 수가 없습니다. 따라서 the most restrictive한 level을 사용하라는 위 권장 사항을 따르자면 package-private class의 method들은private이 아니라면 모두 package-private access level을 사용해야 합니다.

그런데 코딩을 하다보니 이 방법엔 한가지 문제가 있더군요. 가끔 package-private class를 public class로 만들어야 할 경우들이 생기는데 이때 method들이 모두 package-private이면 다른 package에서 사용할 수가 없습니다. 그래서 다시 method들의 access level을 조정해야 할 필요가 생기는데 이 시점은 이미 코드를 작성했을 때와 멀어서 자칫 잘못된 access level을 지정할 수 있게 됩니다.

그래서 생각한건데... package-private class의 method들을 만들 때 access level은 이 class의 access level을 public으로 가정하고 작성하는 것이 어떨까요?

A History of CLU

Posted by – 2009-09-16

Checked exception 관련 글들을 찾아 보다가 읽게 된 문서입니다. CLU라는 프로그래밍 언어를 개발하게 된 배경과 과정에 대한 내용인데 정말 재밌네요. 참고로 문서가 좀 길어보이지만 한 1/3은 부록입니다. :)

A History of CLU

거의 30~40년전 이야기인데 현재 사용하고 있는 언어들이 여기서 앞으로 많이 나간것 같아 보이지 않네요.

As mentioned, the concept of data abstraction arose out of work on structured programming and modularity that was aimed at a new way of organizing programs. The resulting programming methodology is object-oriented.

A keystone of the methodology is its focus on independence of modules.

Achieving independence requires two things: encapsulation and specification.

Specifications are needed to describe what the module is supposed to do in an implementation-independent way so that many different implementations are allowed. (Code is not a satisfactory description since it doesn’t distinguish what is required from ways of achieving it. One of the striking aspects of much of the work on object-oriented programming has been its lack of understanding of the importance of specifications; instead the code is taken as the definition of behavior.)

Specifications also allow code that uses the abstraction to be written before code that implements the abstraction, and therefore are necessary if you want to do top-down implementation.

In essence, having a language enforce encapsulation means that the compiler proves a global property of a program; given this proof, the rest of the reasoning can be localized.

CLU favors program readability and understandability over ease of writing, since we believed that these were more important for our intended users.

We worked on the implementation in parallel with the design. We did not allow the implementation to define the language, however.

이 글을 읽고나니 Kent Beck이 세미나에서 언급했던 Structured Design이라는 책이 읽고 싶어지네요. Kent Beck도 이 책을 언급하며 수십년전에 쓰여진 책인데 필요한 내용이 전부 있다... 뭐 이렇게 소개했었던 것 같은데...

Checked exception, 이거 써도 되나?

Posted by – 2009-09-15

mkseo님 블로그Best Practices for Exception Handling에 관한 글이 올라왔는데 댓글을 읽고 쓰고 하다 궁금한게 생겼습니다.

Checked exception, 이거 써도 되나?

mkseo님이 링크를 걸어준 The Trouble with Checked ExceptionsDoes Java need Checked Exceptions?, Java's checked exceptions were a mistake (and here's what I would like to do about it)등의 글을 읽다 보니 현재까지의 결론은 "java의 checked exception실험은 실패다"정도인 것 같더군요.

몇가지 이유로는

  1. 원래 language designer의 의도와는 달리 많은 exception이 무시되고 있다. 원래 의도는 compile-time에 에러를 냄으로써 개발자들에게 이 예외를 지금 처리하거나 아니면 위로 전달해야 한다는 메시지를 보내는 것이었다. 하지만 예외를 전달하기 위해서는 method의 signature를 수정해야 한다. 개발자들로서는 이 상황을 벗어날 수 있는 가장 쉬운 방법을 찾게 되고, 이게 바로 catch 후 무시하는 것인데 대부분의 코드가 이런 식으로 작성되고 있다. catch (...) {}
  2. 원래 exception의 목적중 하나는 예외가 발생한 지점과 처리할 지점의 분리이다. 즉 low-level에서 발생했지만 거기서 처리가 불가능한 exception들을 위로 전달하여 처리하게 한다... 인데... checked exception은 그 사이에 있는 모든 코드가 이 exception에 대해 알아야만 하게 강제한다. 즉, 전달되는 과정이 투명하지 않다.
  3. Versionability - 어느 method가 A, B라는 checked exception만을 던진다고 선언되었다면 client code들은 이 예외만을 처리하거나 위로 전달하도록 작성된다. 나중에 이 method의 다음 버전에서 C라는 exception을 던질 필요가 생기면 client와의 contract이 깨지게 된다.
  4. Scalability - A, B, C, D라는 method들이 각각 4개씩의 checked exception을 던지고 U라는 method가 이 것들을 호출하는데 예외들을 처리하지 않는다면 U는 총 16개의 checked exception을 던진다고 선언해야 한다. 상위로 올라갈 수록 선언해야 할 exception의 개수는 기하급수적으로 늘어나게 된다.

등이 있습니다. 4번의 경우에는 각 레벨에 맞는 exception을 정의해서 사용하면 해결할 수는 있을 것 같습니다. 즉, A, B, C, D가 던지는 16개의 exception을 U가 던질 때는 자기의 context에 맞는 예외 두어개로 mapping하여 던진다는 식이지요.

암튼.. 그럼 왜 여지껏 저는 checked exception이 매우 그럴 듯해 보였던 걸까요? C#의 한 language designer가 이렇게 얘기했다네요.

Examination of small programs leads to the conclusion that requiring exception specifications could both enhance developer productivity and enhance code quality, but experience with large software projects suggests a different result -- decreased productivity and little or no increase in code quality.

하지만 몇가지 경우엔 checked exception이 유용할 수 있다고 합니다.

  • 예외가 significant boundary를 넘어가는 경우. 예를 들어 CORBA의 machine boundary같은... 이런 경우 좀 더 명시적인 예외 스펙이 도움이 된다.
  • package 내부에서 사용되나 절대 외부로 넘어가서는 안되는 예외의 경우 checked exception을 사용하면 컴파일러가 이를 감시하게 할 수 있다.

예외에 관해 참고할 만한 글들입니다.

Responsive Design seminar – Kent Beck

Posted by – 2009-09-05

http://agile.egloos.com/5087979

정말 오랫만에 세미나를 가서인지 첫 시간은... 잘 잤다. ㅜㅜ 다음은 기억에 남는 얘기들.

Responsive to

Constraints

Feedback from system, people or customers.

Step back

문제를 만났을 때 한발짝 뒤로 물러서서 바라봐라... 쉬운 예로 어떤 코드의 테스트를 작성하는데 구현하기가 너무 어렵다면 한발짝 뒤로 물러서서 애초에 코드의 설계가 잘못된건 아닌지 확인해봐야 한다. 켄트벡이 든 예는 회전문이었는데... 회전문의  throughput, latency, variance등의 조건을 모두 고려하여 설계하기는 불가능하다. 이때 한발짝 물러서서 왜 회전문이 개선되어야 하는지, 혹시 문밖에 있는 인기있는 커피점때문은 아닌지 보자... 만약 그렇다면 커피점을 문안으로 들여오자. 뭐 이런 얘기...

마침 같이 갔던 H씨가 코드가 바뀔때마다 깨지는 테스트때문에 고민하고 있었는데 한발짝 물러서서 꼭 테스트가 필요한지 확인해보고 지워버리라고 조언... ㅎㅎ

Retrospect

자신이 하는 일을 돌아보자. 왜 이렇게 했는지...

Goal

Steady flow of features.

Design - beneficially relating elements

설계란 element들간의 관계인데 서로에게 이롭게 만드는 것.

Ambiguity

최선의 설계가 무엇인지 모호할 때는 그대로 놔두는 것도 필요. 그대로 놔두면 코드는 점점 망가지며 스스로 해결책을 드러낼 수 있다.

Safe steps

위험하며 효율적인(빠른) 방법보다는 안전하며 덜 효율적인 방법을 선호. 물론 안전하며 덜 효율적인 방법을 빨리 사용할 수 있다.

Values

아직 명확하진 않지만... 예를 들면 simplicity, feedback, community

Patterns

대부분의 디자인 결정은 problem domain과 관계가 없고 실제론 컴퓨터에게 시키는 instruction들에 의해 결정되고, 같은 패턴들이 반복되더라.

시간 낭비를 방지한다.

Principles

Strategies

Can see? (a design what you want)

  • Leap - 한번에 구현. 위험하나 효율적
  • Parallel - 동시에 이전 설계와 새 설계를 지원하여 서서히 이전

Can't see?

  • Stepping stone - 이런게 있으면 설계가 쉬워지겠다고 생각하는 항목을 구현 (framework?)
  • Simplification - 문제의 쉬운 버전을 일단 설계하고 얻은 경험을 바탕으로 서서히 원래 문제를 해결

Or

  • Add it anyway
  • Expect to pay the price later - 나중에 문제가 커지면 스스로 해결책을 드러낼 수도...

Coupling and cohesion

  • Coupling - 어떤 element 변경시 다른 element들이 변경될 확률. Hidden coupling은 발견하기가 매우 어렵다.
  • Cohesion - 어떤 sub-element 변경시 다른 sub-element들이 변경될 확률. Coupling보다 추적이 용이하다.

Refactoring

  • Bi-directional
  • Isolate change (Coupling and cohesion) - Cohesion이 높은 element로 extract한 후 변경
  • Interface or implementation - 동시에 interface와 implementation을 변경하지 않는다.

Succession

Succession of vegetative communities.

Data

Design is an island

  • No "best" design - 최선의 디자인은 없다.
  • Improvement
  • Deterioration
  • Sea level
  • Change in basis

Observations

  • Power laws
  • Fractal - 같은 패턴이 여러 규모의 구조에서 발견된다.
  • Symmetry - 예를 들어 4개의 member field들 중 하나만 다른 행동을 한다면 그 클래스에 속하지 않는 녀석이 아닐까?
  • Punctuated equilibrium

이외에 설계시 social 입장을 고려해야 한다는 얘기도 있었다. 좋은 설계이나 팀원들이 이해할 수 없거나 아직 받아들이기 힘든 경우도 고려해야 한다는 얘기였던 듯...

추가

http://www.infoq.com/presentations/responsive-design에서 거의 같은 내용을 볼 수 있네요.

발표 자료는 http://agile.egloos.com/5106266에 있습니다.