mercredi 31 juillet 2019

How to Implement Proxy Pattern in Angular

I am trying to implement Proxy Patten in Angular to check or provide data or send error message when service data is not available . To Implement Proxy Pattern with my Angular Application I searched allot on Internet but I am unable to find it , Please Help me on Implementing Proxy pattern with Angular

How to force derived class to call super class method at multiple layers?

I am trying to find the most elegant way to allow a child and parent to react to an event initiated by the grandparent. Here's a naive solution to this:

abstract class A {
    final public void foo() {
        // Some stuff here
        onFoo();
    }

    protected abstract void onFoo();
}

abstract class B extends A {
    @Override
    final protected void onFoo() {
        // More stuff here
        onOnFoo();
    }

    protected abstract void onOnFoo();
}

class C extends B {
    @Override
    protected void onOnFoo() {
        // Even more stuff here
    }
}

So basically, I'm trying to find the best way to allow all related classes to perform some logic when foo() is called. For stability and simplicity purposes I prefer if it is all done in order, although it's not a requirement.

One other solution I found involves storing all the event handlers as some form of Runnable:

abstract class A {
    private ArrayList<Runnable> fooHandlers = new ArrayList<>();

    final public void foo() {
        // Some stuff here
        for(Runnable handler : fooHandlers) handler.run();
    }

    final protected void addFooHandler(Runnable handler) {
        fooHandlers.add(handler);
    }
}

abstract class B extends A {
    public B() {
        addFooHandler(this::onFoo);
    }

    private void onFoo() {
        // Stuff
    }
}

class C extends B {
    public C() {
        addFooHandler(this::onFoo);
    }

    private void onFoo() {
        // More stuff
    }
}

This method is certainly preferable to the first. However I am still curious if there is a better option.

How to implement "Job finished, delete me" action e.g. menu exit button

I was thinking of creating a menu window, that would handle all the input given, when it's open. It would hold several buttons with associated actions. I stumbled on a problem, how to implement an exit button on the menu. I can't just append it to the rest of the buttons, because the program will crash if exit button is not at the end of the iteration.

I would have to use a separate exit button and set its function in a constructor or set some sort of return so that the entity holding the menu would know it's time to close it but both ideas smell to me. Do you know how it should be solved? Is sort of 'delete this' a must here? Or is there an elegant solution. In simplified version code looks like this:

using Action = std::function<void()>;

struct Button {
    Coords xy;
    bool isPressed(Coords mouse) {
        return mouse == xy;
}

struct Menu : IContent {
    std::map <Action, Button> buttons; //Can't put exitButton here
    std::pair<Action, Button> exitButton;

void handleInput(Coords mouse) {
    for (const auto& pair : buttons)
        if (pair.second.isPressed(mouse))
            pair.first();
    if (exitButton.second.isPressed(mouse))
        exitButton.first(); //must be checked as last one
}
    Menu(Action a) :
        exitButton(std::make_pair(a, { 0, 0} ) {}
}

struct MainFrame {
    std::unique_ptr<IContent> currentContent;

