Boas práticas de desenvolvimento em Deluge

Boas práticas de desenvolvimento em Deluge

O Deluge (Data Enriched Language for the Universal Grid Environment) é a linguagem de script utilizada em diversas aplicações do ecossistema Zoho, como Zoho Creator, Zoho CRM, Zoho Books e Zoho Flow. Ela foi projetada para permitir automações rápidas e integrações entre sistemas sem a complexidade de linguagens tradicionais.

Em projetos empresariais, especialmente quando o Zoho Creator é utilizado como plataforma de desenvolvimento de aplicações corporativas, a forma como o Deluge é estruturado pode impactar diretamente na manutenção, escalabilidade e performance da solução.

Este artigo apresenta boas práticas fundamentais para o desenvolvimento em Deluge em ambientes corporativos, com foco em automação empresarial.


1. Estruture o código com foco em reutilização  

Um erro comum em projetos iniciais é criar scripts longos e repetitivos dentro de workflows, buttons e automações.

A boa prática é centralizar lógicas em funções reutilizáveis.

Exemplo incorreto:

Código duplicado em vários workflows:

if(input.Status == "Aprovado")
{
    input.Data_Aprovacao = zoho.currentdate;
    input.Usuario_Aprovacao = zoho.loginuser;
}

Boa prática  

Criar uma função reutilizável.

Vamos imaginar que o nome do Formulário onde contém os dados é DemoForm. Isso é um exemplo para executar em workflow de Evento de Registro somente Editado e não Criado.

function a ser criada:

 

void registrarAprovacao(int regID)
{

registro = DemoForm[ID == input.regID];
     registro.Data_Aprovacao = zoho.currentdate;
     registro.Usuario_Aprovacao = zoho.loginuser;
}

Uso no Workflow do DemoForm:

if(input.Status == "Aprovado")
{
    thisapp.registrarAprovacao(input.ID);
}

Benefícios  

  • Redução de duplicidade

  • Código mais limpo

  • Facilidade de manutenção

  • Maior padronização


2. Utilize nomenclatura padronizada  

Projetos corporativos podem ter centenas de formulários, workflows e funções. Sem padronização, o código se torna difícil de entender.

Recomendação de padrão  

Funções

fn_nomeDaFuncao

Exemplo:

fn_calcularImposto
fn_criarPedidoVenda
fn_sincronizarCRM

Variáveis

camelCase

Exemplo:

valorTotal
dataEntrega
clienteId

Listas

listaClientes
listaPedidos

Mapas

mapCliente
mapPedido

Essa padronização melhora muito a legibilidade do projeto.


3. Separe lógica de negócio da interface  

Em aplicações empresariais, é importante evitar colocar toda a lógica diretamente em:

  • On Validate

  • On Success

  • On Update

A lógica deve ser separada em funções de serviço.

Estrutura recomendada  

Workflows
   ↓
Funções de serviço
   ↓
Integrações / regras de negócio

Exemplo  

Workflow:

fn_processarPedido(input.ID);

Função:

void fn_processarPedido(pedidoId)
{
    pedido = Pedidos[ID == pedidoId];

    pedido.Status = "Processado";
    pedido.Data_Processamento = zoho.currentdate;
}

Essa separação facilita:

  • manutenção

  • testes

  • reaproveitamento de lógica


4. Evite loops desnecessários  

Loops mal estruturados podem causar problemas de performance, especialmente em aplicações com grande volume de dados.

Problema comum  

for each cliente in Clientes
{
    if(cliente.ID == clienteId)
    {
        info cliente.Nome;
    }
}

Boa prática  

Utilizar busca direta

cliente = Clientes[ID == clienteId];
info cliente.Nome;

Isso reduz drasticamente o consumo de recursos.


5. Controle de erros (Error Handling)  

Em automações empresariais, erros não tratados podem quebrar processos importantes.

Sempre que possível utilize try-catch.

Exemplo  

try
{
    response = invokeurl
    [
        url :"https://api.externa.com/pedido"
        type :POST
        parameters : mapPedido
    ];
}
catch(e)
{
    info "Erro na integração: " + e;
}

Boa prática adicional:

Criar logs de erro em um formulário.

Log_Erros

Campos:

  • Data

  • Usuário

  • Processo

  • Mensagem

Isso ajuda muito na governança da aplicação.


