블로그 이미지
윤영식
Full Stacker, Application Architecter, KnowHow Dispenser and Bike Rider

Publication

Category

Recent Post

2013. 9. 7. 16:07 Languages/JavaScript

구글러 오스마니님의 JavaScript Design Pattern 글에서 패턴을 요약해 본다. 생성자 패턴에 대해 알아보자 



개념

  - 자바스크립트는 모든것이 오브젝트이다 

  - Object constructor가 지정한 타입의 오브젝트를 생성하는데 사용한다 

 


Object Creation

  - 오브젝트를 만드는 3가지 기본 방법 

    비어있는 오브젝트를 만들어 리턴하는 것이다 

var newObject = {};


var newObject = Object.create( null );


var newObject = new Object();


  - 오브젝트에 Key, Value 할당하는 4가지 방법

// 1. Dot syntax

newObject.someKey = "hi dowon";

var key = newObject.someKey;


// 2. Square bracket syntax

newObject["someKey"] = "hi youngsik";

var key = newObject["someKey"];


// ECMAScript 5 olny

// 3. Object.defineProperty

Object.defineProperty( newObject, "someKey", {

  value: "hi dowon",

  writable: true,

  enumerable: true,

  configurable: true

});


var defineProp = function( obj, key, value ) {

  config.value = value;

  Object.defineProperty( obj, key, config);

};


var person = Object.create( null );

defineProp( person, "car", "Seoul");

defineProp( person, "house", "apt");


// 4. Object.defineProperties

// set properties

Object.defineProperties( newObject, {

   "someKey": {

     value: "hi dowon",

     writable: true

   }, 

   "anotherKey": {

      value: "youngsik",

      writable: false

    }

});



Basic Constructors

  - Constructor Function에 new 키워들 사용하여 신규 오브젝트를 생성한다

  - Constructor Function안의 this는 새로 생성된 오브젝트의 레퍼런스이다 

// define constructor function

function Car(model, price) {

  this.model = model;

  this.price = price;

  

  this.toString = function() {

    return this.model + ', ' + this.price;

  }

}


// new로 생성하면 Car.prototype을 통하여 신규 오브젝트를 만들어 주소를 넘겨주면 hd가 주소 레퍼런스를 가진다

var hd = new Car('santafe', 1000);


// 찍어보자

Car {model: "santafe", price: 1000, toString: function}


  - Function은 prototype 프로퍼티를 가지고 있다. prototype은 객체를 레퍼런스를 하는데 별도로 지정하지 않으면 자신의 property 객체를 레퍼런스 한다. 여기서 Car.property 는 Car.property 객체를 레퍼런스 한다  

function Car(model, price) {

  this.model = model;

  this.price = price;

}


Car.prototype.toString = function() {

  return this.model + ', ' + this.price;

}


console.log(hd.toString());

kia, 5000


  Car Constructor Function은 {this.model: <value>, this.price: <value>, prototype: Car.prototype}  가 되고, Car.prototype 객체는 {constructor: Car, toString: function() {...}} 이다. Car Constructor Function의 prototype 프로퍼티는 Car.prototype 객체를 레퍼런싱하고, Car.prototype객체의 constructor 프로퍼티를 통하여 Car Constructor Function을 레퍼런싱하여 상호 참조한다. prototype와 constructor 프로퍼티는 writable이다. 이를 이용해 JavaScript의 Prototypal Inheritance 방식을 사용할 수 있다.



<참조>

  - 오스마니 생성자패턴

  - JavaScript Prototype

posted by 윤영식
2013. 9. 7. 12:56 Git, GitHub/GitHub

깃헙에 아이디를 가지고 있다면 http://<id>.github.io 형식의 정적 홈페이지를 만들어 퍼블리싱 할 수 있다. AngularJS와 Bootstrap을 가지고 린(Lean)하게 자신의 홈페이지를 만들어 보자. 자신의 홈페이지를 한두시간만에 만들 수 있다. AngularJS와 Bootstrap을 사용하기 때문에 정적 홈페이지를 SPA(Single Page Application) 타입으로 클라이언트(브라우져)에서 서버의 도움(통신)없이 애플리케이션처럼 구동 될 수 있도록 만들 수 있다.  예) 쥔장 홈페이지 : http://ysyun.github.io/