    void handleInput(Coords mouse) {
        if (currentContent)
            currentContent->handleInput(mouse);
}

void popMenu() {
currentContent.reset(std::make_unique<Menu>([this]() {
    currentContent.reset(...); //Back to other content, but it's basically 
                               //delete this
}
}

//or idea with return

struct Menu {
bool isPressed(/*...*/) //always returns false, only exitButton would return 
                        //true
}

struct MainFrame { /*...*/
void handleInput(Coords mouse) {
if (currentContent->handleInput(Coords))
    /* switch menu logic */
}

Summing up, is object taking care of its own lifetime bad design?

JavaScript component to handle closing of cross-domain tabs

I want to use window.open and emit an event with the reference to the opened window.

A specific component will have to listen for this event and store the reference to the last opened window. The component will also have to listen for a "close" event coming from the child window through the PostMessage API and close it using the last stored reference.

How can I implement this component in an elegant way following best practices and design patterns?

What design pattern does this?

I did this once a long time ago and followed a design pattern when I did. Now, I need to do it again, I don't really remember how I did it before, and I can't think of the pattern that helped me do it.

I have a class with a whole slew of variables/properties. Some are calculated based on the others, and there is all sorts of cross-calculating going on between these properties.

It's all fine when I first instantiate - all the values and the calculations work just fine. My problem is, when one value changes, I want all of the calculated values derived from it to update themselves based on the new value automatically. And I don't want to write each individual recalc manually if I don't have to - it just becomes a lot of overhead whenever this class gets updated or added to, trying to track down all of the places you need to propagate whatever change you're making.

I think you follow me.

Anyway, can anyone think of what pattern it is that makes this possible? I swear I used to know it. Getting old I guess.

// Like this...
class foo
{
    decimal A = 1233;
    decimal B = 42;

    decimal C = A / B; // I want this to update whenever
                       // the value of either A or B changes.
    decimal D = 123;
    decimal E = 321;

    decimal F = D + E; // I don't want this one to change when
                       // A or B or even C for that matter changes,
                       // and I don't wan to have to cycle through
                       // all of the calculated values that don't
                       // need to change just for find the few that do.
}

How do I change the value of a variable based on another value in POJO?

I have the following POJO class:

@Value
@Builder
@RequiredArgsConstructor
public class XYZ {

    @NonNull
    private final String a;

    @NonNull
    private final Map<Integer, ABC> items;

    @NonNull
    private final State state;

    public enum State {
        STARTED,
    INPROGRESS,
        STOPPED
    }
}

Now, in this, based on different sizes of the map, I wanted to change the value of state field. Eg. When size is 0, then state should be STOPPED and when it is less than 5 and more than 0, then it is INPROGRESS and if it is more than 5, then it should be STARTED.

What is the best way to do this? Should this logic lie inside this POJO or should I explicitly check this whenever I am making change in map explicitly. How can I do it properly? Any ideas?

Latency diagnostic of the data flow from hardware device to UI

For existing software application, I need to include new diagnostic system for Latency of the data flow between the input of the of data until the output. What pattern or strategy I should use to get proper diagnostic?

We have application that include 4 main pieces: 1. Hardware Device 2. Data repository 3. Business Logic 4. UI

Device is sending data constantly. Software collect the data, process, validate, present on the chart and store it in database.

What I need is the way I could track each sample of the data from the input until the output to calculate the time between the start and the end. You should consider that data structure could be replaced from class to class. For instance, at the beginning the data is going to be part of the class DeviceData and at the end as ChartData. Data flow usually used by events and send between classes as Invoke.

What would be the best solution to inject additional code that would uniquely identify the data and keep the track of the time for each samples and their transformation.

Currently, what we do usually is adding logging information for each function which is the part of the flow and manually we try to identify the correct samples to figure out how much time it takes, which is too complicated. There a log of samples every even second.

The expected result would be possibility to get final results such as: Sample started at timeStart Function X - takes duration1 Function Y - takes duration2 …. Sample presented on chart timeEnd

How to return Mono

I have an application which have controller , service and repository. Using Reactive pattern for redis cache . I am deleting key from redis cache , its return type is Mono . How to implement in code> I am calling method of service class for which controller and service is having return type Mono . Data is getting reflected in Service but null value is getting pass to controller. Please suggest

Mono GetcacheAync(String key)

How to apply CQS pattern on multiple data sources?

I'm learning the CQS pattern and I'm wondering how to use it on a system that has practically the same data in multiple systems. The systems may be an SQL database or a REST API, or some other system. But the data is almost the same regardless of the system (some may have less fields than others).

How would you implement a command that creates a new data entity called "device"? There's a Device table in the SQL database and a REST API that accepts a json with device-related data.

I would imagine there would be a SaveDeviceCommand which has one public property DeviceDto (which contains the data to be saved).

The we would have the result for the command (which in this case is only the ID of the newly created device). I know that strictly speaking a command should not return any values, but here I'm willing to bend that rule a bit.

Lastly we would need to implement the CommandHandlers that do that actual work, right? We would implement CreateNewDeviceToDatabaseCommandHandler and CreateNewDeviceToRestServiceCommandHandler. Quite long names I think.

Is there any more elegant way to do this? One command per data storage because we need a data context (e.g. EntityFramework DbContext) for the command handler to actually be able to make the save?

public class SaveDeviceToDatabaseCommandHandler : ICommandHandler<SaveDeviceCommand, SaveDeviceCommandResult>
{
    private readonly ICommandHandler<SaveDeviceCommand, SaveDeviceCommandResult> _saveDeviceCommand;
    private readonly DeviceContext _deviceContext;

    public SaveDeviceToDatabaseCommandHandler(ICommandHandler<SaveDeviceCommand, SaveDeviceCommandResult> saveDeviceCommand,
                                              DeviceContext deviceContext)
    {
        _saveDeviceCommand = saveDeviceCommand;
        _deviceContext = deviceContext;
    }

    public Task<SaveDeviceCommandResult> HandleAsync(SaveDeviceCommand command)
    {
        // Implementation for the entity framework
    }
}

Aggregate Roots DDD/UoW/Repo/Service

I have some questions about the Aggregate Objects for Repositories.

I'm making an Rest Service with DDD/UoW/Repo and Service pattern. Our new cloud web-apps shall use this service. In order to do this we also have to sync data from the old databases, which are still in production. We created a "SyncService" which read and writes to/from the cloud and down to earth.

In my Rest/DDD-design. And i don't want the business logic to run on these, so in the original test project i have a repository for every model and the endpoints just does some simple validation and pushes the data straight to the database using the repository.

Let's say i have these entities:

  • Customer
  • Order
  • OrderLine
  • Article

Database Relationsships:

  • A customer can have many orders.

  • An Order can only have one customer.

  • An Order can have many OrderLine's.

  • An OrderLine can have one Article.

Questions:

  • Are all of these aggregates except Article?

  • And which of these Entities would have a repository?

  • What would the repository look like?

  • Should i make endpoints for the "SyncService" to only talk to generic repositories for insertion?

Thanks in advance.

Cache Aside Pattern and Authentication

I've been reading about Cache Aside Pattern and I am fairly new to it.

Can it be used for authentication as well? For example, storing username / hashedpasswords so application doesn't need to always read from the Database? And if yes, is it considered safe?

How to name a function/method when use table Data Gateway pattern and the SQL query contains multiple join clauses?

There is a DAL in my application code. And I am using Table Data Gateway pattern for DAL which means I create class for each table.

Here is a demo, there are three tables in the database: users, addresses, organizations. I create a UserGateWay class for users table.

class UserGateWay {
  public async findById(id: string) {
    const query = `
      select * from users where user_id = ?
    `;
    return this.knex.raw(query, [id]);
  }

  public async findByIdWithAddress(id: string) {
    const query = `
      select
        u.*,
        addr.*
      from users as u
      inner join addresses as addr using (user_id)
      where u.user_id = ?;
    `;
    return this.knex.raw(query, [id]);
  }

  public async findByIdWithOtherTableDatas(id) {
    const query = `
      select
        u.*,
        addr.*,
        orgs.org_name,
      from users as u
      inner join addresses as addr using (user_id)
      inner join organizations as orgs using (org_id)
      where u.user_id = ?;
    `;
    return this.knex.raw(query, [id]);
  }
}

findById method is simple, the issue is how should I name the findByIdWithAddress and findByIdWithOtherTableDatas methods.

If there are many join clauses within the method, I don't know how to name the method. Especially the very similar but different scenes.

I don't want to name it like findByIdWithAddressAndOrgsAndOthers. Maybe I use this pattern in the wrong way or this pattern is not suitable for table join case?

I need java code example befor we used a Bridge Pattern? [on hold]

I want to do is see a code before i use
Bridge Design Pattern Or in other words,i want see what happens without the bridge pattern Without the Bridge Pattern But using a simple example with java code

mardi 30 juillet 2019

Design pattern for Cab service

I am trying to understand design pattern and thought of implementing Abstract factory pattern to see how cab service like ola, uber could be designed.

I started with something of class segregation like below, but got stuck there after.

/* Ola has car type as Auto, micro, mini, prime.
 * Later add share car type. 
 * 
 * Add cars to the car type
 * */

enum CarType{
    MINI, MICRO, AUTO, PRIME;
}

public class OlaImplementationAbstract {

    public static void main (String[] ags) {

    }
}

class carFactory{

}
abstract class Car {

    public double fare(double distTravelled) {
        return distTravelled;
    }
}

class Mini extends Car {

    public double fare(double distTravelled) {
        return 9 * distTravelled;

    }
}

class Micro extends Car {

    public double fare(double distTravelled) {
        return 8 * distTravelled;

    }
}

class Auto extends Car {

    public double fare(double distTravelled) {
        return 7 * distTravelled;

    }
}

class Prime extends Car {

    public double fare(double distTravelled) {
        return 10 * distTravelled;

    }
}

Could not understand how to proceed further. I just wanted to understand if I got to design such a thing, how to go about it.

How to ensure a class is a singleton in JavaScript/TypeScript? And best way to write singleton class?

In JavaScript, I define a singleton class like this:

class Singleton {
  constructor() {
    if (!Singleton.instance) {
      Singleton.instance = this
    }

    return Singleton.instance
  }
}

And in TypeScript I write the singleton class like this:

class Singleton {
  private static instance: Singleton

  constructor() {
    if (!Singleton.instance) {
      Singleton.instance = this
    }

    return Singleton.instance
  }
}

Are these valid ways of writing singleton classes in JavaScript and TypeScript?

How can I ensure that they are singletons?

Is there a better way to write singleton classes in JavaScript/TypeScript?

Design pattern to process different messages based on message type

I need to process notification messages that gets pushed to my application. where the messages contain notification types like catalog_purchased, catalog_expired, catalog_denied, etc. and In future new set of notification types would be added as well. What would be a good Design Pattern (and any Java 8 features) to process all these messages based on Notification types?

Pipeline pattern and disposable objects

Recently I started to investigate a Pipeline pattern or also known as Pipes and Filters. I thought it is a good way to structure the code and applications which just process the data. I used this article as a base for my pipeline and steps implementation (but this is not so important). As usual blog is covering simple scenario but in my case I need (or maybe not) to work on IDisposable objects which might travel through the process.

For instance Streams

Let's consider simple pipeline which should load csv file and insert its rows into some db. In simple abstraction we could implement such functions

Stream Step1(string filePath)
IEnumerable<RowType> Step2(Stream stream)
bool Step3(IEnumerable<RowType> data)

Now my question is if that is a good approach. Because if we implement that as step after step processing the Stream object leaves first step and it is easy to fall into a memory leakage problem. I know that some might say that I should have Step1 which is loading and deserialising data but we are considering simple process. We might have more complex ones where passing a Stream makes more sense.

I am wondering how can I implement such pipelines to avoid memory leaks and also avoiding loading whole file into MemoryStream (which would be safer). Should I somehow wrap each step in try..catch blocks to call Dispose() if something goes wrong? Or should I pass all IDisposable resources into Pipeline object which will be wrapped with using to dispose all resources produced during processing correctly?

Generating a Pattern Based on Percentages [on hold]

I've been given a series of values that are supposed to be displayed at a certain percentage. I'd like to know if there is an algorithm when given an arbitrary set of values with respective percentages that you can create a pattern that when repeated will equate to that value appearing for its respective percentage amount.

Example:

Given:

A @ 40%, B @ 20%, C @ 10%, D @ 10%, E @ 10%

Solution: BACADAEAB

Currently I'm doing this by hand and hard coding it whenever the values change. I know there's a formula to find the Least Common Multiple (LCM), but it relies on a Greatest Common Divisor (GCD) which seems to be trickier to code.

I don't have any code to produce the results yet, the formula I'm trying to replicate is:

lcm(v1, v2, ...) = (|v1 x v2 x ...|)/(gcd(v1, v2, ...))

Is there an algorithm I can program to produce the formula above or is there a better way to do this?

Laravel design patterns

I have a little hard time with all of those design patterns and things that could help me write maintainable code, clean and reusable.What are the most used design patterns in your Apps? A list or something with them will be nice, there are a lot of design patterns and I dont really know with what should I start.

Are cross-database queries a bad design?

If we have an instance of SQL Server with 5 databases, is it a bad practice to do some cross-database calls to aggregate data in a stored procedure and expose it?

I would normally assume the service does the data aggregation not the stored procedure. Also cross database calls are creating tight coupling, without the possibility of scaling or moving each database individually.

What are the design patters saying in such a case?

Change behavior without modifying base class

I have a class, let's call it A with a method foo(/*with some params*/) . I'm already using that class in my code. Now in case some param bar, that I pass to the above method, has a specific value I'd like my foo() method to return a slightly different result.

Obviously I could create a class B and copy the foo method's code, alter it a bit to fit my needs and at runtime check the value of bar and decide which class to call.

Is it possible using some design pattern to make that change with the following requirements in mind: a) keep using A in my code (probable use an InterfaceA and use that instead of A) so I won't have to change it and b) don't modify the code of class A cause it's possible to later have a class C with an altered foo() and the another and then another...

Most Pythonic/Django way to dynamically load client libraries at runtime

I'm writing a Django application in which we will have multiple client libraries that make calls to third party APIs. We want to be able to determine which client library to load at runtime when calling different endpoints. I'm trying to determine the most Django/Pythonic way to do this

The current idea is to store class name in a model field, query the model in the View, and pass the class name to a service factory that instantiates the relevant service and makes the query. I've also considered writing a model method that uses reflection to query the class name

For example lets say we have a model called Exchange that has an id, a name, and stores the client name.

class Exchange(models.Model):
    exchange_name = models.CharField(max_length=255)
    client_name = models.CharField(max_length=255)

    def __str__(self):
        return self.exchange_name

Then in the View we might have something like:

from rest_framework.views import APIView
from MyProject.trades.models import Exchange
from django.http import Http404
from MyProject.services import *


class GetLatestPrice(APIView):

    def get_object(self, pk):
        try:
            exchange = Exchange.objects.get(pk=pk)
        except Exchange.DoesNotExist:
            raise Http404

    def get(self, request, pk, format=None):
        exchange = self.get_objectt(pk)
        service = service_factory.get_service(exchange.client_name)
        latest_price = service.get_latest_price()
        serializer = PriceSerializer(latest_price)
        return Response(serializer.data)

This syntax may not be perfect but it hasn't been tested. But the idea is that maybe we have

ExchangeA - client1 
ExchangeB - client2
ExchangeC - client3

And for each client we have a service class that all inherit from the same Abstract Base. Each service has an override that are all the same. That way when you call /api/get_latest_price you pass the Exchange id as a query param and the code loads whatever service and client library is relevant. This would be so we could easily add new types to the system, have consistent and small Views, and decouple the business logic. Is this an acceptable, scalable pythonic method? Or is there a better solution for it? Essentially the problem is implementing Polymorphism in django and seperating the domain model from the data model. This has to be a solved problem so I'm curious on the way other people might be doing this. I know it's unusual to be calling a third party API like this but since we are forced to I want to do it in the cleanest most scalable way possible.

Network protocol in Node.js

I'd like to know how people approach building network protocols in asynchronous environments such as node.js.

I have implementation of one such protocol, but code seems to complicated for such simple protocol. This is just an exercise. I know I should not implement encryption protocol myself.

I have decent experience with node.js but not with buffers and streams.

  • Are there any best practices when it comes to using buffers and streams to implement protocols in this asynchronous world? Any design patterns?
  • How can I make this more elegant, more reusable, more flexible? Is my class BufferFiller OK?

Server side:

const net = require('net');
crypto = require("crypto");

const algorithm = "aes-256-cbc";
const host = process.env.HOST || 'localhost';
const port = process.env.PORT || 6000;

class BufferFiller {
    constructor(inputStream) {
        this.inputStream = inputStream;
        this.lastChunkOffset = -1;
        this.lastChunk = null;
    }

    fill(buffer) {
        let bufferFillLength = 0;
        if (this.lastChunk) {
            const copyLen = Math.min(buffer.length - bufferFillLength, this.lastChunk.length - this.lastChunkOffset);
            this.lastChunk.copy(buffer, bufferFillLength, this.lastChunkOffset, this.lastChunkOffset + copyLen);
            bufferFillLength += copyLen;
            this.lastChunkOffset += copyLen;
        }
        if (this.lastChunk && this.lastChunkOffset === this.lastChunk.length) {
            this.lastChunkOffset = -1;
            this.lastChunk = null;
        }
        if (bufferFillLength === buffer.length) {
            return new Promise(resolve => resolve(this));
        }

        return new Promise((resolve, reject) => {
            const onData = chunk => {
                let chunkOffset = 0;
                const copyLen = Math.min(buffer.length - bufferFillLength, chunk.length - chunkOffset);
                chunk.copy(buffer, bufferFillLength, chunkOffset, chunkOffset + copyLen);
                bufferFillLength += copyLen;
                chunkOffset += copyLen;

                if (chunkOffset < chunk.length) {
                    this.lastChunkOffset = chunkOffset;
                    this.lastChunk = chunk;
                }

                if (bufferFillLength === buffer.length) {
                    this.inputStream.removeListener('data', onData);
                    this.inputStream.removeListener('error', onError);
                    resolve(this);
                }
            };
            const onError = err => {
                this.inputStream.removeListener('data', onData);
                this.inputStream.removeListener('error', onError);
                reject(err);
            };
            this.inputStream.on('data', onData);
            this.inputStream.on('error', onError);
        });
    }

    getRemainingBuffer() {
        if (this.lastChunk === null) {
            return Buffer.alloc(0);
        }
        const result = Buffer.alloc(this.lastChunk.length - this.lastChunkOffset);
        this.lastChunk.copy(result, 0, this.lastChunkOffset);
        return result;
    }
};

function exchangeKeysAndPipeThroughDecipher(outputStream, inputStream, nextStream) {
    const iv = Buffer.alloc(16, 0);

    const alice = crypto.createDiffieHellmanGroup('modp14');
    const alicePublicKey = alice.generateKeys();
    const aliceGenerator = alice.getGenerator();
    const alicePrime = alice.getPrime();
    const buf = Buffer.allocUnsafe(4);
    buf.writeUInt32BE(aliceGenerator.length, 0);

    outputStream.write(buf);
    outputStream.write(aliceGenerator);
    outputStream.write(alicePrime);
    outputStream.write(alicePublicKey);

    const bobPublicKey = Buffer.alloc(256);

    new BufferFiller(inputStream)
        .fill(bobPublicKey)
        .then(filler => {
            const symKey = alice.computeSecret(bobPublicKey).slice(-32);
            const decipher = crypto.createDecipheriv(algorithm, symKey, iv);
            decipher.setAutoPadding(false);
            decipher.write(filler.getRemainingBuffer());
            inputStream.pipe(decipher).pipe(nextStream);
        });
};

async function onClientConnected(sock) {
    exchangeKeysAndPipeThroughDecipher(sock, sock, process.stdout);
};

// Create Server instance
var server = net.createServer(onClientConnected);

server.listen(port, host, function() {
    console.log('server listening on %j', server.address());
});

Client side:

const net = require('net');
const crypto = require('crypto');

const algorithm = "aes-256-cbc";
const host = process.env.HOST || 'localhost';
const port = process.env.PORT || 6000;
const client = new net.Socket();

class BufferFiller {
    constructor(inputStream) {
        this.inputStream = inputStream;
        this.lastChunkOffset = -1;
        this.lastChunk = null;
    }

    fill(buffer) {
        let bufferFillLength = 0;
        if (this.lastChunk) {
            const copyLen = Math.min(buffer.length - bufferFillLength, this.lastChunk.length - this.lastChunkOffset);
            this.lastChunk.copy(buffer, bufferFillLength, this.lastChunkOffset, this.lastChunkOffset + copyLen);
            bufferFillLength += copyLen;
            this.lastChunkOffset += copyLen;
        }
        if (this.lastChunk && this.lastChunkOffset === this.lastChunk.length) {
            this.lastChunkOffset = -1;
            this.lastChunk = null;
        }
        if (bufferFillLength === buffer.length) {
            return new Promise(resolve => resolve(this));
        }

        return new Promise((resolve, reject) => {
            const onData = chunk => {
                let chunkOffset = 0;
                const copyLen = Math.min(buffer.length - bufferFillLength, chunk.length - chunkOffset);
                chunk.copy(buffer, bufferFillLength, chunkOffset, chunkOffset + copyLen);
                bufferFillLength += copyLen;
                chunkOffset += copyLen;

                if (chunkOffset < chunk.length) {
                    this.lastChunkOffset = chunkOffset;
                    this.lastChunk = chunk;
                }

                if (bufferFillLength === buffer.length) {
                    this.inputStream.removeListener('data', onData);
                    this.inputStream.removeListener('error', onError);
                    resolve(this);
                }
            };
            const onError = err => {
                this.inputStream.removeListener('data', onData);
                this.inputStream.removeListener('error', onError);
                reject(err);
            };
            this.inputStream.on('data', onData);
            this.inputStream.on('error', onError);
        });
    }

    getRemainingBuffer() {
        if (this.lastChunk === null) {
            return Buffer.alloc(0);
        }
        const result = Buffer.alloc(this.lastChunk.length - this.lastChunkOffset);
        this.lastChunk.copy(result, 0, this.lastChunkOffset);
        return result;
    }
};

client.connect(port, host, function() {
    console.log('Client connected to: ' + host + ':' + port);
    const iv = Buffer.alloc(16, 0);
    const aliceGenLen = Buffer.allocUnsafe(4);
    let aliceGen;
    const alicePrime = Buffer.allocUnsafe(256);
    const alicePublicKey = Buffer.allocUnsafe(256);

    new BufferFiller(client)
        .fill(aliceGenLen)
        .then(filler => {
            const genLen = aliceGenLen.readUInt32BE();
            aliceGen = Buffer.allocUnsafe(genLen);
            return filler.fill(aliceGen);
        })
        .then(filler => filler.fill(alicePrime))
        .then(filler => filler.fill(alicePublicKey))
        .then(filler => {
            const bob = crypto.createDiffieHellman(alicePrime, aliceGen);
            const bobPublicKey = bob.generateKeys();
            client.write(bobPublicKey);
            const symKey = bob.computeSecret(alicePublicKey);
            return symKey.slice(-32);
        })
        .then(symKey => {
            const cipher = crypto.createCipheriv(algorithm, symKey, iv);
            cipher.setAutoPadding(true);
            process.stdin.pipe(cipher).pipe(client);
        });
});

client.on('close', function() {
    console.log('Client closed');
});

client.on('error', function(err) {
    console.error(err);
});

I find implementing protocols in asynchronous world particularly difficult, when you can control how much data you receive from underling buffers, nor when ('data' event triggers with what ever chunk size it wants and when ever it wants).

P.S. I'm stuck with node v8.x, which supports async/await, but I didn't want to hide asynchronicity, on purpose.

lundi 29 juillet 2019

Which design pattern to use for sequential actions and Retries

There is a use case, where a message is created.

The message will be be processed sequentially by different functions until it reaches terminal status.

After each function has processed the status of the message is updated to track the progress. If for any scenario, there is a system issue and we want to retry the same message, then it should start of where it left off based on the status.

Which is the better design pattern to use. State machine or Chain of responsibility. Is there any other pattern which can be recommended for this scenario.

A crude example:

Message (Created with New Status) ----> Function1 Prcoessing --> Message (Status updated to FUNC1COMPLETE) --> etc... till it reachers terminal status.

How to a design a URL shortening service which generates 8 character urls

This is a algorithm design question. The need is as follows: 1. The url service should be able to generate short url with maximum of 8 characters. 2. The url service should be able to generate long/actual url when the short url is supplied to the service. 3. Pseudo code of the above in python.

How to unit test new object creation in interface default method?

There is a default method in the interface that creates new object and uses its functions. So I need to mock it. But I can't figure it out without making another default method which returns new instance. I used to make factories so far that handles object creation and than mock the factory method. But can't do it in interfaces since interfaces can't have instance variables which is factories in this scenario. Any other ideas? I want to be consistent in the project but now I have 2 different approach to avoid object creations in methods. Here is an example:

public interface ISomeInterface
{
    default Object callMe( )
    {
        Object someObject = new Object( ); // need to mock this
        Integer result = someObject.finish();
        result = result + 1;

        return result;
    }
}

I used to refactor the code with factories when I don't use interface like this;

default Object callMeNotInterfaceClass( )
{
    Object someObject = new Object( );
    Integer result = instanceFactory.create().finish(); // I can mock create() method 
    result = result + 1;

    return result;
}

Only solution I implemented so for wrapper method:

public Object callMe( )
{
    Object someObject = new Object( );
    Integer result = wrapperMethodCall.finish(); // only solution so far. But now I have 2 different approaches in the project to avoid object creation.
    result = result + 1;

    return result;
}

default Object wrapperMethodCall() {
    return someObject.someMethodsToBeMocked();
}

How to find regex pattern in {}

I want find 2 pattern to regex

pattern1 is find pattern2 is {str} find

two case in String value

result

pattern1 = [regex1, regex2] pattern2 = [regex3]

sample String

let str = "I want ()의 \"{regex3}\" find pattern."

pattern1 = "\{\{(.*?)\}\}"

pattern2 = ??

Does recurrent render of the same template on the different views follow MVC pattern

I have part_of_my_view.html it loader.render_to_string('part_of_my_view.html', data) newly by classes

View1
View2
View3

data attribute can be slightly changed from view to view. Does recurrent render of the same template follow MVC pattern or should I make it render once in some `ParrentView'?

How to share code for rest api and controller

I'm trying to create a website that also have rest api

I use mvc structure for this website.

So what is the better way to create such website? I see 2 option and for each one I have question that can't figure out which one is better ( I use login action for example in both option )

Option 1: Create a controller for login and also create a endpoint for api, and write all login in two file. This option is really code for example I can add extra condition for login via api. But the problem is If I want to add a new logic for login, I must add it in two file.

Option 2: create a file ( I'm not sure what should call it, service ? ) and In both file call login method from that file.

And here is my questions:

1-Which way is better? ( Also maybe I can use another option ? )

2-In MVC is there a pattern for option 2? what it's name?

3-I always use option 1, and also see a lot of example doing that way, Is this correct to repeat code?

dimanche 28 juillet 2019

Implementing undo/redo in a d3 data model

I am working on an online editor using d3 for my data model. For implementing Undo/Redo I think that the easiest way is to save the whole model after each action. But the editor is aimed to edit large files where the model may contain several millions of elements and so this idea is causing memory issues.

My data model is an array. Because most edits are very local, it seems natural to save some local information to transform the model into the previous state. To implement this idea I was thinking of using something like edit distance and sequence alignment. Another way is to keep track of changes during any action but this solution, despite being more efficient, seems more error-prone to me. Is there any standard way of doing this which I am unaware of? I have studied these useful links:

  1. Undo/Redo implementation
  2. Memento Pattern

C++ design pattern for sockets

The goal is to be able to support both IPv4 and IPv6 for a rather complex application. At present, only IPv4 is handled. There is a class called Socket and a class called TlsSocket which extends from it. Let's say that Socket has a set of methods M1,M2,....,M9. TlsSocket overrides M7, M8 and M9.

Given the current design I was thinking of making Socket an abstract class and extending it twice - SocketIPv4 and SocketIPv6 which would implement methods M5 and M6 differently. However, then I would have to extend them twice again to have a TLS version for both IPv4 socket and IPv6 socket leading to code duplication. I was looking at the best design pattern for the problem at hand and I was convinced that the decorator design pattern would work best.

However, then TlsSocket would inherit from the abstract Socket class and then be composed of a concrete implementation of Socket (either IPv4 or IPv6). Therefore, I would essentially be initializing two Socket instances (one for composition and the other is TlsSocket itself) pointing to the same file descriptor. Everything should work fine but I am slightly uncomfortable initializing two socket instances pointing to the same file descriptor. Is there an alternative design pattern that I have missed and should consider?

How best to create object variables from a method

What is the best way to set object variables that are set by a method? Is the methodology below where self.toppings is first defined in __init__() and then the value is set in the select_toppings() method a good practice on how to set the self.toppings variable? Please let me know if you have better suggestions. Thanks.

class Pizza:

    def __init__():
        self.toppings = None 

    def select_toppings(input):
        self.toppings = input  

When should a module be packaged into a versioned library?

When is it appropriate to take a module (or some unit of software) and convert it into a versioned package?

At my current company, we have a large monolithic application. Specifically, on the front-end we have many es6 modules that are either cross-cutting concerns, business logic, or helpful utilities. These modules are currently placed in a shared/ directory where they get imported into specific pages as needed.

My director has asked me to convert these modules into versioned npm packages that are rigorously tested. This led me down the rabbit hole of wondering when is it, in general, appropriate to take a piece of code and share it as a versioned library.

I can think of potential harm it might cause by doing this: one module contains our form validation logic. Do we really want to allow some part of the application to use v1 of email validation logic, and some other part to use v2?

samedi 27 juillet 2019

When to have class member on heap vs stack?

I am learning C++ OO design. When to declare class member on heap vs stack?

class RacingLiveEvent
{
public:
    playerlist  *pl;
}

vs

class RacingLiveEvent
{
public:
    playerlist  pl;
}

What design/runtime/compiletime considerations will help me decide. Any suggestions please?

I see with heap, I can define each class in its own header file. If I use static object, I need all the dependent class to be in one file.

Observer with a call back to the observed class

How to nicely express something like the observer pattern which returns observed object to the observers?

I need to have a class which is able to periodically query other components to generate some sort of data (I called it sample in the code below) and then process the received data.

The problem is that data generator functions are complex and may generate a significant number of samples. It would be nice to pass them back to the manager as return values and then manager can process them without exposing any other functions. But unfortunately that does not work due to memory constraints (I use C++ without dynamic memory allocations, so no way to move data).

What I have below is broken in two ways: 1) SampleManager exposes unrelated responsibilities, one to register observers and call them, second to process the data. 2) The components using sample manager get it back in the callback and they already have the pointer.

Any idea how I can fix/improve the design?

class ISampleReceiver
{
public:
      virtual void receive(const sample&) = 0;
};

using SampleGeneratorFn = std::function<void(ISampleReceiver*)>;

class SampleManager : public ISampleReceiver
{
      registerSampleGenerator(SampleGeneratorFn);

      virtual void receive(const sample&) {
             // process the sample
      }
};    

And the usage, from multiple different components:

void generator(ISampleReceiver* r)
{
   while (...) {
     sample s = {...}; // generate objects

     r.receive(s);
   }
}

SampleManager manager;

// initialise the manager
manager.registerSampleGenerator(generator);

How to remove strings that start with alphabet using gsub in R?

I have collected tweets and I would like to extract the emoji unicode from each tweet. The emoji unicode is in format and I have used the gsub function to remove all texts before and after the emoji using the function

tweets$text <- gsub(".(<.>).*", "\1", tweets$text)

However, because there may be several emojis per tweet, i have decided to split each column after the character ">".

In some columns, there are strings that are just alphabet characters and does not start with "<".

My question is: How do I remove the string if it does not start with a "<"?

vendredi 26 juillet 2019

Class-to-class communication design

I'm working on a project that has a class structure like this:

class A {
  constructor() {
    this.bInstances = this.makeBInstances(this);
  }

  makeBInstances() {
    // return new B()s
  }

  handleSomethingFromB() {
    // B did something and called this function so that A knows and can do stuff too
  }
}

class B {
  constructor(a) {
    this.a = a;
  }

  doSomething() {
    this.a.handleSomethingFromB( ... );
  }
}

I'm trying to figure out the best way for them to communicate with each other. Passing instances of classes around is not ideal, as it makes testing confusing, verbose and unreliable. Singletons are also vague and unreliable, sure they make it so I don't have to pass instances around, but I'm also having to import the instance and use it so that doesn't quite alleviate my problem. Reinitializing singletons for every test is also tiresome.

The best solution I've thought of thus far is to emit and listen for events. Like this:

class A {
  constructor() {
    // still need to do this?
    this.bees = this.makeBInstances();
    this.listenForBEvents();
  }

  makeBInstances() {
    // return new B()s
  }

  listenForBEvents() {
    document.addEventListener('event_from_class_B', () => {
      // react to B class' signal
      this.doSomething();
    });
  }

  doSomething() {
    // do something
  }
}

class B {
  constructor() {
    this.doCoolStuff();
  }

  doCoolStuff() {
    // Woohoo! I'm doing stuff!
    // create CustomEvent and emit it
    // handle that Event from other class(es)
  }
}

I like this because it makes testing very easy, and de-couples classes from dependencies. So as long as I emit an event that contains the right data, it doesn't matter what instances I have or where the data came from.

My question is: is this the right way to go? Are there any other alternatives?

Is my concept wrong? I am using a visitor pattern, bringing together functionality and ComboBoxes

I suppose I have got a design problem. So lets start from the beginning. This is what I want:

On one side there are ComboBoxes, which need to be filled, letting the user choose between functionality provided. On the other side this functionality has to be called, to fulfill its purpose.

I was thinking about something like this, scattered somewhere in the GUI:

// Parameter type describes what to do. This example shows that a CRC value 
// shall be calculated. But it could be a quadratic formular or any other // calculation as well. So I assume parameter is of type IStrategy.
// And here I assume a further interface exist, lets say ICRCxx.
ChoiceProvider functionality = new ChoiceProvider(CRC16);

// Yes, I know about Items and binding. Method returns functionality
// provided by ICRCxx. For example just { "CRC32", "CRC16 CCITT" } will be 
// returned at the moment.
string[] cellChoice_Of1stComboBox = functionality.GetCalculationNames();
bool functionality.SetCalculationName(string name);

// Here between start values can be chosen, necessary for the calculation.
// For example { "Ox0000", "Ox1D0F" } will be returned, if "CRC16 CCITT"
// has been selected above.
string[] cellChoice_Of2ndComboBox = functionality.GetCalculationVariants();
bool functionality.SetCalculationVariant(string name);

// to be displayed somewhere on GUI
string userResult = functionality.GetUserResult(); 

// Return type may vary depending on chosen calculation within.
var processResult = functionality.GetProcessResult(); 

// This is just a idea to be able to handle processResult.
// Maybe you have got a better idea. About that I had a struggle with
// generics.
Type processResultType = functionality.GetProcessType(); 

I am sorry, a lot of words will still follow.

I already got a class called ChoiceProvider. I made it generic, because first I tried it with recursion, to be able to combine as much ComboBoxes as I want. It is based on an dictionary>, as I am working with names. And T within IChoice>T> could be any kind of calculation.

ChoiceProvider is already working within an visitor pattern, being there the operator. But I failed let it work recursively before (without pattern). Below visitor pattern (visited is TChoice, visitors are of IStrategy. IStrategy lets choose between e.g. ICRCxx and IQuadraticFormular) is a strategy pattern to choose e.g. between CRC16 or CRC32.

But when passing data between methods Visit(IVisited... ) from class Do_Strategy (meaning "do calculate") to class Get_ProcessResult, I struggeled with generics as mentioned above. As I am not an expert with generics.

First I thought to ask you about my problem passing data from one class to another, struggling with generics or with something like this: How to force derived class to implement a static property or field?

But then I realized, that I could not find to a good question to find the right answer (technically or by design). So now I will just ask you about the design.

And here is where I am standing now. I now think about just a main strategy pattern and a second strategy pattern below. But I wasted time. And I would like to be on a got path before I start with something new again.

  • Do you have got a much simpler solution or approach?
  • Is there already some code existing, which could be useful for me?
  • Is there a useful subject about which I should now? (If so please give me the right keyword)
  • What do you think about visitor pattern, is this the right place for it?

Call implemented interface methods, but distinguish their calls on certain objects

I'm facing a design issue where I'm trying to call all objects that implement a certain interface IInitialize that has a method "Initialize".

"IInitialize" can implement several classes like GameManager, Player, Enemy etc.

However IInitialize can be also implemented in other classes that don't have to Initialize themselves in that exact moment when I want to let's say restart the game, so I need some sort of "categorization" of Init calls so other classes don't get called when I don't need them to be.

So here I have few options like creating another empty subclass of "IInitialize" and just make a call to "Initialize" through this type. All classes that Implement subclass will get this call. (it works, but it is a correct approach - not code smell?).

Another option is to create a generic "Initialize" interface and just pass the string or something similar to distinguish between calls.

So to recap: I implement the interface to various classes, let's say "ILife" which has a method "Die" to implement in the class. However I don't want all objects of type to die at a certain time, just the required ones.

Any other ideas or I'm going in the wrong direction?

Thanks in advance!

jeudi 25 juillet 2019

Is okay to have mutiple models/classes for same entity (Different fields)?

Some entities in my application are complex and have many fields that many times I don't need but sometimes I do. Many times in the front end I only see a couple of fields so I was wondering if it is correct to have several models defined for the same entity. Simplified example:

Class PersonModel {
   id
   name
   lastname
}
Class PersonModel {
   id
   name
   lastname
   dni
   childs
   pets
   ...   
}

multiple OR conditions in IF statement in javascript

I have a drop-down and depending on what is selected from the drop-down some of the UI fields will become un-visible to the user to fill. I have an IF statement with many different ORs and have the hard-coded value on the condition. I am very new to coding so I don't know what is the best way to do this. I want to have a clean and reusable code. Also the drop-down values are coming from the database and I did not know how to add to my IF without hard-coding them.
Any help will be appreciated.

if (value === 'Banana Factory' || value === 'Apple Factory ') {
      this.store1Visable = false;
    } else {
      this.store1Visable = true;
    }
    if (value === 'Pineapple Factory' || value === 'Peanut Factory' || value === 'Kiwi Factory' || value === 'Watermelon Factory') {
      this.store2Visable = false;
    } else {
      this.store2Visable = true;
  }
    if (value === 'Pineapple Factory' || value === 'Peanut Factory' || value === 'Kiwi Factory' || value === 'Watermelon Factory'
        || value === 'Banana Factory' || value === 'Grape Factory' || value === 'Peach Factory' || value === 'Kiwi Factory') {
      this.store3Visable = false;
    } else {
      this.store3Visable = true;
    }
    if (value === 'Pineapple Factory' || value === 'Peanut Factory' || value === 'Kiwi Factory' || value === 'Watermelon Factory'
        || value === 'Banana Factory' || value === 'Grape Factory' || value === 'Peach Factory') {
      this.store4Visable = false;
    } else {
      this.store4Visable = true;
    }

I want my code to be clean and reusable to the point if something needs to be added it be an easy change.

nHibernate Pattern for Partial updates for column security

I have a situation where I need to partially update a model because I want to return a model that has column level security. I am aware that dynamic update exists for non changing information using nHibernates dynamic updates.

I am trying to return some data from a model that has empty values from our secured web api. I don't want the data for some columns to ever reach the end user's system. The reason being is that I don't want data being in the system memory to meet compliance. So when a request for a model is sent to the api I will be returning partially filled models. Since the column level security will by dynamic as well I don't know which columns at the time of writing the application will be designated as non-viewable for a user. In other words the fields for the models will vary depending on user security configuration. What patterns are out there to get a partially filled model and allows me to leverage nHibernate without hacky approaches. I hope I was clear enough. I am stumped on a solution that doesn't require dynamic generation of update statements (non orm solution). This is a big deal for us to leverage nHibernate.

model definition: Customer { firstname; lastname; SSN;etc...}

// This is a customer that we don't want to reveal SSN for a non privileged user in the session. And we don't want to hide on frontend. We don't want webapi to send back any SSN.

WebAPI api = new api(); api.SetUserOfSession(SystemUserWithNoPrivilegesToReadSSN);

var customer = api.GetaCustomer(1000); // customer should not have SSN field filled and should be blank

// Get info from gui where SSN was obviously not changed and is blank but customer.firstname = "John"; // update any column besides SSN

api.Save(customer); // This should update firstname but SSN should obviously not get erased with a blank because we never sent it back.

So I expect that the customer object when not getting SSN field be saved to nHibernate which is running within the webapi to ignore the SSN in the update dynamically and not think it is "" because I sent it in. I obviously want to leverage what nHibernate does as an ORM and do not know ahead of time what fields will be data masked on retrieval.

Sub-classes that add new methods

I'm writing a class Tracker that will expose to the client methods to get the current status of user's training, like distance, pace, calories, etc. Imagine this values as getters.

class Tracker{
  float getDistance();
  float getTime();
  float getCalories();
}

Now, thinking ahead, I may discover a way to also get the elevation, and then maybe (not at the same time) the number of steps, so my problem is how to better solve this design.

First thought, classic inheritance 

My first thought was to just subclass this interface, so I'll end up with

class ElevationTracker extends BaseTracker{

   float getElevation();

}

But then, I may want to add a StepTracker, extending the ElevationTracker so I have both stats.

class StepTracker extends ElevationTracker{

   float getStepsCount();

}

This looks a bit weird to me, because the StepTracker now implicitly provides the Elevation stat, and it could have been the other way around, the ElevationTrackerextending StepTracker, in this case it's just a matter of which feature I discover first.

Also, I'm not completely sure if this inheritance is consistent with the specialization philosophy

A single class for everything 

Another idea, maybe the simplest, is to have just one class Tracker and any time I want to add a new feature, change this class by adding a new method to it to retrieve this feature's information; and then the client can update its code to use this new features. So for example, next month I change the Tracker class and it looks like this

class Tracker{
  float getDistance();
  float getTime();
  float getCalories();

  //This is new
  float getElevation();
}

I think this solution like if I had thought of this Elevation feature before (The first time I created Tracker class), I would have added this last method from the beginning.

I do it now just because now the "requirements have changed"

Making each feature a class

Another thought was to not think every feature as the methods of a class, but as a class on its own, meaning that I would have an interface like Tracker

interface Tracker {

  float getValue();

  /** Maybe some other methods */

}

and then have a class for each feature

  • DistanceTracker
  • TimeTracker
  • CaloriesTracker
  • ...

So then I would just add a new ElevationTrackerand a StepTrackerthat are independent from each other.

The problem here is that there are some features that depend on others, like for example PaceTracker and CaloriesTracker may depend on DistanceTracker, so they will probably need receive an instance of DistanceTracker.

Also, the client code may become a bit messy, having to hold an instance for each feature. And the most important pitfall I see is that I would usually use all this trackers together, I probable won't use just the DistanceTracker or just the ElevationTracker, so maybe there's no benefit in having each feature separately

Conclusion

I would like to know which of this options is the best, or if there's another better option. Maybe I can reconsider one of them with some tweaks or adding a design pattern to improve it.

In my opinion, the Single class option provides faster development, considering that, although the others make use of OOP features, they just move the problem of updating a class already written from the Tracker class to another client or intermediate class.

How should we implement constructor code when using the Decorator Pattern if each decorator needs different arguments?

I am working on a C# project, and I was planning on using the Decorator pattern.

Basically, we have to keep track of machine computer servers. Machine computer Servers.

enter image description here A Machine computer Server could be a Worker Or A Machine computer Server could be a Master

A Master will have a List workersList;

A Worker will have a MasterDecorator master;

Could someone please show me how to implement the constructors for the aforementioned decorators in such a way -that I could supply the MasterDecorator entity during the constructor instantiating? -that I could supply the List collection entity during the constructor instantiating?

Generating a Pattern Based on Percentages

Given a set of values that are suppose to be presented in a pattern, create a pattern that reflects the percentages. Ultimately these values are going to be images that have to be displayed a certain percentage of the time, but need to be in a pattern that attempts to show a different image each time.

Example:

Given: A @ 40%, B @ 20%, C @ 10%, D @ 10%, E @ 10%

Conditions: Prefer to not have a repeat, but ultimately is still allowed Percentage increments will only be by 1. (IE: never will have 12.5%) Number of different of values may increase or decrease.

Pattern: BACADAEAB

Currently I'm doing this by hand and hard coding it whenever the values change. I know there's a formula to find the Least Common Multiple (LCM), but it relies on a Greatest Common Divisor (GCD) which seems to be trickier to code.

I don't have any code just yet, the formula I'm trying to replicate is:

lcm(v1, v2, ...) = (|v1 x v2 x ...|)/(gcd(v1, v2, ...))

Building a factory that returns class instances instantiated with different parameters?

I'm building a small policy system for passwords and usernames. These policies can be configured based on a variety of different factors, but for the most part they're relatively straight forward. The policies all implement IPolicy which looks something like:

public interface IPolicy
{
    (bool, ErrorResponse) Verify(string input);
}

Some of the policies require certain parameters to be passed to them during instantiation, such as minimumLength. An example policy may look something like:

public class LowerCasePolicy : IPolicy
{
    private const string _defaultTitle = "LowerCaseCount";
    private readonly int _minimumLength;
    private readonly string _errorMessage;
    private readonly string _errorTitle;

    public LowerCasePolicy(int minimumLength)
    {
        _minimumLength = minimumLength;
        _errorMessage =
            $"Password does not meet the lower case character count requirement set by the password policy ({_minimumLength})";
        _errorTitle = _defaultTitle;
    }

    public LowerCasePolicy(int minimumLength, string errorMessage, string errorTitle = _defaultTitle)
    {
        _minimumLength = minimumLength;
        _errorMessage = errorMessage;
        _errorTitle = errorTitle;
    }

    public (bool, ErrorResponse) Verify(string input)
    {
        var enoughUpper = Regex.Matches(input, "[a-z]").Count >= _minimumLength;
        return !enoughUpper ?
            (false, new ErrorResponse(_errorTitle, _errorMessage))
            : (true, null);
    }
}

I'm trying to build some sort of factory that's capable of returning all of my different policies with their different constructors, but I'm not too sure where to go from here. One potential option I came up with was to create a base PolicyArgs class to pass the parameters, and I could use derived classes for each. Like so:

public class PolicyArgs
{
    public string Title { get; set; }
    public string ErrorMessage { get; set; }
}

public class LowerCaseArgs : PolicyArgs
{
    public int MinimumLength { get; set; }
}

And the constructor for the policy would now look like:

public LowerCasePolicy(PolicyArgs args)
{
    if (args == null)
        throw new ArgumentException();

    if (!(args is LowerCaseArgs lowerCaseArgs))
        throw new ArgumentException();

    _minimumLength = lowerCaseArgs.MinimumLength;
    _errorTitle = lowerCaseArgs.Title ?? _defaultTitle;
    _errorMessage = lowerCaseArgs.ErrorMessage ??  $"Password does not meet the lower case character count requirement set by the password policy ({_minimumLength})";
}

And the factory would look like:

public class PolicyFactory
{
    private readonly Dictionary<Policy, Func<PolicyArgs, IPolicy>> _policyDictionary = new Dictionary<Policy, Func<PolicyArgs, IPolicy>>
    {
        [Policy.LowerCase] = (args) => new LowerCasePolicy(args)
    };

    public IPolicy Create(Policy policy, PolicyArgs args)
    {
        return _policyDictionary[policy](args);
    }
}

I'm not sure if this is truly the best approach, or if there's some better option for handling different policies with different constructor needs. The goal is to be able to simply put these configurations in a database and have my PolicyProvider effectively return an array of IPolicy.

What is the best practice for creating Home/Menu screen of the Android application?

I’m looking for some pattern or good practice. I want to create a home screen in my app and I’m wondering how to do it right. The screen will consist of scrollable cards like in the Play Console app. Each card will show different content (different layout, buttons, there will be some queries to the API, etc.). Is there any pattern to it? I thought about making custom CardView and implement whole logic in there, and then display it in the recyclerView, what do you think about it? I would be grateful for any advice or sample app code.

How to make such animation components in the website?

I came across this website by Google, https://yourplanyourplanet.sustainability.google/ It has some components such as water, energy etc which are animated. My question is how to make such components and add animations to it, it includes the designing part of that component.

What is a good design of a custom communication protcol?

I have to implement a communication protocol stack. There exists already an outlining design. The stack consist of 3 layers (connection-control, security, fragmentation). The functionality of these layers is not relevant here. The idea is, that each layer processes an incoming/outgoing telegram according to its responsibility and hands it to the next layer in the stack. I thinks that’s the usual idea of a stack.

My question is, what a good design is and how are the dependencies of the various items of each layer.

I have thought of two approaches:

  1. A chain like implementation: For an incoming telegram, a process-in data function of the connection control item is called by a preceding item (not in the scope of this post). Then the connection control does something with the telegram and then calls the security items process-in data function, then the security item does something and forwards the telegram to the fragmentation item. The same idea applies for outgoing telegrams, in a reversed direction by calling process-out data functions.

  2. A central control item implementation: In this approach a central control gets the an incoming telegram, it then calls the process-in data function of the connection-control which returns the telegram after doing something. Then the central control item calls the process-in data function of the security item and so on. Maybe this central control item could be implemented as a state-machine, where each state represents one of the communication protocol layers mentioned above.

How to implement functions which act as instance method as well as class methods in python?

I am working on a class which represents a stock portfolio. I have been implementing this by extending over pandas.DataFrame. I have been writing some generic portfolio analyzing visualizations. Till now I have a module with all visualization functions which can be used as

visualization1(portfolio_instance ,*args, **kwargs)

I did wrap them to be used as instance methods like

def visualization(self, *args, **kwargs):
       from module import visualziation1

        return visualziation1(self.data, *args, **kwargs)

But I am pretty sure there is a better way for this

How are these implemented in standard library like pandas for e.g.

df_inst_1.merge(df_inst_2, on = 'something', how= 'left' )

and

pd.merge(df_inst_1, df_inst_2, on ='something', how = 'left')

EF Core - Mapping entities to custom classes throws stackoverflow for cyclic references

I'm building an API POC with asp.net core webapi. I'm trying to separate the EF Core entities from the objects returned by the API so I can customise them for different methods.

To achieve this I've created custom classes to which I map the entities. This breaks down when I'm trying to map Entities having one-to-many or many-to-many relations (2x one-to-many with an intermediary entity in EF Core)

EF Core Entities

public class Country
{
  [Key]
  public string Code { get; set; }
  public string Name { get; set; }

  // Relations
  public virtual ICollection<CountryRegion> CountryRegions { get; set; }
}

public class Region
{
  [Key]
  public string Code { get; set; }
  public string Name { get; set; }

  // Relations
  public virtual ICollection<CountryRegion> CountryRegions { get; set; }
}

public class CountryRegion
{
  public string CountryCode { get; set; }
  public virtual Country Country { get; set; }

  public string RegionCode { get; set; }
  public virtual Region Region { get; set; }
}

API-side custom class example for mapping the Country entity

public class Country
{
  public string Code { get; set; }
  public string Name { get; set; }

  [JsonProperty(NullValueHandling = NullValueHandling.Ignore)]
  public IList<Region> Regions { get; set; }

  public Country() { }

  public Country(Database.Models.Country country)
  {
    this.Code = country.Code;
    this.Name = country.Name;

    if (country.CountryRegions != null)
    {
      this.Regions = country.CountryRegions.Select(cr => new CountryRegion(cr.Region)).ToList();
    }
  }

  public static implicit operator Country(Database.Models.Country country)
  {
    return country != null ? new Country(country) : null;
  }
}

Everything works fine EF-wise, but evidently, when executing this mapping, EF entities will just cycle through the relation and end up throwing a StackOverflowException.

I am almost convinced I am approaching this the wrong way. Is there maybe a pattern that already solves this issue that I've overlooked?

Chain of Responsibility "Exactly one handler"

Was reviewing this article in Wikipedia about chain-of-responsibility:

https://en.wikipedia.org/wiki/Chain-of-responsibility_pattern

It states:

[...] for the chain of responsibility, exactly one of the classes in the chain handles the request.

In the C# example we see the following code in the implementation of the ILogger interface:

    public void Message(string msg, LogLevel severity)
    {
        if ((severity & logMask) != 0) //True only if any of the logMask bits are set in severity
        {
            WriteMessage(msg);
        }
        if (next != null) 
        {
            next.Message(msg, severity); 
        }
    }

As you can see if a logger matches it doesn't halt the chain. Instead it allows the next handler to be invoked and so on. Thus if we issue a logging request like so:

   logger.Message("Foo", LogLevel.All);

More than one handlers will be invoked, which in my eyes means that the example given for C# is more like a Decorator pattern (all handlers invoked) instead of a Chain-of-Responsibility (exactly one handler at most). Am I missing something?

mercredi 24 juillet 2019

Storing Date Components Instead of a Date

My app lets people log the movies they see (for example). Each logged movie usually (but not always) has a date and sometimes has a time. It's not unusual to have one but not the other. Occasionally the dates are only a year ("I watched a Dumbo sometime in 1984"), but could realistically be any combination of day/month/year/time.

I am used to modeling dates as date objects in my app and my backend. But is it a viable approach to store each component separately? When I need to reference an actual date from the components (e.g. for sorting the log) this will be built client-side, or perhaps be stored as a derived property sortDate and updated whenever any of the components change.

What are the limitations and/or pitfalls of this approach? Does anyone have experience modeling their dates this way?

If it's of any consequence, my app is for iOS written in Swift and uses a Parse Server backend.

Purging files and SQL database logs using Factory Method in C#

I am building an application (in C#) using Factory Method to be able to purge files and databases logs that are older than a certain day. I am using Factory method to contain all my purge processes in one central location/application. This is currently what I have so far.

public interface IPurger
{
  void Purge() ;
}

public enum PurgeType
{
  File,
  Database,
}

public class FilePurger : IPurger
{
  public void Purge()
  {
      var files = new DirectoryInfo(@"folderpath").GetFiles();
      foreach (var file in files)
      {
          if (DateTime.Now - file.CreationTime > TimeSpan.FromDays(7))
          {
              File.Delete(file.FullName);
          }
      }
  }
}

public class DbPurger : IPurger
{
  public void Purge()
  {
            using (SqlConnection mySqlConnection = new SqlConnection("server=MYSERVER;database=MYDATABASE;uid=UID;pwd=PASSWORD"))
            {

                using (SqlCommand mySqlCmd = new SqlCommand("dbo.OrderHeaders_Delete", mySqlConnection))
                {

                    mySqlCmd.CommandType = CommandType.StoredProcedure;    
                    mySqlCmd.Parameters.Add("@OlderThanDays", SqlDbType.Int).Value = "7";

                    mySqlConnection.Open();
                    mySqlCmd.ExecuteNonQuery();

                }
            }  
  }
}

public class PurgerFactory
{
  public IPurger CreatePurger(PurgeType type)
  {
    switch(type)
    {
      case PurgeType.File:
        return new FilePurger() ;
      case PurgeType.Database:
        return new DatabsePurger() ;
      default:
        throw new NotImplementedException() ;
    }
  }
}

Currently, the dependencies/parameters for each of the processes are hard coded. The idea is to create a database table in SQL that contains all the dependencies/parameters info such as file path, connection string, older than days, etc. Using a Poco object, the table will connect to the Factory, which will then, using the information from the table, decide which process it needs to execute and will do so accordingly. I'd like to do it this way so that if there's a new log directory/database I'd like to have it purge, I can just add it to the dependencies/parameters table, and the application will pick it up and perform the purge.

I'm beginner developer and I've never worked with Factory methods before, so I would appreciate any help in explaining how I would implement this concept.

C++ class hierarchy in which to add functionality with an interface

C++. Imagine the following situation.

There's a class hierarchy of classes deriving from some base class A. We cannot modify A because it is outside of our scope. (Provided by a library, it is a MFC CView class, but that shouldn't matter here)

So there are A1, A2 etc which are different classes somehow derived from A and providing specific functionality.

Now imagine we define some new interface I to provide some new functionality.

Classes for concrete objects of the application will inherit from both one of the As and I. Let's call them Bs. (There are again several of them, like B1 derived from A1 and I, B2 derived from A2 and I etc.)

Now it happens that to implement the interface of I, there is a lot of common code that needs functionality from A. How can we organize the class hierarchy without repeating ourselves too much.

So for instance if there is a function I::f that needs to call A::f, for all derived classes Bn. It seems like waste to re-implement I::f for every Bn. But obviously, we cannot call A::f directly from I::f, as they aren't related.

I hope you get the point.

What is the pattern that can help us here?

Where to store state in a complex form?

Where to store the state of a complex form in react

let us consider a complex form of registering a driver and owner

the driver will have all these fields

driver = {
firstName: "xyz",
lastName: "abc",
phone: "1234",
email: "m@g.com,
licence: "xy1234"
}

And owner has the following fields

owner = {
firstName: "xyz",
lastName: "abc",
phone: "1234",
email: "m@g.com,
vehicle: "1234"
}

notice how they both have 4 inputs in common so it makes sense to create a reusable component called User, so our component heirarchy becomes

Driver User licence input

at this point if i want to make a post request on the driver data I will have to store the state in the driver and update the state of the driver whenever my inputs in the user component or the licence field changes (onChange)

The catch with this is that the The Entire Driver component re-renderes whenever a single input changes. and this creates a problem when you have a lot of nested components (since the parent re-renders all its children whenever one of them changes)

Is there a better design-pattern for this solution?

Ps. this is has been the most challenging part of React for me

Return Status Code from Service to Controller Web API

Let's say I have an architecture Controller -> Service -> Repository etc Right now my code in the controller looks like this.

GetPlayers(){

if(playerService.verification1()) return NotFound ("message 1");

if(playerService.verification2()) return NotFound ("message 2");

if(playerService.verification3()) return BadRequest("bad request message");

if(playerService.verification4()) return Ok(players);

You get the idea. My controllers have some logic also. I want to have something like this in the controller methods "playerService.DoStuff(); Return Status code with Object (if any)"

What's the best way to do this? I know that the controllers should have very few lines.

Java - reduce code duplication - General coding question

Im looking for the best practice for reducing duplication in my code.

I have this 2 classes with same methods and ONLY difference private final House number; and private final NewHouse number; :

public class Building {

    private final UUID id;
    private final House number;
    private final HouseType houseType;

    Building(UUID Id, House number, HouseType houseType) {
        this.id = id;
        //....//
    }

    public House getNumber() {
        return number;
    }

    //get/set
    //other methods

}

public class NewBuilding {

    private final UUID id;
    private final NewHouse number;
    private final HouseType houseType;

    NewBuilding(UUID id, NewHouse number, HouseType houseType) {
        this.id = id;
        //....//
    }

    public NewHouse getNumber() {
        return number;
    }

    //get/set
    //other methods
}

Is there some way that I can combine this two classes in one and reduce duplication in my code?

Is there some design pattern that I can use? Should I create some 3rd class with common functionality ?

Any suggestions welcome.

How do you dynamically get subclasses in an inheritance hierarchy when there are derived classes mainly for extending state not for behaviour?

I am trying to consume my tumblr data by using Jumblr which is a Tumblr API wrapper client for Java.

I have studied the source code and have seen that since Json response is dynamic, there is a Post POJO and derived POJOs like TextPost, QuotePost, PhotoPost etc. to deserialize to pojos. It handles consuming in a generic way by using Gson with a custom deserializer which uses reflection. In this way, for example it deserializes a Json response to a TextPost and assigns it to Post object.

So in order to get subclass' field, I need to downcast Post object after instanceof checks like this:

List<Post> posts =  blog.draftPosts();
Post post = posts.get(0); //gets a TextPost
if(post instanceof TextPost) {
    System.out.println("title: " + ((TextPost) post).getTitle());
    System.out.println("body: " + ((TextPost) post).getBody()); 
}
else if(post instanceof QuotePost) {
    //...
}
else if...

I am not sure this is the best way. So I am searching for more elegant or a best way or a correct way from the perspective of object-oriented programming concepts like polymorphism or others.

What is the right approach to get subclass or access to it from a superclass?

How do you evaluate API's object oriented design which uses inheritance by extending specific classes which contain extra state? Is it a reasonable approach and what are the other ways from the perspective of the client which will be handling response? Since it is not behavior inheritance, is it right to use inheritance to only inherit state?

From the API source:


public class Post {
    protected PostType type;
    private Long id;
    private String author;
    private String reblog_key;
    private String blog_name;
    //more state and getters/setters
}

public class TextPost extends Post {
    //extra fields
    private String title;
    private String body;

    //getters/setters
}


public List<Post> getPosts() {
    Gson gson = gsonParser();
    JsonObject object = (JsonObject) response;
    List<Post> l = gson.fromJson(object.get("posts"), new 
                        TypeToken<List<Post>>() {}.getType());
    ...
}

private Gson gsonParser() {
        return new GsonBuilder().
            registerTypeAdapter(Post.class, new PostDeserializer()).
            create();
    }

public class PostDeserializer implements JsonDeserializer<Object> {

    @Override
    public Object deserialize(JsonElement je, Type type, JsonDeserializationContext jdc) throws JsonParseException {
        JsonObject jobject = je.getAsJsonObject();
        String typeName = jobject.get("type").getAsString();
        String className = typeName.substring(0, 1).toUpperCase() + typeName.substring(1) + "Post";
        try {
            Class<?> clz = Class.forName("com.tumblr.jumblr.types." + className);
            return jdc.deserialize(je, clz);
....

}


Find pattern mulifasta list based on user input in Perl

I am trying to fix a Perl code. Given the following "file.txt":

>otu1  
AACGCCTTTCCNGGATGGCAAAATTTNTNGTAAA
AGGGCACCCANTTCTGGCTCGAAA  
>otu2
NNAATCGGNNNGGGGCGTAANGAGGTTNCGGCACGG
TNCCCGTTTANCG
>otu3   
CTGGNATAAAAAANNNNTACTTAA

After providing a otu number as argument (i.e. otu2) when calling the program, I want to first (1) check if that otu is present in the file.txt, then (2) find motifs matching with the pattern [NC].[CT] (element N or C, followed by any element . and followed by an element C or T), and finally (3) print out the start‐ and end‐position of every site.

For the first two questions I am trying with the following code but I am encountering problems by integrating subroutines.


#!/usr/bin/perl -w

use warnings;
use strict;

$otu = $ARGV[0];   
check_otu("file.txt");

sub check_otu {
    my $content = shift;
    open(my $fh, '<' , $filename) || die "File not found: $!";
    my $content;    

    while( my $line = <$fh> ) {
        if ( $line =~ /^>/ ) {
            check_pattern($content) if $content=$otu;
            $content = $line;
        }
        else {
            $content .= $line;
        }
    }
    check_motifs($content);
}

}
sub check_pattern{
    my $fasta = $content;
    $count++ if count_pattern($fasta);
}
sub count_pattern {
    my $chain = $content;
    my @all = $chain =~ /([NC].[CT])/g;
    scalar @all;
}

Would you have any suggestion? Any hint for the third question? Thanks for your help

How to dynamically switch UI theme based on different user types in iOS

In my app, I've got a scenario where I need to switch the UI theme design based on user type. For eg: In my Type1 user flow it goes like Registration Screen -> HomePage Screen and in my Type 2 user it should go like Registration Screen-> Contact Screen -> Home Page Screen. And the UI design and themes are different in the case of Type 2 user. For achieve this, below is my sample code flow which is implemented currently.

RegistrationViewController

(This view is available for both users but UI theme is different, like navigation bar color, bg color, button color, fonts, images etc)

override func viewDidLoad() {
        super.viewDidLoad()
        setupViews()
    }


private func setupViews(){

        if Utilities.isUserType1{
            setupViewsForType1User() //Adds themes for type 1 user
        } else {
            setupViewsForType2User() //Adds themes for type 2 user
    }

}

 @IBAction func continueAction(_ sender: Any) {

    if Utilities.isUserType1{
            goToContactView() //Goes to ContactViewController
        } else {
            gotToHomeView() //Goes to HomeViewController
    }

}

ContactViewController (This view is only available for type1 user)

override func viewDidLoad() {
        super.viewDidLoad()
        setupViews()
    }


private func setupViews(){

        //Setupviews 

}

 @IBAction func continueAction(_ sender: Any) {

            gotToHomeView()

}

HomeViewController (This view is available for both users but UI theme is different as mentioned in Registration)

override func viewDidLoad() {
        super.viewDidLoad()
        setupViews()
    }



private func setupViews(){

        if Utilities.isUserType1{
            setupViewsForType1User()
        } else {
            setupViewsForType2User()
    }

}

This works fine, but the problem here is now I've defined an isUserType in Utilities and its not perfectly scalable. For each flow and UI change, I need to put an if-else condition based on this parameter. So, now if I have another user type that needs to be added in the future I would again need another if-else statement and switch UI and flow based on that.

Is there any better approach to solve this problem?

Design a generic rest API which act as an interface for Payment gateway

I need to design a generic rest API which will act as an interface to connect to multiple payment methods.It needs to be scalable and should support integration to different paymnet methods.what will be the genric modules and what will be the specific modules .define the structure and high level class and interface design.

mardi 23 juillet 2019

Is it best practice to use the "Move Accumulation To Collecting Parameter" pattern?

I'm currently reading Joshua Kerivsky's 'Refactoring To Patterns'. One of the refactoring techniques referred to in the book is based upon Kent Beck's 'Collecting Parameter' pattern.

This pattern is described as something you may need when you are needing to accumulate data, (such as with Java's StringBuffer) compared to lots of calls and returns. In the book, he describes a Collecting Parameter as an object that you pass to methods in order to collect info from those methods.

I cannot find many examples of people talking about this online and it seems to be rarely discussed. I'm wondering how/when is best practice to use a pattern like this, as I don't know if it's the 'done thing' these days. I haven't seen it used in production and I generally don't know if it's an 'old world' programming technique.

I see that we are mutating the object every time we want to accumulate data which, if you look at functional programming principles is generally bad practice. But is it okay in an OOP sense?

Simple example of usage (Java):

FROM:

result += "<" + tagName + " " + attributes + ">";

TO:

private void writeOpenTagTo(StringBuffer result) {
    result.append("<");
    result.append(name);
    result.append(" ");
    result.append(attributes.toString());
    result.append(">");
}

Visitor pattern implementation example in JDK, Is predicate is a visitor pattern example? [duplicate]

This question already has an answer here:

Are there any examples of Visitor pattern implementation in JDK ? Is predicate from java 8 can be consider as an example of this pattern.

Problems defining the pattern to extract multiple dates from a json string in java

I have the following code:

    public static void main(String[] args) {
    String str = "{\"$and\":[{\\\"$or\\\":[{\\\"origen\\\":{\\\"$eq\\\":\\\"LEMD\\\"}},{\\\"origen\\\":{\\\"$eq\\\":\\\"LEBL\\\"}}]},{\"horasacta\":{\"$gte\":\"28/02/2015 00:00:00\"}},{\"horasacta\":{\"$lte\":\"28/02/2015 23:59:59\"}}]}";

    Pattern pattern = Pattern.compile("\\{\"(.*?)\":\\{\"\\$(.*?)\":\"[0-9]+/[0-9]+/[0-9]+ [0-9]+:[0-9]+:[0-9]+\"}}");
    Matcher matcher = pattern.matcher(str);
    while (matcher.find()) {
        System.out.println(matcher.group(0));
    }

I want to get the substrings:

{\"departure\":{\"$gte\":\"28/02/2015 00:00:00\"}}
{\"departure\":{\"$lte\":\"28/02/2015 23:59:59\"}}

but the program give me:

{"$and":[{\"$or\":[{\"origin\":{\"$eq\":\"LEMD\"}},{\"origin\":{\"$eq\":\"LEBL\"}}]},{"departure":{"$gte":"28/02/2015 00:00:00"}}
{"departure":{"$lte":"28/02/2015 23:59:59"}}

the 2nd time the find() matches the pattern but the 1st time it doesn't do the job.

Any help?

thanks

Flags for ability system

I would like to prepare an ability config system where I'll be able to construct new ability just from values/flags:

{
Name: "Passive Health Regeneration",
Active: false,
Affectable: "Health",
TickTime: .1,
TickAmount: -1,
Value: 10
}

But I would like to prevent usage of unhandy/useless flags so maybe there are some known good practices about it?

Creating objects at runtime using dependency injection

I read a book about Dependency injection from Mark Seemann and Steven van Deursen and I'm trying to practice what I learned by programming a WPF application in C#.

In my application I need to create custom UserControls at runtime based on what the user is doing. Each custom UserControl naturally needs its own DataContext.

So my custom UserControls might look like this:

class ImageComponent : UserControl
{
    public ImageComponent(object dataContext)
    {
        InitializeComponent();
        DataContext = dataContext;
    }
}

class TextComponent : UserControl
{
    public TextComponent(object dataContext)
    {
        InitializeComponent();
        DataContext = dataContext;
    }
}

and of course the view models. For simplicity I omitted all dependencies if any

class ImageComponentVM : ViewModelBase
{
    // Image property...
}

class TextComponentVM : ViewModelBase
{
     // Text property...
}

Now that I have defined the UserControls and their view models, I need to create their instances somewhere.

I was thinking about something like this, so that the component producer wouldn't have to decide what type it needs to create. The component producer would also contain other logic which I again omitted. Instead of the 'Type' as the Dictionary's key, enum would also do the thing.

class ComponentProducer : IComponentProducer
{
    private Dictionary<Type, Func<object>> dataContextsDictionary;
    private Dictionary<Type, Func<object, FrameworkElement>> componentDictionary;

    public ComponentProducer(Dictionary<Type, Func<object>> dataContextsDictionary,
                             Dictionary<Type, Func<object, FrameworkElement>> componentDictionary)
    {
        this.dataContextsDictionary = dataContextsDictionary;
        this.componentDictionary = componentDictionary;
    }

    public FrameworkElement Produce(..data..)
    {
        var dataContext = dataContextsDictionary[data.something.GetType()].Invoke();
        var component componentDictionary[data.something.GetType()].Invoke(dataContext);
        return component;
    }
}

And in the composition root, I would have something as follows:

    var datacontextDictionary = new Dictionary<Type, Func<object>>
        {
            { typeof(Image), () => new ImageComponentVM() },
            { typeof(string), () => new TextComponentVM() }
        };
    var componentDictionary = new Dictionary<Type, Func<object, FrameworkElement>>
        {
            { typeof(Image), (dataContext) => new ImageComponent(dataContext) },
            { typeof(string), (dataContext) => new TextComponent(dataContext) }
        };
    var componentProducer = new ComponentProducer(componentDictionary);

My current solution looks similar to what I demonstrated. I would like to know different (and right) approaches, how this kind of problem is solved using dependency injection.

Thanks

How to create an extendable software model for different hardware drivers in Python?

I have to conceptualize a software model for different hardware drivers. The hardware in question are measurement instruments with the same core functionality but different additional features. The drivers and also the scripts where the drivers are used are programmed in Python. It should be easy to replace the used hardware by keeping almost the same script. The necessary changes to the script should be minimal when replacing the hardware.

The core model must therefore be the same for all different hardware drivers, so that scripts that only use the core functionality of the hardware are independent of the actually connected hardware. This is easily solvable with inheritance.

But how can this be solved for functionality that are only supported by some instruments and not by others? Let's take the following code as example:

class BaseDriver:
   def coreFunctionA(self):
      pass
   def coreFunctionB(self):
      pass

class DriverModelA(BaseDriver):
   def coreFunctionA(self):
      pass
   def coreFunctionB(self):
      pass

   def additionalFunctionX(self):
      pass
   def additionalFunctionY(self):
      pass

class DriverModelB(BaseDriver):
   def coreFunctionA(self):
      pass
   def coreFunctionB(self):
      pass

   def additionalFunctionX(self):
      pass

class DriverModelC(BaseDriver):
   def coreFunctionA(self):
      pass
   def coreFunctionB(self):
      pass

   def additionalFunctionY(self):
      pass

The core functionality that is the same for all instrument models is summarized in the BaseDriver. But how to handle functions that are only supported by some drivers (like "additionalFunctionX" and "additionalFunctionY")? If the functions additionalFunctionX in DriverModelA and in DriverModelB do the same thing, they should have the same signature, so that the interface is easier to understand by the users. I could put those functions also into the base class and throw an exception for all drivers that don't support this feature. But that would be very ugly code in my opinion.

So do you guys have any idea how to bring these additional functions together? I want to avoid that the same functionality is implemented in different ways for each driver. If a driver supports a certain functionality that is also supported by some other drivers, this functionality should also have the same call semantics or the same interface for all drivers.

Need a design pattern for reducing code complexity and good Data model

I am looking for a design pattern which can replace inner class use case.

public class DrinkMaker {
    private Sugar sugar;
    private TeaPowder teaPowder;
    private Milk milk;
    List<Drinks> drinks ;

    PrepareDrinks (RawItems rawItems ) {
      this.sugar = prepareSugar(rawItems.sugarcane);
      this.teaPowder    = prepareTeapowder(rawItems.teaLeaves);

      // MakeTeaInnerClass has dependency on sugar teapowder
      drinks.add( MakeTeaInnerClass());
      // MakeCoffeInnerClass has dependency on sugar teapowder and already created drinks
      drinks.add( MakeCoffeInnerClass());

    }
}

What I tried

I thought of creating concrete class for MakeCoffeInnerClass as MakeCoffe and MakeTeaInnerClass as MakeTea then use them in DrinkMaker as class level variable. Once we have thepower and sugar ready (after prepareSugar and prepareTeapowder ) let them pass to each instance of MakeCoffe and MakeTea class. like

private MakeTea teamake;
teamake.preare(sugar,teaPowder,drinks);

But this seems like not a good approach as we are simply passing data across classes. Help me to get a design pattern having good data model and less complex so I can make any logic changes with less effort.

How to implement simple generic nesting in C#?

I am nesting multiple generic interfaces together, like

interface A<T1> where T1 : Parent
{
    T1 fun();
}

class B : A<Child>
{
    public Child fun()
    {
        ...
    }
}

interface C<T1, T2> where T2 : A<T1> where  T1 : Parent
{
    T1 fun();
}

class D : C<Child, B>
{
    private B b;

    public Child fun()
    {
        return b.fun();
    }
}

Child is a subclass of Parent.

in this way, the code are so redundant and ugly.

I want to get a simple implementation, like

interface A<T1> where T1 : Parent
{
    T1 fun();
}

class B : A<Child>
{
    public Child fun()
    {
        ...
    }
}

interface C<T2> where T2 : A<?>
{
    ? fun();
}

class D : C<B>
{
    private B b;

    public Child fun()
    {
        return b.fun();
    }
}

Is there any way?

Scala - template method pattern in a trait

I'm implementing a template method pattern in Scala. The idea is that the method returns a Dataset[Metric].

But when I'm converting enrichedMetrics to a DataSet enrichedMetrics.as[Metric] I have to use implicits in order to map the records to the specified type. This means passing a SparkSession to the MetricsProcessor which seems not the best solution to me.

Is there a more proper way to implement the template method pattern in this case?

  trait MetricsProcessor  {

  // Template method
  def parseMetrics(startDate: Date, endDate: Date, metricId: Long): Dataset[Metric] = {
    val metricsFromSource: DataFrame = queryMetrics(startDate, endDate)
    val enrichedMetrics = enrichMetrics(metricsFromSource, metricId)
    enrichedMetrics.as[Metric] <--- //requires spark.implicits
  }

  // abstract method
  def queryMetrics(startDate: Date, endDate: Date): DataFrame

  def enrichMetrics(metricsDf: DataFrame, metricId: Long): DataFrame = {
  /*Default implementation*/
  }
 }