6. Use mapas e listas corretamente  

Deluge trabalha muito com List e Map.

Exemplo de Map  

mapCliente = Map();
mapCliente.put("Nome","Empresa ABC");
mapCliente.put("CNPJ","00.000.000/0001-00");

Exemplo de List  

listaProdutos = List();
listaProdutos.add("Notebook");
listaProdutos.add("Monitor");

Uso em integração  

parametros = Map();
parametros.put("cliente",mapCliente);
parametros.put("produtos",listaProdutos);

Essa estrutura é fundamental para integrações via API.


7. Otimize chamadas de API  

Integrações são comuns em projetos empresariais.

Evite:

  • chamadas repetidas

  • chamadas dentro de loops

  • múltiplas requisições desnecessárias

Problema  

for each pedido in listaPedidos
{
    invokeurl ...
}

Melhor abordagem  

Agrupar dados e enviar em lote quando possível.


8. Documente suas funções  

Projetos corporativos costumam durar anos.
Documentar o código é essencial.

Exemplo  

/*
Função: fn_calcularComissao

Descrição:
Calcula a comissão do vendedor com base no valor do pedido.

Parâmetros:
pedidoId (int)

Retorno:
decimal
*/

Isso ajuda:

  • novos desenvolvedores

  • auditorias

  • manutenção futura


9. Evite lógica excessiva em um único script  

Scripts muito grandes são difíceis de manter.

Regra prática:

Se um script tiver mais de 50–80 linhas, considere dividir em funções menores.

Isso melhora:

  • leitura

  • debugging

  • reutilização


10. Pense em arquitetura desde o início  

Em projetos grandes de Zoho Creator, o Deluge deve ser usado dentro de uma arquitetura bem definida.

Uma arquitetura comum é:

Interface (Forms / Pages)
        ↓
Workflows
        ↓
Funções de serviço
        ↓
Integrações / APIs
       

Essa abordagem segue princípios semelhantes a arquiteturas corporativas modernas, garantindo maior escalabilidade.


Conclusão  

O Deluge é uma linguagem extremamente poderosa para automação empresarial dentro do ecossistema Zoho. No entanto, seu verdadeiro potencial só é alcançado quando o desenvolvimento segue boas práticas de arquitetura, organização e performance.

Ao aplicar princípios como:

  • reutilização de código;

  • padronização de nomenclatura;

  • separação de responsabilidades;

  • tratamento de erros;

  • otimização de integrações;

é possível construir aplicações corporativas robustas, escaláveis e fáceis de manter.

