본문으로 건너뛰기

"interview" 태그로 연결된 3개 게시물개의 게시물이 있습니다.

모든 태그 보기

나를 위한 면접 (Backend Developer Interview Questions)

· 약 27분

BE Interview Questions를 아는 만큼 답해보았다 지극히 주관적이라 정답이 아닐 수 있습니다

Why are global and static objects evil?

  • 전역변수는 어디서 변경되었는지 추적이 힘듦
  • 그리고 자바의 경우 콜스택이 끝나면 비워지는 지역변수와 달리 메모리의 static 영역에 계속 상주해 있음

Tell me about Inversion of Control and how does it improve the design of code

  • 클래스 안에 다른 클래스의 기능이 필요하다면 내부에서 생성자를 이용해 두 클래스 간의 종속이 생겨버리는데
  • IoC를 통한다면 DI 패턴으로 구현해 new A(new B()) 처럼 종속성을 분리시킬 수 있음
  • TypeHint를 통해 의존성을 확인할 수 있으므로 더 직관적이기도 하다
  • What is Inversion of Control?

Active-Record is the design pattern that promotes objects to include functions such as Insert, Update, and Delete, and properties that correspond to the columns in some underlying database table. In your opinion and experience, which are the limits and pitfalls of the this pattern?

  • 장점
    • 하나의 구조로 모든 모델을 제어할 수 있게 해준다.
    • 또한 모든 DB 마다 다른 쿼리문 (예를 들어 페이징)을 손쉽게 처리할 수도 있다.
    • 무엇보다 엄청 빠르게 DB 조작이 가능해진다.
  • 단점
    • DB를 잊어버리게 되는 것 아닐까? ActiveRecord로 개발을 시작하는 건 아니다라고 본다.
    • 여러 테이블의 조인이 힘들고 (조인 조건을 만족하기 위해) 계산이 들어간 쿼리문이라면 어차피 RAW 쿼리를 날려야한다.
    • 프로시져를 사용할 수도 없고, 관계형 모델들은 select를 키값을 통해 여러 번 select 한 뒤 합쳐주는 것 뿐이라 성능상의 이슈도 있다.
    • 결국 필요한 곳에서만 (RESTful 구조의) 사용해서 개발하는 게 좋을 것 같다

Data-Mapper is a design pattern that promotes the use of a layer of Mappers that moves data between objects and a database while keeping them independent of each other and the mapper itself. On the contrary, in Active-Record objects directly incorporate operations for persisting themselves to a database, and properties corresponding to the underlying database tables. Do you have an opinion on those patterns? When would you use one against the other?

The big benefit of the Data Mapper pattern is, your domain objects don't need to know anything about how they are stored in the database. This means that your objects will be lighter because they don't have to inherit the full ORM, but also there will be a stricter, more formal process for interacting with the database because you can't just call the save() method anywhere in your code

Why it is often said that the introduction of null is a "Billion dollar mistake"? Would you discuss the techniques to avoid it, such as the Null Object Pattern introduced by the GOF book, or Option types?

  • null 로 변수를 생성하는 건 안하는 거랑 똑같지만, 안 해주면 프로그램이 뻗어버려서 null 타입 체크를 하거나 default값을 추가한다.
  • 10억 달러짜리 실수

Many state that, in Object-Oriented Programming, Composition is often a better option than Inheritance. What's you opinion?

What is an Anti-corruption Layer?

  • 추상화 한 레이어를 하나 더 두고 하위 도메인들을 쉽게 접근할 수 있게 하는 방법, facade 처럼

Singleton is a design pattern that restricts the instantiation of a class to one single object. Writing a Thread-Safe Singleton class is not so obvious. Would you try?

  • Volatile

How would you deal with Dependency Hell?

  • 의존성 컨테이너를 사용한다.
  • 패키지 매니저툴을 이용하며 버전을 명시한다.
  • maven, composer, npm 등등

Is goto evil?

  • 적절하게, 가독성 있게 사용하면 괜찮다.
  • 리눅스 커널 이런 느낌으로

Code Design

It is often heard that one of the most important goals in Object-Oriented Design is to have High Cohesion and Loose Coupling. What does it mean? Why is it that important and how is it achieved?

  • Coupling
    • 모듈 간에 상호 의존하는 정도
    • 각 모듈 간의 결합도가 약해야 하며 의존하는 모듈이 적어야한다.
    • 결합도가 강하면 시스템 구현 및 유지보수 작업이 어렵다.
  • Cohesion
    • 정보 은닉 개념을 확장한 것
    • 명령어나 호출문 등 모듈의 내부 요소들의 서로 관련되어 있는 정도
    • 모듈이 독립적인 기능으로 정의되어 있는 정도
    • 독립적인 모듈이 되기 위해서는 각 모듈의 응집도가 강해야한다

Why does array index start with '0' in most of languages?

  • 배열이 참조하는 메모리의 위치를 나타내므로 (시작 위치에서의 기준점)

Are comments in code useful? Some say they should be avoided as much as possible, and hopefully made unnecessary

  • 변수명, 메소드명으로 명확하게 표현할 수 있으면 좋은데, 그러긴 현실적으로 힘들고
  • JSDoc 같은 구문으로 주석을 단다면 참조하는 다른 소스에서도 hover만으로 모든 설명을 볼 수 있어서도 좋고

What is the difference between design and architecture?

  • Software architecture is more about the design of the entire system, while software design emphasizes on module / component / class level.
  • Architecture: MVC, 3-tier layered design, etc.
  • Design: What are the responsibilities, functions, of module x? Of class Y? What can it do, and what not?
  • Software Design vs. Software Architecture

C++ supports multiple inheritance, and Java allows a class to implement multiple interfaces. What impact does using these facilities have on orthogonality? Is there a difference in impact between using multiple inheritance and multiple interfaces? Is there a difference between using delegation and using inheritance?

  • implements가 좀 더 유연하다 클래스 안에서 직접 구현해야되는거니까

Pros and cons of holding domain logic in Stored Procedures

  • 장점
    • 한 번 만든걸 계속 호출해서 쓸 수 있음
    • 컴파일 언어의 경우 쿼리만 변경하는거니 유지보수가 좋을 수 있음
    • 계산이 들어가는 쿼리의 경우 SP는 캐싱되므로 이만한게 없음
  • 단점
    • DB에 완전 종속됨
    • DBA가 있어야함
    • git에서 변경점 추적 불가능

