Sobes.tech
Senior

Tell me about the Code-On-Demand principle.

sobes.tech AI

Answer from AI

The Code-On-Demand principle is one of the optional architectural styles in REST, where the server can temporarily extend the client's functionality by transmitting executable code.

This allows the client to be more lightweight, shifting some logic to the server, which is loaded "on demand" when necessary.

Examples of usage:

  • JavaScript in web applications: The server sends JavaScript code to the browser, which executes on the client side to implement interactivity, data validation, asynchronous requests, etc.
  • Plugins and extensions: The server can provide code to extend the functionality of the application or client.

Advantages:

  • Reduced data transfer volume: Code is sent only when needed.
  • Flexibility: The server can dynamically change the client's behavior.
  • A more lightweight client: The client does not need to implement all possible functionalities in advance.

Disadvantages:

  • Implementation and security complexity: A mechanism is required for reliable transmission and execution of code on the client side.
  • Performance: Loading and executing code can take time.
// Example of Code-On-Demand in web: server sends JS for form validation
// Server sends HTML with a form and a script
/*
<html>
<body>
  <form id="myForm">
    <input type="text" id="myInput">
    <button type="submit">Submit</button>
  </form>

  <script src="/validate.js"></script> // Script is loaded "on demand"
</body>
</html>
*/

// Content of /validate.js
// This code runs on the client side after loading
document.getElementById('myForm').addEventListener('submit', function(event) {
  const input = document.getElementById('myInput');
  if (input.value.trim() === '') {
    alert('Field cannot be empty!');
    event.preventDefault(); // Cancels form submission
  }
});