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.

    Access your files securely from anywhere

        All-in-one knowledge management and training platform for your employees and customers.






                              Zoho Developer Community




                                                    • 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.


                                                              Manage your brands on social media



                                                                    Zoho TeamInbox Resources



                                                                        Zoho CRM Plus Resources

                                                                          Zoho Books Resources


                                                                            Zoho Subscriptions Resources

                                                                              Zoho Projects Resources


                                                                                Zoho Sprints Resources


                                                                                  Qntrl Resources


                                                                                    Zoho Creator Resources



                                                                                        Zoho CRM Resources

                                                                                        • CRM Community Learning Series

                                                                                          CRM Community Learning Series


                                                                                        • Kaizen

                                                                                          Kaizen

                                                                                        • Functions

                                                                                          Functions

                                                                                        • Meetups

                                                                                          Meetups

                                                                                        • Kbase

                                                                                          Kbase

                                                                                        • Resources

                                                                                          Resources

                                                                                        • Digest

                                                                                          Digest

                                                                                        • CRM Marketplace

                                                                                          CRM Marketplace

                                                                                        • MVP Corner

                                                                                          MVP Corner







                                                                                            Design. Discuss. Deliver.

                                                                                            Create visually engaging stories with Zoho Show.

                                                                                            Get Started Now


                                                                                              Zoho Show Resources

                                                                                                Zoho Writer

                                                                                                Get Started. Write Away!

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

                                                                                                  Zoho CRM コンテンツ



                                                                                                    Nederlandse Hulpbronnen


                                                                                                        ご検討中の方




                                                                                                                • Recent Topics

                                                                                                                • SAP Business One(B1) integration is now live in Zoho Flow

                                                                                                                  We’re excited to share that SAP Business One (B1) is now available in Zoho Flow! This means you can now build workflows that connect SAP B1 with other apps and automate routine processes without relying on custom code. Note: SAP Business One integration
                                                                                                                • sync two zoho crm

                                                                                                                  Hello everyone. Is it possible to sync 2 zoho crm? what would be the easiest way? I am thinking of Flow. I have a Custom Module that I would like to share with my client. We both use zoho crm. Regards.
                                                                                                                • Showing the map along with mileage expense

                                                                                                                  When you use the GPS to track mileage, it shows you the map of the actual path travelled. It would be very useful and practical to save that map with the mileage expense, so that when the report is created, it provides a map of each mileage expense associated
                                                                                                                • Import MSG to Yandex Mail Account | Fast & Reliable Solution

                                                                                                                  If you are facing problem to import MSG files to Yandex Mail account can be challenging if done manually, especially when handling multiple files. A reliable solution is using the MacGater Mac MSG Converter, which simplifies the entire process with accuracy
                                                                                                                • Copy all reports in a folder

                                                                                                                  I currently have a database that I need to create multiple charts filtered by market. All of the charts are identical, I just change to of the filters and then I have the next market's set of charts. The only way I've been able to copy charts (reports)
                                                                                                                • OpenURL working Intermittently

                                                                                                                  Never had this issue before, everything was working fine up to a few days ago. We have a buttons on reports to open forms with pre-filled fields. Now, there are instances where it will throw and error and gives no feedback. What is really strange is not
                                                                                                                • Trigger workflows from SLA escalations in Zoho Desk?

                                                                                                                  Hey everyone, I’m currently working with SLA escalation rules in Zoho Desk and ran into a limitation that I’m hoping someone here has solved more elegantly. As far as I can tell, SLA escalations only support fairly limited actions (like changing the ticket
                                                                                                                • Zoho Recruit mailserver get blocked by Microsoft!

                                                                                                                  Hi, We have experienced this issue twice now, where Zoho Recruit outbound IP addresses are being blocked by Microsoft. We are confident that Microsoft is the blocking party, as all outbound emails to candidates with @hotmail.com, @live.com, and @outlook.com
                                                                                                                • Calculate Hours Minutes Sec in Zoho Creator Using Deluge

                                                                                                                  check_In = "8-Aug-2023 10:00:00".toDateTime().toLong(); checkout = "8-Aug-2023 18:00:00".toDateTime().toLong(); //difference = start.timeBetween(end); check_In = "8-Aug-2023 17:56:50".toDateTime().toLong(); checkout = "8-Aug-2023 18:00:00".toDateTime().toLong();
                                                                                                                • Build Smarter Apps with AI in Zoho Creator

                                                                                                                  Build Smarter Apps with AI in Zoho Creator This is truly the era of AI, and businesses that adapt now will lead tomorrow. Zoho is already moving ahead in this direction, continuously evolving its platform with powerful AI capabilities. With Zoho Creator,
                                                                                                                • Zia Dashboard Insights : turn your dashboard into decisions

                                                                                                                  When you look at a chart or KPI in a dashboard, you would possibly see something like: Revenue: $2.4M ↓ 18% vs last month. It can be a positive growth or a negative one, or a dip in revenue, a spike in deals, a slowdown in renewals—all you usually see
                                                                                                                • Tickets without registration

                                                                                                                  Hi, would it be possible to give customers the opportunity to be able to read their tickets without registration?
                                                                                                                • Zoho Desk Answer Bot vs. Zia Agents – Knowledge Base & Ticket Access

                                                                                                                  Hi everyone, I’m currently evaluating AI options in Zoho Desk and ran into some limitations with the Answer Bot: Answer Bot limitations Only uses Knowledge Base articles No access to tickets Limited control over sources: Either one Help Center or all
                                                                                                                • Como estruturar automações eficientes no Zoho Creator

                                                                                                                  Como estruturar automações eficientes no Zoho Creator Introdução No contexto de aplicações empresariais, automação não é apenas uma conveniência, é um fator crítico para ganho de produtividade, redução de erros e escalabilidade operacional. O Zoho Creator
                                                                                                                • Changing the status of a work-order

                                                                                                                  Is there a way to change the status of a work-order?
                                                                                                                • Online Payment Fees

                                                                                                                  We don't take many online credit card payments so the merchant service provider (PayPal) charges us the 2.9% fee for processing the amount. I would like the ability for the fee to be automatically added to the total amount for "ease of payment". We'd
                                                                                                                • What is a realistic turnaround time for account review for ZeptoMail?

                                                                                                                  On signing up it said 2-3 business days. I am on business-day 6 and have had zero contact of any kind. No follow-up questions, no approval or decline. Attempts to "leave a message" or use the "Contact Us" form have just vanished without a trace. It still
                                                                                                                • Zia Agents in Zoho CRM: a better way to set up digital employees

                                                                                                                  Hello everyone, If you've been using Zia Agents in Zoho CRM, so far using Connections was the only deployment method you're familiar with. You create an agent in Zia Agents (define its objective, write instructions, use tools, add knowledge base) and
                                                                                                                • Bank Feeds

                                                                                                                  Since Friday my bank feeds wont work. I have refreshed feeds, deactivate and reactivate and nothing is working
                                                                                                                • Logged out

                                                                                                                  Hi, just been working on a sheet when a pop up box appeared telling me I'm going to be logged out in x number of seconds and if I reload I may lose any edits, or words to that effect. It did indeed log me out and I did indeed lose my last edits. Any idea
                                                                                                                • Zoho API

                                                                                                                  I have little experience with API. I'm trying to get a Custom API working with Zoho creator. I have created a Custom API and created an Endpoint URL, but i get a 9400 error code "The provided HTTP method is not valid for this custom API". Based off the
                                                                                                                • #157127950

                                                                                                                  Where did my initial question go?
                                                                                                                • Zoho writer unable to merge documents to PDF with basic fonts in Hebrew or fonts from my computer

                                                                                                                  I created several forms that will be merged into PDF files through Zoho Writer and I am unable to receive the PDF in the basic fonts of the Hebrew language or in the fonts I have on my computer. The writer exports to PDF an exchange font that looks very
                                                                                                                • How I Implemented Subscription-Based Access Control and Expiry Handling in Zoho Creator

                                                                                                                  I recently worked on a use case where users come into the application to request a service, but they should only be able to continue the process after completing a subscription. The challenge was not just controlling access, but also making sure that
                                                                                                                • Zoho Forms API

                                                                                                                  Is there any way to get all form entry list using API? Looking forward to hear from you
                                                                                                                • Zoho Projects : Task should auto-update to 'In Progress' if timer started

                                                                                                                  Namaskaram. Right now, if a Task's timer is started, the Task stays in 'Not Started' status. One has to manually update it to 'In Progress'. From a #uxdesign standpoint, it is an unnecessarily two step process to start working on a task. It would be better that, if I start the timer on a task, it should automatically change to 'In Progress' status. Crafted with ❤️ Zoho Gurus | Zoho One Practice Team @ CubeYogi Zoho Authorised Partner | 7+ Yrs | 200+ Projects | 100+ Customers
                                                                                                                • Laatste facturen en betalingen niet zichtbaar in mijn account

                                                                                                                  Wij gebruiken ZOHO invoice al jaren, maar sinds afgelopen week is mijn laatst verzonden factuur niet zichtbaar in mijn account, en tevens de laatst betaalde facturen zie ik niet. Hoe kan dit? Ik heb de pagina al diverse keren gerefreshed.
                                                                                                                • Undelivered Mail uncategorized-bounce errors when sending invoices

                                                                                                                  Recently we have been getting Undelivered Mail bounce notification when sending invoices. Reason: uncategorized-bounce Some go through no problem some bounce back. We recently sent 10 invoices, 6 received bounce notifications. After reaching out to the
                                                                                                                • Option to Delete Chats in IM

                                                                                                                  Currently, there is no option to delete any chats in IM, regardless of their source.
                                                                                                                • Can I import MSG files into Microsoft 365 without Outlook?

                                                                                                                  Yes, absolutely. You do not need Outlook installed to import MSG files into Microsoft 365. Aryson MSG file Converter is a dedicated tool that eliminates the Outlook dependency entirely, making the migration process simple and efficient for all users.
                                                                                                                • Feature Request - A Way To Search Item Groups

                                                                                                                  Hi Inventory Team, I can't find any way to filter or search by fields of Item Groups. It would be great to see that functionality added. I have a use case where a single product might come from 5 or more suppliers and each supplier's item is an Item in
                                                                                                                • Zoho Books/Inventory - Update Marketplace Sales Order via API

                                                                                                                  Hi everyone, Does anyone know if there is a way to update Sales Orders created from a marketplace intigration (Shopify in this case) via API? I'm trying to cover a scenario where an order is changed on the Shopify end and the changes must be reflected
                                                                                                                • Ticket id issues

                                                                                                                  When I reply a ticket from desktop, it doesn't have ticket id in the subject and it's great. When I reply a ticket from Zoho desk mobile, Zoho adds ticket id in the subject and I don't want that. Please help in this matter.
                                                                                                                • Advanced email configuration - agent's name vs. department name

                                                                                                                  We currently have all four Advanced Configuration options turned ON at the Global-level (Channels > Email > Advanced Configuration) - including the "Show Agent name in Ticket replies and outgoing emails" option. We also had that same option turned ON
                                                                                                                • Add Bounced as an Email Action / Notification for Bounced Emails

                                                                                                                  This is one of the hard requirements for the clients we're servicing. They want to get an internal email notification whenever the email they sent to their contacts have bounced, so that they can look into it and update the email address. Currently, the
                                                                                                                • Files Uploaded to Zoho WorkDrive Not Being Indexed by Search Engines

                                                                                                                  Hello, I have noticed that the files I upload to Zoho WorkDrive are not being indexed by search engines, including Google. I’d like to understand why this might be happening and what steps I can take to resolve it. Here are the details of my issue: File
                                                                                                                • not able to convert pdf to jpg and other forms and vice versa.

                                                                                                                  i want to change my pdf to jpg, word, etc and some times jpg to pdf. i don't know how to do in this.
                                                                                                                • What’s New in Zoho Analytics - March 2026

                                                                                                                  Hello Users! In this month's update, we bring improvements across integrations, security, reporting, and analytics capabilities to help you work with your data more efficiently and with greater control. Explore what’s new and see how these enhancements
                                                                                                                • Zoho People > Performance Management > Appraisal cycle

                                                                                                                  Hello All I am using this 2 users to test out how it work on Performance Management User 1 - Reportee User 2 - Reporting Manager : Li Ting Haley User 1 : Self Appraisal Error How do i fix this error?
                                                                                                                • SalesIQ Tip for Admins: Guide Operators in Real-time Without Interrupting the Chat

                                                                                                                  Consider this. You're a supervisor and you're looking through the active conversations. An associate is mid-chat with a high-value prospect. The prospect asks something unexpected, maybe about a tailor-made subscription plan or a bulk discount that’s
                                                                                                                • Next Page