samedi 31 juillet 2021

Building CSharp application with localization-aware language keys

Intro

I am looking for more customized solution for translating my app. I will be using Humanizer and Smart.Format after obtaining entries. The problem is to define keys to obtain them in the first place.

Requirements

The requirements are:

  1. Language keys must be defined in-code, preferably near place where they are used
  2. Language keys must contain default-English values
  3. All language keys must be listed (XML, CSV, JSON, anything) after building the app suite
  4. Language entries must be provided from external source (like JSON file), without the need for any kind of recompilation
  5. The app may contain multiple executables, shared libraries, etc. all of them in form of CSharp apps

Discarded solutions

First, the things I discarded:

  • Built-in CSharp Resources.dll; They violate (1) and (4)
  • External file with keys. Violates (1)

My idea for handling the problem

Now, my idea for the solution looks that way (and is inspired by C++ GetText)

There is a template class which contains keys:

private sealed class Module1Keys : LocalizationKeys<Module1Keys>
{
    public static readonly LocalizationKey HelloWorld = DefineKey("/foo", "Hello World!");
    public static readonly LocalizationKey HelloWorld2 = DefineKey("/bar", "Hello World2!");
}

And the class LocalizationKeys contains a static method that will actually register keys in simple collection

public abstract class LocalizationKeys<T> where T : LocalizationKeys<T>
{
    protected static LocalizationKey DefineKey(string path, string english)
    {
        var ret = new LocalizationKey(typeof(T), path, english);
        // Following registers localization key in runtime:
        Localization.Instance.RegisterLocalizableKey(ret);

        return ret;
    }
}

The only thing left to handle in this approach is to list localizable keys during build... which is where I had hit the wall. It is very easy to list them during runtime, but I cannot run the code on build time (particularly it may be built as shared library).

Maybe I am overthinking myself and there is better, more clean solution - I don't need to stick with this solution, but Googling around has not yielded anything better...

vendredi 30 juillet 2021

Creating a single factory for unrelated objects

I have several classes that are not related to each other.

public class Apple
{
    
}

public class Giraffe
{
    
}

I can create a separate factory for each but I want to get a structure like below.

Factory<Apple>.CreateSingle();

I want to produce a single apple with the code above. Also with the following code;

Factory<Giraffe>.CreateCollection(20);

I want to get 20 giraffes.

To do this, I created an IFactory generic interface.

public interface IFactory<out T>
{
    T CreateSingle();
    IEnumerable<T> CreateCollection(int count);
}

And a factory for each type;

public class AppleFactory : IFactory<Apple>
{
    public Apple CreateSingle() =>
        new()
        {
           //some code
        };

    public IEnumerable<Apple> CreateCollection(int count)
    {
          // CreateSingle X count times, add to collection and return
    }
}

public class GiraffeFactory: IFactory<Giraffe>
{
    public Giraffe CreateSingle() =>
        new()
        {
           //some code
        };

    public IEnumerable<Giraffe> CreateCollection(int count)
    {
          // CreateSingle X count times, add to collection and return
    }
}

The main factory looks like this;

public static class Factory<T>
{
    private static IFactory<T> GetFactory()
    {
        if (typeof(T) == typeof(Apple)) return (IFactory<T>) new AppleFactory();
        if (typeof(T) == typeof(Giraffe)) return (IFactory<T>) new GiraffeFactory();
        return null;
    }
    public static T CreateSingle() => GetFactory().CreateSingle();
    public static IEnumerable<T> CreateCollection(int count) => GetFactory().CreateCollection(count);


}

The if structure here looks pretty ugly. Is there a way I can do what I want to do in a cleaner way? These days, I am trying to learn design patterns and I force myself to use design patterns. The code may seem unnecessarily cluttered for this reason. It's totally experimental.

Best way to share state between tab-view render props without remounting the components when the state changes

I'm using this library (https://github.com/satya164/react-native-tab-view) to create a tabbed view, where each tab represents a category and renders a list of devices with a checkbox to select/deselect them. Since some of these categories overlap the parent component has to keep track of the selectedDevices, so that when you switch between tabs the next one will be affected by the selection made in the previous ones. That wouldn't be a problem, except for the fact that each tab is basically a ScrollView and so it is of the uttermost importance that every time you make a selection it won't unmount and remount, losing the scrolling position.

TabView has a renderScene prop which allows me to render the various screens. If I pass the selectedDevices through a prop in renderScene it will behave like a factory, basically creating a new React Element each time selectedDevices changes and thus triggering a remount.

If there was a way to set the selected devices only when the screen is about to change (because the user tapped on another tab or swiped to it) that would be good enough because despite the remount that wouldn't affect the scroll position, but using a useEffect cleanup function to set the selected devices won't be of any use because changing tab doesn't unmount the component.

The only solution I've thought of is creating a new Context and use it to share the selectedDevices between the various tab screens. This works very well, avoiding any kind of remount altogether, but somehow I don't like because it feels like a bad design.

Can you think of any better solution?

How to encpsulate components (toolbars) content to prevent the component (toolbar) becomes a monolith?

I am in trouble with my toolbar code of my current app.

My toolbar covers the whole app. That means the toolbar is displayed at every page. Because of this the toolbar is only a part of my root template (app.component.html) and every other page (component) is lazy loaded by the router-outlet. The benefit is to avoid a whole DOM-update of my toolbar.

app.component.html:

<my-toolbar></my-toolbar>
<router-outlet></router-outlet> <!-- loads specific pages lazy -->

But now there is a big problem. The view content (icons, texts, margins, order, etc.) of my-toolbar.component.html is a little bit different on every page. The displayed data is handled by a service. So my toolbar component was became a very big monolith-like construct. In relation to the route there is a big switch case like procedure to find out which content is displayed in the toolbar ... :-(

My aim is to keep the general view content in my-toolbar.component.html and the specific view content should be "injected" with <ng-content> by the specific page. But I can use <ng-content> only if I put the <my-toolbar></my-toolbar> directly in an page template like:

<my-toolbar>
  <!-- specific content -->
</my-toolbar>

At the level of a lower level page component I am not able to access to the higher level toolbar component. Is there still a way to "inject" the specific content from a page component to the higher toolbar component? Note: I want to avoid CSS hacks like negative margin, positioning, etc.

I hope my bad English was understood. ó.Ò

Advantages of Acyclic Visitor over Command with Switch On Type

The visitor pattern is useful in situations where the element hierarchy is stable and the desired functionality for operating on those elements changes often.

In cases where the element hierarchy changes, the visitor pattern suffers from coupling that forces rebuilding all classes in both the element and functionality hierarchies.

To improve on upon this, the Acyclic Visitor uses an extra level of abstraction, with an empty Visitor interface at the top, and a specific interface for each class in the element hierarchy.

Assuming two concrete element types IntMessage and StringMessage, an acyclic visitor would look like this:

abstract class Message // parent for the model/element/data classes
{
    public abstract void Accept(Visitor visitor);
}
class IntMessage : Message  // concrete element type 1
{
    internal int data;

    public override void Accept(Visitor visitor)
    {
        // check if the concrete visitor knows how to work on IntMessage
        if (visitor is IntMessageVisitor)
            (visitor as IntMessageVisitor).Visit(this);   
    }
}
class StringMessage : Message  // concrete element type 2
{
    internal String msg;
    public override void Accept(Visitor visitor)
    {
        // check if the concrete visitor knows how to work on StringMessage
        if (visitor is StringMessageVisitor)
            (visitor as StringMessageVisitor).Visit(this);
    }
}


interface Visitor  // empty parent interface for acyclic visitor
{
}

interface IntMessageVisitor : Visitor
{
    void Visit(IntMessage message);
}
interface StringMessageVisitor : Visitor
{
    void Visit(StringMessage message);
}

A concrete visitor would inherit from all the specific visitor interfaces for the element types that it knows how to visit. The advantage of this is that in cases where new classes are added to the element hierarchy, only concrete visitors who need to visit the new element are forced to change.

class PrintVisitor : StringMessageVisitor, IntMessageVisitor
{
        public void Visit(IntMessage message)
        {
            Console.WriteLine("Int message with data = " + message.data);
        }
        public void Visit(StringMessage message)
        {
            Console.WriteLine("String message with data = " + message.msg);
        }
}

Enough setup, let's move on to the question.

The question is, given the complexity of the acyclic visitor pattern, does it have any real benefit over using a simple command with a switch-on-type?

For example, we could rewrite the PrintVisitor as the following print command:

class PrintCommand : Command
{
    public void Execute(Message message)
    {
        // switch on type
        if (message.GetType() == typeof(IntMessage))
        {
            Console.WriteLine("Int message with data = " + ((IntMessage)message).data);
        }
        else
        if (message.GetType() == typeof(StringMessage))
        {
            Console.WriteLine("Int message with data = " + ((StringMessage)message).msg);
        }
    }
}

If new classes are added to the element hierarchy in the future ( for example DateMessage ), then still only the commands that want to work on the new element type will need to change. The resulting design would be much simpler, without multiple interface inheritance, and double dispatch, at the "cost" of using runtime type information instead of virtual functions.

It seems that as far as OCP and future maintenance there is no extra cost for the switch on type over the acyclic visitor.

Is there ever any reason to prefer the ACyclic Visitor over command with switch-on-type ?

How to replace a charachter in a jstl?

I have a situation similar this: <fmt:formatNumber type="number" value="${$value}" pattern="0.00" maxFractionDigits="2"/>

but i need the pattern in the format pattern="0+00", practically i have to separate decimals by integers with a "plus" symbol.

can you help me some way ?

How to form the dynamic request param for Alamofire param iOS swift?

I am working in iOS swift project. I have handled the all the API in Networking class which is singleton and form the param like below for each request:

For the first API:

let parameters: Parameters = [
    “user_id”: "1o75d"
]

Fir the second API:

let parameters: Parameters = [
    “user_id”: “1o75d”,
   “domain_path”: “”,
   “ios_device_os”:””,
   “ios_device_type”: “”
]

I have to call more than 10 web service when the user enters the userid in the Home Screen.

Instead of form the request for 10 web services like above for each service, is any other way to form the dynamic request using design pattern?

jeudi 29 juillet 2021

How to write complex recursive code cleanly?

I am writing a module in Java that works recursively and has very complex logic. Because the recursive nature of the problem I am trying to solve not using recursion is not an option.

What makes the logic of my program complex include: 1-properly detecting and handling different special cases 2- correctly set or unset some flags which are going to be used when the code returns from the recursion. 3- having a logic that works mostly lazily but for some part it has to work eagerly.

My code has become around 1500 lines of complex and highly coupled code which has made finding errors and bugs a nightmare which sadly they are not rare. I have already have tried separating the logic in smaller pieces and take advantage of OO paradigm and encapsulating each part of logic but the code still hard to understand. I was wondering if there are any design patterns, guidelines or conventions for writing clean and understandable complex recursive code? I have looked around online but I did not found anything really useful.

Best practice to design functions in Swift 5 [closed]

I am learning Swift now and I am at the very beginning. My question contains Swift code but I suppose it is more general question and could be applied to any language.

I had this task:

  1. Write a function which check whether our given number is even or not.
  2. Write a function which checks whether our given number could be divided by 3 or not.

For #1 I made this:

func isEven(_ number: Int) -> Bool {
    number % 2 == 0
}

For #2 I made this:

func isDividedByThree(_ number: Int) -> Bool {
    number % 3 == 0
}

At the lesson we were told by the teacher that it's not good to write similar code in different parts. I noted that I had 2 functions which were doing the same job - to check whether this number could be divided by another number or not. That's why I merged my 2 functions into 1 which checks if the given number could be divided by another given number. So I added one more parameter and got this instead of those 2 functions:

func isDividedBy(dividend x: Int, divisor y: Int) -> Bool {
    x % y == 0
}

My teacher told me: "Don't try to make swiss-army-knife-functions. I want you to make 2 different functions for 2 cases: % 2 and % 3.

After that we were supposed to use these functions as closures in the another function, which was intended to filter array of numbers and give us filtered array without even or divided by 3 numbers.

My last function was like this:

func filterByDivisor(range numbers: [Int], divisor d: Int, closure: (Int, Int) -> Bool) -> [Int] {
    var filteredRange: [Int] = []
    for number in numbers {
        if !closure(number, d) {
            filteredRange.append(number)
        }
    }
    return filteredRange
}
print(filterByDivisor(range: numbersRange, divisor: 2, closure: isDividedBy))
print(filterByDivisor(range: numbersRange, divisor: 3, closure: isDividedBy))

My teacher expected to see:

  1. Two functions to check by divisor.
  2. Final filtering function with 2 parameters: range and closure.

I made:

  1. One function to check by divisor.
  2. Final filtering function with 3 parameters: range, divisor to check and closure.

My teacher was little bit upset but I honestly can't realize if it's really such a big deal? As I've just started my learning path I don't want to argue with him but deep inside I am not agree :)