Em projetos empresariais de médio e grande porte, essas práticas transformam o Zoho Creator de uma simples plataforma de automação em uma plataforma completa de desenvolvimento de aplicações de negócio.


      Zoho Campaigns Resources


        • Desk Community Learning Series


        • Digest


        • Functions


        • Meetups


        • Kbase


        • Resources


        • Glossary


        • Desk Marketplace


        • MVP Corner


        • Word of the Day


        • Ask the Experts


          • Sticky Posts

          • Participe dos encontros exclusivos Zoho User Groups (ZUGs)

            Temos um convite especial para você! Participe dos Zoho User Groups (ZUGs), encontros presenciais que conectam usuários, especialistas e parceiros da Zoho. Esses eventos são a oportunidade perfeita para compartilhar melhores práticas e descobrir como
          • Boas Práticas na Comunidade Zoho Brasil

            Participar da Comunidade Zoho Brasil pode ser uma experiência enriquecedora e colaborativa, mas para que isso aconteça, devemos sempre contribuir para um ambiente positivo e construtivo. Aqui estão algumas dicas de boas práticas para garantir que todos
          • Seja muito bem-vindo à Comunidade Zoho Brasil!

            É com muita empolgação que convidamos você a fazer parte deste novo espaço de colaboração, interação e troca de conhecimentos! Na Comunidade Zoho Brasil você poderá criar tópicos de conversa nos fóruns e também colaborar em discussões produtivas iniciadas
          • A assistente de redação inteligente do Zoho Writer, Zia, agora oferece suporte ao português brasileiro!

            Obtenha sugestões contextuais de ortografia e gramática e melhore a qualidade geral do seu conteúdo com a Zia ao escrever em português. Estamos treinando a Zia em um novo idioma para atender à crescente demanda dos nossos usuários por acesso multilíngue.

          Zoho CRM Plus Resources

            Zoho Books Resources


              Zoho Subscriptions Resources

                Zoho Projects Resources


                  Zoho Sprints Resources


                    Zoho Orchestly Resources


                      Zoho Creator Resources


                        Zoho WorkDrive Resources



                          Zoho CRM Resources

                          • CRM Community Learning Series

                            CRM Community Learning Series


                          • Tips

                            Tips

                          • Functions

                            Functions

                          • Meetups

                            Meetups

                          • Kbase

                            Kbase

                          • Resources

                            Resources

                          • Digest

                            Digest

                          • CRM Marketplace

                            CRM Marketplace

                          • MVP Corner

                            MVP Corner




                            Zoho Writer Writer

                            Get Started. Write Away!

                            Writer is a powerful online word processor, designed for collaborative work.

                              Zoho CRM コンテンツ




                                ご検討中の方

                                  • Recent Topics

                                  • Zoho Desk Ticket SLA Level

                                    Hello, we have 2 levels of SLA escalation for our Tickets. Is there a way to display on the ticket information the level of SLA escalation the ticket currently on? I am aware that we can see in the ticket history the level of escalation that has been
                                  • Allow Font Size 11 in Editors...

                                    That is basic functionality...
                                  • Darshan Hiranandani : How many participants can join a Zoho Meeting at once?

                                    Hi everyone, I'm Darshan Hiranandani, trying to find out the maximum number of participants that can join a Zoho Meeting at once. Has anyone here used Zoho Meeting for larger groups and can share their experience or knowledge about the participant limit?
                                  • 【まだ間に合う!】Zoho ユーザー交流会 | AI活用・CRM・Analytics の事例を聞いて、ユーザー同士で交流しよう!

                                    ユーザーの皆さま、こんにちは。コミュニティチームの藤澤です。 3月27日(金)に東京、新橋で開催する「東京 Zoho ユーザー交流会 NEXUS」へのお申し込みがまだの方は、この機会にぜひお申し込みください!(参加無料) ーーーーーーーーーーーーーーーーーーーーーーーーーーーーーーーーーーーー イベントの詳細はこちらから▷▷ https://www.zohomeetups.com/tokyo2026vol1#/?affl=communityforumpost3 ーーーーーーーーーーーーーーーーーーーーーーーーーーーーーーーーーーーー
                                  • Where is the scheduled report in New UI?

                                    Hi Team, Seems there is not such a field in New UI, hence I have to switch to old UI to handle request..
                                  • Building a Simple Raspberry Pi + Keypad IoT PoC with Zoho Flow

                                    I want to share a simple IoT PoC I recently built that connects a Raspberry Pi to Zoho Flow and Zoho Creator. The goal was to send PIN input data from a hardware keypad to Zoho and trigger a servo and buzzer for visual/audible feedback. This can serve
                                  • Enable integration of CRM CPQ functionality for ZohoOne customers using Zoho Finance application

                                    Hi there. I can't believe I'm needing to launch this idea as I would have thought this was a little obvious. Following a number of conversations with the technical team it's become evident that the CPQ functionality within CRM cannot integrate with Zoho
                                  • What's New in Zoho Billing | January 2026

                                    Excited about the latest enhancements in Zoho Billing? Our January updates bring an intelligent AI assistant, smarter subscription management, and improved tax compliance, saving you time and reducing manual work. Dive into the details below to see how
                                  • Is there a way to sell in a practical method multiple subscriptions of the same product? i.e. domain names

                                    In evaluating Zoho Billing, a hurdle to adopting it is that Zoho Billing does not seem designed to support businesses that sell multiple subscriptions of the same product. In our case, we need to sell and manage several domain names per client. Am I right
                                  • Zoho Writer Frequently not loading

                                    I've reported this as a problem already but I can't log into my email right now or get onto the main site so you're going to hear about it again here: at least once a week, Zoho Writer will just refuse to load entirely. The main page will load and load
                                  • Update P_Leave: code: 7052 "Employee_ID": "Enter Employee ID"

                                    Hi, Zoho People - Update Leaves Can someone assist? ------------------------------------------------------------------------------------------ col = Collection(); col.insert("recordid":id); col.insert("Date_Check_Approval":zoho.currentdate); info zoho.people.update("P_Leave",col.toMap());
                                  • Can't change form's original name in URL

                                    Hi all, I have been duplicating + editing forms for jobs regarding the same department to maintain formatting + styling. The issue I've not run into is because I've duplicated it from an existing form, the URL doesn't seem to want to update with the new
                                  • Can't rename groups on Mac desktop app

                                    I'm working on an up-to-date Mac with a freshly downloaded Notebook app. I'm trying to rename a group within a notebook. Here I have, left to right, a note, a group, and a note. I select the group. On the top left, I select Action. On the dropdown, "Rename"
                                  • Custom CSS for Zoho CRM Team Bookings embeded widget

                                    Hello, we are adding Zoho CRM Team Bookings (crm.zoho.com) in our public website. We know that we can change Theme Color, Font Color and Background Color: Zoho CRM Booking Styling But is it possible to change other CSS attributes e.g. Font Family, like
                                  • Strange behavior in CRM Number Field – Characters allowed but not "e"?

                                    Hi everyone, Has anyone faced this strange issue in Zoho CRM? In a Number field, it is possible to type some characters, but the character "e" cannot be entered. This was really surprising to me. Normally, a number field should restrict all characters
                                  • Best Way to Manage Approvals Within Blueprint Stages?

                                    Hi, I am working on a requirement involving Blueprint and approval logic in Zoho CRM and would appreciate some guidance. I understand that approval processes do not trigger when a record is currently within a blueprint, which makes it challenging to implement
                                  • Marketing Tip #25: Grow your social presence with a simple posting routine

                                    Consistency is one of the biggest growth drivers on social media. Regular content keeps your store visible and helps customers remember you. Even 3–4 posts a week can build momentum over time. The easiest way to stay consistent is to stop trying to create
                                  • How to add "All Open AND Overdue" back to the Home Page Task Component?

                                    Hi everyone, I’m looking for a way to restore the Tasks component dropdown list on the Zoho CRM Home Page. Since the recent update to the Task area in my Home Page Classic View, the dropdown options (e.g., My Next 7 Days + Overdue) are too restrictive
                                  • Duplicate Leads Concerns with Round Robin and Lead Approval Process

                                    It is great to have the Duplicate Lead Approval Process,  there are a few issues with the process that I would greatly appreciate taken consideration in enhancing. It appears that A Lead comes in Lead owner assigned by the Round Robin Check for Duplicate, If the lead is a Duplicate the Lead owner gets an email of a duplicate needs approval email assign to the approval process      This causes problems, The duplicate approval process is done by a different level person, they do not get the email notification
                                  • Dashboard target enhancements

                                    Often individuals in IT are creating dashboards for their sales team. The ability to create a single dashboard that can be used by multiple people is key. A components for a dashboard have the ability to filter by logged in user which is great. However
                                  • How to update "Lead Status" to more than 100 records

                                    Hello Zoho CRM, How do I update "Lead Status" to more than 100 records at once? To give you a background, these leads were uploaded or Imported at once but the lead status record was incorrectly chosen. So since there was a way to quickly add records in the system no matter how many they are, we are also wondering if there is a quicker way to update these records to the correct "Lead Status". I hope our concern makes sense and that there will be a fix for it. All the best, Jonathan
                                  • Finding rhythm through poetry

                                    Poetry has long been a powerful form of expression, discovery, and reflection. For many, it is a way to pen down their thoughts and experiences. The "poetic license" allows writers to shape their words with rhythm and flow. This year, on World Poetry
                                  • Bring your own credentials (BYOC) for connections in Zoho Creator

                                    Hello everyone, We're excited to announce an important step forward in how integrations and authentications work in Zoho Creator. Zoho Creator is a versatile platform for integrations, enabling you to connect with thousands of third-party services using
                                  • CRM x WorkDrive: File storage for new CRM signups is now powered by WorkDrive

                                    Availability Editions: All DCs: All Release plan: Released for new signups in all DCs. It will be enabled for existing users in a phased manner in the upcoming months. Help documentation: Documents in Zoho CRM Manage folders in Documents tab Manage files
                                  • Project Management Bulletin: March, 2026

                                    We are passionate about equipping our users with efficient solutions that help them run their businesses successfully. Our collective efforts over the past 2 years have culminated in the launch of Sprints 3.0— built with reliable features, impactful integrations,
                                  • Composite items inside of composite items; bill of materials needed

                                    Hi Zoho and Everyone, I am evaluating whether Zoho Inventory will work for my small business. I grow and harvest herbs and spices but also get from wholesalers. I use all these items to make herbal teas, but also sell them as individual items on my Shopify store and Etsy. I discovered the composite item bundling and am wondering if I could get some assistance since there is no bill of materials: Our herbal company's best selling tea is a sleepytime tea. Sleepytime Tea can be purchased in three weights
                                  • Automation Series: Sync Task Status with Zoho Desk Tickets

                                    In Zoho Projects, you can automatically close and reopen an associated Zoho Desk ticket when the status of a task is changed. This syncs the current state of the task with the support ticket without manual updates. For instance, a support team handling
                                  • Auto-Generate Line Numbers in Item Table Using HTML & CSS Counters (Zoho Books & Zoho Inventory Custom Templates)

                                    <div> <style> /* Start counter from 0 inside tbody */ tbody#lineitem { counter-reset: rowNumber; } /* Increment counter for each row */ tbody#lineitem tr { counter-increment: rowNumber; } /* Show counter value in first column */ tbody#lineitem tr td:first-child::before
                                  • Does zoho inventory need Enterprise or Premium subsrciption to make Widgets.

                                    We have Zoho One Enterprise and yet we can't create widgets on inventory.
                                  • Introducing Radio Buttons and Numeric Range Sliders in Zoho CRM

                                    Release update: Currently out for CN, JP, AU and CA DCs (Free and standard editions). For other DCs, this will be released by mid-March. Hello everyone, We are pleased to share with you that Zoho CRM's Layout Editor now includes two new field formats—
                                  • New UI for Writer - Disappointed

                                    I've been enjoying Zoho Writer as a new user for about 6 months, and I really like it. One of my favorite things about it is the menu bar, which you can hide or leave out while still seeing most of your page because it is off to the left. I think this
                                  • Zoho CAMPAIGNS working hours

                                    Hi I use Campaigns Automation workflows to automate follow-ups to my Leads. I discovered this weekend that emails are being sent out on Sundays. How do I limit my Campaigns outgoing emails to business working hours? This is very important! Thanks, D
                                  • Depositing funds to account

                                    Hello, I have been using Quickbooks for many years but am considering moving to Zoho Books so I am currently running through various workflows and am working on the Invoicing aspect. In QB, the process is to create an invoice, receive payment and then
                                  • Create Receipt of a Donation (not a sale)

                                    We are a non-profit organization that receives general donations. How do I create a receipt of payment for the donor and categorize the payment as a Gift? I tried the method of creating an invoice; however that automatically created a "Sales" transaction
                                  • Function #2: Create a Deal in Zoho CRM when an Estimate is created in Zoho Books

                                    For those who use Zoho CRM integrated with Zoho Books, here's a nifty function that helps you optimize your sales process by adding a Deal in Zoho CRM whenever an estimate is created in Zoho Books. Custom Function: To create the custom function, go to
                                  • New Custom View -Sorting the Custom fields

                                    While creating a New Custom View in invoice , Customers, Bills ,expense etc , the sorting of custom fields are not available , a query function "order by / sort by  " may also be included in  Define new criteria module  which will be more beneficial to
                                  • Grouping Undeposited Funds to Move to other accounts

                                    In the bank option it would be nice to check what transactions in undeposited funds I want to move to other accounts. Then while checking this it can accumulate totals and created whats essentially a deposit slip. Once the transaction is moved it should
                                  • Sync your CRM Tasks with Zoho Projects

                                    Zoho Projects integration with Zoho CRM helps you manage your tasks more efficiently. You can create all project related activities right inside your CRM using this integration. Create new portal or associate an existing portal, add projects to the portal,
                                  • Zoho CRM strips whitespace in text fields

                                    When editing field text with multiple spaces: CRM - both UI and API trim / compress the whitespace to a single space when saving: Is this known / expected / documented behaviour?
                                  • WorkDrive API returning empty response even after placing file in Team Folder

                                    Hi everyone, I am trying to fetch a file from Zoho WorkDrive using a Deluge standalone function in Zoho People. The API call executes successfully using a configured connection, but the response is coming back empty. I have verified the following: The
                                  • Next Page