1. 깃헙 계정 및 레파지토리

  - https://github.io/ 에서 계정을 만든다 

  - <id>.github.io 레파지토리를 만든다. 예) 계정이 ysyun 이라면 레파지토리는 ysyun.github.io (저장소 이미 만들었음)

     * 주의 : <id>.github.com 이 아니라 <id>.github.io 이다. 

  

  - 로컬 PC에서 git clone 한다 

$ git clone https://github.io/<ID>/<ID>.github.io.git

예)

$ git clone https://github.io/ysyun/ysyun.github.io.git

   


2. AngularJS와 Bootstrap 템플릿 사용하기

  - AngujarJS+Bootstrap Seed를 git clone 한다 

$ git clone https://github.io/lbehnke/angularjs-bootstrap-seed.git

$ cd angularjs-bootstrap-seed/app 


//app 디렉토리에 있는 모든 파일을 <ID>.github.io 디렉토리에 copy한다

$ copy *  <id.github.io 디렉토리>


  - index.html 에서 보여주고 싶은 메뉴를 수정한다. 반드시 메인 페이지는 index.html이고 root 에 위치해야한다

    간단한 자기소개와 그동안 만들었던 제품에 대한 포트폴리오를 넣었다 

<!-- Navigation -->

    <div class="navbar navbar-inverse navbar-fixed-top">

        <div class="navbar-inner">

            <div class="container">

                <a class="btn btn-navbar" data-toggle="collapse" data-target=".nav-collapse">

                    <span class="icon-bar"></span>

                    <span class="icon-bar"></span>

                    <span class="icon-bar"></span>

                </a>

                <a class="brand" href="#/intro">Yun Young Sik</a>

                <div class="nav-collapse collapse">

                    <ul class="nav">

                        <li class="active"><a href="#/intro">Intro</a></li>

                        <li class="dropdown">

                            <a href="#" class="dropdown-toggle" data-toggle="dropdown">Portfolio <b class="caret"></b></a>

                            <ul class="dropdown-menu">

                                <li><a href="#/smartdashboard">Smart Dashboard</a></li>

                                <li><a href="#/edashboard">Pharos e-Dashboard</a></li>

                                <li><a href="#/pharosjava">Pharos Java</a></li>

                            </ul>

                        </li>

                        <!-- <li><a href="#/contact">Contact</a></li> -->


                    </ul>

                </div><!--/.nav-collapse -->

            </div>

        </div>

    </div>


  - app.js 에서 routing정보를 수정한다. AngularJS의 routing 정보이다 

angular.module('myApp', ['myApp.filters', 'myApp.services', 'myApp.directives']).

  config(['$routeProvider', function($routeProvider) {

    $routeProvider.when('/intro', {templateUrl: 'partials/intro.html', controller: GenericViewCtrl});

    $routeProvider.when('/smartdashboard', {templateUrl: 'partials/smartdashboard.html', controller: GenericViewCtrl});

    $routeProvider.when('/edashboard', {templateUrl: 'partials/edashboard.html', controller: GenericViewCtrl});

    $routeProvider.when('/pharosjava', {templateUrl: 'partials/pharosjava.html', controller: GenericViewCtrl});

    $routeProvider.when('/project_b', {templateUrl: 'partials/project_b.html', controller: GenericViewCtrl});

    $routeProvider.when('/contact', {templateUrl: 'partials/contact.html', controller: ContactViewCtrl});

    $routeProvider.when('/imprint', {templateUrl: 'partials/imprint.html', controller: GenericViewCtrl});

    $routeProvider.otherwise({redirectTo: '/intro'});

  }]);



3. GitHub Push

  - git push를 통하여 <id>.github.io 레파지토리에 올린다 

$ git push

Counting objects: 10, done.

Delta compression using up to 4 threads.

Compressing objects: 100% (6/6), done.

Writing objects: 100% (6/6), 680 bytes | 0 bytes/s, done.

Total 6 (delta 4), reused 0 (delta 0)

To https://github.io/ysyun/ysyun.github.io.git

   328f41e..ca12f7e  master -> master


  - push하고 5~10분후에 http://<ID>.github.io 을 호출한다 (웹퍼블리싱에 약간의 시간이 소요된다)


두시간 정도만 투자해 보자. 여러분의 멋진 github 홈페이지를 가질 수 있다 



<참조>

  - http://ID.github.io 홈페이지 만들기 

  - github-pages

