メインコンテンツにスキップ

関数分解とリデューサー合成を用いたリデューサーロジックのリファクタリング

さまざまな種類のサブリデューサー関数がどのように見え、どのように組み合わされるかの例を見ると役に立つ場合があります。 大きな単一のリデューサー関数を、いくつかの小さな関数の合成にリファクタリングする方法のデモを見てみましょう。

注記:この例は、完全に簡潔なコードではなく、概念とリファクタリングのプロセスを説明するために、意図的に冗長なスタイルで記述されています。

初期リデューサー

初期リデューサーが次のようになっているとします。

const initialState = {
visibilityFilter: 'SHOW_ALL',
todos: []
}

function appReducer(state = initialState, action) {
switch (action.type) {
case 'SET_VISIBILITY_FILTER': {
return Object.assign({}, state, {
visibilityFilter: action.filter
})
}
case 'ADD_TODO': {
return Object.assign({}, state, {
todos: state.todos.concat({
id: action.id,
text: action.text,
completed: false
})
})
}
case 'TOGGLE_TODO': {
return Object.assign({}, state, {
todos: state.todos.map(todo => {
if (todo.id !== action.id) {
return todo
}

return Object.assign({}, todo, {
completed: !todo.completed
})
})
})
}
case 'EDIT_TODO': {
return Object.assign({}, state, {
todos: state.todos.map(todo => {
if (todo.id !== action.id) {
return todo
}

return Object.assign({}, todo, {
text: action.text
})
})
})
}
default:
return state
}
}

この関数はかなり短いですが、すでに複雑になりすぎています。 2つの異なる関心領域(フィルタリングとTODOリストの管理)を扱っており、ネストによって更新ロジックが読みづらくなっており、どこで何が起こっているのかが正確にはわかりません。

ユーティリティ関数の抽出

最初のステップとして、更新されたフィールドを持つ新しいオブジェクトを返すユーティリティ関数を分離するのが良いでしょう。 また、配列内の特定のアイテムを更新しようとする際に繰り返されるパターンがあり、それを関数に抽出することができます。

function updateObject(oldObject, newValues) {
// Encapsulate the idea of passing a new object as the first parameter
// to Object.assign to ensure we correctly copy data instead of mutating
return Object.assign({}, oldObject, newValues)
}

function updateItemInArray(array, itemId, updateItemCallback) {
const updatedItems = array.map(item => {
if (item.id !== itemId) {
// Since we only want to update one item, preserve all others as they are now
return item
}

// Use the provided callback to create an updated item
const updatedItem = updateItemCallback(item)
return updatedItem
})

return updatedItems
}

function appReducer(state = initialState, action) {
switch (action.type) {
case 'SET_VISIBILITY_FILTER': {
return updateObject(state, { visibilityFilter: action.filter })
}
case 'ADD_TODO': {
const newTodos = state.todos.concat({
id: action.id,
text: action.text,
completed: false
})

return updateObject(state, { todos: newTodos })
}
case 'TOGGLE_TODO': {
const newTodos = updateItemInArray(state.todos, action.id, todo => {
return updateObject(todo, { completed: !todo.completed })
})

return updateObject(state, { todos: newTodos })
}
case 'EDIT_TODO': {
const newTodos = updateItemInArray(state.todos, action.id, todo => {
return updateObject(todo, { text: action.text })
})

return updateObject(state, { todos: newTodos })
}
default:
return state
}
}

これにより、重複が減り、読みやすさが向上しました。

ケースリデューサーの抽出

次に、それぞれのケースを独自の関数に分割できます。

// Omitted
function updateObject(oldObject, newValues) {}
function updateItemInArray(array, itemId, updateItemCallback) {}

function setVisibilityFilter(state, action) {
return updateObject(state, { visibilityFilter: action.filter })
}

function addTodo(state, action) {
const newTodos = state.todos.concat({
id: action.id,
text: action.text,
completed: false
})

return updateObject(state, { todos: newTodos })
}

function toggleTodo(state, action) {
const newTodos = updateItemInArray(state.todos, action.id, todo => {
return updateObject(todo, { completed: !todo.completed })
})

return updateObject(state, { todos: newTodos })
}

function editTodo(state, action) {
const newTodos = updateItemInArray(state.todos, action.id, todo => {
return updateObject(todo, { text: action.text })
})

return updateObject(state, { todos: newTodos })
}

function appReducer(state = initialState, action) {
switch (action.type) {
case 'SET_VISIBILITY_FILTER':
return setVisibilityFilter(state, action)
case 'ADD_TODO':
return addTodo(state, action)
case 'TOGGLE_TODO':
return toggleTodo(state, action)
case 'EDIT_TODO':
return editTodo(state, action)
default:
return state
}
}

これで、各ケースで何が起こっているのかが非常によくわかりました。 また、いくつかのパターンが現れ始めていることがわかります。

ドメインによるデータ処理の分離

アプリリデューサーはまだアプリケーションのすべての異なるケースを認識しています。 フィルターロジックとTODOロジックが分離されるように、分割してみましょう。

// Omitted
function updateObject(oldObject, newValues) {}
function updateItemInArray(array, itemId, updateItemCallback) {}

function setVisibilityFilter(visibilityState, action) {
// Technically, we don't even care about the previous state
return action.filter
}

function visibilityReducer(visibilityState = 'SHOW_ALL', action) {
switch (action.type) {
case 'SET_VISIBILITY_FILTER':
return setVisibilityFilter(visibilityState, action)
default:
return visibilityState
}
}