I want to know opinion of another experienced programmers, could you please share?

Singleton with Dependency Injection in ASP.NET Core

We can inject dependency thanks to: services.AddSingleton() in .NET Core. Is there any aim of creating a special class(Singleton) with special body (private constructor, static GetInstance() etc.) Shouldn't we just use the services.AddSingleton() with a "normal" class?

Writing code that run across different regions

I am working on enhancing a Spring boot Microservice that is developed for the Consumer registration in the UK region. The service domain model and validation logic is coded based on the consumer registration details in UK. The Micro service accepts UI to provide Consumer's name, address etc and run some validation on that before registering consumer with system.

I have to enhance this service to run for the US region. The existing domain model won't fit for the US. In UK, consumer's address format is different than US. Also, there is no SSN in the UK region. There are different address verification systems in UK vs US.

So overall, I cannot use the same Micro service developed for US region. I wanted to ask, how do we develop Services that works across different geographies considering differences in the domain model and requirement for integration with different back-end systems (address validation for example).

Django admin - property options based on a related parent model

I have a parent and a child class. The relation between them is many-to-one like this:

class Parent(AccessmanagerMixin, models.Model):
    name = models.CharField(max_length=150)
    def __str__(self) -> str:
        return self.name

class Child(AccessmanagerMixin, models.Model):
    name = models.CharField(max_length=150)
    parent_group = models.ForeignKey(Parent, on_delete=models.CASCADE,  null=True )
    def __str__(self) -> str:
        return self.name

they both have a many-to-many relation with the User class, named read_users (its a custom security on object level).

class AccessmanagerMixin(models.Model):
    read_users = models.ManyToManyField(User, related_name='read_users')
    class Meta:
        abstract = True

For example in the admin I would like to use the users from Parent read_users as an option for selecting the read_users for the Child entity? How can I do this in a best way? Can I override the read_users property in the Child admin.ModelAdmin.

Create different DB object depending on Key

I want to create an object of different DBs(SQL, Oracle, Mongo, etc.). Depending on a key(Coming from UI) I have will decide which object to create. Which design pattern I shall use for this problem? I want to use a generic method to create an object. The system should be decoupled.

mercredi 28 juillet 2021

Big projects that require very good performance really don't use polymorphism?

For quite some time I have been interested in perfomance in C ++.

A lot of things keep coming up, whether in conferences or in books:

Do not use a virtual function, have the data in the cache, the branches etc.

There are many benchmarks with examples of video games to show the differences in performance. The thing is, the examples are always very simple.

How does that really work in code that is more than 20 lines? in AAA video games, finance etc.

If I have 100 types of objects that have different update, different behavior and other joys, it's easy to set up via polymorphism or function pointers.

Now, by following the advice given to make a powerful code, the above options are not possible. We will therefore prefer to have 100 arrays that we will update separately. We will have good access to the cache, the functions will probably be inline etc. in short, the performance will in principle be better.

So, I have 100 arrays and 100 differents functions that i will have to call at each frame. The tables dynamically change depending on what happens, new players appear, a monster dies etc. Some array will have 0 elements active, others 10... I would call functions that will have no work (array without active element) but I have no choice, I have to have a flag or look if elements are active or not in my array.

I end up with something like this:

obj1update ();
obje2update ();
....

obj1behavior ();
obj2behavior ();
....

obj1render ();
obj2render ();
.....

objectxy ();
....

Of course, there will undoubtedly be a function which manages all the update calls on the objects, one for the behavior etc but to simplify it gives as above.

To stay in the video game, if the x action of a player causes the arrival of y monsters, there are several types of monsters which have different functions. We will therefore put the monsters in our tables and this time the functions dealing with these monsters will have work.

We can use the ECS pattern or a derivative but they will potentially have very different behaviors (an ia that directs them or other), different components and therefore different functions will be needed to process them. They will be called hard in the code since we don't have polymorphism or function pointers and we will have to check at each frame if they have something to process or not.

Is it really done that way? suppose i have 500 types? 1000 ?

powershell | select-string pattern + line unter the pattern

is there a way to select a string pattern, and get also the line after the pattern.

my metadata look like :

"t": "d",
      "n": "00001212",
        "22.06.2031",
        "",
        "",
        "batman",

my codeline looks like:

$contentNameFolder= $content__ | Select-String -Pattern '"n": * ' 

my output looks like :

"n": "00001212",

what i want to get is:

"n": "00001212",
        "22.06.2031",

i was trying to add into my code -context 1,2 or something like that but this dont worked for me.

mardi 27 juillet 2021

laravel service-repository pattern static vs non-static methods

i've got a laravel project where service and repository classes are created as following:

class UserService
{
    public function save($data)
    {
        return User::create($data);
    }

    public function update($id, $data)
    {
        return User::where('id', $id)->update($data);
    }

    public function delete($id)
    {
        return  User::where('id', $id)->delete();
    }
}
class UserRepository
{
    public function findAll()
    {
        return User::all();
    }

    public function find($id)
    {
        return User::find($id);
    }
}

and then those are initiated in the controller like following:

    protected $userRepository;
    protected $userService;

    public function __construct(UserRepository $userRepository, UserService $userService)
    {
        $this->userRepository = $userRepository;
        $this->userService = $userService;
    }

now my question is, since there's nothing else but static method call inside those class methods, is there any reason/benefit for make those methods non static and initiating those on the controller firsthand instead of make those static as well for the ease of use?

How to print half pyramid pattern with fibonacci series using python

How to print the following pyramid pattern with Python using for loop.

0
01
011
0112
01123

refactoring if else to strategy design pattern

I want to refactor below if else based logic to use strategy pattern but as per my understanding strategy pattern comes into hand when we want to choose different type at run time but in my case, type(carService) is same but want to invoke different method on the same type based on carType enum. If additional car types added in future then this if else condition will become complex.

Can some one share some example how to refactor below logic to strategy pattern.

    if (CarType.PREMIUM.name().equals(carType)) {
            carService.getPremiumCarDetails();
    } else if (CarType.NORMAL.name().equals(carType)) {
            carService.getNormalCarDetails();
    }

How to achieve Open Closed Principle if in the future you need to add more attributes?

The problem at hand is to identify Owners based on some logic then return back an object with all of those Owners. So if client needs 3 Owner then return back an object with those 3 Owners. Example: Owner A, Owner B, Owner C. That object will then be used to add on to another object, Account, that will be send to the Database.