In your opinion, why have Object-Oriented Design dominated the market for so many years?

  • 관심사의 분리

Languages

Tell me the 3 worse defects of your preferred language

  • PHP
    • 컴파일 언어가 아니라 느림 (PHP7부턴 달라짐, OpCache를 사용하면 되긴함)
    • 쓰레드가 없음 (PHP React나 Guzzle promise 같은 걸 사용하면 event driven 방식으로 되긴 함)
    • 인식이 안 좋음
    • 함수명이 너무 제각각임 (어떤 건 snake_case 어떤건 붙혀서)

Why is there a rising interest on Functional Programming?

  • 각 실행 단계를 이뮤터블로 만들어 Side effect를 없앤다.
  • 테스트가 쉽다.
  • 가독성이 높아진다

What is a closure, and what is useful for? What's in common between closures and classes?

  • FE 인터뷰에 정리해놓았다

What are generics useful for?

  • 타입 캐스팅

What are high-order functions? What are they useful for?

  • 함수를 파라미터로 전달받거나, 함수를 리턴하는 함수로 다형성을 지원해 재사용이 가능하다

What does it mean when a language treats functions as first-class citizens?

  • 변수나 데이터에 할당 가능
  • 파라미터로 넘길 수 있어야함
  • 리턴값으로 리턴이 가능해야함

Show me an example where an Anonymous Function can be useful

  • 모든 콜백에서 유용함

Whats the Stack and what's the Heap? What's a Stack Overflow?

  • Stack: LIFO
  • Heap: 최소 또는 최대 값이 루트에 있는 완전 이진 트리
  • Stack Overflow: 지식인 또는 Stack이 꽉 찼는데 삽입하려 들 때

Some languages, especially the ones that promote a Functional approach, allow a technique called Pattern Matching. Do you know it? How is Pattern Matching different from Switch clauses?

  • C#에서 is 구문을 말하는건가?
  • switch는 하나의 타입에서만 비교가 가능한데, 패턴매칭을 쓰면 더 동적으로 비교가 가능하다

If Cat is an Animal

is TakeCare<Cat> a TakeCare<Animal> ?

  • 같지는 않지만 집어넣을 수는 있다

In the last years there has been a lot of hype on Node. What's your opinion on the use in the back end of a language that was initially conceived to run in the browser?

  • Atwood's Law: any application that can be written in JavaScript, will eventually be written in JavaScript.

참고

Web development

Why first-party cookies and third-party cookies are treated so differently?

  • first-party cookie
  • 자사 쿠키는 방문하는 웹사이트가 설정하며 해당 사이트에서만 사용
  • third-party cookie
  • 타사 쿠키에서 분석 등의 용도로 사용

How would you manage Web Services API versioning?

  • 시맨틱 버저닝

From a Back End perspective, are there any disadvantages or drawbacks on the adoption of Single Page Applications?

  • 백엔드 관점
  • 장점: 웹을 SPA로 가면 API가 필요하고, 디바이스 확장성에 대해 좋음
  • 단점: SEO 때문에 어차피 SSR 해줘야됨

Why do we usually put so much effort for having stateless services? What's so good in stateless code and why and when statefullness is bad?

REST and SOAP: when would you choose one, and when the other?

In Web development, Model-View Controller and Model-View-View-Model approaches are very common, both in the Back End and in the Front End. What are they, and why are they advisable?

  • MVC
    • Controller로 사용자의 입력이 들어옵니다.
    • Controller는 Model을 데이터 업데이트 및 불러오고
    • Model은 해당 데이터를 보여줄 View를 선택해서 화면에 보여주게 됩니다.
  • MVVM
    • View에 입력이 들어오면 Command 패턴으로 ViewModel에 명령을 합니다.
    • ViewModel은 필요한 데이터를 Model에 요청 합니다.
    • Model은 ViewModel에 필요한 데이터를 응답 합니다.
    • ViewModel은 응답 받은 데이터를 가공해서 저장 합니다.
    • View는 ViewModel과의 Data Binding으로 인해 자동으로 갱신 됩니다.
  • MVC, MVP, MVVM 비교

Databases

How would you migrate an application from a database to another, for example from MySQL to PostgreSQL? If you had to manage that project, which issues would you expect to face?

  • Oracle => MySQL
  • date 처리에서 애를 먹었는데, 덤프를 바로 옮기지 않고 데이터를 가져와 다시 넣는 방식으로 마이그레이션 했다
  • Right join (+ 조인)을 Left로 바꾸는데 시간이 걸렸다
  • MySQL => Maria
  • 완벽 호환, utf8mb4로 콜렉션과 차셋도 바꿔줌

Why databases treat null as a so special case? For example, why in SQL SELECT * FROM table WHERE field = null does not match records with null field?

  • 저걸 처리하기 위해선 IS NULL 구문을 사용해야함

ACID is an acronym that refers to Atomicity, Consistency, Isolation and Durability, 4 properties guaranteed by a database transaction in most of the database engines. What do you know about this topic? Would you like to elaborate?

  • 원자성
    • Atomicity
    • 트랜잭션 내의 명령은 반드시 완벽히 수행
    • 모두가 수행되거나 오류시 전부가 취소되어야함
  • 일관성
    • Consistency
    • DB의 전체 요소는 트랜잭션 수행 전과 트랜잭션 수행 완료 후의 상태가 같아야함
  • 독립성
    • Isolation = 격리성 = 순차성
    • 둘 이상의 트랜잭션이 병행 실행되는 경우 다른 트랜잭션 연산이 끼어들 수 없음
    • 수행 중인 트랜잭션은 완료될 때 까지 다른 트랜잭션에서 참조 불가
  • 영속성
    • Durability = 지속성
    • 시스템이 고장나도 영구적으로 반영

How would you manage database schema migrations, that is, how would you automate the changes a database schema is affected to, as the application evolve, version after version?

  • 프레임워크에서 migration 기능을 지원한다면 그걸 사용할 것이다

How is Lazy Loading achieved? When is it useful? What are its pitfalls?

  • 장점: 실제 로직이 실행될 때 로드가 되므로, 자원 소모를 해당 액션이 실행되기 전까지로 미룰 수 있다
  • 단점: N+1 problem.