function addTodo(todosState, action) {
const newTodos = todosState.concat({
id: action.id,
text: action.text,
completed: false
})

return newTodos
}

function toggleTodo(todosState, action) {
const newTodos = updateItemInArray(todosState, action.id, todo => {
return updateObject(todo, { completed: !todo.completed })
})

return newTodos
}

function editTodo(todosState, action) {
const newTodos = updateItemInArray(todosState, action.id, todo => {
return updateObject(todo, { text: action.text })
})

return newTodos
}

function todosReducer(todosState = [], action) {
switch (action.type) {
case 'ADD_TODO':
return addTodo(todosState, action)
case 'TOGGLE_TODO':
return toggleTodo(todosState, action)
case 'EDIT_TODO':
return editTodo(todosState, action)
default:
return todosState
}
}

function appReducer(state = initialState, action) {
return {
todos: todosReducer(state.todos, action),
visibilityFilter: visibilityReducer(state.visibilityFilter, action)
}
}

2つの「状態の一部」リデューサーは、状態全体のうち自分の部分のみを引数として受け取るようになったため、複雑なネストされた状態オブジェクトを返す必要がなくなり、結果としてシンプルになりました。

ボイラープレートの削減

もうすぐ終わりです。 多くの人がswitch文を好まないため、アクションタイプとケース関数のルックアップテーブルを作成する関数を使用するのが一般的です。 ボイラープレートの削減で説明されている`createReducer`関数を使用します。

// Omitted
function updateObject(oldObject, newValues) {}
function updateItemInArray(array, itemId, updateItemCallback) {}

function createReducer(initialState, handlers) {
return function reducer(state = initialState, action) {
if (handlers.hasOwnProperty(action.type)) {
return handlers[action.type](state, action)
} else {
return state
}
}
}

// Omitted
function setVisibilityFilter(visibilityState, action) {}

const visibilityReducer = createReducer('SHOW_ALL', {
SET_VISIBILITY_FILTER: setVisibilityFilter
})

// Omitted
function addTodo(todosState, action) {}
function toggleTodo(todosState, action) {}
function editTodo(todosState, action) {}

const todosReducer = createReducer([], {
ADD_TODO: addTodo,
TOGGLE_TODO: toggleTodo,
EDIT_TODO: editTodo
})

function appReducer(state = initialState, action) {
return {
todos: todosReducer(state.todos, action),
visibilityFilter: visibilityReducer(state.visibilityFilter, action)
}
}

スライスによるリデューサーの結合

最後のステップとして、Reduxの組み込みユーティリティである`combineReducers`を使用して、トップレベルのアプリリデューサーの「状態の一部」ロジックを処理できます。 最終的な結果は次のとおりです。

// Reusable utility functions

function updateObject(oldObject, newValues) {
// Encapsulate the idea of passing a new object as the first parameter
// to Object.assign to ensure we correctly copy data instead of mutating
return Object.assign({}, oldObject, newValues)
}

function updateItemInArray(array, itemId, updateItemCallback) {
const updatedItems = array.map(item => {
if (item.id !== itemId) {
// Since we only want to update one item, preserve all others as they are now
return item
}

// Use the provided callback to create an updated item
const updatedItem = updateItemCallback(item)
return updatedItem
})

return updatedItems
}

function createReducer(initialState, handlers) {
return function reducer(state = initialState, action) {
if (handlers.hasOwnProperty(action.type)) {
return handlers[action.type](state, action)
} else {
return state
}
}
}

// Handler for a specific case ("case reducer")
function setVisibilityFilter(visibilityState, action) {
// Technically, we don't even care about the previous state
return action.filter
}

// Handler for an entire slice of state ("slice reducer")
const visibilityReducer = createReducer('SHOW_ALL', {
SET_VISIBILITY_FILTER: setVisibilityFilter
})

// Case reducer
function addTodo(todosState, action) {
const newTodos = todosState.concat({
id: action.id,
text: action.text,
completed: false
})

return newTodos
}

// Case reducer
function toggleTodo(todosState, action) {
const newTodos = updateItemInArray(todosState, action.id, todo => {
return updateObject(todo, { completed: !todo.completed })
})

return newTodos
}

// Case reducer
function editTodo(todosState, action) {
const newTodos = updateItemInArray(todosState, action.id, todo => {
return updateObject(todo, { text: action.text })
})

return newTodos
}

// Slice reducer
const todosReducer = createReducer([], {
ADD_TODO: addTodo,
TOGGLE_TODO: toggleTodo,
EDIT_TODO: editTodo
})

// "Root reducer"
const appReducer = combineReducers({
visibilityFilter: visibilityReducer,
todos: todosReducer
})

`updateObject`や`createReducer`のようなヘルパーユーティリティ、`setVisibilityFilter`や`addTodo`のような特定のケースのハンドラー、`visibilityReducer`や`todosReducer`のような状態の一部ハンドラーなど、いくつかの種類に分割されたリデューサー関数の例ができました。 また、`appReducer`は「ルートリデューサー」の例であることがわかります。

この例の最終的な結果は元のバージョンよりも明らかに長くなっていますが、これは主にユーティリティ関数の抽出、コメントの追加、および`return`文の分離など、明確にするための意図的な冗長性によるものです。 各関数を個別に見てみると、責任の量が減り、意図がより明確になっているはずです。 また、実際のアプリケーションでは、これらの関数は`reducerUtilities.js`、`visibilityReducer.js`、`todosReducer.js`、`rootReducer.js`などの別々のファイルに分割されるでしょう。