함수와 메소드의 차이

Posted by epicdev Archive : 2013. 4. 18. 00:02

여태껏 함수와 메소드, 변수와 필드등의 용어들을 혼재해서 막 써왔었는데 이번 기회에 확실하게 기억해 놓아야 겠습니다.

아래의 표를 보시면 각 객체지향언어에서 멤버 변수와 멤버 함수들을 어떻게 지칭하는지 알 수 있습니다.


출처: http://blog.naver.com/cdincdin?Redirect=Log&logNo=30129625682



  

Java에서 중첩 루프 한번에 탈출 하는법

Posted by epicdev Archive : 2012. 1. 26. 22:22
중첩 루프를 돌면서 어떠한 조건이 만족하면 탈출하는식의 코드를 자주 코딩을 하게 된다.
이런 유형은 대개 아래와 같다.

일반적으로 이런 경우에는 아래와 같은 방법으로 코딩을 하게 된다.
혹은 중첩 루프를 함수로 만들어서 if 절 안의 break를 return으로 바꿔서 한번에 루프를 탈출하는 방법을 쓰기도 한다.
C++의 경우 goto를 사용하면 더 간단하게 이 문제를 해결할 수 있다.
물론 goto는 무조건 사용하지말라고 배웠다면 이러한 방법이 꺼려지겠지만,
거의 유일하게 goto를 써도 욕을 먹지 않는 경우가 바로 아래의 경우이다.
flag에 대한 설명을 주저리 주저리 할 필요도 없고, 코드의 가독성 또한 훨씬 높아진다.
하지만 Java에서는 goto문이 없다. 즉, C++에서처럼 goto를 사용해서 중첩 루프를 탈출 할 수 없다는 것이다.
하지만 Java에서는 이와 비슷한 다른 문법적 장치가 있다.
Java에서는 위와 같이 코딩을 하면 중첩 루프를 한번에 탈출할 수 있다.
왜 이런지 이해가 되지 않는다면 아래처럼 named block을 사용했다고 생각하면 된다.
혹은
  

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

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 블록이 우리가 뜻하는 바를 이렇게 간결하게 표현 해 준다.


 
  

const identifiers are often better than #define because:

they obey the language’s scoping rules
you can see them in the debugger
you can take their address if you need to
you can pass them by const-reference if you need to
they don’t create new “keywords” in your program.
In short, const identifiers act like they’re part of the language because they are part of the language. The preprocessor can be thought of as a language layered on top of C++. You can imagine that the preprocessor runs as a separate pass through your code, which would mean your original source code would be seen only by the preprocessor, not by the C++ compiler itself. In other words, you can imagine the preprocessor sees your original source code and replaces all #define symbols with their values, then the C++ compiler proper sees the modified source code after the original symbols got replaced by the preprocessor.

There are cases where #define is needed, but you should generally avoid it when you have the choice. You should evaluate whether to use const vs. #define based on business value: time, money, risk. In other words, one size does not fit all. Most of the time you’ll use const rather than #define for constants, but sometimes you’ll use #define. But please remember to wash your hands afterwards.

  
 «이전 1  다음»