The so called "N + 1 problem" is an issue that occurs when the code needs to load the children of a parent-child relationship with a ORMs that have lazy-loading enabled, and that therefore issue a query for the parent record, and then one query for each child record. How to fix it?

  • Eager loading을 사용하거나 JPA의 경우 join fetch를 사용한다

In your opinion, is it always needed to use database normalization? When is it advisable to use denormalized databases?

  • 삽입, 삭제, 갱신 이상이 해결된다면, join의 감소를 위해 비정규화도 적절히 필요하다

NoSQL

What is Eventual Consistency?

데이터 삽입이 끝났지만 어떤 클라이언트에서는 업데이트 된 내용을 확인할 수 없다, 하지만 곧 확인할 수 있다

The Brewer's Theorem, most commonly known as the CAP theorem, states that in the presence of a Network Partition (the P in CAP), a system's designer has to choose between Consistency (the C in CAP) and Availability (the A in CAP). Can you think about examples of CP, AP and CA systems?

  • 일관성, 가용성, 분단허용성

  • Consistent - Available : Postgres, MySQL같은 전통적인 RBMS

  • Consistent - Partition Tolerant : BitTable, Hypertable, HBase, MongoDB, Terrastore, Redis, Scalaris, MemcacheDB, BerkeleyDB

  • Available - Partition Tolerant : Amazon Dynamo, Cassandra, CouchDB, Amazon SimpleDB, Riak

  • CAP Theorem, 오해와 진실

  • NoSQL에 대해서 #2

How would you explain the recent rise in interest for NoSQL?

  • Redis

In which case would you use a document database like MongoDB instead of a relational database like MySQL or PostgreSQL?

code versioning

Could you describe GitHub Flow and GitFlow workflows?

  • Git Flow: feature > develop > release > hotfix > master
  • GitHub Flow: feature 별 브랜치 > master, PR

What's a rebase?

  • 여러 브랜치를 하나의 브랜치(커밋)으로 합치기

Concurrency

Why do we need Concurrency, anyway?

  • I/O를 기다리지 않고 다른 일을 처리하고 싶을 때, CPU 코어들을 최대한 쓰고 싶을 때

Why is testing multithreading / concurrent code so difficult?

  • 언제 값이 변경되는지 잡기가 힘들어서

What is a Race Condition? Code an example, using whatever language you like

  • 두 개 이상의 스레드에서 공유된 리소스에 접근할 때 순서에 따라 결과가 달라지는 현상
  • for 문으로도 보여줄 수 있다

What is a Deadlock? Would you be able to write some code that is affected by deadlocks?

  • 이미 리소스를 점유한 스레드의 Lock이 해제될 까지 서로의 스레드가 계속 기다리는 현상

What is Process Starvation? If you need, let's review its definition

  • 우선 순위가 낮은 프로세스가 우선 순위가 높은 프로세스 때문에 계속 기다리는 현상

What is a Wait Free algorithm?

Distributed Systems

What are the Fallacies of Distributed Computing?

  • The network is reliable.
  • Latency is zero.
  • Bandwidth is infinite.
  • The network is secure.
  • Topology doesn't change.
  • There is one administrator.
  • Transport cost is zero.
  • The network is homogeneous.
  • Fallacies of distributed computing

When would you use Request/Reply and when Publish/Subscribe?

  • 클라이언트에서 요청을 한 뒤 업데이트가 되야하면 Request/Reply
  • 요청이 없어도 업데이트가 되야하면 Pub/Sub

Suppose the system you are working on does not support transactionality. How would you implement it from scratch?

  • 임시 테이블과 트랜잭션 성공테이블을 나눈다

Software Lifecycle and Team Management

What is the biggest difference between Agile and Waterfall?

  • 고객과의 커뮤니케이션
  • 일정 주기를 가지고 점진적인 기능개발

How would you manage a very late project

  • 차를 만들지 않고 바퀴부터 만들겠다
  • 앱 환경에 따라 나중에 개발할 부분을 먼저 찾겠다

Are Program Managers useful?

  • 항상 필요하다
  • 클라이언트나 보스로 부터의 의견 절충을 해주지 않으면 설계도가 나와 건물 다 올렸는데 철근 추가하는 미친 짓을 해야되니까.

logic and algorithms

How would you sort a 10GB file? How would your approach change with a 10TB one?

  • 머지 소트

How would you programmatically detect file duplicates?

  • contents를 md5나 sha1 해싱 후 비교

Software Architecture

When is a cache not useful or even dangerous?

  • 서버로 데이터를 전송할 때

Why does Event-Driven Architecture improve scalability?

  • 노드 간의 이벤트가 있을때마다 로직을 처리할 수 있어서
  • 의존성을 줄일 수 있어서
  • 장애 복구가 쉬워서 (이벤트만 발급)

Scale out vs scale up: how are they different? When to apply one, when the other?

  • Scale out: 서버 대수를 늘리는 것, 수평 스케일, 분산처리
  • Scale Up: 서버 제원을 늘리는 것, 수직 스케일, 서버가 부담을 받을 때

What is CQRS (Command Query Responsibility Segregation)? How is it different from the oldest Command-Query Separation Principle?

What is Three-Tier architecture?

  • HTTP를 처리하는 Web Server

  • 웹 애플리케이션을 실행하는 WAS(Web Application Server)

  • 그리고 DBMS 로 각각의 계층으로 분리하는 3 Tier 방식의 아키텍처

  • 3 Tier 아키텍쳐

  • 다층구조

How would you design a software system for scalability?

   => Front        => Back
LB => Front => LB => Back => DB => Replication DB
=> Front => Back
=> Static Resources

What are the strategies to deal with the C10k problem?

  • C10k
  • 하나의 시스템 당 동접 수가 10k를 효율적 운영방안
  • 이벤트 드리븐과 비동기, LB로 부하 분산, 세션 수 제한 (기다리게)

How would you design a decentralized (that is, with no central server) P2P system?

  • BlockChain Node와 SockJS로의 P2P 데이터 동기화

What are the disadvantages of the Publish-Subscribe pattern at scale?

  • 디버깅
  • sub에서 메시지를 받았는지는 모른다

When is it OK to use tight coupling?

  • 강결합은 나쁜 것으로만 배워서 잘 모르겠다.
  • 이 답변은 너무 모호한 설명인 듯