I was thinking of creating an OwnerIdentifier interface that classes can implement. Then have a class that has a method that takes in a variable arguments that will iterate through all the OwnerIdentifier concrete implementation and the method returns back a Map<Owner, String>. Owner is an Enum type and String is the owner alias. Once I have the map I can use that to build the model.

HOWEVER, I'm not sure if that is really the best approach...... Because I would have to then map the values in the Map to a particular field in the Account object. Then if new type of Owner are added, I would have to change the Account object...

Any suggestions would help a lot!!!

WAP to print this pattern in c [closed]

       1
      2 2
     3 3 3

and so on.... I have tried a few times to make this pattern but couldn’t create the exact code for the spaces that has to be provided between the numbers

Design implementation: Using Structs inside Libraries with interface and dynamic lib address

Base on some articles on using library with struct in it.

  1. sample article
  2. eth doc for library shows the design pattern of using struct in library

Below are sample codes from sample article.

Count.sol

pragma solidity ^0.6.4;

library Count{
    struct hold{
        uint a;
        mapping( uint => bool ) isGood;
    }
    
    function subUint(hold storage s, uint b) external view returns(uint){
        
        require(s.a >= b); // Make sure it doesn't return a negative value.
        return s.a - b;
        
    }

}

Math.sol

pragma solidity ^0.6.4;


import { Count } from  './Count.sol';

contract Math {
    
    using Count for Count.hold;
    
    Count.hold  h;
    address h1;
    
    constructor() public {
        h.a = 123;
        h.isGood[1] = true;
    }
    
    function subHold(uint a) public view  returns(uint){
        return h.subUint(a);
    }
    
    function show(uint a) public view returns ( bool){
        return h.isGood[a];
    }
}

Problem:

I try to add an interface to my library and because I would like to upgrade my library in the future, so I try to store it as address so that I can access it with new address h.

But I'm confused how I should write it as there is no article about it to do anymore research on this.

Count.sol

pragma solidity ^0.6.4;

library Count{
    struct hold{
        uint a;
        mapping( uint => bool ) isGood;
    }
    
    function subUint(hold storage s, uint b) external view returns (uint){
        require(s.a >= b); // Make sure it doesn't return a negative value.
        return s.a - b;
        
    }
    
    function setA(hold storage s, uint _a) external returns (bool){
        s.a = _a;
    }
    
    function setGood(hold storage s, uint _a, bool _good) external returns (bool){
        s.isGood[_a] = _good;
        
        return true; // successful
    }
    
    function showGood(hold storage s, uint _a) external view returns (bool) {
        return s.isGood[_a];
    }

}

Math.sol

pragma solidity ^0.6.4;


import { ICount } from  './ICount.sol';
import { Count } from  './Count.sol';

contract Math {
    
    using Count for ICount;
    
    address h;
    
    constructor() public {
        ICount(h).setA(123);
        ICount(h).setGood(1, true);
    }
    
    function subHold(uint a) public view  returns(uint){
        return ICount(h).subUint(a);
    }
    
    function show(uint a) public view returns ( bool){
        return ICount(h).showGood(a);
    }
}

ICount.sol

pragma solidity ^0.6.4;

import { Count } from  './Count.sol';  // this makes my code not dynamic, but I need the type declaration for functions below

interface ICount {
    function subUint(Count.hold calldata s, uint b) external view returns(uint);
    function setA(Count.hold calldata s, uint _a) external returns (bool);
    function setGood(Count.hold calldata s, uint _a, bool _good) external returns (bool);
    function showGood(Count.hold calldata s, uint _a) external view returns (bool);
}

There are several problems in the above codes and I'm stuck.

Firstly ,I have to increase the number of function in the Count.sol since struct is not easily accessible directly. Which is ok, if it is what it takes.

Secondly, I tried to use address of library and store it at h and convert it to with ICount(h).function and use it as function. but There are many problem.

Thirdly, as shown at ICount.sol, I do not want to import Count.sol, but I need the type Count for function parameter type declaration.


Purposes of doing all above and what I try to achieve.

  1. Interface is to set a standard for future and backward compatibility.
  2. Interface is used to convert address to Count so function can be called.
  3. Count.sol is used because my Math.sol is getting too big for compilation. I need to move related code with the same purpose to Count.sol

Please advise and sorry the amended code doesn't compile because I'm stuck entirely.

Which Design pattern is the best for Database handling in Android [closed]

I was curiously exploring a few sample applications and getting my hands on design patterns as well. Per my understanding, a Factory pattern or a Facade pattern should be good for the general-purpose Database + Android applications to work together.

Although I would love to hear other alternatives (which might be better).

How do I avoid code duplication in my case?

I am currently working on code that converts one data model to another. More precisely, it is a Hafas model, but it is not very important. The problem is that I have to support multiple versions of this model. I currently have a converter for version 1.23 and version 1.29. Thousands of lines of code, about 50 methods that are 97% identical.

So I get XML with the data that I first need to deserialize to the POJO classes I constructed and then convert them with my algorithms.

The problem is that these versions use different packages of my POJO classes that have 99% same names.

Here is one example: Converter for 1.23 version:

public void convertHafasLegsInsideCustomTrip(TripStructure myTrip, LegList hafasLegs) {
    for (Leg hafasLeg :
            hafasLegs.getLeg()
    ) {
        // We have to convert each Hafas Leg to Trias TripLegStructure
        TripLegStructure myTripLeg= convertToTriasTripLeg(hafasLeg);

        if (myTripLeg!= null)
            myTrip.getTripLeg().add(myTripLeg);
        else
            throw new NullPointerException("ERROR: HAFAS TripResult conversion ended up with NULL object");
    }
}

Converter for V1.29:

public void convertHafasLegsInsideCustomTrip(TripStructure myTrip, LegList hafasLegs) {
    for (Leg hafasLeg :
            hafasLegs.getLeg()
    ) {
        // We have to convert each Hafas Leg to Trias TripLegStructure
        TripLegStructure myTripLeg= convertToTriasTripLeg(hafasLeg);

        if (myTripLeg!= null)
            myTrip.getTripLeg().add(myTripLeg);
        else
            throw new NullPointerException("ERROR: HAFAS TripResult conversion ended up with NULL object");
    }
}

The problem is that the LegList and Leg inside packages are different. So in the first case, they are imported from the generated POJO classes for version 1.23 and in the second example from the POJO classes for version 1.29.

The algorithm that converts is almost identical and I have many other methods that are 100% identical, only a few of them are different because some classes have different names in these two packages.

My next problem is that I may later implement a converter for another version that will also have similar features and I don't want to duplicate the code for each of them.

Is it always bad to use default exchange in RabbitMQ?

I've already used RabbitMQ a lot in my work, and sometimes I use the default exchange in some scenarios. For example, I need to post a time-consuming render job to one specific render queue, and some background worker programs will consume it. It was like this:

default exchange => VideoRenderQueue
default exchange => ModelRenderQueue

The confusion I have here is people considering using default exchange as an anti-pattern in the case of software design, as it creates coupling between publisher and consumer. So instead of using the default exchange, I started to declare a new direct exchange every time I have a new type of rendering queue and bind the rendering queue to it (see below). But soon I doubted that if this approach is no different from using the default exchange.

videoRenderExchange => VideoRenderQueue
modelRenderExchange => ModelRenderQueue

So what is the best practice should I follow in this scenario? Or is there something that I missed here?

lundi 26 juillet 2021

Scenario to handle DB column Change lead to change in other places in entities

I have a scenario where in Database table columns are inline with Web API entities. For example, Employee table column salary has type int and backend entities are also integer. What if we need to change the datatype of column Salary to Double. Do we need to change in the API entities as well which represents DB table structure?

If there any way we can handle this?

When to use strategy or facade?

So me and my group is working on this real estate program (school assignment), we are troubled if we used misused Strategy pattern, and should use Facade instead. I am writing codes for CRUD of database, I used Strategy pattern to call those CRUD methods (add,delete,update) from the jform. We are still starting to learn different design patterns, so we would like to as help if this is a correct implementation.

This is my code for Strategy Pattern

public interface methods {
    public void doOperation(int id, String type, int area, String address, String listingStatus);
}

public class methodUse {
    private methods method;

    public methodUse(methods method) {
        this.method = method;
    }
    
    public void executeMethod(int id, String type, int area, String address, String listingStatus){
         method.doOperation(id, type, area, address, listingStatus);
    }
}

public class methodUpdate implements methods{
    private SystemAdmin systemAdmin = new SystemAdmin();

    @Override
    public void doOperation(int id, String type, int area, String address, String listingStatus) {
        systemAdmin.updatePropertyListing(id, listingStatus);
    
    }
}

public class methodDelete implements methods{
   private SystemAdmin systemAdmin = new SystemAdmin();


    @Override
    public void doOperation(int id, String type, int area, String address, String listingStatus) {
      systemAdmin.deleteListing(id);
    }
}

public class methodAdd implements methods{
    private SystemAdmin systemAdmin = new SystemAdmin();

    @Override
    public void doOperation(int id, String type, int area, String address, String listingStatus) {
        systemAdmin.addListing(id, type, area, address, listingStatus);
    }
    
}

The classes are called on the jform every time the specific button is clicked, ex. add button executes strategy add.

I would like to ask you all if what we did was the right implementation of Strategy pattern.

Openapi Rest endpoint for actions

I am planning to implement rest API which are actions like

/uptime?hosts=h1,h2,h3
/reboot?host=h1,h2,h3
/hoststatus?host=h1

What is the best way to design the endpoint with action. In all the rest design patterns/documents I see endpoint should be resources (noun) but in my case I have actions need to be performed on list of host.

