Clean Code | SAP UI5
유지보수하기 쉽고 테스트 가능한 UI5 앱을 위한 가이드라인: 구조, 이름, async/await, 선언적 바인딩, 프래그먼트, 포매터, 성능.
10분 분량ui5 · fiori · sap
유지보수하기 쉽고 테스트 가능하며 확장 가능한 SAP UI5 앱을 작성하기 위한 실전 가이드라인입니다. 구조, 이름 짓기, 비동기 패턴, 바인딩, 프래그먼트, 포매터, 오류 처리, 성능 팁을 JS/TS 예제와 함께 다룹니다.
핵심 원칙
- 작고 집중된 모듈: 컨트롤러는 얇게, 로직은 헬퍼/서비스로.
- 명확한 이름: 모델/컨트롤은 명사, 핸들러는 동사, 약어 금지.
- 일관된 구조:
onInit,onExit, 공개 핸들러, 그다음 비공개 헬퍼(_helper). - 매직 문자열 금지: ID, 모델 이름, 이벤트/채널 이름, 라우트를 한곳에 모으세요.
- 명령형 DOM 변경보다 XML의 선언적 바인딩을 선호하세요.
- 단일 데이터 흐름: 관심사마다 하나의 진실 공급원 (뷰 모델 vs OData 모델).
- 유용한 메시지와 함께 빨리 실패하고, 사용자 피드백에는 MessageManager를 쓰세요.
프로젝트 구조 (예시)
webapp/
component.js
manifest.json
model/
models.js # factory for JSONModel, i18n, device
constants.js # model names, routes, ids
formatters.js # pure formatters
services.js # fetch/XHR wrappers
controller/
Main.controller.js
view/
Main.view.xml
fragments/
UploadDialog.fragment.xml상수 (매직 문자열 금지)
// webapp/model/constants.js
export const MODELS = Object.freeze({
I18N: "i18n",
VIEW: "view",
ODATA: "",
});
export const IDS = Object.freeze({
TABLE: "ordersTable",
DIALOG_UPLOAD: "uploadDialog",
});
export const ROUTES = Object.freeze({
LIST: "OrdersList",
OBJECT: "OrdersObjectPage",
});모델 팩토리
// webapp/model/models.js
import JSONModel from "sap/ui/model/json/JSONModel";
export function createViewModel() {
return new JSONModel({
busy: false,
search: "",
selectedCount: 0,
});
}component.js나 onInit에서 등록합니다.
// in Component or controller onInit
import { MODELS } from "../model/constants";
import { createViewModel } from "../model/models";
this.getView().setModel(createViewModel(), MODELS.VIEW);컨트롤러 구조 (async/await, 헬퍼)
// webapp/controller/Main.controller.js
sap.ui.define(
[
"sap/ui/core/mvc/Controller",
"sap/ui/core/Fragment",
"sap/ui/core/message/MessageManager",
"sap/ui/core/BusyIndicator",
"../model/constants",
"../model/services",
],
function (
Controller,
Fragment,
MessageManager,
BusyIndicator,
constants,
services
) {
"use strict";
return Controller.extend("demo.controller.Main", {
onInit() {
this._mm = sap.ui.getCore().getMessageManager();
this.getView().addDependent(
this._mm.registerObject(this.getView(), true)
);
},
async onRefresh() {
await this._withBusy(async () => {
await this._reloadList();
});
},
onOpenUpload() {
return Fragment.load({
name: "demo.fragments.UploadDialog",
controller: this,
id: this.getView().getId(),
}).then((d) => {
this._upload = d;
this.getView().addDependent(d);
d.open();
});
},
onCloseUpload() {
this._upload?.close();
this._upload?.destroy(true);
this._upload = null;
},
// Private helpers
async _reloadList() {
const table = this.byId(constants.IDS.TABLE);
await table?.getBinding("items")?.refresh();
},
async _withBusy(fn) {
BusyIndicator.show(0);
try {
return await fn();
} finally {
BusyIndicator.hide();
}
},
});
}
);참고:
- 중첩 콜백 대신
async/await를 쓰세요. - BusyIndicator와 새로고침 로직을 캡슐화하세요.
- 뷰 상태는 전역 변수가 아니라 뷰 모델에 두세요.
XML 뷰: 선언적 바인딩
<!-- webapp/view/Main.view.xml -->
<mvc:View xmlns:mvc="sap.ui.core.mvc" xmlns="sap.m" controllerName="demo.controller.Main">
<VBox width="100%">
<Toolbar>
<Title text="Orders" level="H2"/>
<ToolbarSpacer/>
<Button text="Refresh" press="onRefresh" type="Emphasized"/>
<Button text="Upload" press="onOpenUpload"/>
</Toolbar>
<Table id="ordersTable" items="{ path: '/Orders' }">
<columns>
<Column><Text text="ID"/></Column>
<Column><Text text="Customer"/></Column>
<Column><Text text="Total"/></Column>
</columns>
<items>
<ColumnListItem>
<cells>
<Text text="{ID}"/>
<Text text="{CustomerName}"/>
<ObjectNumber number="{path: 'Total', type: 'sap.ui.model.type.Currency', formatOptions: { showMeasure: false }}"/>
</cells>
</ColumnListItem>
</items>
</Table>
</VBox>
<dependents>
<core:Fragment id="uploadFrag" type="XML" fragmentName="demo.fragments.UploadDialog" xmlns:core="sap.ui.core"/>
</dependents>
</mvc:View>팁:
- visibility/enabled는 JS가 아니라 모델 속성(
{view>/busy})에 바인딩하세요. - 바인딩에서 type/formatOptions를 쓰고, 문자열을 직접 포맷하지 마세요.
포매터 (순수하고 재사용 가능하게)
// webapp/model/formatters.js
export function currency(value, currency = "EUR") {
if (value == null) return "";
return new Intl.NumberFormat(undefined, { style: "currency", currency }).format(value);
}
``+
Use in XML:
```xml
<Text text="{ parts: ['Total'], formatter: '.formatters.currency' }"/>포매터를 순수 함수(부수 효과 없음)로 유지하면 테스트가 쉬워집니다.
서비스 (HTTP/NW RFC/백엔드 래퍼)
// webapp/model/services.js
export async function requestJSON(url, options = {}) {
const res = await fetch(url, {
headers: { "Content-Type": "application/json" },
...options,
});
const data = await res.json().catch(() => null);
if (!res.ok) throw new Error(data?.error?.message || res.statusText);
return data;
}fetch 로직을 컨트롤러 안에 두지 말고 한곳에 모아 오류와 헤더 처리를 표준화하세요.
MessageManager로 오류 처리
try {
await this._withBusy(() => services.requestJSON("/api/orders"));
} catch (e) {
const msg = new sap.ui.core.message.Message({
message: e.message,
type: sap.ui.core.MessageType.Error,
});
sap.ui.getCore().getMessageManager().addMessages(msg);
}장점: 일관된 오류 경험, 메시지 팝오버 지원, i18n.
프래그먼트 (조합과 재사용)
<!-- webapp/fragments/UploadDialog.fragment.xml -->
<core:FragmentDefinition xmlns="sap.m" xmlns:core="sap.ui.core">
<Dialog title="Upload">
<content>
<FileUploader width="100%"/>
</content>
<endButton><Button text="Close" press="onCloseUpload"/></endButton>
</Dialog>
</core:FragmentDefinition>규칙:
- 프래그먼트는 "멍청하게" 유지하세요 (무거운 로직 없음). 이벤트는 컨트롤러가 처리합니다.
- 메모리 누수를 막으려면 닫을 때 항상
destroy(true)로 프래그먼트를 제거하세요.
테스트하기 쉬운 패턴
- 순수 함수(포매터, 매퍼, 검증기)를 분리해 단위 테스트를 쉽게 하세요.
- 의존성 주입(가능하면 서비스를 컨트롤러에 전달)으로 목을 쓰세요.
- 상태를 정적 싱글턴에 두지 말고 모델을 쓰세요.
성능 팁
- 수동 페이지네이션보다 growing/무한 스크롤이 있는
ListBinding을 쓰세요. autoExpandSelect와$select로 OData에서 필요 이상으로 가져오지 마세요.- 검색 liveChange를 제한하고, 비싼 작업에는 디바운스를 거세요.
- 반복문 안에서
byId를 호출하지 말고 필요하면 참조를 캐시하세요. JSONModel.setData(객체 전체 교체)를 남용하지 말고, 작은 변경에는setProperty를 쓰세요.
UI5에서 TypeScript (선택)
// tsconfig.json (snippet)
{
"compilerOptions": {
"target": "ES2020",
"module": "ESNext",
"strict": true,
"types": ["@types/openui5"],
"moduleResolution": "bundler"
}
}장점: 핸들러/서비스의 더 강한 계약, 더 나은 에디터 지원, 더 안전한 리팩터링.
체크리스트 (TL;DR)
- 컨트롤러는 얇게, 로직은 헬퍼/서비스에.
- 선언적 바인딩, 순수 포매터, 재사용 가능한 프래그먼트.
- 매직 문자열 금지, ID/모델/라우트는 한곳에.
- Async/await + busy 래퍼, 일관된 오류 처리 (MessageManager).
- 순수 함수 테스트, 서비스는 의존성 주입.
- 성능을 위해 바인딩과 요청을 조정.