A major advantage of a tightly coupled architecture is that it enables the rapid and efficient processing of large volumes of data, provides a single point of truth instead of several, often redundant, data sources, and enables open access to data throughout the organization.

Service Oriented Architecture and Microservices

What are the differences between Soa and Microservices?

Let's talk about web services versioning, version compatibility and breaking changes

시맨틱 버저닝

What are the pros and cons of MicroService architecture

  • 장점
    • 기능을 모듈로서 개발이 가능함
    • DB 또는 언어를 알맞게 선택이 가능함
    • 개별 디버깅, QA가 쉬움
  • 단점
    • 혼자 개발 못함
    • 엄청난 문서화가 필요함
    • 다른 서비스와 통신하는 비용 필요

Security

How do you write secure code? In your opinion, is it one of the developer's duties, or does it require a specialized role in the company? And why?

  • 린팅
  • 소나큐브
  • Gitlab 13.8 의 보안 체크
  • 방화벽

What do you know about Cross-Site Scripting?

What do you know about Cross-Site Forgery Attack?

  • CSRF는 인증된 사용자를 통해 공격자가 원하는 명령을 수행하게 하는 기법
  • CSRF 토큰을 사용해 페이지가 처음 로드 될 때 토큰 값을 가지고 있고, 서버에 요청을 보낼 때 토큰을 같이 보내 비교한다

How does HTTPS work?

What's a Man-in-the-middle Attack, and why does HTTPS help protect against it?

  • 전송 구간에서도 암호화가 되어 전송되니까 중간자공격이 통할리가.

How can you prevent the user's session from being stolen?

  • Session Expire를 당연히 줘야하고, IP 체크

General

What's the difference between TCP and HTTP

  • 4번째 레이어와 7번째 레이어
  • HTTP는 response 받으면 응답을 끊지만 TCP는 끊을 때까지 계속 연결
  • TCP가 하위니까 속도가 더 빠름

What are the tradeoffs of client-side rendering vs. server-side rendering

  • CSR은 CDN에
  • SSR은 Bot만이 들어올 수 있게.

나를 위한 면접 (Frontend Developer Interview Questions)

· 약 14분

FE Interview Questions를 아는 만큼 답해보았다 지극히 주관적이라 정답이 아닐 수 있습니다

사용자의 액션에 의해 이벤트 발생 시 이벤트는 document 레벨까지 버블링 되어 올라간다. 이 때문에 자식 엘리먼트에서 발생하는 이벤트를 부모 엘리먼트에서도 감지할 수 있다. 이러한 동작을 이용해 사용할 수 있는 방법이 event delegation이다. 특정 엘리먼트에 하나하나 이벤트를 등록하지 않고 하나의 부모에 등록하여 부모에게 이벤트를 위임하는 방법

// 버튼마다 onClick Event Listener 등록
document.getElementById("btn1").addEventListener("click", (event) => {});

document.getElementById("btn2").addEventListener("click", (event) => {});

document.getElementById("btn3").addEventListener("click", (event) => {});

// Event Delegation
document.getElementById("div").addEventListener("click", (event) => {
switch (event.target.id) {
case "btn1":
break;
case "btn2":
break;
case "btn3":
break;
}
});

this는 어떻게 작동하는가?

  • Global Context: window

  • Function Context: "use strict" ? 실행 시 할당 : window

  • Object method: 자기 자신 객체

  • Object Prototype Chain: 자기 자신 객체

  • Getter, Setter: get 또는 set 되는 속성 객체

  • 생성자: 생성된 자신

  • call, apply: 지정해 주는 객체

  • bind: 바인딩 될 때의 this

  • Dom Event: event.currentTarget === event.target === this

  • in-line Event: Element

  • 출처

prototype 기반 상속은 어떻게 하는가?

Object.create로 prototype을 확장하던지 proto로 prototype link를 걸던지

AMD와 CommonJS는 뭐고 어떻게 생각하나?

  • AMD: requireJS
  • CommonJS: NodeJS 방식

결국엔 UMD 패턴으로 모듈을 만들어야한다. 둘 다 실무에서 쓰려면 번들링이 필요하고, Webpack 쓸 바에 두 개 다 필요없이 import 구문으로 처리하겠다.

다음 코드가 즉시 호출 함수 표현식(IIFE)로 동작하지 않는 이유?

Immediately Invoked Function Expression

// function foo(){}()

함수선언문을 어떻게 실행하냐 함수를 괄호로 감싸면 됨

null과 undefined 그리고 undeclared의 차이점

  • null: 선언되었지만 값 없음
  • undefined: 선언조차 안됨
  • undeclared: 선언문 (var 등) 없이 전역변수로 할당되는 유효범위를 지정하지 않은 건데 린팅에 어긋남

클로져(Closure)는 무엇이며, 어떻게/왜 사용?

  • 무엇: 초기화시의 상태를 내부에 가지고 있는 형태의 함수
  • 어떻게:return으로 공개할 메소드 또는 데이터를 꺼냄
  • 왜: private 기능 구현, for문에서 context 참조

익명함수(anonymous functions)는 주로 어떤 상황에서 사용?

  • 함수 표현식 (변수로 함수 선언), callback

당신의 코드를 어떻게 구성하는지?

  • ESLint airbnb + prettier + commitlint

호스트 객체 vs 네이티브 객체

  • Host Objects: 사용자에 의해 생성된 객체
  • Native Objects: 브라우저 또는 구동 엔진에 내장된 객체

다음 코드의 차이점?

function Person() {} // 선언문
var person = Person(); // 함수 표현식
var person = new Person(); // 생성자

.call과 .apply의 차이점?

  • call()은 함수에 전달될 여러 개의 인자를 받는데 비해
  • apply()는 배열로 된 하나의 인자를 받는다

Function.prototype.bind?

  • 호출될 때의 함수의 this 값을 넘겨준 값으로 바인딩

document.write()는 언제 사용?

  • 스크립트 심을 때 document.write는 block 되지 않으므로
  • 근데 appendChild로 심을 수 있어서 안씀

AJAX

  • XMLHttpRequest 객체를 사용해 비동기 방식으로 서버와 통신을 하는 것
  • 장점: 화면 전환 없이 특정 영역만 갱신 (업데이트) 가능
  • 단점: 없음

JSONP vs AJAX

  • JSONP는 스크립트 태그를 심어서 로드될 때 콜백 함수를 호출하는 거고 get만 가능
  • Same origin policy를 벗어날 수 있음

