Camera의 setDisplayOrientation 메소드

Posted by epicdev Archive : 2011. 10. 3. 15:52
출처: http://developer.android.com/reference/android/hardware/Camera.html#setDisplayOrientation(int)

public final void setDisplayOrientation (int degrees)

Since: API Level 8

Set the clockwise rotation of preview display in degrees. This affects the preview frames and the picture displayed after snapshot. This method is useful for portrait mode applications. Note that preview display of front-facing cameras is flipped horizontally before the rotation, that is, the image is reflected along the central vertical axis of the camera sensor. So the users can see themselves as looking into a mirror.

This does not affect the order of byte array passed in onPreviewFrame(byte[], Camera), JPEG pictures, or recorded videos. This method is not allowed to be called during preview.

If you want to make the camera image show in the same orientation as the display, you can use the following code.

 public static void setCameraDisplayOrientation(Activity activity,
         
int cameraId, android.hardware.Camera camera) {
     android
.hardware.Camera.CameraInfo info =
             
new android.hardware.Camera.CameraInfo();
     android
.hardware.Camera.getCameraInfo(cameraId, info);
     
int rotation = activity.getWindowManager().getDefaultDisplay()
             
.getRotation();
     
int degrees = 0;
     
switch (rotation) {
         
case Surface.ROTATION_0: degrees = 0; break;
         
case Surface.ROTATION_90: degrees = 90; break;
         
case Surface.ROTATION_180: degrees = 180; break;
         
case Surface.ROTATION_270: degrees = 270; break;
     
}

     
int result;
     
if (info.facing == Camera.CameraInfo.CAMERA_FACING_FRONT) {
         result
= (info.orientation + degrees) % 360;
         result
= (360 - result) % 360;  // compensate the mirror
     
} else {  // back-facing
         result
= (info.orientation - degrees + 360) % 360;
     
}
     camera
.setDisplayOrientation(result);
 
}
 

Parameters
degreesthe angle that the picture will be rotated clockwise. Valid values are 0, 90, 180, and 270. The starting position is 0 (landscape).
  

Java 필드 초기화

Posted by epicdev Archive : 2011. 10. 3. 15:27
출처: http://download.oracle.com/javase/tutorial/java/javaOO/initial.html

Initializing Fields

As you have seen, you can often provide an initial value for a field in its declaration:
public class BedAndBreakfast {

    public static int capacity = 10;  //initialize to 10

    private boolean full = false;  //initialize to false
}
This works well when the initialization value is available and the initialization can be put on one line. However, this form of initialization has limitations because of its simplicity. If initialization requires some logic (for example, error handling or a for loop to fill a complex array), simple assignment is inadequate. Instance variables can be initialized in constructors, where error handling or other logic can be used. To provide the same capability for class variables, the Java programming language includes static initialization blocks.

Note: It is not necessary to declare fields at the beginning of the class definition, although this is the most common practice. It is only necessary that they be declared and initialized before they are used.


Static Initialization Blocks

static initialization block is a normal block of code enclosed in braces, { }, and preceded by the static keyword. Here is an example:
static {

    // whatever code is needed for initialization goes here
}
A class can have any number of static initialization blocks, and they can appear anywhere in the class body. The runtime system guarantees that static initialization blocks are called in the order that they appear in the source code.

There is an alternative to static blocks — you can write a private static method:

class Whatever {
    public static varType myVar = initializeClassVariable();
	
    private static varType initializeClassVariable() {

        //initialization code goes here
    }
}
The advantage of private static methods is that they can be reused later if you need to reinitialize the class variable.
 

Initializing Instance Members

Normally, you would put code to initialize an instance variable in a constructor. There are two alternatives to using a constructor to initialize instance variables: initializer blocks and final methods.

Initializer blocks for instance variables look just like static initializer blocks, but without the static keyword:

{

    // whatever code is needed for initialization goes here
}
The Java compiler copies initializer blocks into every constructor. Therefore, this approach can be used to share a block of code between multiple constructors.

final method cannot be overridden in a subclass. This is discussed in the lesson on interfaces and inheritance. Here is an example of using a final method for initializing an instance variable:

class Whatever {
    private varType myVar = initializeInstanceVariable();
	
    protected final varType initializeInstanceVariable() {

        //initialization code goes here
    }
}
 
This is especially useful if subclasses might want to reuse the initialization method. The method is final because calling non-final methods during instance initialization can cause problems. Joshua Bloch describes this in more detail in Effective Java. 

