Design standard to combine data from different databases

Asked

Viewed 231 times

2

I’m taking data from two different databases and need to format this data for Json.

The problem is not accessing the two banks and getting the information. The problem is that my class became more complex than it should have been. One of the fields in my Json is dependent on data that is in another database. So, for every time I build Json with data from one database, I need to go to another database to fill in this information. Here’s an example of code:

public class JsonClipAlerta
    {
        public JsonClipAlerta()
        {
        }

        public long Id;
        public IList<string> EnderecosEletronicos { get; set; }
        public IList<ExpressoesStruct> Expressoes { get; set; }
        public string IdCript { get; set; }

        public static JsonClipAlerta FromClipAlerta(ClipAlerta arg, Usuario usuarioLogado)
        {
            var crypto = ContainerHelper.Resolve<IServicoDeCriptografia>();
            var jsonClipAlerta = new JsonClipAlerta();
            var repositorioEnderecoEletronico = ContainerHelper.Resolve<ComuniqueSeWorkflow.Dominio.IRepositorios.IRepositorioEnderecoEletronico>();

            jsonClipAlerta.Id = arg.Id; 
            jsonClipAlerta.IdCript = crypto.Criptografar(arg.Id);
            jsonClipAlerta.Expressoes = arg.Expressoes.Select(e => new ExpressoesStruct { id = crypto.Criptografar(e.Id), text = e.Descricao }).ToList();
            jsonClipAlerta.EnderecosEletronicos = repositorioEnderecoEletronico.RetornaColecao (arg.EnderecosEletronicos.ToList()).Select(ee => ee.Endereco).ToList();

            return jsonClipAlerta;
        }        
    }

    public struct ExpressoesStruct {
        public string id;
        public string text;
    }
  • But if you have two banks will always have to go in the other to get the rest of the information, what’s the problem? Post the class too, because your code only has the final part, you refer to the filter using lambda?

  • 1

    @Laerte this is making the class very complex. I would like to know if there is some design Pattern to help me this. I had imagined a simple class that would just parse everything already ready and format pro Json.

  • I’m not sure I understand the scenario. Are you saying that to get your "Jsonclipalerta" object properly filled out, you need to do a search on a base that came from the "Clipalerta" parameter and then make the call to repositoryEnderecoEletronico.Returncollected() with information from it? If so, where does Clipalerta come from and who filled it?

  • @Diegojeronymo, Clipalerta is coming from the bank. When I call Jsonclipalerta.Fromclipalerta(Clipalerta), I already pass the Clipalerta filled missing only the field Addresselectronic addresses. I’m thinking about doing a Builder to mount the Clipalerta. What do you think?

  • @tiagopotencia I can’t say in this case if it’s worth it, because it’s not clear in the case of Clipalerta how it’s created or what its responsibility is in its context. Does it serve as a class for storing the data of your first query or is it a more complex entity? The Builder, being a creative Rider, depends on who should know how to build it and whether it can be built through different combinations (either by different parameters or actions that trigger different characteristics)and you need to better understand the scenario to tell whether or not he is a good choice.

  • I recommend that in the question you better specify the context of your Jsonclipalerta and Clipalerta classes, and indicate who has the responsibility to call them, who knows/depends on who and what the expected result is. I can’t recommend any specific technique or Pattern design to you without clearly understanding what flow you’re trying to represent with your code.

  • Solved your doubt?

Show 2 more comments

1 answer

1

There are several approaches to solving this problem, one of them is using the principles of SOLID along with Software Design Patterns.

We can start with the principle of "Single Responsability" (the "S" of SOLID) or sole responsibility and ask: "whose responsibility is it to create a Jsonclipalerta?" Perhaps an object factory is more suitable for this task. "How many factories will there be in the program?" Probably only one. " This factory will have what 'suppliers' of information?" Maybe we can hire (or "inject") suppliers through a contract (or "interface").

Soon we can use a combination of Patterns: we will then create a factory of unique instance objects that will receive via injection dependencies the two information providers, we will combine a Singleton with Factory Method Pattern plus Dependency Injection Design Pattern to have high cohesion, that is, each class with a responsibility and low involvement, that is, each class does not depend on another class, other than interfaces, which is the principle "D" (Dependency inversion principle) of SOLID that says we must depend on abstractions (interfaces) instead of implementations (classes).

Our goal is that we can create the Json as follows:

JsonClipAlerta json = JsonClipAlertaFactory.Instance
.CreateJsonClipAlerta(new JsonClipArguments { Id = 100, InitialDate = DateTime.Now });

So a possible factory solution would be:

    public sealed class JsonClipAlertaFactory
    {
          // providers que serão inicializados no construtor
          private readonly IProviderClipAlerta providerClip;
          private readonly IRepositorioEnderecoEletronico providerEndereco;

          // Factory method que cria os objetos
          public JsonClipAlerta CreateJsonClipAlerta(JsonClipArguments args)
          {
             ClipAlerta clip = this.providerClip.GetClipAlerta(args.Id);

             var jsonClip = new JsonClipAlerta()
             {
                // Informações vindas do primeiro provider
                Id = clip.Id,
                Expressoes = clip.Expressoes,

                // Informações vindas do segundo provider 
                EnderecosEletronicos = this.providerEndereco
                .RetornaColecao(clip.EnderecosEletronicos.ToList())
             };

             return jsonClip;
          }

          // Singleton com construtor privado que recebe os providers
          private JsonClipAlertaFactory(
             IProviderClipAlerta providerClip,
             IRepositorioEnderecoEletronico providerEndereco)
          {
             this.providerClip = providerClip;
             this.providerEndereco = providerEndereco;
          }

          public static JsonClipAlertaFactory Instance 
          { 
              get { return Nested.instance; } 
          }

          private class Nested
          {
             // Construtor estático para dizer ao compilador C# 
             // não marcar tipo como 'beforefieldinit'
             static Nested() { }

             // Passando os providers para o construtor privado
             internal static readonly JsonClipAlertaFactory instance =
                new JsonClipAlertaFactory(
                    new ProviderClipAlerta(), 
                    new RepositorioEnderecoEletronico());
          }
       }

With the following illustration classes for our Factory example above:

  // Classes de 'ilustração' usada na nossa Factory acima
 public class ClipAlerta
   {
      public long Id { get; set; }
      public IList<ExpressoesStruct> Expressoes { get; set; }
      public IList<string> EnderecosEletronicos { get; set; }
   }

   // Interfaces e classes dos providers   
   public interface IProviderClipAlerta
   {
      ClipAlerta GetClipAlerta(long id);
   }

   public interface IRepositorioEnderecoEletronico
   {
      IList<string> RetornaColecao(IList<string> listaEmails);
   }

   public class ProviderClipAlerta : IProviderClipAlerta
   {
      public ClipAlerta GetClipAlerta(long id)
      {
         throw new NotImplementedException();
      }
   }

   public class RepositorioEnderecoEletronico : IRepositorioEnderecoEletronico
   {
      public IList<string> RetornaColecao(IList<string> listaEmails)
      {
         throw new NotImplementedException();
      }
   }

   // Struct para auxiliar a passagem de parametros
   public struct JsonClipArguments
   {
      public long Id;
      public DateTime InitialDate;      
      // outros parametros..
   }

Browser other questions tagged

You are not signed in. Login or sign up in order to post.