네로개발일기

개발자 네로의 개발 일기, 자바를 좋아합니다 !

'2021/10'에 해당되는 글 16건


반응형

# public 클래스에서는 public 필드가 아닌 접근자 메서드를 사용하라.

## 1. public 클래스의 가변 필드

- 절대 가변 필드를 public으로 노출하면 안된다.

* 캡슐화의 이점을 제공하지 못한다.
* API를 수정하지 않고는 내부 표현을 바꿀 수 없다.
* 불변식을 보장할 수 없다.
* 외부에서 필드에 접근할 때 부수 작업을 수행할 수 없다.

- 패키지 바깥에서 접근할 수 있는 클래스라면 접근자(getter)를 제공하자.
- 클래스 내부의 표현 방식을 언제든 바꿀 수 있다.

- package-private 클래스, private 중첩 클래스는 데이터 필드를 노출해도 괜찮다.
* package-private: 패키지 바깥 코드를 손대지 않고 데이터 표현 방식을 바꿀 수 있다.
* private 중첩: 이 클래스를 포함하는 외부 클래스까지로 제한한다.

## 2. public 클래스의 불변 필드

- 직접 노출할 때의 단점이 줄어들긴 하지만 좋은 방법은 아니다.
- 단점1. API를 변경하지 않고는 표현방식을 바꿀 수 없다.
- 단점2. 필드를 읽을 때 부수적인 작업을 수행할 수 없다.
- 장점1. 불변식을 보장할 수 있다.



728x90
반응형
blog image

Written by ner.o

개발자 네로의 개발 일기, 자바를 좋아합니다 !

반응형

# 클래스와 멤버의 접근 권한을 최소화하라. => 정보 은닉/캡슐화

- 잘 설계된 컴포넌트: 클래스 내부 데이터와 내부 구현 정보를 외부 컴포넌트로부터 얼마나 잘 숨겼는가/ 오직 API를 통해서만 다른 컴포넌트와 소통 [정보 은닉/캡슐화]

 

## 1. 정보 은닉의 장점: 개발 속도, 디버깅, 성능의 최적화, 재사용성, 동작 검증

1. 시스템 개발 속도를 높인다. 여러 컴포넌트를 병렬로 개발할 수 있기 때문

2. 각 컴포넌트를 빠르게 파악하여 디버깅 기능, 다른 컴포넌트로 교체하는데 부담도 적다.

3. 정보 은닉이 성능을 높여주지는 않지만, 성능의 최적화에는 도움이 된다.

4. 재사용성을 높여준다. 외부에 의존하지 않고 독자적으로 동작할 수 있는 컴포넌트라면, 그 컴포넌트와 함께 개발되지 않은 환경에서도 유용하게 쓰일 가능성이 크다.

5. 시스템 전체가 개발되지 않은 상태에서도 개별 컴포넌트의 동작을 검증할 수 있다.

 

## 2. 정보 은닉의 기본 원칙

1) 모든 클래스와 멤버의 접근성을 가능한 좁혀라.

- 클래스와 멤버의 접근 제한자를 private 등으로 낮은 접근 수준을 부여하는 것이다.

- 우리가 가장 많이 사용하는 클래스에는 public과 package-private 두 가지를 가장 많이 사용한다. Top Level Class 나 Interface를 public으로 선언하면 공개 API가 되지만 package-private로 선언하면 해당 패키지안에서만 사용 가능하다.

- 패키지 외부에서 클래스를 사용할 일이 없다면 package-private로 선언하여 API가 아닌 내부에서 언제든지 수정할 수 있게 한다.

 

2) 멤버에 부여할 수 있는 접근 제한자

- 멤버: 필드, 메서드, 중첩 클래스, 중첩 인터페이스

- private/ package-private/ protected/ public

1. private: 해당 멤버를 선언한 클래스에서만 접근이 가능.