출처: http://wahlstroem.org/bjorn/2008/07/24/instance-initializers-in-java/

At work I noticed an interesting piece of code. I wrote it in error, as I meant to write a static initializer (code that is run once when a static class is being referenced)


static {
// initialize static variables
}

but instead I wrote this


{
// initialize variables
}

It compiled nicely, but what is it good for?

The effect is not that of a static initializer, but it is actually run before the constructor; But not when referenced statically. You can have as many instance initializers as you want, and they are appearing to run in the order they are defined.

The author of “Java in a Nutshell” writes so nicely:

An instance initializer is simply a block of code inside curly braces that is embedded in a class definition, where a field or method definition normally appears.  A class (any class — not just anonymous classes) can have any number of instance initializers.  The instance initializers and any variable initializers that appear in field definitions for the class are executed in the order they appear in the Java source code.  These initializers are automatically run after the superclass constructor has returned but before the constructor, if any, of the current class runs.

This puzzles me, because this seems at first hand to be what we have constructors for. They are the blocks of code that is run whenever we instantiate a class, and should do all the complex logic and initialization that needs to be done to assure data integrity.

But; What about anonymous classes? You know, the ones that are used frequently in event-programming


someObject.addEventListener(new MouseAdapter() {
    public void mouseClicked(MouseEvent e) { // .... }
});

They cannot have constructors, but I imagine it can be useful to have complex (more than one line..) initialization even there. Also, according to more seasoned programmers than my self, instance initializers can be used to make the code easier to read, since the initialization block can be placed right next to the variables.

The initializers are run in the order they are defined, and you can have as many you want. In contrast to constructors, which you can only have one of without an argument list. This could also be useful with regards to code readability, since complex constructors, like any block of code, should be avoided.

But beware, long-time maintenance could be troublesome if one isn’t careful. So-called “pretty”-tools often reorganize the code, e.g. alphabetically or by visibility. Since the instance initializers are run in the order they are defined, one has to make sure that they are not co-dependent. That would be a java-equivalent to Spaghetti Hell! 

'Archive' 카테고리의 다른 글

세부사항을 코드에서 몰아내라  (0) 2011.10.03
Camera의 setDisplayOrientation 메소드  (0) 2011.10.03
디미터 함수 법칙 (혹은 디미터 법칙)  (0) 2011.10.03
패키지의 순환적 의존성  (0) 2011.10.03
응답집합  (0) 2011.10.03
  

디미터 함수 법칙 (혹은 디미터 법칙)

Posted by epicdev Archive : 2011. 10. 3. 14:39
디미터 법칙은 객체의 모든 메소드는 다음에 해당하는 메소드만을 호출해야 한다고 말한다.

1. 객체 자신의 메소드
2. 메소드의 매개변수로 넘어온 인자의 메소드
3. 메소드 내부에서 생성 된 객체의 메소드
4. 메소드가 포함하고 있는 객체의 메소드

class Demeter {
    private A a;

    private int func() { return 0; }

    public void example(B b) {
        C c = new C();
        int f = func(); // 1번의 경우
        b.invert(); // 2번의 경우
        a = new A();
        a.setActive(); // 3번의 경우
        c.print(); // 4번의 경우
    }
}
실용주의프로그래머
카테고리 컴퓨터/IT > 프로그래밍/언어
지은이 앤드류 헌트 (인사이트, 2007년)
상세보기

'Archive' 카테고리의 다른 글

Camera의 setDisplayOrientation 메소드  (0) 2011.10.03
Java 필드 초기화  (0) 2011.10.03
패키지의 순환적 의존성  (0) 2011.10.03
응답집합  (0) 2011.10.03
객체간의 의존 관계가 combinatorial explosion 할 때의 징후  (0) 2011.10.03
  

패키지의 순환적 의존성

Posted by epicdev Archive : 2011. 10. 3. 14:25
패키지 구성의 원리 중 패키지 간의 의존 관계가 순환관계를 형성하면 안 된다는 ADP (Acyclic Dependencies Principle)이 있다. 뭔가를 고치면 그 영향이 다른 것들을 거쳐 전파되다가 다시 애초의 시작점으로 되먹임 되어 순환 할 수 있기 때문이다.

 
실용주의프로그래머
카테고리 컴퓨터/IT > 프로그래밍/언어
지은이 앤드류 헌트 (인사이트, 2007년)
상세보기
  

응답집합

Posted by epicdev Archive : 2011. 10. 3. 14:21
응답집합 (response set 혹은 RFC 혹은 response for a class)이 큰 클래스는 작은 클래스보다 에러를 발생시키기 쉽다고 한다. 이 때 응답집합은 클래스의 메소드가 직접 호출하는 함수의 수를 의미한다.


응답집합의 정의

클래스의 객체에 메시지가 보내졌을 때, 그 결과로 호출되는 모든 (내외부) 메소드들의 집합의 원소 개수
대략적인 근사값을 얻기 위해서는 해당 클래스 메소드 바디에서의 메소드 호출 종류만 세기도 한다. 응답집합은 테스트 가능성에 대한 직접적인 metric 중 하나다.

 
실용주의프로그래머
카테고리 컴퓨터/IT > 프로그래밍/언어
지은이 앤드류 헌트 (인사이트, 2007년)
상세보기
  
1. 단위 테스트를 링크하기 위한 명령어가 테스트 프로그램 자체보다 긴 대규모 C 혹은 C++ 프로젝트

2. 한 모듈의 '간단한' 수정이 이와 관계없는 모듈을 통해 시스템 전역에 퍼져나가는 경우

3. 개발자가 수정한 부분이 시스템에 어떤 영향을 미칠지 몰라 코드의 수정을 두려워 하는 경우

 
실용주의프로그래머
카테고리 컴퓨터/IT > 프로그래밍/언어
지은이 앤드류 헌트 (인사이트, 2007년)
상세보기

'Archive' 카테고리의 다른 글

패키지의 순환적 의존성  (0) 2011.10.03
응답집합  (0) 2011.10.03
리소스 할당과 해제의 균형과 예외  (0) 2011.10.03
리소스의 할당과 해제  (0) 2011.10.03
예외는 예외적인 문제에 사용하라  (0) 2011.10.03
  

리소스 할당과 해제의 균형과 예외

Posted by epicdev Archive : 2011. 10. 3. 13:45
예외를 지원하는 언어는 리소스 해제에 복잡한 문제가 있을 수 있다. 예외가 던져진 경우, 그 예외 이전에 할당 된 모든 것이 깨끗이 청소된다고 어떻게 보장 할 수 있겠는가?


C++에서 예외와 리소스 사용의 균형

C++은 try...catch 예외 메커니즘을 지원한다. 불행하게도, 이 말은 예외를 잡은 다음 다시 던지는 루틴에서는 언제나 그 루틴에서 나가는 경로가 최소한 두 개는 존재한다는 얘기다.

void doSomething(void) {
    Node* n = new Node;
    try {
        // Do something
    } catch(...) {
        delete n;
        throw;
    }
    delete n;
}

우리가 생성한 노드가 해제되는 장소가 두 군데라는 점을 눈여겨보라. 하나는 루틴이 정상적으로 나가는 경로에 있고, 다른 하나는 예외처리 장소에 있다. 이것은 명백한 Don't repeat yourself 원칙 위반이며, 언제 터질지 모르는 유지보수 문제이기도 하다.

하지만 우리는 C++의 작동방식을 이용 할 수 있다. local 객체들은 자기를 둘러싼 블록에서 나갈 때 자동으로 파괴된다. 이것 덕분에 몇 가지 방법이 생긴다. 만약 상황이 허락한다면, 'n'을 포인터에서 스택에 놓이는 실제 Node 객체로 바꾸면 된다.

void doSomething(void) {
    Node n;
    try {
        // Do something
    } catch(...) {
        throw;
    }
}

이렇게 되면 예외가 생기든 그렇지 않든 Node 객체의 자동 파괴를 C++에게 맡길 수 있다.

포인터에서 다른 것으로 바꾸는 일이 불가능 하다면, 리소스를 다른 클래스로 감싸면 동일한 효과를 볼 수 있다.

class NodeResource {
    Node* n;
public:
    NodeResource() { n = new Node; }
    ~NodeResource() { delete n; }
    Node* operator->() { return n; }
};

void doSomething(void) {
    NodeResource n;
    try {
        // Do something
    } catch(...) {
        throw;
    }
}

이제 wrapper 클래스 NodeResource가 자신의 객체들이 파괴 될 때 관련 노드들 역시 파괴되도록 하는 일을 확실히 해준다. 편의성을 위해, wrapper 클래스는 -> 연산자도 제공해서 사용자가 Node 객체에 들어있는 필드에 바로 접근 할 수 있게 해준다.
이 기법이 너무나도 유용하기 때문에, 표준 C++ 라이브러리에도 동적으로 할당 된 객체들의 자동 wrapper를 제공하는 템플릿 클래스 auto_ptr이 있다.
void doSomething(void) {
    auto_ptr p (new Node);
    try {
        // Do something
    } catch(...) {
        throw;
    }
}

자바에서 리소스 사용의 균형


public void doSomething() throws IOException {
    File tmpFile = new File(tmpFileName);
    FileWriter tmp = new FileWriter(tmpFile);
    try {
        // Do something
    } catch(...) {
        // Do something
    } finally {
        tmpFile.delete();
    }
}

이 루틴에서 사용하는 임시파일은 루틴에서 어떻게 나가든 지워야 한다. Finally 블록이 우리가 뜻하는 바를 이렇게 간결하게 표현 해 준다.


 
  

리소스의 할당과 해제

Posted by epicdev Archive : 2011. 10. 3. 13:22
리소스를 할당한 순서의 반대로 해제하라. 이렇게 해야 한 리소스가 다른 리소스를 참조하는 경우에도 리소스를 고아로 만들지 않는다.

코드의 여러 곳에서 동일한 리소스 집합을 할당하는 경우, 할당 순서를 언제나 같게 하라. deadlock 가능성이 줄어들 것이다. (프로세스 B가 리소스2를 이미 확보하고서 리소스1을 획득하려고 하고 있는데 프로세스 A가 리소스1을 가진 상태로 리소스2를 요청하려고 한다면, 이 두개의 프로세스는 영원히 기다리게 될 것이다.)

어떤 종류의 리소스를 사용하고 있는지는 중요하지 않다. 트랜잭션이나 메모리이건, 파일 혹은 쓰레드, 윈도우이건 모두 기본 패턴이 적용된다. 리소스를 할당하는 것이 누구이든, 그 리소스를 해제할 책임까지 져야 한다.

 
실용주의프로그래머
카테고리 컴퓨터/IT > 프로그래밍/언어
지은이 앤드류 헌트 (인사이트, 2007년)
상세보기
  

예외는 예외적인 문제에 사용하라

Posted by epicdev Archive : 2011. 10. 3. 12:41
예외가 있다는 것은 즉 컨트롤의 이동이 즉각적이고 로컬하지 않다는 것을 말한다. 일종의 연쇄 goto 같은 것이다. 예외를 정상적인 처리 과정의 일부로 사용하는 프로그램은 고전적인 스파게티 코드의 가독성 문제와 관리성 문제를 전부 떠안게 된다. 이런 프로그램은 캡슐화 역시 깨트린다. 예외 처리를 통해 루틴과 그 호출자들 사이의 결합도가 높아져 버린다.

에러 처리기는 또 다른 대안이다

에러 처리기는 에러가 감지되었을 때 호출되는 루틴이다. 특정 부류의 에러를 처리하기 위해 어떤 루틴을 등록하게 된다. 해당하는 에러가 났을 때 그 처리기가 호출 될 것이다.

자바의 RMI 기능을 사용하는 클라이언트 서버 애플리케이션을 구현한다고 생각 해 보라. RMI가 구현 된 방식 때문에, 원격 루틴을 호출 할 때마다 RemoteException을 처리할 준비가 되어있어야 한다. 문제는 이런 예외를 처리하기 위해 코드를 추가하는 것은 지겨운 일이며, 로컬과 리모트 루틴 모두에서 작동하는 코드를 작성하기가 어렵다는 것이다. 한 가지 가능한 우회로는 원격이 아닌 클래스로 원격 객체를 wrapping 하는 것이다. 그러면 이 클래스는 에러 처리기 인터페이스를 구현하며, 원격 예외가 감지되었을 때 호출 될 루틴을 클라이언트 코드가 등록하도록 한다.
 
실용주의프로그래머
카테고리 컴퓨터/IT > 프로그래밍/언어
지은이 앤드류 헌트 (인사이트, 2007년)
상세보기

'Archive' 카테고리의 다른 글

리소스 할당과 해제의 균형과 예외  (0) 2011.10.03
리소스의 할당과 해제  (0) 2011.10.03
죽은 프로그램은 거짓말을 하지 않는다  (0) 2011.10.03
타인의 버그를 대하는 자세  (0) 2011.10.02
GUI와 쉘  (0) 2011.10.02
  

죽은 프로그램은 거짓말을 하지 않는다

Posted by epicdev Archive : 2011. 10. 3. 11:50
프로그래밍을 하다보면 '그런 일은 절대 일어날 리 없어'라는 사고에 빠지기 쉽다. 우리 중 대다수는 파일이 성공적으로 닫혔는지, 혹은 트레이스문이 우리가 예상한 대로 찍히는지 확인하지 않는 코드를 작성한 경험이 있다. 그리고 다른 모든 조건이 동일하다면, 그럴 필요가 없었을지도 모른다. 문제의 코드는 정상 조건 하에서는 실패하지 않았을 것이다. 하지만 우리는 지금 방어적으로 코딩하고 있다.

모든 에러는  정보를 준다. 여러분은 에러가 발생할 리 없다고 스스로를 설득하고선 그걸 무시하기로 할 수 있다. 반면에 실용주의 프로그래머는 만약 에러가 있다면 정말로 뭔가 나쁜 일이 생긴 것이라고 자신에게 이야기한다.

<실용주의 프로그래머 팁>
일찍 작동을 멈추게 하라

망치지 말고 멈추라

가능한 한 빨리 문제를 발견하게 되면, 좀 더 일찍 시스템을 멈출 수 있다는 이득이 있다. 게다가 프로그램을 멈추는 것이 할 수 있는 최선일 때가 많다.

자바 언어와 라이브러리는 이 철학을 포용했다. 런타임 시스템에서 뭔가 예상하지 못한 것이 발생하면 RuntimeException을 던진다. 만약 이 예외가 catch되지 않으면 프로그램의 최상위 수준까지 스며 나올 것이고, 결국 스택 트레이스를 출력하며 프로그램을 멈춰버릴 것이다.

다른 언어에서도 똑같이 할 수 있다. 예외 처리가 지원되지 않거나 라이브러리가 예외를 던지지 않으면, 여러분 자신이 직접 에러를 처리해야 한다. C에서는 매크로가 이 작업에 매우 유용할 것이다.
#define CHECK(LINE, EXPECTED) \
    { int rc = LINE; \
    if (rc != EXPECTED) \
        ut_abort(__FILE__, __LINE__, #LINE, rc, EXPECTED); }

void ut_abort(char* file, int ln, char* line, int rc, int exp) {
    fprintf(stderr, "%s line %d\n'%s': expected %d, got %d\n",
        file, ln, line, exp, rc);
    exit(1);
}

그러면 다음을 사용해서 결코 실패하면 안 되는 호출을 감쌀 수 있다.

check(stat("/tmp", &stat_buff), 0);

만약 실패한다면, stderr에 다음과 같은 메시지가 출력될 것이다.

source.c line 19
'stat("/tmp", &stat_buff)': expected 0, got -1

분명히 실행 중인 프로그램을 그냥 종료해 버리는 것은 때로 적절치 못하다. 해제되지 않은 자원이 남아 있을 수도 있고, 로그 메시지를 기록 할 필요가 있을 수도 있고, 열려있는 트랜잭션을 청소해야 하거나, 다른 프로세스들과 상호작용해야 할 필요가 있을지도 모른다. 그렇지만 기본 원칙은 똑같다. 방금 불가능한 뭔가가 발생했다는 것을 코드가 발견한다면, 프로그램은 더 이상 유효하지 않다고 할 수 있다. 이 시점 이후로 하는 일은 모두 수상쩍은 게 된다. 되도록 프로그램을 빨리 종료해야 할 일이다. 일반적으로, 죽은 프로그램이 입히는 피해는 절름발이 프로그램이 끼치는 것보다 훨씬 덜한 법이다.

 
실용주의프로그래머
카테고리 컴퓨터/IT > 프로그래밍/언어
지은이 앤드류 헌트 (인사이트, 2007년)
상세보기

'Archive' 카테고리의 다른 글

리소스의 할당과 해제  (0) 2011.10.03
예외는 예외적인 문제에 사용하라  (0) 2011.10.03
타인의 버그를 대하는 자세  (0) 2011.10.02
GUI와 쉘  (0) 2011.10.02
예광탄 코드와 프로토타이핑의 차이점  (0) 2011.10.02
  
 «이전 1 ··· 9 10 11 12 13 14 15 ··· 17  다음»