How to invoke one function from another in PlantUML preprocessing?

less than a minute read 06-10-2024
How to invoke one function from another in PlantUML preprocessing?


Calling Functions in PlantUML Preprocessing: Streamlining Your Diagrams

PlantUML is a powerful tool for creating diagrams, but sometimes you need to repeat complex elements or use shared logic. This is where preprocessing shines, allowing you to define reusable functions within your PlantUML code. But how do you call these functions within your diagrams?

Let's explore this with a real-world example:

Scenario: You're designing a system architecture diagram. You have multiple components with similar shapes and connections. Instead of repeating the same code for each component, you can create a function to handle this.

Original Code:

@startuml
!include <aws/aws>

component "Service 1" as S1
component "Service 2" as S2
component "Service 3" as S3

S1 --> AWS.S3
S2 --> AWS.S3
S3 --> AWS.S3

@enduml

The Problem: You're repeating the connection to AWS.S3 for each service. This code is repetitive and prone to errors.

Solution: Create a function to handle the connection:

!include <aws/aws>

!function connectToS3($component)
$component --> AWS.S3
!endfunction

component "Service 1" as S1
component "Service 2" as S2
component "Service 3" as S3

!call connectToS3(S1)
!call connectToS3(S2)
!call connectToS3(S3)

@enduml

Analysis:

  • !function and !endfunction: These define the function's scope.
  • $component: This is a parameter passed to the function.
  • !call: This keyword is used to invoke the function.

Benefits:

  • Code Reusability: Avoid repeating the same code multiple times.
  • Maintainability: Easy to modify the connection logic by editing the function.
  • Readability: Cleaner and more understandable diagrams.

Further Exploration:

  • Multiple Parameters: You can pass multiple parameters to your functions.
  • Function Chaining: You can call one function from another to build complex logic.
  • Custom Functions: You can create custom functions for specific tasks, like generating shapes or relationships.

Remember: PlantUML preprocessing offers a flexible way to manage complex diagram generation. By using functions effectively, you can write cleaner, more maintainable code and create visually appealing diagrams with ease.

Resources:

Let me know if you have any other PlantUML questions!