mercredi 3 août 2022

Strategy pattern but with different initializer for classes

I am currenttly working on a messenger library for emails and want to send emails in different ways. This should be achived by initializing the needed object and then sending an email.

Because the resulting function is always the same, namely it needs a receiving E-mail address, a message text and maybe an attachment, I thought that it makes sense to use a strategy pattern in order to make the code more maintainable.

This is the interface, which will always be the same:

public interface IMailService
{
    void SendEMail(List<string> toEMails, string subject, string messageText);
    void SendEMail(List<string> toEMails, string subject, string messageText, List<Attachment> attachments);
}

The problem however is that the E-mail classes, which implement this functionality are initialized differently.

The smtp Version for example looks like this:

     public SmtpMailService(string server, int serverPort, bool enableSsl, string username, string password, string fromAddress)
    {
        _fromAddress = fromAddress;
        _mailClient = new SmtpClient(server);

        _mailClient = new SmtpClient(server, serverPort)
        {
            Credentials = new NetworkCredential(username, password),
            EnableSsl = enableSsl
        };
        _mailClient.Timeout = 1000000;
        
    }

And the exchange class is initialized this way:

    public void Initialize(string server, string username, string password, string domain, ExchangeVersion exchangeVersion, string fromAddress)
    {
        ExchangeService svc = new ExchangeService(exchangeVersion);
        svc.Credentials = new NetworkCredential(username, password, domain);
        svc.Url = new Uri(string.Format("https://{0}/ews/exchange.asmx", server));

        exchangeService = svc;
    }

It is also planned to implement other ways to send emails using different services.

How can I create a strategy pattern out of this? Or am I having the wrong idea and is a different pattern better?

What is an efficient way to generate and process numbered text menus?

I have a program accessed over USSD where the user dials *123# and is presented with a numbered text menu. Like so

1 item 1
2 item 2
3 item 3
4 item 4

The user enters a number and is either presented with a submenu:

1 sub 1
2 sub 2

or is asked to enter an integer:

Enter amount between 25 - 1000

I have a few requirements to make the menus:

  1. dynamic so I can easily swap the submenus (e.g., enter amount should be third step) or step 1 should go to the end of the main menu.
  2. efficiently read user input if he enters an entire sequence like *123*2*(amount)*(destination)
  3. associate a step (to enter integer) with a token, so I can gather all the inputs to a map and then feed it to a function. For example, parsing the example in 2 would give me {amount: 200, destination: 38228382}
  4. input parsing should be efficient, so the app can perform under high load

I have searched a lot, but it looks like people either hard code things or their app is proprietary. For now, I have saved regex patterns for each step to a database so if the user enters *123# they are shown the main menu, for *123*2# a message is shown to enter amount and for *123*2*200# another message is shown to enter destination. If the user goes through the menu step by step, I concatenate all the steps and try to match them with a pattern. This is not efficient because for each input I am evaluating a lot of regex patterns. I also get the entered input with hard coded indexes, i.e., [2] is amount, which is bad too.

I was wondering if anybody could tell me if there are patterns/algorithms designed for generating/parsing numbered text menus?

Simplifying a trait method with too many arguments?

I have a trait, which defines several functions. One of these functions has too many arguments. It also is a default implementation and inside, it makes calls to other trait functions via self. My question is how do I reduce the number of arguments to the function without going into massive refactoring?

My first instinct was to go with a builder pattern. I would define a new struct that would contain all the arguments to the function. With this, I would modify the default trait implementation to instead return a builder object and then have the user supply the arguments to the builder. Finally, the actual implementation code would then go in to some .build() or execute function.

The problem with that approach is that the default implementation uses self. This means that I need to have the build function take the trait as an argument, something like fn build(&self, &impl MyTrait) -> Result<>. I don't like this because this is kinda ugly:

let res = something.handle()
              .withArg1(...)
              .withArg2(...)
              .build(something);

What better ways can I simplify this?

mardi 2 août 2022

How can I get a specific object of specific type from list of objects

I have an animal manager class that has a list of object that implement the IAnimal interface. It has a method that must get the cats only from that same list. How can i design my code in a better way to achieve this ?

