vendredi 17 décembre 2021

Extracting characters between double quotes

In my project I need to extract some parameters from a settings file. Below is a section of the line that I am reading, the parameter I need to extract is the Program Prefix.

...  ProgramPrefix="" ReceiveTimeout="80000" ...

I need to extract what is between the double quotes for ProgramPrefix. The problem is that in-between these quotes can be any alphanumeric character, symbol, space, or no character at all.

Below is my current solution for extracting any character before the second double-quote, the problem it doesn't work for the case of nothing being between the double quotes

    EOPdefL = string.find(line,"ProgramPostfix=")
    EOPdef = string.match(line,'([^"]+)',EOPdefL+16)

When there is nothing in-between the double quotes the output for EOPdef is:

EOPdef = ReceiveTimeout=

I would like EOPdef to just return an empty string if there are no characters.

EOPdef = ""

how to design Page for Email Sending structure like Gmail design pattern in dot net core mvc

I have created Email API and also created controller in my application where I added API method as well, now I want to design a structure so that I can add emailId, subject, body like Gmail in design with their all feature in dot met core MVC.

Does including Collections in Entities violate what an entity is supposed to be?

I am building a Web API using Dapper for .NET Core and trying to adhere to Clean Architecture principles. The API is consumed by an external Angular front-end.

I have repositories that use Dapper to retrieve data from the database, and this data then passes through a service to be mapped into a DTO for display to the user.

It is my understanding that an entity should be an exact representation of the database object, with no extra properties, and that I should use DTOs if I require some additional properties to show the user (or if I wish to obscure certain properties from the user too).

Suppose I have a DTO:

public class StudentDTO
{
  public Guid Id { get; set; }
  public string Name { get; set; }
  public List<Assignment> Assignments { get; set;}
}

and its corresponding Entity:

public class Student
{
  public Guid Id { get; set; }
  public string Name { get; set; }
}

With this model, should I want to get a student with all of their assignments, I'd need to have two repository calls, and do something like this in the service:

public StudentDTO GetById(Guid id) 
{
  var student = this.studentRepository.GetById(id);
  var assignments = this.assignmentRepository.GetByStudentId(id);
  return SomeMapperClass.Map(student, assignments);
}

But this seems inefficient and unnecessary. My question is, should I not just retrieve the Assignments when I get the student entity in the repository, using a JOIN? Or would this violate what an entity is supposed to be?

I apologise, I do realise this is a rather simple question, but I'd really like to know which method is the best approach, or if they both have their use cases

jeudi 16 décembre 2021

Java - Generic for Payment processing with Strategy pattern

I am trying to implement Strategy pattern approach for payment processing in my Spring webflux based application.

My application supports multiple payment method like, Card Payment, Cash Payment, ... Also, we have to support Square & Stripe for Card payment.

Model class,

// Model interface
public interface PaymentModel {

}

// Base model with attributes needed for all payment types
public class BaseModel implements PaymentModel {

    private Float amount;
    private Integer userId;
}

public class SquareCardModel extends BaseModel {

    private String merchantId;
    private String device;
    private String orderId;

}

public class StripeCardModel extends BaseModel {

    private String merchantId;
    private String orderId;

}

public class CashModel extends BaseModel {

    private String name;
    private String orderId;

}

Service Class,

@Service
public interface PaymentService<T extends PaymentModel> {

    Mono<ServerResponse> pay(T model);

    String method();
}

@Service
public class CashPaymentService implements PaymentService<CashModel> {

    private static final String PAYMENT_METHOD = "cash";

    @Override
    public Mono<ServerResponse> pay(CashModel model) {
        // TODO Auto-generated method stub
        return null;
    }

    @Override
    public String method() {
        return PAYMENT_METHOD;
    }

}

@Service
public class SquarePaymentService implements PaymentService<SquareCardModel> {

    private static final String PAYMENT_METHOD = "cash";

    @Override
    public Mono<ServerResponse> pay(SquareCardModel model) {
        // TODO Auto-generated method stub
        return null;
    }

    @Override
    public String method() {
        return PAYMENT_METHOD;
    }

}

@Service
public class StripePaymentService implements PaymentService<StripeCardModel> {

    private static final String PAYMENT_METHOD = "cash";

    @Override
    public Mono<ServerResponse> pay(SquareCardModel model) {
        // TODO Auto-generated method stub
        return null;
    }

    @Override
    public String method() {
        return PAYMENT_METHOD;
    }

}

Factory Class,

@Service
public class PaymentFactory<T> {

    private final List<PaymentService<? extends PaymentModel>> paymentServices;

    @Autowired
    public PaymentFactory(List<PaymentService<? extends PaymentModel>> paymentServices) {
        this.paymentServices = paymentServices;
    }

    public PaymentService<? extends PaymentModel> retrievePaymentService(final String paymentMethod) {
        Optional<PaymentService<? extends PaymentModel>> paymentService = paymentServices.stream()
                .filter(service -> service.method().equals(paymentMethod)).findFirst();

        if (paymentService.isEmpty()) {
            throw new IllegalArgumentException("Unsupported Payment method ");
        }
        return paymentService.get();
    }

}

User choose the payment method and the call comes to the backend,

@Transactional
    public Mono<ServerResponse> payBilling(ServerRequest request) {
            return request.bodyToMono(PaymentDto.class).flatMap(paymentReq -> {
                if (paymentReq.getPaymentType().equals("CC")) { // For Card
                    return processCardPayment(usr, paymentReq);
                } else {
                    return badRequest().bodyValue("Not supported yet !");
                }
            });
    }