How to optimize my code that uses different packages with the same class names?

I am working on a converter that converts one data model to another. Specifically, it is a Hafas model where the API sends me a Hafas response in XML format. It doesn't matter which model it is, but that it uses different pojo classes for different versions of this model.

I use two versions of Hafas (for now) and both versions have separate schemes, so the pojo classes that I generate are constructed differently. The problem is that both versions are different but still use the same or similar class names. The algorithm that reads them and translates them into another data model is almost the same. Over 900 lines of code with perhaps a few modified lines of code.

Examples

1st Version:

public void convertAndInsertHafasLegsInsideTriasTrip(TripStructure myTrip, LegList hafasLegs) {
        for (Leg hafasLeg :
                hafasLegs.getLeg()
        ) {
            TripLegStructure myTripLeg = convertToTriasTripLeg(hafasLeg);

            if (myTripLeg != null)
                myTrip.getTripLeg().add(myTripLeg);
            else
                throw new NullPointerException("ERROR: HAFAS TripResult conversion ended up with NULL object");
        }
    }

2nd version:

public void convertAndInsertHafasLegsInsideTriasTrip(TripStructure myTrip, LegList hafasLegs) {
        for (Leg hafasLeg :
                hafasLegs.getLeg()
        ) {
            TripLegStructure myTripLeg = convertToTriasTripLeg(hafasLeg);

            if (myTripLeg != null)
                myTrip.getTripLeg().add(myTripLeg);
            else
                throw new NullPointerException("ERROR: HAFAS TripResult conversion ended up with NULL object");
        }
    }

LegList class and Leg class in the first and second versions of the converter is different because both versions use different packages with pojo classes. So LegListand Leg come in different packages.

My problem is that I have dozens of methods that are exactly the same and maybe a few that are different because the class names are different in these two packages.

Another problem is if for example I have to implement a converter I have another version that is also similar to these, again I have to duplicate thousands of lines of code.

Is there a JS design pattern to combine N objects into 1 façade object and have code editors know which methods it has?

for example suppose I have:

var obj_a = {
  foo: function() {}
}

var obj_b = {
  bar: function() {}
}

How should I declare obj_c to have both methods so that typing obj_c. would popup foo and bar as valid autocomplete options?

interface implementation from different api's

i have a view that implements an interface that receives model a and model b.

i have also two api's responses(A,B) that after some manipulations i create from them the wanted models (A->a, B->b).

The thing is, i also want to support new apis (A*,B*) that for some users will replace the old apis. A* & B* jsons will not be the same as the old ones so different manipulations should be carried out in order to generate a and b models.

what is the correct design for that?

Can this be considered as a valid implementation of singleton class in C++?

#include <iostream>
using namespace std;

class Singleton {
public:
    int val;
    static int count;
    Singleton() {
        if (count == 1) throw 0;
        Singleton::count++;
        val = 100;
    }
};

int Singleton::count = 0;

int main () {
    try {
        Singleton a, b;
    } catch (...) {
        cout << "error\n";
    }
    return 0;
}

So we count the number of objects created, and throw from the constructor when count is about to exceed 1. Will throwing from constructor abort the creation of object?

samedi 24 juillet 2021

SVG - how to achieve diagonal two-color fill

I'm trying to fill a rounded-corner rectangle, with two colours, one colour either side of a diagonal line across the corners.

I've tried adding a triangular filled polygon, but this shows through the parent rectangle transparent corners.

So I've tried using a pattern, which is almost working.

The issue is that the pattern seems to be starting at co-ords 0,0 of the entire SGV, not the shape it's filling.

Example here:

<?xml version="1.0"?>
<svg xmlns="http://www.w3.org/2000/svg" xmlns:xlink="http://www.w3.org/1999/xlink" xmlns:svgjs="http://svgjs.dev/svgjs" version="1.1" width="800" height="800">
  <defs>
    <pattern x="0" y="0" width="100" height="100" patternUnits="userSpaceOnUse" id="SvgjsPattern1008">
      <polygon points="0,0 100,100 0,100" fill="#ff00ff" stroke-width="1" patternUnits="objectBoundingBox"/>
      <polygon points="0,0 100,0 100,100" fill="#00ff00" stroke-width="1" patternUnits="objectBoundingBox"/>
    </pattern>
  </defs>
  <rect width="100" height="100" x="0" y="75" rx="20" ry="20" fill="url(&quot;#SvgjsPattern1008&quot;)"/>
</svg>

How can I get it so the pattern starts in the top-left corner of the rectangle?

Thanks in advance for any help.

Also, I'm looking for a pure SVG solution, no CSS.

Andy

How to choose design pattern for processing of input data?

I have a code snippet that is used to process strings of text files. The function processFile function is called for every file in the directory

void processFile(const std::string& sourceFileName) {
    std::ifstream sourceFile;
    sourceFile.exceptions(std::ifstream::failbit | std::ifstream::badbit);
    try {
        sourceFile.open(sourceFileName);
        if (sourceFile.is_open()) {
            while (sourceFile.peek() != EOF) {
                std::string line;
                std::getline(sourceFile,line);
                // process line here
            }
            sourceFile.close();
        }
    }
    catch (const std::ifstream::failure& exception) {
        std::cout << "some exception text here" << std::endl;
        return;
    }
    catch (...) {
        std::cout << "some another exception text here" << std::endl;
    }
}

Besides files, I also need to read data from pipes and from sockets. What design pattern can you use to abstractly read an entity? Could you please give me some examples?

which design pattern is used in the code bellow

Can someone please tell me which design pattern is used in the code bellow? ``` class UnixText { function write($txt){echo $txt;} function lf() {echo "\n";}

    }
    
    class MSWindowsText
    {
    function write($txt){echo $txt;}
    function crlf()   {echo "\r\n";}

    }

    interface Writer
    {
    function write($txt);
    function newLine();
    }

    class UnixWriter implements Writer{
    private $target;

    public function __construct($unixText){$this->target=$unixText; }
    function write($txt){$this->target->write($txt);}
    function newLine(){$this->target->lf();}
    }

    class MSWindowsWriter implements Writer{
    private $target;

    public function __construct($winText){$this->target=$winText;   }
    function write($txt){$this->target->write($txt);}
    function newLine(){$this->target->crlf();}
    }
    ```

Abstract Factory or Builder Class for similar objects with minor differences?

I have an app, where I have 10 different order types, these are huge objects of like 400 properties, with minor differences between them, at this point adding a new order type, or changing something in one of them requires huge amounts of effort.

Since I am doing a refactor coupled with a redesign shortly, I have been looking for a way to make things easier for me.

The Factory method looks very appealing, but I cannot imagine it working for me, since I have some methods that are implemented only on some or a single order type. But ideally a factory would have been the best, just calling the same functions, and not having the client worry about the order type, but i think this is not possible, since for example, for some order types I have subscriptions, for others I have simple payments, or some have different kinds of artworks attached to them, or different kinds of target audience. But they do not differ in a huge way, just some functions are not doing exactly the same thing, should I have a general way of naming functions, that generally describes the action and implement it for the particular order in that way?

I have been thinking if something like a builder class would make more sense in this context, I am not a very experienced person in this kind of design and planning.

Should I provide more context on this, or provide some examples, come up with some mock data? Or can we make and educated guess? Or an opinion, on what could make my life easier.

vendredi 23 juillet 2021

How a javascript pubsub/observer sees the function of another object?

I have this simple code, while trying to learn the basics of implementing the pubsub method in javascript.

people object emits a simple event and events object is the pubsub, takes the event and emits it to all that listen

Then stats that listens for that event, executes a function, with the data that came from the pubsub.

<html>
<h1>hello</h1>
<script>                    

    var events = {
        events:{},
        on:function(eventName, fn){
            this.events[eventName] = this.events[eventName] || [];
            this.events[eventName].push(fn);
        },
        emit:function (eventName, data) {
            if (this.events[eventName]) {
                this.events[eventName].forEach(function(fn){ 
                    console.log('events this ', this);
                    fn(data)
                });
            }
        }
    } 

    var stats = (function(){ 
        var counterstats = 0  
        events.on('peoplechange', setPeople);
        function setPeople(a) { 
            console.log('stats this ', this);
            counterstats++;
            console.log('stats people ', a )
        }
        
    })(); 

    var people = (function(){ 
        console.log('people this ', this);
        events.emit('peoplechange', 5);
    })();  
</script>
</html>

I am asking, how events knows and communicates with setPeople that is inside stats. setPeople is a method of an object, not exposed.

How events sees it? I thought I had to do events.on('peoplechange', events.setPeople); so events knows where this method belongs to.

I print the this of the function in the emit, and the this of the setPeople in the stats and they all point to Window.

I still cannot explain how events sees setPeople inside the stats, without specifying further.

Any explanation would be great. Apologies for asking basic things

Hashable subclasses of mutable classes in Python

I want to build a subclass of a class which is basically a wrapper around a list/dictionary, and I want to use instances of this class as keys. In order to have easy access to the list/dictionary methods, I figured I can just subclass them, but then I lose hashability.

