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);}

Security flow diagram to protect confidential information for external user

I am working on a POC to create flow diagram to secure protected data for external user. We are planning to work on market place where external user will login via external application and paired with a group they belong to. Once pairing is completed between external user and group then as a next step external user can call an api to see all the information associated with the paired group. We needs to impose an security that external user is calling api using same external application once pairing happen. External user can be associated with multiple external application and raise pairing request with same group using market place.

  1. There are application to application interaction.
  2. External user login on market place through external system. It’s a user interface where all the user can login if they have credential.
  3. After successfully login user can see list of group associated with logged in user.
  4. User can select group using market place ui and raise a pairing request.
  5. Once pairing is done then user is authorized to call group api to see detail of that group.
  6. All the external user will call these api using a external application.
  7. As a security we need to validate external user is calling group api using same external system once they raised pairing request on market place.