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.

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

    • Incorrect Functioning of Time Logs API (Version 3)

      We need to fetch the list of time logs for each task for our company internal usage. We are trying to achieve it by using the next endpoint: https://projects.zoho.com/api-docs#bulk-time-logs#get-all-project-time-logs Firstly, in the documentation the
    • Zoho CRM Queries Now Support Databases and Cloud Data Sources

      Hello everyone! We're thrilled to announce a major enhancement to the Queries feature in Zoho CRM! Queries now support a broader range of external data sources, allowing you to fetch live data and combine it with CRM records, all using a unified query
    • Salesforceに添付ファイルを格納したい

      お世話になっております。 Salesforceに添付ファイルを格納したく、カスタムオブジェクトに連携し、 「ファイルのアップロード」項目を設けました。 実際、エラーもなく送信出来たのですが、実際生成されたカスタムオブジェクトのレコードを見ると、どこにも添付ファイルがありません。仕様として、この添付ファイルはSalesforceのどこに格納されるのでしょうか? 今回作りたいフォームは、複数の書類を添付するため、Zohoformのファイルアップロード項目「本人確認書類」「源泉徴収票」などの項目を、Salesforce側にも設けた「本人確認書類」「源泉徴収票」という各項目にURLリンクとして紐づけたいと思っておりました。
    • Dynamic image in form works in the app but not on the customer portal.

      img = frm_Fichas[ID == input.Nombre].Foto; imgno = Nophoto[ID2 = 1].Image; if(len(img) > 1) { img = img.replaceAll("/sharedBy/appLinkName/",zoho.appuri); img = img.replaceAll("viewLinkName","Fichas_de_personal_public"); img = img.replaceAll("fieldName","Foto");
    • Is it possible to retrieve function (Deluge) code from Zoho CRM externally?

      Hi Everyone, Is it possible to fetch or retrieve the Deluge function code from Zoho CRM using an external method (API or any other approach)? I would like to know if there is any way to access or extract the function script outside of Zoho CRM, or if
    • Uplifted homepage experience

      Editions: All editions. Availability update: 17th February 2026: All editions in the CA and SA DC | JP DC (Free, Standard and Professional editions) 23 February 2026: JP (All Editions) | AU, CN (Free, Standard, Professional editions) 27 February 2026:
    • Allow Font Size 11 in Editors...

      That is basic functionality...
    • 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..
    • Approval Workflow for Purchase Orders Abrir

      The requirement is , that all purchase orders greater than or equal to 5000 go through an approval process from certain people, but within books I only see that the approvers can be by levels or any approver but we cannot enter a rule like these. Can
    • WeTravel + Zoho CRM Integration - Has Anyone Built a Connector or Extension?

      Hi all, I'm exploring options for integrating Zoho CRM with WeTravel (booking & payment platform for tour operators). Zapier seems to be the common method but seems limited. I'm wondering if anyone in the community has developed a more comprehensive solution,
    • Option in pipeline deal to select which hotel or branch or store if client has more than one local store

      Hi, I would like to know if there is an option in the deal pipeline to select which hotel, branch, or store a deal is related to—if the company has more than one location. For example, I have a client that owns several hotels under the same company, and
    • Undo article like/dislike

      It seems to be not possible to undo your like/dislike for an article. Would be great if you can. Kind regards, Helen
    • Nested notebooks

      Dear Sir/Madam, I would like to know if it is possible to nest notebooks. It would be very helpful when there are too many, as it would improve organization. Thank you for your response. Best regards.
    • Tax in Quote

      Each row item in a quote has a tax value. At the total numbers at the bottom, there is also a Tax entry. If you select tax in both of the (line item, and the total), the tax doubles. My assumption is that the Tax total should be totalling the tax from
    • Issue with "Send Email" from Quotes not loading Email Template data

      Hi everyone, I'm currently experiencing an issue when using the "Send Email" option from a Quote record in Zoho CRM. What’s happening: When I go to the Quotes module and select a record, then click Send Email, the attached file (Quote) correctly pulls
    • Dynamically Fetching Lookup Field Display Value

      I have an audit trail form, Audit_Changes, that tracks old vs new values across different forms. For lookup fields, the old/new value is the ID, but I also need the display value. What's a best practice for dynamically fetching the display value of the
    • Stop Scrolling, Start Asking: Meet Zia for Your Files

      Hey everyone 👋 The era of 'scrolling and searching' is officially over. Whether it's a dense legal contract or a long meeting recording, searching for specific details is a massive time-sink. We think you should be able to interact with your files, not
    • Introducing a smarter, faster, and more flexible charting experience

      Hello Zoho Sheet users, We're delighted to share the latest news about a major update to charts in Zoho Sheet! The new version supports dynamic data ranges, granular styling options, faster loading, and other interesting enhancements that allow you to
    • How to create a new Batch and update Stock via Inventory?

      Hi everyone, We are building an automation where a user enters batch details (Batch Number, Mfg Date, Expiry, and Quantity) into a Custom Module. I need this to trigger an API call to Zoho Inventory to: Create the new batch for the item. Increase the
    • How do I open MSG files in Microsoft Word?

      If you want to open MSG files in Microsoft Word is not natively supported, as MSG is an email file format created by Microsoft Outlook. However, there are professional approaches to access MSG content in Word. First, open the MSG file in Outlook and copy
    • Unable to charge GST on shipping/packing & Forwarding charges in INDIA

      Currently, tax rates only apply to items. It does not apply tax to any shipping or packing & forwarding charges that may be on the order as well. However, these charges are taxable under GST in India. Please add the ability to apply tax to these charges.
    • How to add packing & forwarding charge in purchase order & quotation???

      Hello Zoho Team I have just started using Zoho for my company and I wanted to make purchase order. My supplier charges fix 2% as packing & forwarding on Total amount of material and then they charge me tax. For example, Material 1 = 100 Rs Material 2
    • How to create a boxplot chart in Zoho Analytics?

      Hi, I'm looking forward to making a boxplot in Zoho Analytics, either with all my data or with a time segmentation. No documentation or YouTube video explaining that was found. I guess this is a feature gap. How feasible would it be to add this to Analytics?
    • What are the create bill API line item requiered fields

      While the following documentation says that the line items array is requiered it doesn't say what if any files are requiered in the array. Does anyone know? API documentation: https://www.zoho.com/inventory/api/v1/bills/#create-a-bill I'm trying to add
    • WorkDrive issues with Windows Explorer Not Responding

      We are using WorkDrive to collaborate on editing video content. We have a lot of files and quite a few are a few gigs. Recently anytime I try and work with the files Explorer freezes for a couple minutes whether it's dragging the files into Premiere or
    • Connecting Zoho Inventory to ShipStation

      we are looking for someone to help connect via API shipStation with Zoho inventory. Any ideas? Thanks. Uri
    • Where is the settings option in zoho writer?

      hi, my zoho writer on windows has menu fonts too large. where do i find the settings to change this option? my screen resolution is correct and other apps/softwares in windows have no issues. regards
    • Using IMAP configuration for shared email inboxes

      Our customer service team utilizes shared email boxes to allow multiple people to view and handle incoming customer requests. For example, the customer sends an email to info@xxxx.com and multiple people can view it and handle the request. How can I configure
    • When Does WorkDrive integrate with Books?

      When Does WorkDrive integrate with Books?
    • POP mailbox limits

      If I am accessing a remote POP mail server using Zoho Mail is there a mailbox quota for the account or is it all related to my mail account storage limits?
    • Warranty Service and Repair in Zoho FSM

      Hi There, We are a retail store that sells products and also performs installations and repairs. Our field technicians handle this work. Some repairs are covered by manufacturers, who reimburse us for both parts and labour. In these cases, we perform
    • Zoho Sheet for Desktop

      Does Zoho plans to develop a Desktop version of Sheet that installs on the computer like was done with Writer?
    • WhatsApp phone number migration

      Hi @Gowri V and @Pheranda Nongpiur, Thanks for implementing the promised enhancements to the integration between Zoho CRM and WhatsApp. The previous discussion has been locked, so I'm opening this new one. I am copying below a specific
    • WebDAV support

      I need WebDAV support so that I can upload/download (and modify) documents from my local file system. Is anything planned in his direction?
    • Suggestions for Improved Table Management and Dashboard Filter Controls in Zoho Analytics

      Dear Zoho Analytics Community, I hope you are doing well. I would like to share a few suggestions based on issues I am currently experiencing while working with visualizations and dashboards. Firstly, when I create a new visualization using the Sales-Order
    • SPF: HELO does not publish an SPF Record

      I am using Zoho mail. Completed all of the required prerequisites from the dashboard to avoid any issues with mail delivery. But when checking on mail-tester.com getting the following error. Can anyone help me solve this?
    • How do I create an update to the Cost Price from landed costs?

      Hi fellow Zoho Inventory battlers, I am new to Zoho inventory and was completely baffled to find that the cost price of products does not update when a new purchase order is received. The cost price is just made up numbers I start with when the product
    • Price Managment

      I have been in discussions with Zoho for some time and not getting what I need. Maybe someone can help explain the logic behind this for me as I fail to understand. When creating an item, you input a sales rate and purchase rate. These rates are just
    • Actual vs Minimum

      Hi all, I am sure I am not the only one having this need. We are implementing billing on a 30-minute increment, with a minimum of 30 minutes per ticket. My question is, is there a way to create a formula or function to track both the minimum bill vs the
    • Generate leads from instagram

      hello i have question. If connect instagram using zoho social, it is possible to get lead from instagram? example if someone send me direct message or comment on my post and then they generate to lead
    • Next Page