Sample code below (in C#)

public interface IAnimal
{
    void doSomeThing();
}

public class Cat : IAnimal
{
    public void doSomeThing()
    {
        Console.WriteLine("Cat");
    }
}

public class Dog : IAnimal
{
    public void doSomeThing()
    {
        Console.WriteLine("Dog");
    }
}

public class AnimalManager
{
    private List<IAnimal> animals = new List<IAnimal>();

    private void manageCat()
    {
     //get cats from animals list.
    }
}

lundi 1 août 2022

Repository pattern and relationships

A question on how to properly implement the Repository pattern.

Proposed scenario (I'm using Typescript here, but it shouldn't matter):

  1. Data store

Table/Collection Exchanges: holds data about different Exchanges that operate in different Markets Table/Colletion Brokers: holds data about Brokers that operate assets through an Exchange Table/Collection BrokersRegistrations: holds a key to an Exchange, a key to a Broker, and also some relationship data, such as the date when the broker registered on that exchange, his/her current situation (active?), maybe the plan he/she is registered to

  1. Entities

Exchange, Broker, BrokerRegistration

  1. DTOs

Some helper types:

    export type CreateDTO<T> = Omit<T, 'id'>;
    export type UpdateDTO<T> = T;
    export type DeleteDTO<T extends { id: any }> = Pick<T, 'id'>;

For each entity:

    import { CreateDTO, UpdateDTO, DeleteDTO } from '@shared';
    import { BrokerId } from '@core/broker';
    import { Position } from '@core/position';
    
    export interface BrokerDTO {
      id: BrokerId;
      name: string;
      positions: Position[];
    }
    
    export type CreateBrokerDTO = CreateDTO<BrokerDTO>;
    export type UpdateBrokerDTO = UpdateDTO<BrokerDTO>;
    export type DeleteBrokerDTO = DeleteDTO<BrokerDTO>;
  1. Mappers

For each Entity:

    import { Mapper } from '@shared';
    import { BrokerDTO, Broker, PersistedBroker } from '@core/broker';
    
    export class BrokerMapper extends Mapper<BrokerDTO, Broker, PersistedBroker> {
      fromDTO(brokerDTO: BrokerDTO): Broker {
        return new Broker({
          id: brokerDTO.id,
          name: brokerDTO.name,
          positions: brokerDTO.positions,
        });
      }
    
      fromPersistence(persistedBroker: PersistedBroker): Broker {
        const { name, positions } = persistedBroker;
    
        return new Broker({ name, positions });
      }
    
      toDTO(broker: Broker): BrokerDTO {
        const { id, name, positions } = broker;
    
        return { id, name, positions } as BrokerDTO;
      }
    }

Now to the Repositories...

  1. Which ones should I create? One for each entity (BrokerRepository, ExchangeRepository, BrokerRegistrationRepository)?
  2. Suppose I want to have a ExchangeRepository.fingBrokersByName(name: string): Broker[] method, this method should return a collection of Brokers currently registered in that Exchange, but only if the name somewhow matches. How would you implement this? 2.1) Should it really return a collection of Broker, or should it instead return only a colleciton of Broker ids, and then the client is responsible for the BrokerRepository.findById(id) call? 2.2) I mean, in order to return a collection of Broker this ExchangeRepository method will probably have to call first BrokerRegistrationRepository.findAll(exchangeId): BrokerRegistration[] or BrokerRegistration.findByName(exchangeId, name)BrokerRegistration[] and then for each BrokerRegistration returned call BrokerRepository.findById(id). 2.3) Or would you instead make BrokerRegistrationRepository.findAll(exchangeId) return a collection of Broker already, instead of only their registration data?

I guess I need some guidance on how to implement relantionships with the Repository pattern.

Any help will be appreciate.

Have a nice day.

Consume back-end REST API with React application - repository vs. service

I work on a React app consuming RESTful API. My API on top of basic CRUD operations exposes business functions falling under controller archetype (executable functions, with parameters and possibly return values). E.g.:

http://api.example.com/carts
http://api.example.com/users
http://api.example.com/documents
http://api.example.com/carts/{id}/checkout
http://api.example.com/users/{id}/block
http://api.example.com/documents/{id}/print

Within the team however we have disagreement regarding how API access layer should be called. We struggle to choose between *Repository and *Service.

On one hand these functionalities can be perceived as some collections abstractions and facades and it make sense to call them repositories. On the other hand however they expose some business, domain logic which definitely does not fall under repository pattern and is definitely a service.

Normally (in the back end) a repository could be either a service dependency or can be used standalone. Repository serves the purpose of accessing and modifying a collection, while a service is facade for some more complex business operations.

This separation however does not seem to make a lot of sense in the front end, where the only difference is the API endpoint website will call. Thus it's pointless to separate them, since realistically they are within the boundaries of the same concern.

What are your opinions about it? What kind of nomenclature do you use in your apps? Thanks for help and suggestions ;)

Swift Design Choice - Protocol or Class? (mimicking Java's Abstract Class)

I'm making Tetris. What is the best solution for shared code amongst the pieces? A class, protocol, or something else?

Tetrimino template capabilities:

func moveDown()
func rotateRight() // based on data table
func rotateLeft()  // based on data table

Each type of piece can rotate and move, but the way it rotates is determined by unique data tables. The data tables are the same between all instances of that piece (e.g. all long pieces rotate in the same way), and there is mainly shared functionality upon initialization.

It would make sense to use a protocol with a static variable for the data tables, and a default constructor that is run by conforming classes before running their unique code.

However, with a protocol, the static variables cannot be overridden, nor can a base initializer be provided that conforming classes can add onto. But if I use a class to get around these problems, then Tetrimino instances can be made, when it should just be a template.

What's the best design pattern for this?