MVC / MVVM — Design Patterns

MVC (Model-View-Controller) dan MVVM (Model-View-ViewModel) adalah architectural patterns yang memisahkan kode menjadi bagian-bagian dengan tanggung jawab…

MVC (Model-View-Controller) dan MVVM (Model-View-ViewModel) adalah architectural patterns yang memisahkan kode menjadi bagian-bagian dengan tanggung jawab berbeda.

Mengapa perlu pemisahan? Tanpa struktur, kode cenderung jadi "spaghetti" — logic bisnis, tampilan, dan data handling tercampur di satu tempat. MVC/MVVM membantu memisahkan concerns.

MVC — Model View Controller:

User Action → Controller → Model → View → User Sees
// Model — murni data & logic
class TodoModel {
  constructor() {
    this.todos = [];
  }

  add(text) {
    this.todos.push({ id: Date.now(), text, done: false });
  }

  toggle(id) {
    const todo = this.todos.find(t => t.id === id);
    if (todo) todo.done = !todo.done;
  }

  getAll() {
    return [...this.todos];
  }
}

// View — murni tampilan
class TodoView {
  render(todos) {
    console.log("=== Todo List ===");
    todos.forEach(t => {
      const status = t.done ? "[x]" : "[ ]";
      console.log(`${status} ${t.text}`);
    });
  }
}

// Controller — menghubungkan Model dan View
class TodoController {
  constructor(model, view) {
    this.model = model;
    this.view = view;
  }

  addTodo(text) {
    this.model.add(text);
    this.view.render(this.model.getAll());
  }

  toggleTodo(id) {
    this.model.toggle(id);
    this.view.render(this.model.getAll());
  }
}

const model = new TodoModel();
const view = new TodoView();
const controller = new TodoController(model, view);

controller.addTodo("Belajar JavaScript");
controller.addTodo("Buat project");

MVVM — Model View ViewModel:

Model ↔ ViewModel ↔ View

Perbedaan utama: two-way data binding. ViewModel otomatis sync dengan View.

// ViewModel di React = Custom Hook!
function useTodoViewModel() {
  const [todos, setTodos] = useState([]);

  // Business logic di ViewModel
  const addTodo = (text) => {
    setTodos(prev => [...prev, { id: Date.now(), text, done: false }]);
  };

  const toggleTodo = (id) => {
    setTodos(prev => prev.map(t =>
      t.id === id ? { ...t, done: !t.done } : t
    ));
  };

  const remaining = todos.filter(t => !t.done).length;

  // Expose ke View
  return { todos, addTodo, toggleTodo, remaining };
}

// View — hanya tampilan, logic di ViewModel
function TodoApp() {
  const { todos, addTodo, toggleTodo, remaining } = useTodoViewModel();
  // render UI...
}

MVC di dunia nyata:

MVVM di dunia nyata:

Mana yang lebih baik? Tidak ada yang "lebih baik" secara absolut. MVC lebih sederhana dan cocok untuk server-side. MVVM lebih natural untuk reactive UI frameworks seperti React dan Vue.

Yang penting bukan labelnya, tapi prinsipnya: pisahkan data, logic, dan tampilan.