Sobes.tech
Middle+

What is a data bus and how is it used in programming?

sobes.tech AI

Answer from AI

Data bus (Event Bus or Message Bus) is a software pattern that allows different components of a system to interact with each other without knowing the detailed structure and existence of each other directly. Components publish events to the bus, and other components can subscribe to the types of events they need.

The bus acts as an intermediary, routing events from publishers to subscribers.

Usage in programming:

  • Loose coupling: Components become less dependent on each other. Changing one component minimally affects others.
  • Extensibility: Easily add new components that either publish or subscribe to events.
  • Microservices architecture: Used for interaction between independent services.
  • UI components: Allows interface components to exchange information without direct method calls.
  • Reactive systems: Foundation for building systems that respond to events.

Example implementation in Node.js:

Can be implemented using the standard EventEmitter module.

// Creating a data bus (based on EventEmitter)
const EventEmitter = require('events');
const eventBus = new EventEmitter();

// Component 1: Subscribes to the 'userCreated' event
eventBus.on('userCreated', (user) => {
  console.log(`User created: ${user.name}`);
});

// Component 2: Publishes the 'userCreated' event
function createUser(user) {
  // User creation logic...
  console.log(`Creating user ${user.name}...`);
  eventBus.emit('userCreated', user); // Publishing event
}

// Usage
createUser({ name: 'Ivan', id: 1 });
What is a data bus and how is it used in programming… - sobes.tech