2. package-private(default): 해당 멤버가 소속된 패키지 안의 모든 클래스에서 접근할 수 있다. 접근 제한자를 명시하지 않았을 때 적용되는 default 접근 제한자. (단, interface는 default public이다.)

3. protected: package-private의 범위를 포함하고, 해당 멤버를 선언한 클래스를 상속받은 하위 클래스에서도 접근이 가능한 접근 제한자.

4. public: 모든 곳에서 접근이 가능한 접근 제한자.

 

* 주의: public 클래스의 protected 멤버는 공개 API

 

## 3. 멤버 접근성의 제약

상위 클래스의 메서드를 재정의할 때 상위보다 좁게 설정할 수 없다.

 

## 4. 주의점

- 코드 테스트만을 위해 클래스, 인터페이스, 멤버를 공개 API로 만들면 안된다.

1) public 클래스의 인스턴스 필드는 되도록 public이 아니어야 한다.

- 필드가 가변 객체를 참조하거나, final이 아닌 인스턴스 필드를 public으로 선언하면 그 필드에 값을 제한할 수 없기 때문에 불변성을 보장할 수 없게 된다. 또한 필드가 수정될 때 다른 작업을 할 수 없게 되기 때문에, public 가변 필드를 갖는 클래스는 일반적으로 스레드로부터 안전하지 않다.

- 또한, 필드가 final이면서 불변 객체를 참조하더라도 문제는 발생할 수 있다. 이유는 final이기 때문에 다른 객체를 참조하도록 변경할 수 없지만, 이미 참조하고 있는 참조된 객체 자체는 수정될 수도 있다.

 

2) 정적 필드에서의 public 필드 예외

- public static final 필드 공개는 허용한다. 이런 필드는 반드시 기본 타입 값이나 불변 객체를 참조해야 한다.

 

3) 클래스에서 public static final 배열 필드를 두거나 이 필드를 반환하는 접근자 메서드를 제공해서는 안된다.

- 클라이언트에서 배열의 배용을 수정할 수 있기 때문이다.

[권장 방법]

1. public 불변 리스트를 추가

private static final Thing[] PRIVATE_VALUES = {...};
public static final List<Thing> VALUES = Collections.unmodifiableList(Arrays.asList(PRIVATE_VALUES));

 

2. 복사본을 반환하는 public 메서드를 추가: 방어적 복사

private static final Thing[] PRIVATE_VALUES = {...};
public static final Thing[] values() {
	return PRIVATE_VALUES.clone();
}

 

- 타입과 성능에 따라서 사용

 

## 5. Java9: 모듈 시스템 개념의 도입

- 패키지: 클래스의 묶음

- 모듈: 패키지의 묶음, 자신이 속하는 패키지 중 공개(export)할 것을 module-info.java 파일에 선언한다. 클래스를 외부에 공개하지 않으면서도 같은 모듈을 이루는 패키지 사이에서 자유롭게 공유할 수 있다.

- 암묵적 접근 수준: public, protected 수준의 효과가 모듈 내부로 한정된다.

 

1) 모듈에 적용되는 새로운 두 접근 수준은 주의해야 한다.

- 모듈의 *.jar 파일을 모듈 경로가 아니라 애플리케이션 클래스 패스에 두면, 모듈 안 패키지가 모듈이 없는 것처럼 행동

- JDK: 자바 라이브러리에서 공개하지 않은 패키지는 모듈 밖에서 접근할 수 없다.

 

2) 모듈의 장점을 누리기 위한 조치

- 패키지를 모듈 단위로 묶는다.

- 모듈 선언에 패키지들의 의존성을 명시한다.

- 소스 트리 재배치

- 모듈 안으로부터(모듈 시스템을 적용하지 않는) 일반 패키지로의 모든 접근에 특별한 조치를 취해야 한다.

 

 

summary

1. 접근성은 가능한 최소한으로

2. 꼭 필요한 정보들만 public API로 설계

3. class, interface, field가 의도치 않게 public으로 공개되지 않도록