호이스팅

  • 자바스크립트 엔진이 실행 컨텍스트를 생성하면서 scope 를 정의 할때
  • 코딩 순서에 상관없이 선언부에 대한 처리를 맨 위로 끌어올려 먼저 해석하는 것

Event Bubbling

  • 자식 이벤트가 부모로 전달 되는 것
  • event.stopPropagation으로 막을 수 있음
  • 다른 리스너를 실행시키지 않는건 event.stopImmediatePropagation

속성(Attribute) vs 요소(property)

  • Attribute: HTML 요소에 추가적인 정보 전달
  • Property: Attribute에 대한 HTML DOM tree에서의 표현

내장된 JavaScript 객체를 확장하는 것이 좋지 않은 이유?

  • 그것을 참조한 모든 객체가 확장한 구문을 따라가기 때문에

document load event vs DOMContentLoaded event

  • document.load: DOM 안의 모든 게 로딩이 끝나야 발생 (더 느림)
  • DOMContentLoaded: DOM 초기화시 발생

== vs ===

  • 타입 체크

동일출처정책(the same-origin policy)

  • js나 문서가 다른 origin에서 fetch되지 못하게 하는 정책

삼항식(Ternary statement)을 사용하는 이유?

  • if else의 간소화

use strict

When adding 'use strict';, the following cases will throw a SyntaxError before the script is executing:

  • Octal syntax var n = 023;

  • with statement

  • Using delete on a variable name delete myVariable

  • Using eval or arguments as variable or function argument name

  • Using one of the newly reserved keywords (in prevision for ECMAScript 2015): implements, interface, let, package, private, protected, public, static, and yield

  • Declaring function in blocks if (a < b)

  • Obvious errors

    • Declaring twice the same name for a property name in an object literal {a: 1, b: 3, a: 7} This is no longer the case in ECMAScript 2015 (bug 1041128).
    • Declaring two function parameters with the same name function f(a, b, b)
  • 출처

전역 scope를 사용했을 때

  • 장점: 어디에서나 접근 가능
  • 단점: release 꼬임, 추적 힘듦.

때때로 load event를 사용하는 이유? 단점과 대안은?

  • DOM의 모든 게 로드가 끝난 후에 이벤트를 걸어야할 것이 있을 때 사용 (lazy loading)

SPA에서 SEO에 유리하도록 만들기 위한 방법

  • Sitemap, JSON-LD, UA가 Bot일 경우 SSR

Promise vs Callback

  • 장점: Chaining, 가독성, 여러 Promise를 한 번에 제어 가능
  • 단점: 없다

JavaScript를 디버깅할 때 사용하는 도구?

  • VSCode, Chrome Dev Tools

객체 안의 속성과 배열의 아이템을 순회할 때 사용하는 문법?

  • Object: for in hasOwnProperty, Object.keys().forEach, for of
  • Array: for, Array.forEach, for of

mutable object vs immutable object

  • mutable: 변경 가능
  • immutable: 변경 불가능, Object freeze 또는 Object assign으로 metadata 수정

JavaScript에서 immutable 객체의 예

  • String: 문자열이 생성되면 그 다음에 수정할 수 없음
  • Symbol: 유일한 값

immutability의 장단점?

  • 장점: 변경점 찾기 및 디버깅이 쉬움
  • 단점: mutable한 코드보다 훨씬 느림

자신의 코드에서 불변성(immutability)을 어떻게 달성할 수 있나요?

  • eslint-plugin-functional 또는 immutableJS

동기방식과 비동기 방식 함수의 차이

  • 은행 번호표

event loop

  • JS에서 사용하는 동시성 처리 모델
// 현재 아무 메시지도 없다면 새로운 메시지 도착을 동기적으로 기다림
while (queue.waitForMessage()) {
queue.processNextMessage();
}

call stack

  • 함수 호출시 저장되는 스택, 재귀를 생각하면 됨

task queue

  • 비동기 함수가 저장되는 큐, call stack이 비워지면 실행 됨

function foo() 와 var foo = function() 에서 foo 의 차이

  • 전자는 호이스팅, 후자는 안 됨

let, var, const의 차이점

  • var: function-scoped 로 호이스팅, 재선언 가능
  • let: block-scoped 로 재선언 불가, 재할당 가능
  • const: block-scoped 로 재선언 불가, 재할당 불가

test code를 작성하면서 개발하는 방식의 장단점

  • 장점: 결과가 나와있고 로직을 맞추면되서 디버깅, 리팩토링이 쉬워지고 유지보수에도 좋음
  • 단점: 시간

test code를 테스트하는 툴 사용경험

  • Jest, Puppeteer, supertest

단위 테스트 vs 기능 테스트

  • unit test: unit 즉 method 별로 테스트
  • functional test: 전체 시스템에서 기능을 테스트, 많은 method와 서비스가 연결되어있음

code style linting tool을 사용했을때 장점?

  • 모두가 일관된 스타일로 코딩 가능, 가독성 증가

성능관련 이슈들을 발견하기 위해서 사용하는 방법?

  • 실행시간 timestamp 로깅
  • Chrome Dev Tools Performance 탭

웹사이트 scrolling 성능을 향상시키기 위한 방법?

  • throttle

브라우저의 layout, painting, compositing

  • Layout: 각 element가 차지하는 공간과 배치할 공간을 결정

  • Painting: element를 그리고, element의 모든 시각적 부분을 그리는 작업

  • Compositing: element를 올바른 순서로 화면에 그려 페이지를 렌더링

  • 출처

웹사이트의 assets을 여러 도메인으로 서빙했을 때 장점

브라우저 마다 다르지만 HTTP1.1에서는 하나의 호스트당 평균 4개의 동시 다운로드만 가능해서, 병렬 처리를 하기 위해 여러 도메인으로 서빙을 했었다 하지만 이젠 http2로 다 해결 가능

참고

URL로 접속했을 때 어떤 플로우로 화면에 웹사이트가 그려지는지 네트워크 관점

  • 로컬 DNS에서 URL IP 확인
  • 3way handshake로 IP에 TCP 연결 설정 후 HTTP 헤더와 Body 요청 전송
  • 응답받은 HTTP 헤더와 Body로 웹사이트 렌더링