I understand that this is incompatible with the __eq__ of the mutable classes (and I don't need it), so I came up with the following solution.

class Foo(list):
    __hash__ = object.__hash__
    __eq__ = object.__eq__

Though I doubt this will come up in my specific applications, I guess this might cause problems if another class (with its own __hash__) would appear between Foo and list in the MRO of a subclass.

  1. Is there a more Pythonic way of doing this? I could just add a list/dictionary as an attribute and then simply use the attribute (which would make code elsewhere more cumbersome) or the list/dictionary methods I need (but that'd be much more messy if I need more than a couple of methods).
  2. Is there some pattern/recipe that would allow me to do this sort of thing in a cooperative setting (in other words, how should I change the code if I do in fact anticipate another class between Foo and list in MRO)?

We have so many XML files. We will validate, parse and compare these files with existing data. How to develop this feature with patterns

Like I explain at the header. I will give you the happy path step by step following:

XML's are so different but all of them contains what data we needs. And we take the data what we need.

  1. Upload 1 XML file with xmlType(let's we say AType) via API.
  2. Convert multipart.File to the xlsx.File.
  3. Chose correct path with the switch case and xmlType.
  4. Call validation function ValidateATypeFile(). (Check the headers that we need)
  5. Call xml reading function ReadATypeFile(). (Collect the data that we need)
  6. Call existing data from database.
  7. Compare with xml data and existing data.
  8. Find changes and return a JSON list which includes existing version and new version.

Which patterns fit this feature? Beside the patterns do you suggest any other approach this kind of feature.

Boolean expression tree with predicates?

I am trying to design an expression tree builder that can be used to build an expression tree that can be evaluated lazily with provided context (hash map). Required set of operators is AND/OR/NOT, <,<=,>,>=,=,!=, in_range(inclusive or not). Expression tree must support a short circuiting (not computing more than needed for the final result). Evaluation result is either true or false. Which nodes in my case must be intermediate and which are the leafs? I suppose AND/OR/NOT are intermediate ones and predicates (<,<=,>,>=,=,!=, in_range) will be leaf nodes? Or each predicate will be represented as a subtree?

API Design Pattern (In Go)

Problem

Let's say I have a multi tenant api that manages users. I separate my app into 3 tiers: app, business, and data layers. My app layer will take in the request for the client and pass it into my business layer (I use a struct called Service as my business layer) function to update. The func will look like this:

func (s Service) UpdateUser(ctx context.Context, tenantID int, clientID int, user users.User)
  • ctx because it's Go and I use it in my data layer
  • tenantID and clientID used to make sure this caller is authorized to update the user
  • user to obviously update the user

My problem is that this is a simple function and I have 4 params. ctx is just a given but I now have to pass tenantID and clientID into every single function I make for authz purposes. For more complex functions, this could be 6 or 7 params.

Options

1) Keep as is

Pros:

  • simple and clear

Cons:

  • redundant (every function has the same tenantID and clientID) and long function parameters

2) Make input structs

example:

func (s Service) UpdateUser(ctx context.Context, updateUserInput users.UpdateUserInput)

Pros:

  • short and simple parameters

Cons:

  • abstracting required params to an object (this means you either make a New func that takes in all these same params or you have to check every request to make sure the caller filled in the proper fields)

3) New Service each request to app layer

The app layer will call something like NewService(tenantID int, clientID int)

example:

func (s Service) UpdateUser(ctx context.Context, user users.User)

Pros:

  • funcs become simple like in option 1

Cons:

  • creating a new service each time in the app layer (ex: in http api, each endpoint invocation creates a new service)

Other options are welcome.

Final Thought

Option 3 is interesting to me. Intuitively it doesn't feel right, but is it that bad to make a new struct each request? I mean, that is already happening when a request comes in, what is just one more?

This also doesn't have to be a Go specific discussion, I would also like to know how others might do it in other languages. But I would like to know about Go.

wrap result of method to an intermediate object which deferred execution of original method

pseudocode:

class Transaction {
    withTransaction(trx);
    exec()
}

class Test {
    @somedecorator 
    getUserById(id) {
        return this.trx(this.tableName).where({ id });
    }
}

const inst = new Test()
const res = inst.getUserById(1);
res.withTransaction(myTrx);// call `this.trx(this.tableName).where({ id });` with `myTrx`  
res.exec()// return result of `this.trx(this.tableName).where({ id });` with default trx

Example in plane JS what behavior I want to get

class BaseRepo {
    constructor(tableName, trx) {
        this.tableName = tableName;
        this.trx = trx
    }

}
function getUserByIdFn(id) {
    return this.trx() + `(id number => ${id})`;
}

function decorateMethod(fn, self){
    return (...args) => {
        return {
            withTransaction(trx) {
                return fn.call({
                    ...self,
                    trx,
                },...args)
            },
            then(resolve) {
                return resolve(fn.call(self, ...args));
            }
        }
    }
}
class UserRepo extends BaseRepo {
    constructor(trx) {
        super('user', trx)
    }
    getUserById = decorateMethod(getUserByIdFn, this);
}
// trx here is function for simplicity 
const user = new UserRepo(() => 'original function  result');
(async function main() {
    const result1 = await user.getUserById(1);
    console.log(result1); // original function  result(id number => 1)
    const result2 = user.getUserById(3);
    const t = result2.withTransaction(() => 'another call'); 
    console.log(t); // another call(id number => 3)
})()

I need some approach to wrap getUserById result to in Transaction object which deferred execution of original method. I know how todo that with plane Js, but how do it in Typescript with all typing. Is it possible to do somehow? Some best practice?

Combine one-to-one and many-to-many (django)

I have a model named "db_connector" and another one "project_site".


A "project_site" can have many to many relation with "db-connector". But the "project_site" should have one default db-connector.


What is the best design-pattern for this? Can I combine many to many and one to one like this: Many to many relation for alternative connectors linked to a project_site and one to one for the default connector linked to a project_site?

The user can specify a db_connector, if the user doesn't specify a database_conector, the default db_connector can be used?

jeudi 22 juillet 2021

OOD Practice Problems preferably with solutions [closed]

I have a book I'm using to learn Object Oriented Design, however I need practice problems + (preferably) solutions to really refine my understanding.

Please tell me any links or resources where I can find OOD practice problems and possibly ones with solutions as well. I appreciate, thank you.

How will you design classes with many parameters and different clients

For example, if we have a class with 8 parameters:

class TestClass(
    private val paramA: ParamA, 
    private val paramB: ParamB,
    private val paramC: ParamC,
    private val paramD: ParamD,
    private val paramE: ParamE,
    private val paramF: ParamF,
    private val paramG: ParamG,
    private val clientA: ClientA,
    private val clientB: ClientB
)

Most of the time, when this class is used, first 7 parameters will always be passed. The last 2 parameters will depend on the use case. If we need use clientA to call other functions, it will pass clientA, and clientB will be null. If we need use clientB to call other functions, it will pass clientB, and clientA will be null. Inside the class, either clientA or clientB will be used to call other functions, depending on which one is not null.

Can we use different approach here? I don't like using if...else... to check clientA or clientB is null then do other things. Can we replace the two parameters with

private val clientGeneric: ClientGeneric

then clientA and clientB can inherit from ClientGeneric and be passed to TestClass. But I don't see a good way to make clientA and clientB inherit from a ClientGeneric class.

Lambda Expressions and Polymorphism (EF Core) how to design this? [duplicate]

Assume the following base class

public abstract class BaseAction : Entity
{
    public DateTime CreationTime { get; private set; }
    public DateTime? CancellationTime { get; set; }
    public abstract Expression<Func<BaseAction, bool>> GetIdentifierExpression();
}

and the following attempt at a derived class

public class DerivedAction : BaseAction
{
    public string Name { get; set; }

    public override Expression<Func<BaseAction, bool>> GetIdentifierExpression()
    {
        ParameterExpression parameterExpression = Expression.Parameter(typeof(DerivedAction));
        return
            Expression.Lambda<Func<DerivedAction, bool>>(
                Expression.AndAlso(
                    Expression.AndAlso(
                        Expression.Equal(Expression.Constant(null),
                            Expression.Property(parameterExpression, nameof(CancellationTime))
                        ),
                        Expression.Equal(Expression.Constant(null),
                            Expression.Property(parameterExpression, nameof(ExecutionTime))
                        )
                    ),
                    Expression.Equal(Expression.Constant(Name),
                        Expression.Property(parameterExpression, nameof(Name))
                    )
                ),
            parameterExpression
        );
    }
}

I want to find a way to have a more specific implementation of GetIdentifierExpression in the derived class but the above does not compile since there is no implicit conversion between Expression<Func<DerivedAction, bool>> and Expression<Func<BaseAction, bool>>

The method eventually would get called like so

bool CheckActionIsInDB(BaseAction action)
{
    using var context = contextFactory.CreateDbContext();
    var set = context.Set<BaseAction>();
    return set.Any(action.GetIdentifierExpression());
}

Any ideas how to achieve such polymorphism on a method that returns Expressions?

Universal NoSQL or SQL driver library for Databases in nodejs apps?