private Mono<? extends ServerResponse> processCardPayment(
            PaymentDto paymentReq) {
            PaymentService<PaymentModel> paymentService = (PaymentService<PaymentModel>) paymentFactory
                    .retrievePaymentService(paymentReq.getPaymentType());
            PaymentModel paymentModel = buildPaymentModel((String) paymentReq.getPaymentType(), paymentReq,
                    jsonMap);
            return paymentService.pay(paymentModel);
    }

    private PaymentModel buildPaymentModel(final String paymentMethod, final PaymentDto paymentReq,
        if (paymentMethod.equals("squarePayment")) {
            SquareCardModel model = new SquareCardModel();
            model.setAmount(paymentReq.getTotal());
            model.setMerchantId(paymentReq.getMerchantid());
            model.setOrderId(orderId);

            return model;
        }

        return null;

    }

Questions:

  1. Not sure if I have implemented generics properly with the strategy pattern.
  2. Also, I dont like type casting here. (PaymentService). is there any better approach?
  3. Why do I still need to use if for creating different model.

if (paymentMethod.equals("squarePayment")) {

PaymentService<PaymentModel> paymentService = (PaymentService<PaymentModel>) paymentFactory
                        .retrievePaymentService(paymentReq.getPaymentType());
                PaymentModel paymentModel = buildPaymentModel((String) paymentReq.getPaymentType(), paymentReq,
                        jsonMap);
                return paymentService.pay(paymentModel);

mercredi 15 décembre 2021

Has the recombine step been left out of modern education?

My first programming instructor taught me to code correctly the first time, by verifying all code on paper before we even touched a computer.

Many of the modern code analysis tools flag long methods for being too long, by exceeding some arbitrary length.

These programs purpose splitting a "long" method into several single-use methods.

Designing, writing and testing with these many smaller methods and classes is easier, no question.

However, newcomer(outside) readability degrades with each split.

When I was taught to split the design into parts, I was also taught to recombine single-use methods and in-line multi-use methods as much as possible.

My question is: Has the recombine step been left out of modern CS education?

Suitable Design pattern [closed]

I am looking for the suitable design pattern for my use case. Let's I have list of account and I would like to enrich each of the account depends of the criteria. e.g.:

  • if the account belongs to US account, account will be prepend with prefix US
  • all the confidential field will be masked
  • etc

I am thinking to use pipeline to solve this problem. Can someone give some advise?

Pipeline design pattern implementation

Thanks

A design pattern or architecture related to rendering components based on roles and permissions?

I want to know if there's a software design pattern that can solve a challenge I'm facing. I have a web application that works with several different user role types like SuperAdmin, Admin, Reseller, Dealer, Customer, Volunteer, etc...

And our React code is littered with if statements that check a person's role as well as other conditions to decide "what type of ui component" to present them. Here's a very simplified example:

// Container.js
<div>
   <h1>Something</h1>
   {['SuperAdmin', 'Admin'].includes(user.role) && (<input type="text" value="{record.first_name}" />)}
   {['Reseller', 'Dealer'].includes(user.role) && (<span className="border-2">{record.first_name}</span>)}
   {['Customer', 'Volunteer'].includes(user.role) && process.env.NETWORK_MODE === 'intranet' && (
    <div className="bg-grey">
        <span>Created at {record.create_at}</span>
        <span>This customer wants to be anonymous</span>
    </div>
   )}
   {['Reseller'].includes(user.role) && user.accountBalance > 0 && user.statementDate > (new Date()) && (
     <div>Please pay your bills</div>
   )}
</div>

The above example is very difficult for us to manage because there are over 100 components . When we need to change the access permissions for a role type or add other conditions, we have to go through every component and look for any stray if statements. We were thinking of writing some automated tests, but feel like we need to refactor the UI code before that's practical.

Are there some software engineering design patterns that would be relevant to my situation? If so, just state the names and i'l read up on it.


Right now, I'm contemplating an approach like this:

// Container.js
<div>
   <h1>Something</h1>
   <Customer user={user} />
   <BillNotice user={user} />
</div>

// Customer.js
const Customer = ({user}) => {
   if(['Admin', 'SuperAdmin'].includes(user.role)) return <CustomerVersion1 />;
   if(['Role', 'Role'].includes(user.role) && condition1 && condition2 ...etc...) return <CustomerVersion2 />;
   if(['Role', 'Role'].includes(user.role) && condition1 && condition2 ...etc...) return <CustomerVersion3 />;
   ...etc...
}

const CustomerVersion1 = () => <Component />;
const CustomerVersion2 = () => <Component />;
const CustomerVersion3 = () => <Component />;

...etc...

// BillNotice.js
const BillNotice = ({user}) => {
   if(['Admin', 'SuperAdmin'].includes(user.role)) return <BillNotice1 />;
   if(['Role', 'Role'].includes(user.role) && condition1 && condition2 ...etc...) return <BillNotice2 />;
   if(['Role', 'Role'].includes(user.role) && condition1 && condition2 ...etc...) return <BillNotice3 />;
   ...etc...
}

const BillNotice1 = () => <Component />;
const BillNotice2 = () => <Component />;
const BillNotice3 = () => <Component />;

Basically I'm making each component responsible for deciding how it should present itself. Then I can write unit test for each component by mocking the user argument and see if the appropriate component is returned. If this approach actually has a name, that would be great and I can read up more on it!