Long-Polling과 Websocket, Server-Sent Event

  • Long-Polling: response를 닫지 않고 계속 보내주는 것
  • Websocket: subscribe 후에 양방향으로 메세지 교환
  • Server-Sent Event: Push, HTTP 사용

request headers

  • Expires headers tell the browser whether they should request a specific file from the server or whether they should grab it from the browser's cache.

  • Date: The date and time that the message was sent

  • The Age response-header field conveys the sender's estimate of the amount of time since the response (or its revalidation) was generated at the origin server.

  • The If-Modified-Since request-header field is used with a method to make it conditional: if the requested variant has not been modified since the time specified in this field, an entity will not be returned from the server; instead, a 304 (not modified) response will be returned without any message-body.

  • Do Not Track: disable either its tracking or cross-site user tracking

  • Cache-Control: Tells all caching mechanisms from server to client whether they may cache this object. It is measured in seconds

  • Transfer-Encoding: The form of encoding used to safely transfer the entity to the user. Currently defined methods are: chunked, compress, deflate, gzip, identity.

  • ETag: An identifier for a specific version of a resource.

  • X-Frame-Options can be used to indicate whether or not a browser should be allowed to render a page in a frame, iframe or object.

  • 출처

  • HTTP Cache 튜토리얼

HTTP Methods

  • GET: 리소스 요청
  • HEAD: 리소스 요청이나 body가 없음
  • POST: 리소스 생성
  • PUT: 리소스 업데이트
  • PATCH: 리소스 부분 업데이트
  • DELETE: 리소스 삭제
  • OPTIONS: Cross Domain request에서 해당 메소드가 안전한지 확인하기 위해 사용

나를 위한 면접 (ALL)

· 약 21분

실무에 치이느라 기본적인 걸 까먹을까봐 정리해보자 정보처리 에서 컴퓨터 기초를 보면 되고. 지극히 주관적이라 정답이 아닐 수 있습니다

미적분

편미분까진 안물어보더라

베이지안 확률

사후확률 = 가능도 * 사전확률 / 증거

// 붉은 점이 얼굴에 보일 때 수두 환자일 확률은 어떻게 구할까?
P(수두 | 붉은점) = P(붉은 점 | 수두) * P(수두) / P(붉은점)

자료구조

B Tree

m-원 트리의 단점임 한쪽으로 편중된 트리를 생성되는 경우를 보완하고자 루트노드로부터 리프노드의 레벨을 같도록 유지한 트리

BASIS FOR COMPARISONB-TREEBINARY TREE
Essential constraintA node can have at max M number of child nodes(where M is the order of the tree).A node can have at max 2 number of subtrees.
UsedIt is used when data is stored on disk.It is used when records and data are stored in RAM.
Height of the treelogM N (where m is the order of the M-way tree)log2 N
ApplicationCode indexing data structure in many DBMS.Code optimization, Huffman coding, etc.

space complexity B-tree is O(n). Insertion and deletion time complexity is O(logn).

출처

B+ Tree

B+은 index node와 data node로 구성

출처

B* Tree

B-tree의 경우에 각 노드가 최소한 반 이상 차 있어야 하는 조건각 노드가 최소한 2/3이상 차있어야 한다로 변경하면 이것이 B*tree이다

공간 활용도를 높일 수 있다. 출처

Binary Tree

모든 노드의 차수가 2 이상을 넘지 않는 트리를 말한다, 왼쪽자식노드는 부모노드의 값보다 작이야하며 오른쪽 자식노드는 부모노드의 값보다 커야한다.

Binary Search Tree

이진탐색(binary search)과 연결리스트(linked list)를 결합한 자료구조의 일종입니다. 이진탐색의 효율적인 탐색 능력을 유지하면서도, 빈번한 자료 입력과 삭제를 가능하게끔 고안됐습니다.

  • 모든 원소는 서로 다른 유일한 키를 가짐
  • 왼쪽 서브트리에 있는 원소들의 값은 그 루트의 값보다 작음
  • 오른쪽 서브트리에 있는 원소의 값들은 그 루트의 값보다 큼
  • 왼쪽 서브트리와 오른쪽 서브트리도 이진 탐색 트리임

O(n), 완전 이진 트리에 가까울 수록 O(log2(n))

출처

Insertion Sort

앞에서부터 하나씩 비교하여 위치를 삽입

O(n^2)

function insertionSort(unsortedList) {
var len = unsortedList.length;
for (var i = 1; i < len; i++) {
// Copy of the current element.
var tmp = unsortedList[i];
// Check through the sorted part and compare with the number in tmp. If large, shift the number
for (var j = i - 1; j >= 0 && unsortedList[j] > tmp; j--) {
// Shift the number
unsortedList[j + 1] = unsortedList[j];
}
// Insert the copied number at the correct position
// in sorted part.
unsortedList[j + 1] = tmp;
}
}

출처

Selection Sort

하나씩 뒤로 비교하여 최소값을 맨 앞으로 삽입

O(n^2)

function selectionSort(items) {
var length = items.length;
for (var i = 0; i < length - 1; i++) {
// Number of passes
// min holds the current minimum number position for each pass; i holds the Initial min number
var min = i;
// Note that j = i + 1 as we only need to go through unsorted array
for (var j = i + 1; j < length; j++) {
// Compare the numbers
if (items[j] < items[min]) {
// Change the current min number position if a smaller num is found
min = j;
}
}
if (min != i) {
// After each pass, if the current min num != initial min num, exchange the position.
// Swap the numbers
var tmp = items[i];
items[i] = items[min];
items[min] = tmp;
}
}
}

출처

Quick Sort

pivot을 하나 뽑는다 보통 list.length / 2 -1 을 선택한다. pivot 앞에는 pivot보다 작게, pivot 뒤에는 pivot보다 크게 값을 바꿔치고 재귀를 돌린다

최악 O(n^2), 평균 O(nlogn)

const quickSort = (list) => {
if (list.length < 2) {
return list;
}

const pivot = list[0];
// const pivot = list[Math.floor(list.length / 2)];
const smaller = list.filter((item) => item < pivot);
const bigger = list.filter((item) => item > pivot);

return [...quickSort(smaller), pivot, ...quickSort(bigger)];
};

참고

List

Linked List

List vs Linked List

리스트가 대부분 좋다 연결 리스트는 중간에 삽입 삭제시 좋다 리스트는 끝에 넣을 떄 좋다