posted by 윤영식
2013. 9. 4. 14:05 AngularJS/Start MEAN Stack

Mobile 서비스 개발을 위하여 JavaScript 기반의 기술 스택을 선택하여 사용하다 보니 1년사이에 MongoDB, Express.js, Angular.js, Node.js를 공부하고 솔루션에 적용하게 되었다. 그간 해당 기술들을 추상화한 프레임워크들을 사용하여 개발을 진행해 왔다. 그러나 가끔 풀리지 않는 문제에 대한 근원적인 해결책을 찾는데는 다시 처음부터 추상화 내역에 대한 이해가 바탕이 되지 않으면 풀리지 않았다. 


즉, 기본 스택을 추상화한 스택사용시에는 추상화 영역에 대한 사용경험과 전반적인 이해가 없이는 오히려 시간공수만 더 늘어나는 격이 된다. 예로 Express와 MongoDB를 좀 더 수월하게 사용키위하여 Trains, Sails Framework들을 사용해 보았고 나름의 장점은 있으나 왠지 남의 옷을 입은듯한 느낌이랄까? 문제 발생시 빠른 대응이 어려웠다 (개인적으론 Trains Framework의 Node.js단의 IoC 방식을 좋아한다)


따라서 소규모 팀으로 개발하면서 하나의 가치를 빠른 시간안에 전달하고자 한다면 기본 Stack기반으로 진행하면서 필요한 시점에 스스로 추상화 모듈을 만들어 사용하는 방법이 좋지 않을까 생각한다. (Don't Invent Wheel 이니 초기엔 쓸만한 것을 GitHub에서 찾아 응용하고 없으면 개발하자) 그런 의미에서 mean.io 에서 기본 Stack에 충실하면서 현재 사용되는 최신 개발 기술들 - Jade, Bootstrap, Mongoose, Bower, Grunt 같은 - 도 함께 접목되어 적당히 어려운 상태이므로 개발시 집중(Flow)을 가능케 하는 구조를 가지고 있다. (너무 어려우면 흥미를 읽고, 너무 쉬우면 긴장감이 떨어진다. 적당히 어려우면 흥미와 긴장감을 주어 개발시 집중을 가능케 한다) 



1. 설치

  - 홈페이지에서 zip 파일 다운로드 

  - 프로젝트로 이동해서 

$ cd mean


// 사전에 node.js 설치 

// Node, npm 설치 shell

$ npm install .

 

// 사전에 mongodb 설치하고 start

$ grunt



2. 접속 

  - http://localhost:3000/

    + Sign Up 할 수 있다

    + 테스트 글을 CRUD 할 수 있다 

    


  - MongoDB 

> show collections

articles

sessions

system.indexes

users


해당 스택을 통해 SPA(Single Page Application) 개발에 대한 Lean(신속한) 스타트업을 시도하자.

 


<참조>

  - mean.io

posted by 윤영식
2013. 8. 30. 17:24 Languages/JavaScript
자바스크립트 개발시 피해야하는 중요한 3가지 사용패턴에 대해서 알아보자 


1. Object 상속에 의한 오염

  - Object의 prototype을 통하여 확장을 하지마라

  - 예를 보자 

    두번째 Object.prototype.e 를 확장하면 모든 오브젝트에 e="E"가 불필요하게 반영된다. 즉 모든 오브젝트에 상속된다 

var obj = {a: "A", b: "B", c: "C", d: "D"};
for (var key in obj) {
   alert(key +': '+obj[key]); //displays "a: A", "b: B", "c: C", "d: D"
}
 
// Anti-Pattern
Object.prototype.e = "E";
for (var key in obj) {
   alert(key +': '+obj[key]); //displays "a: A", "b: B", "c: C", "d: D", "e: E"
}
 
var obj2 = {a2: "A2", b2: "B2", c2: "C2", d2: "D2"};
for (var key in obj2) {
   alert(key +': '+obj2[key]); //displays "a2: A2", "b2: B2", "2c: C2", "d2: D2", "e: E"

}

  - 상속의 방법

function Person(name, sex) { 

  Person.prototype.populationCount++; 
  Person.prototype.getName=function(){ return name }; 
  Person.prototype.getSex=function(){ return sex }; 
  Person.prototype.setSex=function(newSex){ sex = newSex; }; 
  Person.prototype.die=function(){ Person.prototype.populationCount -- ; };
}
Person.prototype.populationCount=0;
 
var rob = new Person('Rob','male');
var jeanie = new Person('Jeanie','female');
alert(rob.populationCount);  // displays 2
 
//the following creates a new public property for rob and sets it to 12
rob.populationCount+=10;
alert(rob.populationCount); //displays 12
alert(jeanie.populationCount); //still displays 2
 
Child.prototype = Object.create(Person.prototype);
Child.prototype.constructor = function Child(name, sex, age) {
    //call the parent constructor
    Person(name, sex);
    Child.prototype.getAge = function() { return age; };
}
var child = new Child('Ralph', 'male', 3);
 
alert(child.getName()); //displays "Ralph"
alert(child.getAge());  //displays 3



2. Global Namespace에 의한 오염

  - 보통 var를 사용하지 않고 x=2 처럼 하면 window.x=2가 되어 전역영역을 오염시킨다. 따라서 변수선언시 반드시 var 를 사용한다 

  - Group 변수를 통해서 오염을 방지하자 

   var Finance = {};

Finance.INTEREST_RATE = 2.5;
Finance.calcAnnualizedInterest(startVal, endVal) {
  //...
}

  - 또는 ECMAScrpt 5 "use strict"를 script 맨위체 포함시킨다. 또는 function 안에 놓고 제한된 scope에서 strict mode를 사용할 수도 있다

  function strictFunc(){

  "use strict";
  // code ...
}

  - 예를 보자 

    i 의 결과값으로 5가 나온다. Global Namespace를 오염시키는 function - foo, bar -, variable - i - 같은 것은 절대 사용하지 말자 

function foo() { return 1; }

function bar() { for (i=0; i<5; i++) {} }

 

i = foo();

bar();



3. True, False에 대한 부적절한 사용에 의한 오염 

  - 자바스크립트에서 zero (0), empty string (""), null, undefined, NaN 은 모둔 false 값이다 

  - 비교문이나 루프문에서 조건 사용시 축약한다  

// Anti-Pattern

if (testString != undefined && testString != '') {

  //do something

  }


// 변경 : 위 조건절과 동일 

if (!testString) {

  //do something
}

  - ===, ==! 를 항상 사용한다 

// 주의

   var zero = 0;

if (zero === false) {
  // doesn't execute because zero is 0, not false
}



<참조>

  - 원문 : Three JavaScript Anti-Patterns and How to avoid them

  - Another Anti-Patterns 

  - Anti-Patterns를 피하고 성능을 향상시키는 방법들 : Slide 및 동영상

posted by 윤영식
2013. 8. 23. 10:40 Lean Agile Culture/Lean Startup
페이스북의 글이 너무 좋아서 그냥 막 펐습니다. 

윤석찬
 · 2,243명이 좋아합니다.
2시간 전 · 
  • 정부에서 창조 경제의 일환으로 IT 기반 지식을 통한 융합 인재를 양성하겠다고 초등생 부터 프로그래밍 교육 개설에 열의를 가지고 있죠? 아마 얼마전 나온 Cod dot org의 아래 동영상이 큰 영향을 준것 같습니다.
    http://www.youtube.com/watch?v=lHZxmcP-CHI

    최근에는 일부 대학들도 교양 필수 과목으로 프로그래밍 교육을 하려는 움직임을 보였고, 그 중에 한 대학이 저에게 문의를 해와서 제가 드린 소견을 잠시 소개하고자합니다.

    사실 프로그래밍이 별로 필요없는 대부분 분야 교수님은 반발이 심하다고 합니다. 프로그래밍이 아니라 전공별 요구되는 전산 관련 활용(예: SPSS나 그래픽 SW 활용)을 배워야지 전공 구분 없이 모든 학생들에게 프로그래밍을 배우는 것은 무리가 있다다는 것이죠. 

    예를 들어, 생명과학부 학생중에 생물정보학을 전공하는 학생도 있지만, 순수 연구만 하는 학생들이 더 많은데, 그런 학생들조차 프로그래밍을 배워야 한다는 것은 많은 학생들에게 고통을 주는 것이라는 것입니다. 

    이런 인식은 프로그래밍 교육이 가지고 있는 사고적 변화와 문제 해결 능력 배양 같은 근본적인 목적 보다는 "SW 도구 활용"이나 "언어 교육"같은 실용적인 측면에서만 바라보기 때문에 생기는 오해인 것 같습니다. 따라서, 교양 과목 답게 "사고와 활용"이라는 양측면이 강조된 두 가지 교육 과목을 한번 제안해 봅니다. 

    1. 전산적 사고 (Computational Thinking)
    우선 "전산적 사고(Computational Thinking)"라는 수업을 개설하시길 권해 드립니다. 컴퓨터로 이해하는 각종 알고리즘과 문제 해결 절차 방법론을 배우고, 향후에 어떤 수준의 프로그램을 짜더라도 그쪽을 이해할 수 있는 보편적 능력을 갖는게 중요하기 때문입니다.

    프로그래밍 언어 교육 보다 선행되어야 할 수업 내용으로 미국 초중고에서 CS(전산과학) 입문용 과목까지 광범히 하게 진행되고 있습니다. 아래에는 커리큘럼과 교육용 예제를 자세하게 참고할 수 있습니다. 
    http://www.google.com/edu/computational-thinking/
    http://scratched.media.mit.edu/resources/computational-thinking
    http://www.iste.org/learn/computational-thinking
    http://www.cs.cmu.edu/~CompThink/index.html

    국내에서는 포항공대 황승원 교수님이 2007년에 교양 교과목으로 한번 개설하신 바 있습니다.
    http://www.postech.edu/~swhwang/ct.html
    (FAQ 참조: http://webcache.googleusercontent.com/search?q=cache%3AaFohHRkYWGQJ%3Awww.postech.ac.kr%2F%7Eswhwang%2Fctfaq.hwp )

    전산 사고 훈련을 하다보면 필수적으로 컴퓨터 언어의 구조에 대해 이해하게 되고, 숙제를 위해서 간단한 언어 하나씩은 배울 수 있게 됩니다. 언어는 도구라서 특정하지 말고, 과외 학습으로 문제 풀이를 위한 방법으로 자연스럽게 익히도록 해 주는게 좋겠습니다.

    2. 크리에이티브 엔지니어링(Creative Engineering)
    두번째 교과목은 뭔가를 만들어서 세상에 이바지 해보자는 목적이면 좋을 것 같습니다. 이를 위해서는 아주 쉽게 뭔가를 만들어 볼수 있는 서버 인프라, 프론트, 백엔드, API를 모두 조금씩 활용할 수 있는 가벼운 방법을 사용해 보는게 좋겠습니다.

    추천할 만한 커리큘럼으로 현재 스탠포드대에서 코세라에 개설한 Startup Engineering와 제가 제주대에서 강의했던 클래스를 잘 섞으면 잘 나올 것 같습니다.
    https://www.coursera.org/course/startup
    http://code.google.com/p/web-engineering-class/

    무엇 보다 중요한 것은 자기 전공과 관련된 간단한 아이디어를 직접 구현하는 프로젝트를 병행하게 하는 것일 것 같습니다. 예를 들어, 복지 전공인 경우 자기 지역의 복지시설을 지도에 매핑하는 서비스를 만들어 본다던지, 어문학 전공자라면 간단한 사전 서비스를 만들어 본다던지, 특정 해외 문화에 대한 정보를 제공하는 모바일 페이지라던지요.

    그냥 HTML로 문서를 만드는 게 아니라 간단한 기능을 추가하게 하고, 코드를 github에 공개하고 이를 직접 아마존 웹서비스 같은데 올려 실제 동작하게 하는 것을 해보는 것만으로도 큰 성취감을 얻을 수 있을 것 같네요.

    그 외에 비 전공자로서 더 배우고 싶은 학생들을 위해 심화 트랙을 하나 기본 전산학과나 컴퓨터 광학과에 두어 비전산 전공자를 위한 가벼운 커리큘럼을 운영하시도록 하는게 좋을 듯 합니다. 

    대부분 전산 교육은 MS 오피스나 포토샵 같은 "소프트웨어 도구 활용법"이거나, C/PHP/Java 같은 "프로그래밍 언어 습득"에 한정되는 경우가 많습니다. 전산적 사고를 배우고, 이를 기반으로 자신이 관심이 있는 문제를 해결하는 실용적인 프로그래밍 기술을 가르쳐 준다면, 더 많은 인재들이 IT를 활용한 창조적인 아이디어에 도전할 수 있을 것입니다.


posted by 윤영식