Edited: I am looking for a "universal" driver that supports most of noSQL or SQL databases for nodejs. According to the principles of loose coupling of outer resources, it should be possible to exchange one NoSQL database agains another without much changing its code (https://12factor.net/backing-services).

Is there really such principles in practice out there, or libraries that support that approach?

How to print sideways in Javascript?

I want to print a triangl. I am getting my expected result but it's printing in consecutive lines. I want to print the "*" sideways for every for loop's output. How do I do it?

Code:

let a,b,c;
a = 5;
b = 1;
while(b <= a){
  for(c=1;c<=b;c++){
    console.log('*');
  }
  b++;
  console.log('\n')
}

Output

enter image description here

Kotlin: perform the specific action on the object depending on its type

I am new to Kotlin and want to know how to solve the following problem in the most idiomatic way with this language.

Let's say we have the base class Symbol and a bunch of its subclasses: SymbolA, SymbolB, and so on. We receive a list of symbols (instances of Symbol subtypes) and want to do some action on each symbol depending on its type. Assume also that we are planning to add more subclasses of Symbol and more new kinds of actions on them in future.

Example

For example, we was asked to transform each symbol in the list with the transformation corresponding to the type of symbol (assume that the transformation is fixed for each type). I will list the possible sollutions appearing in mind.

Possible Approach 1

Maybe the simplest possible approach is to declare the following abstract method in Symbol class:

open class Symbol {
    /*...*/
    abstract fun transform() -> Symbol
}

so that each derived class should implement its corresponding transformation inside the transform() method. The problem with this approach, I think, is that we have mixed the internals of Symbols with the logic that operates on the data. What if we will be asked to add few more similar actions and so on? I think that this is exactly the case when we would like to decouple the operations from the data.

Possible Approach 2

The second approach I thought of is to use the visitor pattern. It looks nice, however, as far as I understand, it becomes problematic when we would decide to introduce additional Symbols (subclasses of Symbol).

Possible Approach 3

Use type introspection (e.g. Kotlin's is, or Java's instanceof operator). For example, we can do the following:

fun transform(symbol: Symbol) : Symbol {
    return when(symbol) {
        is SymbolA -> /*  perform the transformation of SymbolA  */
        is SymbolB -> /*  perform the transformation of SymbolB  */
            ...
        else -> TODO("Transformation is not implemented for: ${symbol::class}")
    }
}

Possible Approach 4

Use reflection. We can introduce the following interface:

interface Transformation <T: Symbol> {
    fun transform(symbol: T) -> Symbol
}

Then implement the corresponding transormation for each subclass of Symbol and use a heterogeneous map to set/get the transformation corresponding to the type of symbol. I would also expect for this solution to be the slowest one compared to the previous solutions.

Summary

What I want to know:

  1. Any other related solution (pattern) I am not aware of?
  2. Which one is the most flexible and maintainable solution to this particulat problem?
  3. Which solution is most idiomatic/natural for Kotlin language?

Thanks in advance!

mercredi 21 juillet 2021

Please help a regular expression problem for a string

String aa = "aa\nbb\r\ncc";

I want to have a regular expression pattern to find the "\n" , but skip the "\r\n" . Thanks so much if anyone can help it ?

How to avoid including OpenCV to my header?

Hope all's well for y'all. I just have a rookie-level question on C++ coding, hope to collect some ideas. I am writing a image-processing model which is to be wrapped to a C-based DLL API.

/* myModel.h */

#include "opencv2/imgproc.hpp"
#include "opencv2/objdetect.hpp"
#include "nlohmann/json.hpp"
#include <variant>

class myModel
{
   public:

      myModel();

      loadCascadeClassifier( std::string fpath );

      struct DetectedResults
        {
            bool is_detected,
            cv::Rect bounding_box;
            cv::Point center;
        };

      myModel::DetectedResults detect( cv::Mat& input_image );

   private:

      std::vector< cv::Rect > box_stack;

      cv::CascadeClassifier Classifier;

      nlohmann::json json_params;

      // some other members...
}


/* myModel.cpp */

// Implementations...

The code can work without problem, but including myModel.h in other projects becomes troublesome. I realize that including resources in myModel.h may not be a good practice, since:

  1. other projects using myModel.cpp /.h need to have the same include/libraries and linkers.
  2. re-compilation takes time once myModel.h changed
  3. I don't know but is it good to use included objects as input arguments?

Therefore I researched some articles like this., which indicates to avoid inclusion in header by either:

Forward Declaration

Not applicable in my case. Looks like I cannot forward-declare incomplete-type classes for OpenCV objects, according to this discussion

Private Implementation

Should I try this one? Trying to figure out how to apply this.

This is not to seek for a solution of a bug, so any thoughts from you in any form will be welcomed. I'd be happy to learn how C++ pros tackle with such problem. Thanks in advance!

TL;DR How to avoid including resources in header myModel.h?

Which design pattern is good to receive bids from different fronts to a single backend in javascript

I want some guidance, I am working on a WordPress plugin that offers to bid.

There are 2 types of users who can place a bid for an auction. An actual user OR an admin who is able to place a bid to any auction on the behalf of any user.

Well from the frontend, the user is able to place a bid as well as from the backend admin can place a bid on the behalf of a user, and there is a live table that is rendering all the biddings. but the issue is that when the admin adds a bid it shows up in the table but if any user from frontend places a bid this doesn't pop up in the same table .. thou admin has to reload the page to see if any bid appears from the frontend.

I was using setInterval() with an ajax call, but the issue is with setIntervel that if there is any bid from frontend user it keeps loading again and again.

someone suggested following the Observer Design pattern to resolve this hurdle. which I tried but no luck...

I think the Observer design pattern won't help me here.

// The news class is the Observable class or "subject"
class News {
    // A list of observers
    constructor() {
        this.observers = [];
    }

    // Method for subscribing to, or "observing" observable
    addSubscriber(subscriber) {
        this.observers.push(subscriber);
    }

    // Method for unsubscribing from observable
    unsubscribe(subscriber) {
        var index = this.observers.indexOf(subscriber);
        this.observers.splice(index, index);
    }

    // Method for sending data to subsribers
    transmit(data) {
        console.log('transmit: ', data);
        this.observers.forEach(subscriber => subscriber.receive(data));
    }
}


// The News Outlets are subscribers to the news in different languages
class NewsOutlet {
    // We will set the language when we instantiate the news outlet
    constructor() {
        this.data = '';
        this.news = '';
    }

    receive(data) {
        this.data   = data;
        var self    = this;

        // Translate after receiving
        jQuery.ajax({
            url: Observer.ajaxurl,
            type : 'POST',
            encoding: 'UTF-8',
            dataType: 'JSON',
            data: {
                action: 'get_live_room_auction_status',
                last_timestamp : Observer.last_timestamp
            },
            success: function(result) {
                self.news = result;
                self.reportTheNews();
            }
        });

    }

    reportTheNews() {
        // A shady workaround for our HTML efforts!
        jQuery('.bidders-list tbody').append(this.news);
        // document.getElementById(elemId).innerText = this.news;

    }

}


let news = new News;
let enOutlet = new NewsOutlet();

news.addSubscriber(enOutlet);

var sendNews = function( auction_id, timestamp ) {
    news.transmit(timestamp);
    news.observers.forEach(function(o){
        o.reportTheNews();
    });
}

Java searching for a right pattern

There is the next task I have :

Create an application that represents a Taxi station with 10 taxies. Taxi station enables: -Order taxi -Cancel taxi -Be aware when taxi gets available A person that orders a taxi may be a regular customer or a VIP customer. If a VIP orders a taxi, he/she should be first in line regardless of the time he requested the service. Where no taxi is available, a person should be kept on the waiting list. When a taxi becomes available, a person according to priority gets the free taxi. Print to console every reservation accepted/queued. Execute:

  1. Create a taxi station with 10 taxis
  2. Order a taxi for 9 regular persons
  3. Order a taxi for 1 VIP person
  4. Order taxi for 2 regular person
  5. Order a taxi for 1 VIP person
  6. 1 Taxi is back in the station
  7. Order a taxi for 1 VIP person
  8. the Second taxi is back at the station
  9. Third taxi is back at the station

So, the question is: Which design pattern fits the most to this task? How would you solve this case? Thanks in advance!

mardi 20 juillet 2021

Custom pattern visual recognition

im wondering if exist a way to "tell" to the code, in a visual/graphical way, on the chart, which is the indicator spatial configuration (angles, value and so on..) that will trigger a long or short order.. The indicator I'm building will tell me exactly when buy the bottom or sell the top,thank to some patterns. For me is simple to recognise those.. Will be great, and faster to let the code to learn each specific pattern in a visual way. Ta-lib has internal classic patterns.. Can I build my own?

Java inheritence with different typed variables

with the code below is there a way to make these two extremely similar classes inherit from a single superclass? they differ almost exclusively in variable types. If not is there a design pattern that seems most appropriate for this case? I've been looking at maybe using a factory pattern but I'm not sure if that's the most appropriate for the situation.

class stringCharacteristic {
    String name = "";
    String value = "";

    public String getValue() {
        return value;
    }

    public stringCharacteristic setValue(String value) {
        this.value = value;
        return this;
    }

    public String getName() {
        return name;
    }

    public stringCharacteristic setName(String name) {
        this.name = name;
        return this;
    }
}

class intCharacteristic {
    String name = "";
    int value = 0;

    public int getValue() {
        return value;
    }

    public intCharacteristic setValue(int value) {
        this.value = value;
        return this;
    }

    public String getName() {
        return name;
    }

    public intCharacteristic setName(String name) {
        this.name = name;
        return this;
    }
}

Group classes that are based on a template?

I don't want to shoot myself in the foot, so I will provide a little context in case this is an XY problem and there is a better way to deal with this: I have a lot of data in a lot of binary files; these data come from various hardware so I have data in int, float, double, long double, etc.

These data have a header to identify where it comes from (which equipment), type of data (int, double, etc.) what was being done when the data was obtained (physics run, calibration, testing, etc.) and other things.

The best, and most intuitive way, to handle these data I have thought about is the following:

Have a Header class that gives the information about the data:

class Header {
    public:
        int event_id;
        int time_stamp;
        int data_size;
        int trigger_mask;
};

And then have a class template for the data (header plus a vector containing the actual data):

template<class T> class Data {
    public:
        Header data_header;
        std::vector<T> values;
};

The problem is that people might want to, depending on the analysis they want to do, group different Data<X> objects. The easiest example would be if people want to group the data (same type) collected by all the EQUIPMENT Xs.

std::vector<Data<double>> x_signals;

But what if people want to group all the data produced by EQUIPMENT X and loop through it. This is not necessarily all of the same type, the same equipment can throw some data in double for some things, and some other data in int.

Another case would be when people are reading the Data objects from the binary file. They may want to have a std::vector<Data> and push to it the data as they read it from the file. But this also wouldn't be possible.

The possible solutions I have though about are:

  1. Do nothing, and it would be the users problem how to handle these Data objects. They could have e.g
std::vector<Data<int>> int_data;
std::vector<Data<double>> double_data;
std::vector<Data<float>> float data;

And then they can push the Data they read into the correct container. If they want the Data with a specific characteristic (event_id, time_stamp, etc.) they would have to loop through all the containers above (and maybe store the indices of the data they want somewhere else).

  1. Provide a variadic template that keeps different Data types in a tuple:
template<class ...Types> class DataPack {
    public:
        std::tuple<Types...> data_pack;
};

But this would require the number of Data objects to be known before hand for a DataPack. We couldn't push Data into a DataPack as we read the file, and there is no way we can know how many Data objects we collected before we read the file.

  1. Make Data inherit from Header. This way we can have vectors of "headers" and use polymorphism. The problem is that Data is not a type of header; Data has a header. Inheritance feels weird and non-intuitive, which is a bit of a red flag.

I am a bit confused, and I don't know what the best approach would be. Am I thinking about all this in the wrong way? All three options seem to have a different degree of ugliness; I don't feel happy or confident with any of them.

Handler pattern?

I came across several java projects at my company (but this could be done with any OOP language) where we receive an object and depending on some fields we have to do a particular process. To avoid doing a huge list of if/else the following pattern is used :

Create handlers that have a common interface :

public interface IEventHandler {
    boolean support(Event event);
    void handle(Event event);
}

public class Handler1 implements IEventHandler {

    public Handler1() {
    }

    @Override
    public boolean support( Event event ) {
        return event.is1();
    }

    @Override
    public void handle( Event event ) {
        //Do something
    }
}

then you "register the handlers" and loop to execute the action :

List<IEventHandler> handlers = List.of(new Handler1());

for ( final IEventHandler handler : handlers ) {
  if ( handler.support( event ) ) {
    handler.handle( event );
  }
}

I'm pretty sure this is an anti-pattern but I'm not sure how this pattern is called to find better alternatives.

lundi 19 juillet 2021

Handling large simultaneous workloads using pub/sub?

I'm working on a problem where large no. of operations have to simultaneously be kicked off based of an event. For example, user types a destination and dates and wants the best offer from over 200 "travel partners".

To satisfy this, I'm planning on an event-driven architecture where upon user providing the appropriate input, a message is published to a topic, and this topic has worker subscribed to it which in turns generates additional events, one for each travel partner to get offers from.

So Essentially:

  • (1) publish message to Topic "TRAVEL_DESTINATION_REQUEST" upon user input being provided
  • (2) a worker is subscribed to this topic
  • (3) worker at (2), For each travel partner in system, publish event with data {date:..., destination:...,travel_partner_id: ...etc} to topic FIND_OFFER.
  • (4) workers subscribed to FIND_OFFER query travel_partner_id and persist the response somewhere.

So if you have 200 travel partners, above would push 200 events to FIND_OFFER topic for workers to handle per each user query.

Is this how you would go about solving a problem as such? If not how would you go about it? Sequentially is obviously not possible since we can't have the user seat there waiting and travel partner api calls may differ in response times...

In GKE world, is pub/sub a good candidate for such an approach? Does anyone know if pod load-balancing would cause any issues with this model?

How to give a specific pattern to a textbox in windows form C#

I am working in a c# windows form application and I need to have the below explained pattern in a textbox.

First: Numeric value (0123456789)

Second: One of arithmetic - multiply, plus, minus, or divide (+*-/)

Third: Decimal number (.)

Below are the examples

1234567890*17.325 or

1234567890+17.325 or

1234567890-17.325 or

1234567890/17.325

It should allow to type only numbers and arithmetic in the textbox and should not repeat arithmetic.

After validating, those 3 components should be taken into 3 cells in a datagridview separately when a command button is clicked.

Ex:

  • Number to Column 1 (123456789)

  • One of arithmetic to Column 2 (+,-,* or /)

  • Decimal number to Column 3 (17.325)

How can I do this? Any help would be much appreciated.

Abstract Designing Pattern

I was learning Abstract Designing Pattern and I have created the below code for understanding. My question is why I am seeing 'None' in the output of this code. I have created a Chair and Bed of two types Modern and Old. And I have created a factory for each type for producing that type of product.

Just getting started so maybe it's some silly mistake that I can't find :))