4. public 클래스는 상수용 public static final 필드 외에는 public 필드 없이

5. public static final이 참조하는 객체가 가변인지 불변 객체인지 확인

 

728x90
반응형
blog image

Written by ner.o

개발자 네로의 개발 일기, 자바를 좋아합니다 !

반응형

How to list database tables using the "rails console"?

Rails console을 이용해서 데이터베이스 테이블 확인하는 방법

> ActiveRecord::Base.connection.tables

간단하지만 매번 까먹어서 적어놓는다.

728x90
반응형
blog image

Written by ner.o

개발자 네로의 개발 일기, 자바를 좋아합니다 !

반응형

ruby에서 time zone 관련 요약

사용하지 말아야 하는 것 DON'T USE

* Time.now
* Date.Today
* Date.Today.to_time
* Time.parse("2021-10-21 18:19:20")
* Time.strptime(string, "%Y-%m-%dT%H:%M:%S%z")

사용해도 되는 것 DO USE

* Time.current
* 2.hours.ago
* Time.zone.today
* Date.current
* 1.day.from_now
* Time.zone.parse("2020-10-21 18:06:22")
* TIme.strptime(string, "%Y-%m-%dT%H:%M:%S%z").in_time_zone

 

Time zones in Rails

rails는 ruby와 같은 API를 제공하는데 rails에서 time zones 와 관련된 것을 볼 수 있다.

$ rails time:zones:all

* UTC -12:00 *
International Date Line West

...

* UTC +00:00 *
Casablanca
Dublin
Edinburgh
Lisbon
London
Monrovia
UTC

...

* UTC +09:00 *
Osaka
Sapporo
Seoul
Tokyo
Yakutsk

...

 

Three time zones

rails에서 3가지 time zones가 있다.

- system time

- application time

- database time 

# This is the time on my machine, also commonly described as "system time" (시스템 타임)
> Time.now
=> 2015-07-04 17:53:23 -0400

# Let's set the time zone to be Fiji (피지의 타임존으로 등록해도)
> Time.zone = "Fiji"
=> "Fiji"

# But we still get my system time (여전히 시스템 타임이 출력)
> Time.now
=> 2015-07-04 17:53:37 -0400

# However, if we use `zone` first, we finally get the current time in Fiji (타임존을 등록)
> Time.zone.now
=> Sun, 05 Jul 2015 09:53:42 FJT +12:00

# We can also use `current` to get the same
> Time.current
=> Sun, 05 Jul 2015 09:54:17 FJT +12:00

# Or even translate the system time to application time with `in_time_zone`
> Time.now.in_time_zone
=> Sun, 05 Jul 2015 09:56:57 FJT +12:00

# Let's do the same with Date (we are still in Fiji time, remember?)
# This again is the date on my machine, system date
> Date.today
=> Sat, 04 Jul 2015

# But going through `zone` again, and we are back to application time
> Time.zone.today
=> Sun, 05 Jul 2015

# And gives us the correct tomorrow according to our application's time zone
> Time.zone.tomorrow
=> Mon, 06 Jul 2015

# Going through Rails' helpers, we get the correct tomorrow as well
> 1.day.from_now
=> Mon, 06 Jul 2015 10:00:56 FJT +12:00

 

[출처]

https://thoughtbot.com/blog/its-about-time-zones

 

It's About Time (Zones)

An overview of time zones in Rails.

thoughtbot.com

 

728x90
반응형
blog image

Written by ner.o

개발자 네로의 개발 일기, 자바를 좋아합니다 !

반응형

# rails how to generate model array column

 

model을 만들 때 rails g model 명령어를 사용한다.

$ rails g model user Article title:string body:text

 

class CreateArticles < ActiveRecord::Migration[6.0]
  def change
    create_table :articles do |t|
      t.string :title
      t.text :body

      t.timestamps
    end
  end
end