연결 리스트는 검색시 링크를 따라가므로 비효율적이다. 리스트가 순차라 검색시에 좋다. 공간의 효율성은 연결 리스트

효율성 비교

function LinkedList() {
this.head = null;
}

LinkedList.prototype.push = function (val) {
var node = {
value: val,
next: null,
};

if (!this.head) {
this.head = node;
} else {
current = this.head;
while (current.next) {
current = current.next;
}
current.next = node;
}
};

var sll = new LinkedList();
sll.push(2);
sll.push(3);
sll.push(4);

// check values by traversing LinkedList
sll.head; // Object {data: 2, next: Object}
sll.head.next; // Object {data: 3, next: Object}
sll.head.next.next; // Object {data: 4, next: null}

출처

Graph

  • 그래프(Graph)는 연결되어 있는 원소간의 관계를 표현하는 자료구조이다. 나와 연관된 인간 관계를 나타내는 인맥 지도, 수도 배관에 대한 배수 시스템, 물질의 분자 구조 등은 연결 구조가 다양하기 때문에 선형 자료 구조나 트리로는 표현 할 수가 없다.
  • 그래프는 연결할 객체를 나타내는 정점(vertex)와 객체를 연결하는 간선(edge)의 집합으로 구성된다. 그래프 G를 *G=(V,E)*로 정의하는데, V는 그래프에 있는 정점들의 집합을 의미하고, E는 정점을 연결하는 간선들의 집합을 의미한다.

출처

// Implement a Graph
// basic operations:
// - add vertex (node)
// - add edge (node -> node)

function GraphNode(val) {
this.val = val;
this.edges = {};
}

function Graph() {
this.vertices = {};
}

// O(1) operation
Graph.prototype.addVertex = function (val) {
// add vertex only if it does not exist.
if (!this.vertices[val]) {
this.vertices[val] = new GraphNode(val);
}
};

// O(E) operation - edges
Graph.prototype.removeVertex = function (val) {
if (this.vertices[val]) {
// once you remove a vertex, you need to remove all edges pointing
// to the vertex.
delete this.vertices[val];

Object.keys(this.vertices).forEach(
function (key, index) {
if (this.vertices[key].edges[val]) {
delete this.vertices[key].edges[val];
}
}.bind(this),
);
}
};

// O(1) operation
Graph.prototype.getVertex = function (val) {
return this.vertices[val];
};

// O(1) operation
Graph.prototype.addEdge = function (start, end) {
// check to see if vertices exists.
// if it exists, set the edges and be done.
if (this.vertices[start] && this.vertices[end]) {
// check to see if edge exists, if it does, increment it's weight
if (this.vertices[start].edges[end]) {
this.vertices[start].edges[end].weight += 1;
} else {
// edge does not exist, set weight to 1.
this.vertices[start].edges[end] = { weight: 1 };
}
}
};

// O(1) operation
Graph.prototype.removeEdge = function (start, end) {
if (this.vertices[start] && this.vertices[end]) {
if (this.vertices[start].edges[end]) {
delete this.vertices[start].edges[end];
}
}
};

// O(1) operation
Graph.prototype.getEdge = function (start, end) {
return this.vertices[start].edges[end] || null;
};

Graph.prototype.neighbors = function (val) {
return this.vertices[val] ? this.vertices[val].edges : null;
};

var graph = new Graph();

graph.addVertex(5);
graph.addVertex(2);
graph.addVertex(6);
graph.addVertex(7);
graph.addEdge(2, 5);
graph.addEdge(6, 7);
graph.addEdge(7, 5);
console.log(graph.getEdge(2, 5));
console.log(graph.getEdge(6, 7));
graph.removeVertex(5);
console.log(graph.getEdge(2, 5));
console.log(graph.neighbors(6));
console.log(graph.neighbors(5));

출처

알고리즘

시간복잡도

  • 알고리즘이 문제를 해결하는 데에 얼마나 걸리는 지를 분석하는 것
  • 프로그램을 실행시켜 완료하는데 걸리는 시간을 의미

빅오표기법

  • 실행 시간은 최대한 이만큼 커지지만 더 천천히 커질 수도 있다는 의미인 점근적 표기법 형태를 사용하는 것 (점근 표기법)
  • 최악의 경우를 표기하는 방법

빅오에서 n이 의미하는것

  • 입력 데이터 개수

최단거리 알고리즘

  • 다익스트라 알고리즘
  • A* 알고리즘

슬라이딩 윈도우

이 문제가 도움 될 듯

데이터베이스

정규화

  • 관계형 데이터베이스의 설계에서 중복을 최소화하게 데이터를 구조화하는 프로세스

목적

  • 이상이 있는 관계를 재구성하여 작고 잘 조직된 관계를 생성하는 것에 있다.
  • 일반적으로 정규화란 크고, 제대로 조직되지 않은 테이블들과 관계들을 작고 잘 조직된 테이블과 관계들로 나누는 것을 포함한다.

비정규화

  • 과도한 정규화로 인해서 테이블의 수가 증가하게 되면, 다수의 JOIN이 발생함에 따라서 성능 저하가 발생할 수 있다. 보통의 경우 정규화 과정을 모두 거친 다음 마지막 단계에서 비정규화를 실시한다.
  • 단, 테이블을 합치는 것만이 비정규화는 아니다.

인덱싱 자료구조

B-Tree 알고리즘은 가장 일반적으로 사용되는 인덱스 알고리즘으로서, 상당히 오래전에 도입된 알고리즘이며 그만큼 성숙해진 상태입니다. B-Tree 인덱스는 칼럼의 값을 변형하지 않고, 원래의 값을 이용해 인덱싱하는 알고리즘 입니다.

R-Tree 다차원 공간

Hash 인덱스 알고리즘은 컬럼의 값으로 해시 값을 계산해서 인덱싱하는 알고리즘으로, 매우 빠른 검색을 지원합니다. 하지만 값을 변형해서 인덱싱하므로, 전방(Prefix) 일치와 같이 값의 일부만 검색하고자 할 때는 해시 인덱스를 사용할 수 없습니다. Hash 인덱스는 주로 메모리 기반의 데이터베이스에서 많이 사용합니다.

