vendredi 29 décembre 2023

How to use the Command Pattern when dealing with different parameters

Having a look at the UML diagrams for the Command Pattern reported here and here, the class of the invoker object (the one that inkoves the execute() method of a command object) must provide a setCommand() method to allow the client code to set the proper command object on the invoker: but how can such method be used when dealing with command objects that have different parameters which, additionally, are known only at runtime? I'll try to make an example.

class Messenger
{
  public function sendEmail(string $email, string $subject, string $body): void { ... }
  public function sendSms(string $phone, string $text): void { ... }
}

interface Command
{
  public function execute(): void;
}

class SendEmailCommand implements Command
{
  private readonly Messenger $messenger;
  private readonly string $email;
  private readonly string $subject;
  private readonly string $body;

  public function __constructor(Messenger $messenger)
  {
    $this->messenger = $messenger;
  }

  public function setEmail(string $email): void { $this->email = $email; }
  public function setSubject(string $subject): void { $this->subject = $subject; }
  public function setBody(string $body): void { $this->body = $body; }

  public function execute(): void
  {
    $this->messenger->sendEmail($this->email, $this->subject, $this->body);
  }
}

class SendSmsCommand implements Command
{
  private readonly Messenger $messenger;
  private readonly string $phone;
  private readonly string $text;

  public function __constructor(Messenger $messenger)
  {
    $this->messenger = $messenger;
  }

  public function setPhone(string $phone): void { $this->phone = $phone; }
  public function setText(string $text): void { $this->text = $text; }

  public function execute(): void
  {
    $this->messenger->sendSms($this->phone, $this->text);
  }
}

In such a scenario how much is it useful to have a setCommand(Command $command) on the invoker class? In some languages I would even get an error later when trying to call setX() because the Command interface doesn't define them. Would it be a bad idea to do something like this?

class EmailSendButton()
{
  private readonly Messenger $messenger;

  public function __constructor(Messenger $messenger)
  {
    $this->messenger = $messenger;
  }

  public function onClick(): void
  {
    $email = $this->getEmail();
    $subject = $this->getSubject();
    $body = $this->getBody();

    $sendEmailCommand = new SendEmailCommand($this->messenger);
    $sendEmailCommand->setEmail($email);
    $sendEmailCommand->setSubject($subject);
    $sendEmailCommand->setBody($body);
    $sendEmailCommand->execute();
  }
}

I know it is not ideal to instantiate a class inside another class, it creates coupling, but how would you solve it?

I was thinking about setCommand(SendEmailCommand $sendEmailCommand) instead of the easier setCommand(Command $command) but it adds more complexity on the client code than benefits IMO.

mercredi 13 décembre 2023

How to set fields for an object based the object circumstances, without relying on boolean flags?

We have a huge object which sets one by one a lot of fields. However, we've come to a point where we set 3 flags in order to create it based on what we need, which break clean code rules. Basically it looks something like this:

method(boolean flag1, boolean flag2, boolean flag3){
    if (flag1){
        field1 = customValue1;
    }
    if (flag2){
        field2 = customValue2;
    }
    if (flag3){
        field3 = customValue3;
    }

How can I refactor this so it follows the standard (get rid of all the flags)?

Making a separate method for each case wouldn't be alright I think because I would have a LOT of code duplicates (this method has over 200 lines of code due to the number of fields and the way the business logic works in general). Then I thought of creating some sort of Supplier object for each possible case, but... just no. What are my options?

mercredi 6 décembre 2023

how to make logic for pattern "*" question in python

Make the pattern

*
**
***
****
*****

using loops in python

There is some problem in the logic of this for loop can u check and please tell

for i in range(0, 5):
     
        for j in range(0, i+1):
         
            print("* ",end=""
)
      
        print("\r")

mardi 5 décembre 2023

Dynamic BLoC Implementation Switching in Flutter Using Bloc Pattern and Custom Class Loader

I'm facing a challenge in designing a Flutter application with the BLoC state management pattern. The app is intended to be generic but used by multiple clients, some of whom have specific needs requiring customized versions of the main app.

To achieve this, I've implemented a custom class loader that dynamically loads either the default class or an overridden specific class. This applies not only to the app's main classes but also to BLoC implementations. For example, I have a StockBloc and an overridden version called SpeStockBloc. The registration of overridden classes happens at the beginning of the app using MyClassLoader()[StockBloc] = SpeStockBloc.new.

The issue arises when I attempt to consume the StockBloc in a view using context.watch<StockBloc>. Instead of recognizing the overridden SpeStockBloc, it looks for the exact StockBloc type in the widget tree. I understand that it's the correct behavior of Bloc and Provider.

I'm seeking advice or alternative approaches on how to dynamically switch between BLoC implementations at runtime while utilizing context.watch or a similar mechanism, ensuring it takes overridden types into account.

Any insights or suggestions on how to handle this scenario efficiently would be greatly appreciated.

Custom class loader :

/// Class to provide (if registered) a construction function that overrides
/// the initial construction for the [Type] used as a parameter
class DynamicClassLoader {
  final Map<Type, Function> _mappedClasses = <Type, Function>{};

  static final DynamicClassLoader _instance = DynamicClassLoader._internal();

  /// Singleton factory
  factory DynamicClassLoader() {
    return _instance;
  }

  DynamicClassLoader._internal();

  /// Checks if a specific class is registered
  bool hasOverride(Type type) =>
      _mappedClasses.containsKey(type) && _mappedClasses[type] != null;

  /// Access operator for a construction function of an instance of type [type]
  Function? operator [](Type type) {
    return _mappedClasses[type];
  }

  /// Obtains an instantiation function for the overridden class
  Function newInstantiation(Type type, Function fallback) =>
      hasOverride(type) ? this[type]! : fallback;

  /// Assignment operator for a construction method for a type [type]
  void operator []=(Type type, Function func) {
    _mappedClasses.update(
      type,
      (
        Function value,
      ) =>
          func,
      ifAbsent: () => func,
    );
  }
}

/// Access function to the method [DynamicClassLoader.newInstantiation]
Function newInstantiation<Class>(Function fallback) =>
    _newInstantiation(Class, fallback);

Function _newInstantiation(Type type, Function fallback) =>
    DynamicClassLoader().newInstantiation(type, fallback);

Stock bloc :

import 'package:flutter_bloc/flutter_bloc.dart';
import 'package:meta/meta.dart';
import 'package:test_bloc/class_loader.dart';

class StockBloc extends Bloc<StockEvent, StockState> {
  /// factory
  factory StockBloc({required int myCustomParam}) =>
      newInstantiation<StockBloc>(StockBloc.std)(myCustomParam: myCustomParam);

  StockBloc.std() : super(StockInitial()) {
    on<StockEvent>((event, emit) {
      // TODO: implement event handler
    });
  }
}

@immutable
class StockEvent {}

@immutable
sealed class StockState {}

final class StockInitial extends StockState {}

spe stock bloc :

import '../stock_bloc.dart';

class SpeStockBloc extends StockBloc {
  SpeStockBloc() : super.std() {
    on<StockEvent>((event, emit) {
      // TODO: implement event handler
    });
  }
}

sub_cmp :

import 'package:flutter/material.dart';
import 'package:flutter_bloc/flutter_bloc.dart';
import 'package:test_bloc/bloc/bloc/stock_bloc.dart';

class SubCmp extends StatelessWidget {
  const SubCmp({super.key});

  @override
  Widget build(BuildContext context) {
    StockState bloc = context.watch<StockBloc>().state;

    return const Text("Sub cmp");
  }
}

main :

import 'package:flutter/material.dart';
import 'package:test_bloc/bloc/bloc/bloc/spe_stock_bloc.dart';
import 'package:test_bloc/bloc/bloc/stock_bloc.dart';
import 'package:flutter_bloc/flutter_bloc.dart';
import 'package:test_bloc/class_loader.dart';
import 'package:test_bloc/sub_cmp.dart';

void main() {
  runApp(
    const MyApp(),
  );
}

void registerSpe() {
  DynamicClassLoader()[StockBloc] = SpeStockBloc.new;
}

class MyApp extends StatelessWidget {
  const MyApp({super.key});

  // This widget is the root of your application.
  @override
  Widget build(BuildContext context) {
    return MaterialApp(
      title: 'Flutter Demo',
      theme: ThemeData(
        colorScheme: ColorScheme.fromSeed(seedColor: Colors.deepPurple),
        useMaterial3: true,
      ),
      home: const MyHomePage(title: 'Flutter Demo Home Page'),
    );
  }
}

class MyHomePage extends StatefulWidget {
  const MyHomePage({super.key, required this.title});
  final String title;

  @override
  State<MyHomePage> createState() => _MyHomePageState();
}

class _MyHomePageState extends State<MyHomePage> {
  @override
  Widget build(BuildContext context) {
    return Scaffold(
      appBar: AppBar(
        backgroundColor: Theme.of(context).colorScheme.inversePrimary,
        title: Text(widget.title),
      ),
      body: BlocProvider(
        create: (context) => StockBloc(myCustomParam: 10),
        child: const Center(
          child: Column(
            mainAxisAlignment: MainAxisAlignment.center,
            children: <Widget>[
              SubCmp(),
            ],
          ),
        ),
      ),
    );
  }
}


Modelling Gof Observer patterns in UML

I am modeling my project, which I will subsequently implement in Java, using UML. My project involves managing a gym. More specifically, I am currently modeling my GoF Observer diagram. By what I've understood, I can't allow my Graphic Controller, with the models (entity), correct me if I'm wrong. On the other hand, if I let my application controller to implement the Observer, how can I notify the graphic controller that an exercise changed his status? Here I put my two ideas: enter image description here enter image description here

lundi 4 décembre 2023

How do I create a pattern using an array? [closed]

I have to create a pattern using an array, but I have no idea what to do. Class videos aren't helpful, if someone could please help me with this i'd appreciate it.

The pattern I need to make looks like this: Xs patterned to look like C++ logo

I honestly don't know what I'm supposed to do to make this work, we didn't go over arrays in depth and it has to be an array for me to recieve the grade. There's a few more patterns I have to make but I think if i figure this out I'll be able to do those on my own. A visual example of how the code should look would be incredibly helpful.

DB calls in FluentValidator class in DDD implemetation

We are implementing DDD in our project and we are using fluent for data validation.

FluentDataValidation class has some service calls(like diff db calls and AD call) for validating data.

Is this valid in DDD design to have service layer called from Validator class?

        public PublicValidator(IMetadataService metadataService)
    {
        this.When(status => status.IsStatusInComplete(), () =>
        {
            this.RulesWhenStatusIsInComplete(metadataService);
        })
        .Otherwise(() =>
        {
            this.RulesWhenStatusIsOtherThanIncomplete(metadataService);
        });

        this.RuleFor(s => s.Employers)
        .Must((r, p) => !r.people())
        .WithMessage(PeopleMessages.Dates);

        this.When(s => s.Employers != null && s.Employers.Count > 0 && !s.HasDefault, () =>
        {
            this.RuleForEach(s => s.Employers).ChildRules(a =>
            {
                a.RuleFor(s => s.Einperp)
                .NotEmpty()
                .Must(o => (metadataService.GetEmployerByEinperp(o) != null))
                .WithMessage(Constants.IncorrectMetadata);}