Ruby를 배우는 Java 개발자가 알아야 할 10가지 part 2

Java 개발자가 알아야 할 10가지

Item #6 객체들은 강한 타입이며 정적 타입이 아니다.

타입은 값들(value)의 집합이다.
타입은 연산(operation)들의 집합이다.

C Code (Weak)

#include 
extern float two();
int main() {
    float x = 1.5   two();
    printf("%f\n", x);
    printf("%d\n", x);
    return 0;
}

int two() { return 2; }

# Output
nan
0

Java Code (Strong)

public class Main {
  public static
    void main (String args[]) {
    double x = 1.5   Two.two();
    System.out.println(x);
  }
}

public class Two {
  public static int two() {
    return 2;
  }
}

# Output
3.5

Ruby Code (?)

require 'two'

x = 1.5   two
puts x
printf "%d", x

def two
  2
end

# Output
3.5
3

언어의 타입을 안전하게 해주는 것은 무엇일까?

  • 컴파일러가 변수의 타입을 안다.
  • 모든 변수를 선언한다.
  • 컴파일러가 타입 에러를 잡는다.

Or 연산할 때, 컴파일 시에, 런타임에 부적절한 타입을 잡아낸다.

Ruby Code

def factorial(n)
  result = 1
  (2..n).each do |i|
    result *= i
  end
  result
end

puts factorial(20)
puts factorial(21)

# Output
2432902008176640000
51090942171709440000

Java Code

public class Fact {
  static long factorial(long n) {
    long result = 1;
    for (long i=2; i<=n; i  )
      result *= i;
    return result;
  }
  public static
    void main (String args[]) {
    System.out.println(factorial(20));
    System.out.println(factorial(21));
  }
}

# Output
2432902008176640000
-4249290049419214848

Lanaguage Typing Systems

    Java

  • 강한 타입
  • 정적인 타입
  • 명시적 타입
    Ruby

  • 강한 타입
  • 동적인 타입
  • 함축적 타입

Item #5 인터페이스 걱정은 이제 그만

루비는 바보 타입(Duck Typing)을 사용한다.
- 만일 그것이 오리 같이 걷고, 오리 같이 운다면..
- 우리는 그것을 오리라고 여기겠다. (아니면 말고~)

공통 인터페이스를 구현할 필요가 없다

class Duck
  def talk() puts "Quack" end
end
class DuckLikeObject
  def talk() puts "Kwak" end
end
flock = [
  Duck.new,
  DuckLikeObject.new ]
flock.each do |d| d.talk end
This entry was posted in Ruby & Languages and tagged . Bookmark the permalink. Post a comment or leave a trackback: Trackback URL.

Post a Comment

Your email is never published nor shared. Required fields are marked *

*
*

You may use these HTML tags and attributes: <a href="" title=""> <abbr title=""> <acronym title=""> <b> <blockquote cite=""> <cite> <code> <del datetime=""> <em> <i> <q cite=""> <strike> <strong>