Code:

from abc import ABC, abstractmethod

class Chair(ABC):
    @abstractmethod
    def get_type():
        pass

class ModernChair(Chair):
    def get_type(self):
        print("Modern Chair!")

class OldChair(Chair):
    def get_type(self):
        print("Old Chair!")
        
class Bed(ABC):
    @abstractmethod
    def get_type():
        pass

class ModernBed(Bed):
    def get_type(self):
        print("Modern Bed!")

class OldBed(Bed):
    def get_type(self):
        print("Old Bed!")

class BaseFactory(ABC):
    @abstractmethod
    def get_chair():
        pass
    
    @abstractmethod
    def get_bed():
        pass

class ModernFactory(BaseFactory):
    @staticmethod
    def get_chair():
        return ModernChair()
    
    @staticmethod
    def get_bed():
        return ModernBed()

class OldFactory(BaseFactory):
    @staticmethod
    def get_chair():
        return OldChair()
    
    @staticmethod
    def get_bed():
        return OldBed()

m_chair = ModernFactory.get_chair()
m_bed = ModernFactory.get_bed()
o_chair = OldFactory.get_chair()
o_bed = OldFactory.get_bed()

for obj in list([m_chair, m_bed, o_chair, o_bed]):
    print(obj.get_type())

Output:

Modern Chair!
None
Modern Bed!
None
Old Chair!
None
Old Bed!
None

Thanks in advance

How to composite using-by objects (real world example)

Hey i have question with a real word example. Its related to my two other, but not really answered questions here:

https://softwareengineering.stackexchange.com/questions/423392/no-trivial-god-class-refactoring

and

https://softwareengineering.stackexchange.com/questions/425113/different-composition-techniques-from-the-perspective-of-the-client

Let's say we have a switch with the methods switchOn(), switchOff(). The switch(es) are included in some other structure, for example a switch-bag, from where i can pull out the switches. This can be seen as a ready system.

Now i want to introduce the possibility of switching these switches on after a certain time automatically: A time switch

The time switch ueses now the "normal" switch. The normal switch doesn't have to know something about the time switch.

So but now the client can pull out the normal switch from the switch-bag and now he want also to get to the time-switch related to these normal switch, maybe to configure a new time.

And this is my question, how can the client get to the time-switch?