위 명령어를 사용하면 위와 같은 Migration 파일이 생성된다.

title은 string 타입으로, body는 text 타입으로 테이블이 생성된다. 

 

아래 명령어를 통해 들어가보면 

$ rails g model --help
 Available field types:

    Just after the field name you can specify a type like text or boolean.
    It will generate the column with the associated SQL type. 
    For instance:
    
        `rails generate model post title:string body:text`

    will generate a title column with a varchar type and a body column with a text
    type. If no type is specified the string type will be used by default.
    
    You can use the following types:
        integer
        primary_key
        decimal
        float
        boolean
        binary
        string
        text
        date
        time
        datetime

    You can also consider `references` as a kind of type. 
    For instance, if you run:
    
        `rails generate model photo title:string album:references`
        
    It will generate an `album_id` column. You should generate these kinds of fields when
    you will use a `belongs_to` association, for instance. 
    `references` also supports
    polymorphism, you can enable polymorphism like this:
    
        `rails generate model product supplier:references{polymorphic}`
        
    For integer, string, text and binary fields, an integer in curly braces will
    be set as the limit:
    
        `rails generate model user pseudo:string{30}`
        
    For decimal, two integers separated by a comma in curly braces will be used
    for precision and scale:
    
        `rails generate model product 'price:decimal{10,2}'`
        
    You can add a `:uniq` or `:index` suffix for unique or standard indexes
    respectively:
    
        `rails generate model user pseudo:string:uniq`
        `rails generate model user pseudo:string:index`
        
    You can combine any single curly brace option with the index options:
    
        `rails generate model user username:string{30}:uniq`
        `rails generate model product supplier:references{polymorphic}:index`
        
    If you require a `password_digest` string column for use with
    has_secure_password, you can specify `password:digest`:
    
        `rails generate model user password:digest`
        
    If you require a `token` string column for use with
    has_secure_token, you can specify `auth_token:token`:
    
        `rails generate model user auth_token:token`

 

 

 

그런데 배열 타입의 칼럼을 생성할 수 있지 않을까 하는 의문이 들었다 ! 

 

1. migration 파일을 만들어준다.

$ rails g migration Article add_subjects_to_article subjects:text
명령어 설명
- g: generate => g migration 하면 migration 파일을 만들어준다. 예) g controller... , g model ... 등등
- Article: 대신 Table 명
- add_subjects_to_article: 설정하고 싶은 migration 파일 이름
- subjects:text: subjects을 text 타입으로

2. DB가 PostgreSQL인 경우 migration 파일에 다음과 같이 추가해준다.

class AddSubjectsToArticle < ActiveRecord::Migration
  def change
    add_column :articles, :subjects, :text, array: true, default: []
  end
end

여기서 중요한 것은 array: true, default: [] 이다. 이 부분을 직접 작성해준다.

 

2-1. DB가 SQLite3인 경우 app> models> article.rb 에서 

클래스 안에 serialize :subjects, Array 라고 작성한다.

 

3. migrate를 한다.

$ rails db:migrate

 

 

 

 

출처

https://stackoverflow.com/questions/32409820/add-an-array-column-in-rails

 

Add an array column in Rails

How do you declare an array column in Rails? Detail I have the following model rails generate model User address:text but I want a model which can store multiple addresses per user. The following

stackoverflow.com

http://blog.plataformatec.com.br/2014/07/rails-4-and-postgresql-arrays/

 

Rails 4 and PostgreSQL Arrays « Plataformatec Blog

In this post we show how Rails treats PostgreSQL array type, and how to use PL/pgSQL custom functions to do unique validations in PostgreSQL arrays.

blog.plataformatec.com.br

 

추가 (2021.10.23)

코드를 짜다보니 느끼는 거지만 array 칼럼보다는 1:N 연관관계로 설정하는 것이 좋아보인다 !

728x90
반응형
blog image

Written by ner.o

개발자 네로의 개발 일기, 자바를 좋아합니다 !