Fractal-Tree 알고리즘은 B-Tree의 단점을 보완하기 위해 고안된 알고리즘입니다. 값을 변형하지 않고 인덱싱하며 범용적인 목적으로 사용할 수 있다는 측면에서 B-Tree와 거의 비슷하지만 데이터가 저장되거나 삭제될 때 처리 비용을 상당히 줄일 수 있게 설계된 것이 특징입니다. 아직 B-Tree 알고리즘만큼 안정적이고 성숙되진 않았지만 아마도 조만간 B-Tree 인덱스의 상당 부분을 대체할 수 있지 않을까 생각합니다.

출처

캐싱시 자료구조

  • Hash Table and a Linked List

디비 클러스터링

개념 참조 운영 참조

Isolation level

  • Read Uncommitted
  • Read Committed
  • Repeatable Read
  • Serializable

개념 참조 이하 참조

Read Uncommitted Isolation Level

SELECT 문장을 수행하는 경우 해당 데이터에 Shared Lock이 걸리지 않는 Level입니다. 따라서, 어떤 사용자가 A라는 데이터를 B라는 데이터로 변경하는 동안 다른 사용자는 B라는 아직 완료되지 않은(Uncommitted 혹은 Dirty) 데이터 B를 읽을 수 있습니다.

Read Committed Isolation Level

SQL Server가 Default로 사용하는 Isolation Level입니다. 이 Level에선 SELECT 문장이 수행되는 동안 해당 데이터에 Shared Lock이 걸립니다. 그러므로, 어떠한 사용자가 A라는 데이터를 B라는 데이터로 변경하는 동안 다른 사용자는 해당 데이터에 접근할 수 없습니다.

Repeatable Read Isolation Level

트랜잭션이 완료될 때까지 SELECT 문장이 사용하는 모든 데이터에 Shared Lock이 걸리므로 다른 사용자는 그 영역에 해당되는 데이터에 대한 수정이 불가능합니다. 가령, Select col1 from A where col1 between 1 and 10을 수행하였고 이 범위에 해당하는 데이터가 2건이 있는 경우(col1=1과 5) 다른 사용자가 col1이 1이나 5인 Row에 대한 UPDATE이 불가능합니다. 하지만, col1이 1과 5를 제외한 나머지 이 범위에 해당하는 Row를 INSERT하는 것이 가능합니다.

Serializable Isolation Level

트랜잭션이 완료될 때까지 SELECT 문장이 사용하는 모든 데이터에 Shared Lock이 걸리므로 다른 사용자는 그 영역에 해당되는 데이터에 대한 수정 및 입력이 불가능합니다. 예를 들어, Repeatable Read의 경우 1에서 10 사이에 해당되는 데이터에 대한 UPADTE이 가능하였습니다. 하지만 이 Level에서는 UPDATE 작업도 허용하지 않습니다.

ACID

원자성, 일관성, 독립성, 영속성

Atomicity

트랜잭션 내의 명령은 반드시 완벽히 수행 모두가 수행되거나 오류시 전부가 취소되어야함

Consistency

DB의 전체 요소는 트랜잭션 수행 전과 트랜잭션 수행 완료 후의 상태가 같아야함 (질량 보존 법칙처럼)

Isolation

둘 이상의 트랜잭션이 병행 실행되는 경우 다른 트랜잭션 연산이 끼어들 수 없음 수행 중인 트랜잭션은 완료될 때 까지 다른 트랜잭션에서 참조 불가.

Durability

시스템이 고장나도 영구적으로 반영

CRUD

Create(생성), Read(읽기), Update(갱신), Delete(삭제)

InnoDB와 MyISAM의 차이

image from hexo

MariaDB가 MySQL보다 나은점

증분 백업

정해진 시간을 기준으로 그 이후에 변경된 파일만을 백업하는 방식

서버

서버 로드밸런싱

설명할 수 있음

이미지 클러스터링

k-means (피벗 추출 후 2진수 비교인데 아직 이해하기가 힘들다, 18년 말에는 딥러닝을 파보자!)

Build Process 설명

Deploy Server

Git Flow

브랜치 관리 전략

  • feature: develop에서 분기 후 기능 개발 후 develop으로
  • develop: 개발 브랜치
  • release: master로의 merge를 위한 준비
  • hotfix: master의 버그 픽스 후 develop과 master로 빠른 수정
  • master: 프로덕션 브랜치

image from hexo

참고

WAS 세팅 및 튜닝

프론트앤드

Virtual DOM

DOM 조작의 실제 문제는 각 조작이 레이아웃 변화, 트리 변화와 렌더링을 일으킨다는겁니다.

Virtual DOM 은 변화가 일어나면 그걸 오프라인 DOM 트리에 적용시키죠. 이 DOM 트리는 렌더링도 되지 않기때문에 연산 비용이 적어요. 연산이 끝나고나면 그 최종적인 변화를 실제 DOM 에 던져주는거에요. 딱 한번만 한는거에요.

사실, 이 과정은 Virtual DOM 이 없이도 이뤄질수 있어요. 그냥, 변화가 있을 때, 그 변화를 묶어서 DOM fragment 에 적용한 다음에 기존 DOM 에 던져주면 돼요.

그러면, Virtual DOM 이 해결 하려고 하는건 무엇이냐? 그 DOM fragment를 관리하는 과정을 수동으로 하나하나 작업 할 필요 없이, 자동화하고 추상화하는거에요. 그 뿐만 아니라, 만약에 이 작업을 여러분들이 직접 한다면, 기존 값 중 어떤게 바뀌었고 어떤게 바뀌지 않았는지 계속 파악하고 있어야하는데 (그렇지 않으면 수정 할 필요가 없는 DOM 트리도 업데이트를 하게 될 수도 있으니까요), 이것도 Virtual DOM 이 이걸 자동으로 해주는거에요. 어떤게 바뀌었는지 , 어떤게 바뀌지 않았는지 알아내주죠.

마지막으로, DOM 관리를 Virtual DOM 이 하도록 함으로써, 컴포넌트가 DOM 조작 요청을 할 때 다른 컴포넌트들과 상호작용을 하지 않아도 되고, 특정 DOM 을 조작할 것 이라던지, 이미 조작했다던지에 대한 정보를 공유 할 필요가 없습니다. 즉, 각 변화들의 동기화 작업을 거치지 않으면서도 모든 작업을 하나로 묶어줄 수 있다는거죠.

출처

ES6

SEO

Angular

React

Vue