There are a few possibilites:

  • I refactor the normal switch class to a third-class where the normal-switch and the time switch lives bundled in it. But for this, i break some other client code which still uses the normal switch, but get now from the switch bag a "Combinator"-Class/Object out of it.
  • I don't change anything of the normal switch class. The client if he wants to get access to the time switch have to ask a Map which time switch is related to it. (I think this approach is classical a relation-programming style like a sql relationship database and its not anymore real object-oriented style)
  • I extend the normal switch: Here i also have different options:
    • I change it to a big facade, which delegates the calls to the normal-switch and time switch (its similar to my first solution with the combinator, but here with an facade don't breaking some existing client code)
    • i extend the normal switch letting the existing normal switch code untouched and introduce a component holder. Into this component holder i inject the time switch. So i have these methods there: switchOn(); switchOff(); getComponent("timeSwitch"). But these approach feels like a entity-component system (https://medium.com/ingeniouslysimple/entities-components-and-systems-89c31464240d) but is that still object oriented programming?

i think the last solution is the best one, because its the most flexible.

But what do you think which approach is the best, maybe some approach i didnt mentionend here?

Edit: One more thing you must to know here: The time switch is one extension of the normal switch. One of many. So i want to add of course different more things XYZ switches/behavior extensions to the normal switch

unique_ptr as general purpose dispose object

Suppose I have a situation, where I have an SDK which provides certain interface, which implies some manual resources management or state changes. It is supposed to be used like this:

// SDK has state B by default
SDK->setStateA();
something();
requiring();
stateA();
SDK->setStateB();

Is it a good idea to incapsulate state changes as custom allocator/deleter for unique_ptr object or, probably, it would be better to get this behaviour through some manual Dispose pattern implementation.

Since it's not a resource allocation, I have doubts. It might cause confusion and make code cryptic.

My other concern is that I need a return code from both init and clean up steps. I could use lambdas and get those through captures, but it looks even more cryptic.

Maybe someone tried it already and saw how it makes code look after a while?

How Ioc container Implement Singleton LifeScope in Asp.net Core?

As singleton can Becomes an anti-pattern, my question is how Asp.net core ioc-container implement Singleton lifescope and witch design-patterns it used for implement that ?

dimanche 18 juillet 2021

Pattern recognition in time series data

I am looking for an existing python API which can split a time series data by timestamp according to the various patterns present in it (CYCLIC,SEASONAL,INCREASING TREND,DECREASING TREND). For example if the plot of a data against time has cyclic pattern over a 6 months then increasing trend pattern for next 4 months then decreasing trend for 7 months. I want the API to split the data by this timestamps by denoting the pattern name. Thankyou in advance.

Designing Module

I have a list of modules say 1, 2, 3, and so on. And I have a list of validations say A, B, C, D, and so on. Each module needs to perform some validations ex:-

  • module 1 will need to perform A and B validation,
  • module 2 will need to perform A, B, and C validation
  • module 3 will need to perform B and D validation

So could you tell which best design pattern I should follow in .net core so that I can perform the same efficiently? Some code samples will also help preferably in c#, but Java will also work.

Why would you ever throw a single exception?

If its justifiable to write code that returns success/error objects when something goes wrong in a function instead of throwing an exception. Then why would you ever throw an exception as opposed to returning that as another fail case in your returned error object. What reason could there be to favor throwing an exception?

Its always said that "exceptions are for exceptional cases" but why? what is the advantage of an exception for some said exceptional case?

If the argument is that return codes can easily be ignored by the caller, then why would I ever use the return success/error object and not instead only throw exceptions? ignoring performance reasons.

What is the correct way to express "select all when nothing is specified in parameter"?

Let's say we have an HTTP endpoint to get all elements by name?

GET /elements?name={name}

{name} can have a value of CSV or be absent

valid:

  GET /elements?name=Bill,Mary,Ann
  GET /elements?name=Mike
  GET /elements

invalid:
  GET /elements?name=

Somehow we find out in controller that name is not passed. We know that the contract implies to return all values for elements. Possible decisions on further actions (I've seen in different projects) are:

  • using a NULL or a "dummy" substitution like a secret char sequence "!@$@%#$" and juggling them in database while building a query
  • using if (present) { executeQueryA } else { executeQueryB } logic

I am not sure I like either of these approaches, because when there is more than one optional filter these designs become unmaintainable. Something makes me believe that there is a better way to handle the situation.

What would be a proper design on back-end and in database query to handle the case "select all" when nothing is given? Just a general idea and some pseudo-code will be much appreciated.

How to deal with base class methods that are incompatible with the derived class?

Imagine that you're making a GUI and have a DataViewList class that is a widget that displays rows of data (like this for example). You have methods AddRow(std::vector<std::string> row), DeleteRow(std::vector<std::string> row) and AddColumn(std::string name), DeleteColumn(std::string name).

Now lets say you want to make a new class that displays a music playlist. It has predetermined columns (Title, Album, Year) and you don't want to ever add any new columns or delete existing ones. Also you want to be able to add Song objects to the list in a single method call, so you need a method that can do that. How do you implement such a class?

The most basic idea is to just create a new class MusicPlaylsit that inherits publicly form DataViewList and add the predetermined columns in the constructor. Then overload the AddRow methods such that it accepts Song objects as an argument. This approach has a big problem: Someone could call MusicPlaylist::AddColumn or other methods that are incompatible with the logic of the MusicPlaylist class. Since MusicPlaylist should only ever have the three predefined columns, then there shouldn't be a way to add or delete columns (or access any other incompatible base class methods such as the base class non-overloaded AddRow method).

To solve this, I can use composition instead of inheritance and re-implement any methods that I may want to use. In my opinion this is a bad idea because if I want to change something in the future, it's more difficult than inheritance because I cant override the base class methods.

Another option is to inherit as protected. This prevents using incompatible base class methods AND allows for overriding in case of future inheritance. The problem is, now I have to explicitly declare every method I want to use as public with using, which seems to be against the whole point of object oriented programming (being able to change something in a deep base class and still have any inherited class be able to use it) because newly added public methods in DataViewList will not be visible in MusicPlaylist or any classes that inherit from it until they have been explicitly made public.

So my question is: which pattern should I use when creating a new class that has an "is a" relationship to a base class, but is only partially compatible with it's methods?

Thanks

samedi 17 juillet 2021

How to design polling with changing interval in Kotlin?

There is a "buffer of elements" that a program must process somehow with function fun process(Element element){ ... }. Most of the time (80%) the queue is empty, and other time its load is not predictable: maybe 1 element per minute, maybe 1000 elements per second. We cannot see the whole buffer population, just ask "give at most X elements for processing". The goal is continuously process elements as fast as we can, optimally utilizing current executor.

Executor could be anything with contract fun submit(delay: Duration, task: () -> T): Unit, where each task somehow leads to calling process(element).

By "optimally utilizing current executor" I mean:

  1. submit minimal amount of tasks when the queue is empty
  2. submit just enough tasks to process current load
  3. avoid long running tasks (i.e. longer than 5 seconds)
  4. do not overpopulate the executor's tasks queue

(see an example below)

What is a known approach to implement such a component (tasks source)?

Such things as Quartz or Timer seem to have no needed flexibility out of the box to be useful for solving the problem.

I tried several attempts to implement this "flexible scheduling", and found out that there are several complex corner cases and it will take significant amount of time to implement a correct solution. Thereby as a trade-off for now I decided to use a straightforward solution with constant interval polling, which is too slow on high load and too fussy on low load, but at least works stable.

Did not manage to find any relevant information on the topic; maybe I use misleading keywords. So anything would be helpful: at least links to articles or discussions. And it would be perfect if there is a production ready tool that solves this problem.

Example:

  The component continuously submits tasks in an infinite loop.
  Its reaction affects only amount of tasks per submission and their delay reported to the executor.
--------------------------------------------------------
   event                        component's reaction  
--------------------------------------------------------
 queue is empty              detected zero load
                                - decrease amount of tasks being submitted (to not less than 1)
                                - increase (i.e. double) delay for next task submission

 10 elements arrived         detected some load
                                - keep amount of tasks unchanged (no info about the load size)
                                - decrease delay to 0

 queue is empty              it appears that on task processed the full load at on turn
                                - keep amount of tasks unchanged
                                - increase delay for next task submission 
   
 1000 elements arrived       detected some load
                                - keep amount of tasks unchanged (no info about the load size)
                                - decrease delay to 0

 990 still in queue          still have some load
                                - increase (i.e. +1) amount of tasks
                                - keep delay on 0 

 ...

 500 still in queue          still have some load (... now we submit 10 tasks per cycle)
                                - keep amount of tasks unchanged 
                                  (because executor has some tasks 
                                   in "not started" and "not finished" states)
                                - keep delay on 0 
 
 ...

 queue is empty              detected zero load
                                - decrease amount of tasks being submitted (to not less than 1)
                                - increase (i.e. double) delay for next task submission

Configurable View to display different components

i am asking myself how to approach this task with a good design pattern. My Scenario is like the customer can choose how his application behave in an adminpanel. So actually he his filling a form to make a configuration for his App. This configuration, is stored in a Database or where you like.

After creating this Config, the App should now be able to response to it. For Example the config says that in a specific screen an input field should be available so the app will display it. In react or react-native it is quite easy to hide elements with if / else statements. But is there an other way to solve this problem? A Design Pattern that can handle it? Like a Factory or something similar. It feels so wrong to make these big if else cases..

I would be happy to hear from you guys! It is my first post here.

Singleton issues with node libraries that includes the project library

I have a private node library called Utility. This library is also used by my other private libraries (Foo) as well.

When I use Foo in my project, it includes the Utility library in the node_modules of Foo. If I want to use the Utility library and Foo library at the same time, the singleton gets messed up because my project uses the Utility Library's singleton and the Foo library uses its own singleton from its own copy of the Utility Library from Foo's node_modules. Thus breaking the idea of being a single instance.

Is there a workaround to have the Foo library use the project's Utility singleton instead of the one from Foo's node_modules?

Is it recommended to make all classes inherit from a base class in c++?

I'm wondering whether should I make all my classes inherit from a base class, so as to be able to apply something like (garbage collection mechanism)

vendredi 16 juillet 2021

C++ Design Problem Regarding Templating, Containers and Inheritance

I have a problem with my design regarding interfacing algorithmic classes I have written and a third-party API. I will write some pseudocode to help explain my problem. I would prefer not to involve boost if possible.

The Problem

I have an algorithm class I will call Alg (it can be thought of as a search/optimisation algorithm) and a "super" algorithm class I will call SuperAlg which holds a number of Alg objects in a std::vector<Alg>. The SuperAlg evaluation function relies on a third-party algorithm, and thus needs to convert the result of any number of these Alg class objects into a third-party type. Each Alg may be associated with a different third-party type, which is known at the construction-time of the Alg class objects. The SuperAlg evaluation function looks something like:

double SuperAlg::evaluate(const std::vector<AlgResultType>& input) {
    ThirdPartyValues values;
    for (const auto& i : input) {
        values.insert(convert(i));
    }
    ThirdPartyAlg alg;
    return alg.error(values);
}

Here:

  • the ThirdPartyValues::insert is a templated function in the third-party API that knows how to take many different third-party types
  • ThirdPartyAlg::error takes a ThirdPartyValues and returns a double.
  • input is a vector of all the results from the Alg searches, with a 1-to-1 correspondence with the std::vector<Alg> owned by the SuperAlg class.

There are a lot of these third-party types and let's say that if I know the type and have the result of an Alg search (AlgResultType), I know how to perform the conversion. i.e. The convert function is known:

ThirdPartyType convert<ThirdPartyType>(const AlgResultType& result);

The fundamental problem is this: How can I specify the type of i I need to convert to in SuperAlg::evaluate? Recall that this type is known at the construction time of each Alg and somehow needs to be retained.

Some Solution Thoughts

  • If Alg/AlgResultType are templated with ThirdPartyType and the convert<ThirdPartyType> function is exposed through their interface, then they cannot be held in a dynamic-sized homogeneous containers and c++ doesn't have a dynamic-sized heterogenous container type.
  • Often the way around holding many different types (e.g. due to their template), Alg<ThirdPartyType>/AlgResultType<ThirdPartyType> in this case, is to have a common base class and have std::vector hold this base class, however this base class would need to have the convert<ThirdPartyType> function in order to be useful in SuperAlg::evaluate, which relies on the template parameter.
  • Some sort of container of types whereby each Alg or AlgResultType could be associated with a ThirdPartyType, but I know of no such container.