Home > Enterprise >  How can I optimize my code so that I dont duplicate it
How can I optimize my code so that I dont duplicate it

Time:12-09

I'm trying to create a procedure that puts "-" between different dates and "0" if the is single digit, but i'm having a very hard time not duplicating my code.

   procedure put (Date : in Date_Type) is
      
   begin
    
      Put(Date.Y, Width => 1);
      Put("-");
      if Date.M <= 9 then
         Put("0");
      end if;
      Put(Date.M, Width => 1);
      Put("-");
      if Date.D <= 9 then
         Put("0");
      end if;
      Put(Date.D, Width => 1);
      
   end put;

This is the best solution I came up with

CodePudding user response:

Came to this solution, I didnt duplicate my code but I somehow feel like I made it more complicated

   procedure Zero(item : in integer) is
      
   begin
      
     Put("-");
     if item < 10 then
        Put('0');
     end if;
     Put(Item,Width =>0);
      
   end Zero;
   
   procedure put (Date : in Date_Type) is 
      
   begin
    
      Put(Date.Y, Width => 0);    
      Zero(Date.M);    
      Zero(Date.D);
      
   end put;

CodePudding user response:

An example of a nested procedure is:

with Ada.Text_IO;         use Ada.Text_IO;
with Ada.Integer_Text_IO; use Ada.Integer_Text_IO;

procedure Main is
   subtype Year_Num is Integer range 1_900 .. 2_040;
   subtype Month_Num is Integer range 1 .. 12;
   subtype Day_Num is Integer range 1 .. 31;

   type Date_Type is record
      Y : Year_Num;
      M : Month_Num;
      D : Day_Num;
   end record;

   procedure Put (Date : Date_Type) is
      procedure zerofill (Val : in Integer) is
      begin
         Put ("-" & (if (Val < 10) then "0" else ""));
         Put (Item => Val, Width => 0);
      end zerofill;
   begin
      Put (Item => Date.Y, Width => 0);
      zerofill (Date.M);
      zerofill (Date.D);
   end Put;
   
   A_Date : Date_Type := (2022, 12, 8);
begin
   Put (A_Date);
end Main;

The nested nature of this answer is because the zerofill procedure is defined within the put procedure.

  • Related