jeudi 31 janvier 2019

Most efficient way of storing and retrieving rows in a table based on location coordinates?

Imagine I run a website that stores user-submitted content along with the location coordinates of the user. and I want to serve users with content created close to their own location. How would I design the database to retrieve rows while minimizing table scans?

Efficient way to implement some services(Java Beans) when they have a shared database

we have two projects as proj1 and WS. our platform is JavaEE. These projects have a shared DB so they can do anything with data at their part. For now we would like to implement another web service in the WS project. meanwhile our projects are running on different clusters so they are not local for each other. So the problem is If we implement the service in the WS project then our remote calls are OK (calls from out) but calling from proj1 will have some network and performance costs, against local calls, for us. On the other hand implementing another function on the proj1 will duplicate codes and we should be care about any changes in a WS implementations. I am confused to choose a way to implement this service. I will appreciate any clue and guide.

Call a factory methods using Kotlin DSL

I want to be able to write Kotlin DSL that calls a factory method to create an instance of a object instead of directly calling the constructor.

I have a factory named, PersonFactory that implements a method called getPresonTypeOne(name: String, age:Int, address: String). PersonTypeOne has three member variables named name, age, and address. I want to be able to write Kotlin DSL that calls getPresonTypeOne to create an instance of PersonTypeOne instead of directly calling the PersonTypeOne constructor.

I ideally what something that looks like this

class PersonTypeOne(
      val name: String, 
      val age: Int, 
      val address: String) {
    ...
}


personTypeOne {
    withName {
       ...
    }
    withAge {
       ...
    }
    withAddress {
       ...
    } 
}

I would like that DSL to get effectively result in a call that looks like this : personFactory.getPresonTypeOne(name, age, address)

I have looked around quite a bit, but I have only found examples of me being able to do this by directly calling the PersonTypeOne constructor.

Creating a smart pointer member of class referencing itself is a elegant design pattern in c++?

I would like to know if following code is a good pattern in C++?

There is no problem at all. The code works. But I would like to know if this can lead to some sort of problem.

#include <iostream>
#include <memory>

template <typename T>
class Class {
    public:
        std::shared_ptr<Class> shared_ptr;

        Class() : shared_ptr(this) {}
        ~Class() { shared_ptr.reset(); }
};

Passing parameters to a builder with component sub-builders

What is an appropriate design for passing keyword arguments to a builder that contains component sub-builders which each use a distinct portion of the parameter set? Is it better to pass in a single keyword parameter set which is then parsed by each sub-builder? Or is it better to explicity specify which parameter sets belong to which sub-builders when calling the parent builder?

I know "better" can be subjective in these kinds of situations but I am wondering if there is some collective wisdom I can draw from, here. Also, note that in the details below I'm using a feature specific to the Python language but any thoughts on how other languages manage this situation is appreciated.

Details - I am using a builder design pattern where BuilderA contains sub-builders BuilderB() and BuilderC. My current thought on the design was to pass the same set of keyword arguments to each sub-builder:

class BuilderA():
    def __init__(self):
        self.builder_b = BuilderB()
        self.builder_c = BuilderC()

    def build(self, **build_parameters):
        artifact_b = self.builder_b.build(**build_parameters)
        artifact_c = self.builder_c.build(**build_parameters)
        # ... do something to create BuilderA's artifact ...

Each sub-builder has distinct keyword parameters:

class BuilderB():
    def build(self, param_1=None, param_2=None, **ignored_kwds):
        # ...

class BuilderC():
    def build(self, param_3=None, param_4=None, **ignored_kwds):
        # ...

Alternatively, BuilderA's API could look like this:

class BuilderA():

    def build(self, builder_b_parameters={}, builder_c_parameters={}):
        artifact_b = self.builder_b.build(**builder_b_parameters)
        artifact_c = self.builder_c.build(**builder_c_parameters)
        # ... do something to create BuilderA's artifact ...

Is one of these designs, generally, more acceptable than the other? Or is there another option I haven't considered?

Thoughts - The first design is cleaner but prevents BuilderB and BuilderC from sharing keyword names. Plus, it requires that each of their builders includes **ignored_kwds in its build method declaration. The danger of this approach is that if the user misspells a keyword argument then there can be unexpected behavior without error. On the other hand, the second design makes the interface to BuilderA more cumbersome but resolves the aforementioned issues.

Are there any Design Patterns for Service Layer in MVC Application?

I am designing a service layer for a web application where there are overlapping services. While there are several ways to solve such problems, I would like to hear design patterns recommended by the experts in such scenarios.

I am designing a taxi app for some practice. I have two main entities here car and a driver. So, I have two separate controllers lets call them DriverController and CarController and two interfaces in the service layer lets Call CarService and DriverService and there default impls which connect to DAO layer. All of these together are good to facilitate basic CREATE/DELETE/UPDATE/MODIFY on Car and Driver entity.

No, let's say I want my application to return the list of cars owned by a particular driver

For example: {"drivername":"alex","cars":[{"carname":....etc....}]}

I would design an endpoint like GET /drivers/{drivername}/cars

which would trigger the driver controller.

Now, in the service layer, I am confused where should I write a business logic for this task. Should I add another method to the Driver Interface or should I have another interface extending this? Should I add another method like getCarsForDriver in the DefaultDriverServiceImpl or should I extend this DefaultDriverServiceImpl and add a method to it?

Here there is a one-to-many relationship between a driver and a car. Are there any design patterns/approaches to address such relationships?

How to design an API wrapper by following Domain Driven design principles?

The question effectively is for any API wrapper with a domain object that has bulky operations on it. My use case has Files as the concrete object.

I am working on a creating an API wrapper and need some assistance with its design. The project revolves around files, and operations(edit/merge/convert) on it. I am reading about DDD and trying to bring that in my project. My goal is to write clean maintainable code, and I am having a tough time doing that.

File is the core object of my project, and operations like file edit, file merge will be the verbs that'll act on the file. I am thinking of having a file domain class with the verbs (edit, convert) as the functions inside the class. The problem is, all the file operations are async API calls which need different processing based on the call results. So if someone calls file edit, I'll invoke a backend API which'll take its own time. Writing all the API flow inside the File class makes it harder to read and maintain, especially with the error handling. I feel that I am not doing it right. How can I break it down into simpler pieces? I was thinking of adding another layer which manages the file operations, but not really sure how to proceed on that. The goal of this question is to know if I am thinking in the right direction in DDD aspects. Should the operations really be inside the file class or should they be invoked via another layer, especially if they're so bulky. Thanks!

I am referring this link for learning DDD concepts : https://lostechies.com/gabrielschenker/2015/05/07/ddd-special-scenarios-part-1/

If you downvote the question, please let me know how can I phrase it better, or should I even questions like this here. I've seen matching questions here, but none of them address my concern.

Is there a way to combine two methods that are identical with one major difference?

I have two methods that are accessing data from an external object. Both methods do the same thing, up until accessing data (different data for each method).

public function GetObjectTitle(){
    //some code identical to getObjectTitle() that finds correct codes to know which objects to access
    $tempArray
    foreach ($arrayOfObjects as $object)
    {
        if (!$object->getObjectMember()) {
            $tempArray[] = "";
        } else {
            $tempArray[] = $this->Record->getRecordForIdp($object->getUser()->getId())->getTitle();
        }
    }
    return $objects = $tempArray;


public function GetObjectDepartment(){
    //some code identical to getObjectTitle() that finds correct codes to know which objects to access
    $tempArray
    foreach ($arrayOfObjects as $object)
    {
        if (!$object->getObjectMember()) {
            $tempArray[] = "";
        } else {
            $tempArray[] = $this->Record->getRecordForIdp($object->getUser()->getId())->getDepartment();
        }
    }
    return $objects = $tempArray;

The only difference is towards the end at the getDepartment and getTitle calls. I thought about passing in these two methods as variables but wonder if there is a better way.

Best way to undo previous steps in a series of steps

I'm trying to find a better way to execute the following functions. I have a series of steps that need to be completed, and if any fail, I need to undo the previous step like so:

try:
    A = createA()
except:
    return None

try:
    B = createB(A)
except:
    deleteA(A)
    return None

try:
    C = createC(B)
except:
    deleteB(B)
    deleteA(A)
    return None

try:
    D = createD(C)
except:
    deleteC(C)
    deleteB(B)
    deleteA(A)
    return None

return D

I would prefer not to repeat myself if possible. How can I improve this? Is there a known pattern to follow?

One thing I have considered would be adding deleteB() to deleteC(), and deleteA() to deleteB(). Is that the best possible way to do it?

Best design pattern for selecting a group with in a list with the value of the condition may vary?

public class Swimmers extends SwimmersPrototype{
    List<Swimmer> swimmers;
    SortStrategy sortStrategy;

    public Swimmers() {
        swimmers = new ArrayList();
    }

    @Override
    public SwimmersPrototype clone() throws CloneNotSupportedException{
        Swimmers swp = (Swimmers)super.clone();
        return swp;
    }

    public void setSortStrategyAndSort(SortStrategy s) {
        setSortStrategy(s);
        sort();
    }

    public void setSortStrategy(SortStrategy s){
        sortStrategy = s;
    }

    public void addSwimmer(Swimmer s){
        swimmers.add(s);
    }

    public List<Swimmer> sort() {
        return (swimmers = sortStrategy.sort(new ArrayList<>(swimmers)));
    }

    public List<Swimmer> getSwimmers() {
        return swimmers;
    }
}

I've Swimmers class to act as an in-memory database of Swimmer records. I've three tables one to show list of swimmer, second one to list swimmers with only age between 18-25, and the last one to list swimmers with only age 26-35.

Swimmer class have an age property, but the age of a Swimmer may change and may result in another age group, like if John is 25 and celebrate his birthday while in the game, he must be in the second group.

So here which design pattern is best to select a group based on some condition in a list, also the value of the condition may vary so it results change in a group?

Helper method that returns a thing, or causes a return in the calling scope / context

I can't figure out how to factor out this code.

  private CompletionStage<Response<String>> foo(RequestContext rc) {

    final Optional<String> campaignIdOpt = rc.request().parameter("campaignId").filter(s -> !s.isEmpty());
    final Optional<String> creativeIdOpt = rc.request().parameter("creativeId").filter(s -> !s.isEmpty());

    Optional<Uuid> campaignIdOptOfUuid = Optional.empty();
    if (campaignIdOptOfUuid.isPresent()) {
      try {
        campaignIdOptOfUuid = Optional.of(UuidUtils.fromString(campaignIdOpt.get()));
      } catch (IllegalArgumentException e) {
        LOG.error(String.format("Invalid campaignId: %s", campaignIdOpt.get()), e);
        return CompletableFuture.completedFuture(
            Response.forStatus(Status.BAD_REQUEST.withReasonPhrase("Invalid campaignId provided.")));
      }
    }

    Optional<Uuid> creativeIdOptOfUuid = Optional.empty();
    if (creativeIdOptOfUuid.isPresent()) {
      try {
        creativeIdOptOfUuid = Optional.of(UuidUtils.fromString(creativeIdOpt.get()));
      } catch (IllegalArgumentException e) {
        LOG.error(String.format("Invalid creativeId: %s", creativeIdOpt.get()), e);
        return CompletableFuture.completedFuture(
            Response.forStatus(Status.BAD_REQUEST.withReasonPhrase("Invalid creativeId provided.")));
      }
    }

    // Simplified, do something with Uuids.
    return bar(campaignIdOptOfUuid, creativeIdOptOfUuid);
  }

Basically, we very frequently need to parse Google protobuf Uuids from a query string to pass on to another service that will find (or not find). We need to pass along an empty optional if a parameter was not set or an empty string, as both cases mean, "Don't filter by this parameter." Finally, if the string doesn't parse at all, then we want to immediately return an error 400 (Bad Request), rather than pass along a non-sense param to the service.

So, codewise, I want a utility method that

  1. takes an Optional<String>, and
  2. returns an Optional<Uuid> if present, Optional.empty() otherwise, and
  3. if an exception is thrown, return an error from the original context.

But obviously, I can't "double-return." What pattern do I use to achieve this though? I tried to create an encapsulator for both an Optional<Uuid> and a CompletionStage<Response<String>> but it was awkward. Is there some idiomatic way of doing this?

What does a proxy mean in Python?

http://flask.pocoo.org/docs/1.0/reqcontext/#notes-on-proxies says

Some of the objects provided by Flask are proxies to other objects. The proxies are accessed in the same way for each worker thread, but point to the unique object bound to each worker behind the scenes as described on this page.

Is "proxy" a concept in Python language or somewhere else (such as design patterns)?

What is its definition?

Thanks.

Command Pattern + MVP - Access Data In Presenter From A Command (Design Problem)

I'm having a problem in the design of my application. I have a few commands which one of them needs to access a Dictionary (commands) within the presenter that holds the list of commands in order to show the user the list of all available commands. My question is, what is a good design solution to tackle this problem? I really don't want to make the commands field static or DI the presenter inside the command, would appreciate your help, thanks.

Form1Presenter.cs:

    private Dictionary<string, ICommand> commands { get; }

    public Form1Presenter(IForm1View form1View)
    {
        this.commands = new Dictionary<string, ICommand>();

        var commands = Program.container.GetAllInstances<ICommand>();
        foreach (ICommand command in commands)
        {
            this.commands.Add(command.Name, command);
            command.Completed += Command_Completed;
        }
    }



public class HelpCmd : ICommand
{
    public string Name => "/help";

    public string Description => "List of available commands.";

    public event EventHandler<CommandResult> Completed;

    private readonly StringBuilder commandsStr;

    public HelpCmd()
    {
        commandsStr = new StringBuilder();
        foreach (ICommand command in placeholder) // <---- Access dictionary here
        {
            commandsStr.AppendLine(command.ToString());
        }
    }

    public void Execute(object parameter)
    {
        var cmdInfo = parameter as CommandInfo;

        var info = new CommandResult
        {
            Message = cmdInfo.Message,
            Text = commandsStr.ToString(),
            SendType = SendType.Text
        };

        Completed?.Invoke(this, info);
    }

    public override string ToString()
    {
        return $"*{Name}* - {Description}";
    }
}

find patterns in digraphs

someone can help me? I'm trying to write simple code in java to find a patterns ( understood as recurrent sequence of elements in a superstructure) in digraphs (DAG) random generated. I know for example the K-recurring substring to identify pattern but the are another known techniques?

thank you!

mercredi 30 janvier 2019

Storing templated objects in a vector (Storing Class

There is a templated class, let it be

template<typename T> class A { std::vector<T> data; };

The problem I am facing here is, users can create several types of this class, but I need to track them, best case is I have a reference of these objets in another vector, but that would not work since all types are different. Can you recommend a good design pattern which can encapsulate this.

I can store pointers and then typecast it, but its not elegant.

Microservices client acknowledgement and Event Sourcing

Scenario

I am building courier service system using Microservices. I am not sure of few things and here is my Scenario

  1. Booking API - This is where customer Place order
  2. Payment API - This is where we process the payment against booking
  3. Notification API - There service is responsible for sending the notification after everything is completed.

The system is using event-driven Architecture. When customer places booking order , i commit local transaction in booking API and publish event. Payment API and notification API are subscribed to their respective event.

My Questions is

How do we acknowledge the client ? When customer places booking order i commit local transaction and publish event but i need to wait for Payment and Notification service to acknowledge me back via events when they are done. After publishing the event my booking service can't block the call and goes back to the client (front end). How does my client app will have to check the status of transaction or it would know that transaction is completed? Does it poll every couple of seconds ?

That's was best case scenario . But since this is distributed transaction and any service can go down and won't be able to acknowledge back . In that case how do my client (front end) would know since it will keep on waiting. I am considering saga for distributed transactions.

What's the best way to achieve all of this ?

Event Sourcing

I want to implement Event sourcing to track the complete track of the booking order. Does i have to implement this in my booking API with event store ? Or event store are shared between services since i am supposed to catch all the events from different services . What's the best way to implement this ?

Many Thanks,

Ideal way to design pages in react? - ReactJS

I know this is a subjective question but After rigorous searching on google, I am not still satisfied with the design of pages for a website like facebook in react. What should be the design principle for making pages?
Should it be the page component(that is aware of API calls and concerned with how things work)for all children components and pass data down directly to the child components?

SMART PAGE CONTAINER COMPONENT
    |
    |data
    |
    v
DUMB UI COMPONENT like COMMENTS, USER POST, USER ACTIVITY etc. 

Should it be the page component that is only concerned with the layout of the other SMART CONTAINER COMPONENTS(that are individually aware of API calls and concerned with how things work) and pass data down to their respective dumb child components?

PAGE CONTAINER
    |
    |layout
    |
    v
SMART CONTAINER COMPONENT like COMMENTS CONTAINER, USER ACTIVITY CONTAINER, USER POST CONTAINER etc.
    |
    |data
    |
    |
    v
DUMB UI COMPONENT like COMMENTS, USER ACTIVITY, USER DETAIL etc. 

If it can't be described in answer please provide some reading links for the same

Java prototype clone is not working as expected?

public abstract class SwimmersPrototype implements Cloneable {
    public SwimmersPrototype clone() throws CloneNotSupportedException{
        return (SwimmersPrototype)super.clone();
    }
}

SwimmersPrototype.java

public class Swimmers extends SwimmersPrototype{
    List<Swimmer> swimmers;
    SortStrategy sortStrategy;

    public Swimmers() {
        swimmers = new ArrayList();
    }

    public List<Swimmer> sort() {
        return sortStrategy.sort(swimmers);
    }

    @Override
    public SwimmersPrototype clone() throws CloneNotSupportedException{
        SwimmersPrototype swp = (Swimmers)super.clone();
        return swp;
    }
}

Here i want to clone an object of this class, Swimmers.

public class Swim extends javax.swing.JFrame {
    Swimmers swimmers;
    Swimmers swimmersCopy;
    /**
     * Creates new form Swim
     */
    public Swim() {
        initComponents();
        swimmers = new Swimmers();
        fillSwimmers();
        fillTable(swimmers.getSwimmers());
        jTableListener();

        try {
            swimmersCopy = (Swimmers)swimmers.clone();

        } catch (CloneNotSupportedException ex) {
            Logger.getLogger(Swim.class.getName()).log(Level.SEVERE, null, ex);
        }
    }
}

After calling sort, that change swimmers list of the original class, the copy object, swimmersCopy is also changed.

Here I'm just displaying swimmers list of original object in a table, I can sort by a property on it, but whenever default sort button is clicked i want to list swimmers by the default order that they inserted before? But applying sort, changes the swimmers list of the cloned object too?

Can I use a generic return type without having to downcast?

I have 2 different types of credential objects in my code.

What I'm trying to do is use a generic function to construct and return the correct object based on Object.TYPE

So essentially I want to change the return type and the construction based on whatever condition.

My code seems to be working but in my implementation I need to use a forced downcast.

I also had to create a "dummy protocol" for my 2 different credentials which also seems "wrong"

This makes me suspicious that Im going about it the wrong way.

How can I do this without downcasting?

public protocol C {    
}

// Generic Creation method

public enum Credentials {
    case CredentialsIA(apiKey: String, apiSecret: String)
    case CredentialsO(username: String, secret: String, ipsName: String)
    func crendential<T:C>( type: T.Type) -> T {
        switch self {
        case .CredentialsIA(let apiKey, let apiSecret):
            return IACredentials(kAPIKey: apiKey, kAPISecret: apiSecret) as! T
        case .CredentialsO(let username, let secret, let ipsName):
              return OCredential(kUsername: username, kAPIKey: secret, kIPSName: ipsName) as! T
        }
    }
}

Credential Types

public struct IACredentials: C {
    public let kAPIKey: String
    public let kAPISecret: String
    public init(kAPIKey: String, kAPISecret: String) {
        self.kAPIKey = kAPIKey
        self.kAPISecret = kAPISecret
    }
}
public struct OCredential: C {
    public let kUsername: String
    public let kAPIKey: String
    public let kIPSName: String
    public init(kUsername: String, kAPIKey: String, kIPSName: String ) {
        self.kUsername = kUsername
        self.kAPIKey = kAPIKey
        self.kIPSName = kIPSName
    }
}

Instantiation

let credentialsA: Credentials = Credentials.CredentialsIA(apiKey: kAPIKey, apiSecret: kAPISecret)

let credentialsB : Credentials = Credentials.MIPCredentialsOriient(username: "sds", secret: "sdsd", ipsName: "sssd")

Usage after init

 let credential:IACredentials = credentialsA.crendential(type: IACredentials.self)

Replacing if else statement with any design pattern or better approach

This code doesn't look clean and this if condition can grow

public int VisitMonth(int months) { int visit = 0;

        if (months <= 1)
        {
            visit = 1;
        }
        else if (months <= 2)
        {
            visit = 2;
        }
        else if (months <= 4)
        {
            visit = 3;
        }
        else if (months <= 6)
        {
            visit = 4;
        }
        else if (months <= 9)
        {
            visit = 5;
        }
        else if (months <= 12)
        {
            visit = 6;
        }
        else if (months <= 15)
        {
            visit = 7;
        }
        else if (months <= 18)
        {
            visit = 8;
        }
        else if (months <= 24)
        {
            visit = 9;
        }
        else if (months <= 30)
        {
            visit = 10;
        }
        else if (months <= 36)
        {
            visit = 11;
        }
        else if (months <= 48)
        {
            visit = 12;
        }
        else if (months <= 60)
        {
            visit = 13;
        }
        else
        {
            visit = 14;
        }
        return visit;
    }

Is their any better solution to this problem? sadly that function isn't linear so it's not easy to code that in mathematical way

How to implement Factory Pattern for components in a React App?

Im currently using React in my company for building our main Software product... The development of the app was started a year ago, and we don't expected that our app growed so much like it does. Now we are dealing with some kind of problems that could have been avoided if we had done a good architecture design from the beginning .

For summarize, one of the most central problems that we have is the code duplication... and the large amount of "import" statements with relative routes in the top of each new component that we make...

I would like to know if is recommended for solve this kind of problems use the Factory Pattern for reusing the React components and how to successfuly implement it?

Thanks in advance

passing a new value through multiple layers in legacy code

I have a monolith backend application. I have a client layer (to call a second service) which lies after several layers of business logic, lets say 3-4 layers of services and other classes. Its in java 6. I have a new requirement to forward a string value to that layer from my controller layer with minimal modification to the middle tier layers.

What can be possible good ways?

  1. I know of one -ThreadLocal. Is ThreadLocal safe to use in java 6 if i use it.
  2. Are there other design patterns that I can use in this scenario.

I certainly can't change contracts for all middle layers now.

mardi 29 janvier 2019

optimal method of searching for users for sending reminders via push notifications

I have a use case where I need to remind my app users (both android & ios) each day
for certain activities they have upcoming or which are overdue. The timings of these activities have been defined by users and can change anytime.

Currently I run a node script which keeps scanning my mongoDb database and selects the eligible users and sends the notifications every 15 minutes. Since there are multiple activities and each scanning function takes a bit of time to execute the efficiency of the script is low which keeps on getting worse as my user collections get larger.

Is there a better way than keep scanning the mongo database every 15 minutes?.

solutions tried:

  1. Indexing. It isn't helping much in this case as we already have mutiple indices and the queries being used cover almost all the user fields.
  2. Optimizing the selection query

How to map "real-world" processes to classes in OOP?

I tried to search SO and Google about this, but I didnt find anything really relevant.

When we are talking about OOP principles of design and programming we are using objects like cars, peoples (employees and clients) and ofcourse shapes (square and triangular).

But what about processes? How to model it? For example, I have system that processes electronic documents from other systems, makes correlations and all interoperability stuff. It's obvious to create classes for electronic documents. But what about system itself? How should I model it? Like a single big class (with name EDProcessing for example) with properties for db-connections (or EF objects) and different electronic documents? Or as static class (module) with methods that create db-objects every time they called?

Another example is the system that watching for real-world process like fueling and make all equations and data-processing for it. How should I define it?

how to create html design show in image using css?

demo image

  • i want to create html design something like that show in image
  • i want to use this design for generate dynamic PDF background

What is the best OOP solution of my problem?

For a good while now, Im trying to structure my code better and focus on using OOP concepts more and more in my code .

I have a simple question about the following scenario and how it is solved the best in the view of design pattern.

I have a game, in which a player can rob a shop. The shop is represented by the "Shop" object and the robbery is represented by the "RobEvent". And I have a "Spawner" object, which handles the spawning of the securities, when someone attempts to rob a shop.

My central problem is, that I have the feeling, that the RobEvent object has too much information and functionality described below and that I could split information and functionality in more objects and for this I need the help of you!

public class Main {

public static void main(String[] args)
{

}

public class Shop {

    private String name;
    private Location location;
    private boolean isBeingRobbed = false;

    /*
     * Here one of the problems, should the shop have the 
     * data of the npcs, which will appear
     * in the shop when the player attempts to rob it.
     * Should it have methods to place "spawn" positions of 
     * the securities, the type, the amount etc.
     * and store it here? 
     * 
     */

    public Shop(String name, Location location){
        this.name = name;
        this.location = location;
    }

    public boolean isBeingRobbed(){
        return isBeingRobbed;
    }

    protected void setBeingRobbed(boolean bool){
        this.isBeingRobbed = bool;
    }
}

public class RobEvent extends Looper {

    private Shop shop;

    RobEvent(Shop shop){
        this.shop = shop;
    }

    public void start(){
        shop.setBeingRobbed(true);
    }

    @Override
    protected void logic(){
    /*
     * Big chunk of game logic
     * Spawning the securities, checking if they 
     * all appeared(they got a delay of few seconds each),
     * check if he ran away before everything 
     * spawned, check if he killed all, check if all appeared
     */
    }

    private void completed(){
        shop.setBeingRobbed(false);
    }
}

public class Spawner {


    /* not important things
     * 
     * just has a method to 
     * handle the spawn of a security 
     */     

    public void spawn(NPC npc){
        /*
         * spawn the npc aka security
         */
    }

}

}

My biggest problem is, that the logic() method gets really big. It is a method, which gets looped every second by the super class.

More detail: - The RobEvent has to know if it is currently spawning securities and do specific things, - it has to check if all got spawned and do specific things, - it has to check if the player ran away before it was completed and do specific things, - it has to check if the player killed all and do specific things etc.

Most annoying is keeping track of the spawned securities, because if he runs away, they all have to be despawned. I have the feeling that this is too much information in this object and that I could for example maybe split the tracking of the spawned securities in a seperate object and just do something like "tracker.despawn" when the RaidEvent has a specific state.

EDIT: Code is jut a really simplefication of the actual code.

I am confused between Unit of work pattern and Factory Pattern

factory Pattern Source https://en.wikipedia.org/wiki/Factory_method_pattern

In class-based programming, the factory method pattern is a creational pattern that uses factory methods to deal with the problem of creating objects without having to specify the exact class of the object that will be created. This is done by creating objects by calling a factory method—either specified in an interface and implemented by child classes, or implemented in a base class and optionally overridden by derived classes—rather than by calling a constructor.

My question is that unit of work pattern, and factory pattern is the same pattern with a different name I am not sure

What's the functional design pattern for a discriminated union with protected creation, and public read access?

Discriminated unions are typically used as data holders, but occasionally I find myself having the need to prevent creation of a discriminated union, but to still be able to pattern match over it using familiar syntax.

For the sake of argument, let's say we represent a URI with a string, but I want to create a type that has a guaranteed validated URI (i.e., it's valid per the RFC). Just using Some/None doesn't work here, as I still want to access any invalid string as well. Also, I like a mild refactoring experience.

I can solve this problem as follows, which I think shows what I intend to do (leaving out the error cases for simplicity):

[<AutoOpen>]
module VerifiedUriModule =
    module VerifiedUri =
        type VerifiedUri = 
            private 
            | VerifiedUri of string

        let Create uri = VerifiedUri uri  // validation and error cases go here

        let Get (VerifiedUri uri) = uri

    let (|VerifiedUri|) x =
        VerifiedUri.Get x

The extra level with the AutoOpen is simply to allow unqualified access of using the active recognizer.

I may end up using a typical Result type, but I was wondering whether this is a typical coding practice, or whether whenever I find myself doing something like this, I should hear a voice in my head saying "rollback, rollback!", because I'm violating classical functional programming principles (am I?).

I realize this is a case of information hiding and it looks much like mimicking OO class behaviors with data. What would be the typical F#'ish approach be (apart from creating a class with a private ctor)?

Factory pattern for multiple nested dependencies?

I understand the factory pattern on a simple form but not much if the class requires multiple nested dependencies. E.g.,

$cfg = new Cfg();
$cfg->setA('a');
$cfg->setB('b');

$qux = new Qux('x');    
$bar = new Bar($cfg, $qux);    
$foo = new Foo($cfg, $bar);

In the above example, how do you properly make a factory pattern for class Foo so that when you run $factory->build(); you get an instance of Foo with all its dependencies?

it is good practices to use Strategy/Factory pattern in application, having one end-point ? Even the request and response are different

Hope you guys doing well.

I am currently working on Rest Application and I kind of need a suggestion. So I have multiple legacy Java applications(5-6) and currently writing the new application to handle all those as a integrated service layer.

So the structure is all old applications will make a individual REST call to new Application with request payload and will get the response back.

To addition to that, all the Requests and Responses payloads are not same and using different attributes.

and as per my lead, he said we need to use Strategy pattern for this new application so that there will be only one end point. My Question is: In one Model(class; getters & setters) I have 40-50 attribute so Json Payload is already too big and some of them are lists and as for now I need to make Models class for other 4 applications which is having other 40-50 attributes, but to achieve the goal I need to add all those into One Model Class for following the Strategy pattern is that good practices?

Instead of this we can make a different end-point to specific request and response, in this way Json Payload will be easy for refactoring and to handle for future perspective too?

How to select a design pattern which solves a given problem?

Consider a database of a large number of swimmers in a league or statewide organization. Each swimmers swims several strokes and distances throughout a season. The best times for swimmers are tabulated by age group. Within a single four-mount season, many swimmers will have birthdays and therefore move into anew age groups.

1, write a program which displays list of swimmers who did best in their age groups in a given season.

I'm doing my assignment on Design Pattern, how to know which design pattern i use?

Which OO design patterns are relevant for data storage for big suites of test cases?

When creating a test suite with very different tests and many independent modules to test, what is a good structure for the test data?

I am working in a project where we develop automated tests of an ERP system and we are having a discussion on the team about how to structure the data that will be used for testing.

We test things like creating a new customer, new order, new products, new supplier, verify a delivery and so on. In most cases these events take place in more or less unrelated components of the system (and in some cases even external systems). Of course, there are many different kinds of customers, products (e.g., products that are combined), orders (e.g., return orders), delivery (e.g., pickup at the company, delivery to the customer)

The team leader wants one big tree based text file with one branch for customer, one for products etc. You should then, if you have a test case X that needs one customer and one product, refer from the customer to the product. Currently, we reuse these "leafs" so if you in another test case Y needs the same product as in X you use the same product.

IMO this is a recipe for a disaster. This text file is gonna be HUGE and, as a consequence, impossible to overview and people are gonna change "objects" to make them fit their special need without consideration of how it affects other people using the same object.

Therefore I am looking for design patterns (or other ideas) for how to organize test data.

Typically the code is organized into one helper class per component that contains functions frequently used in that component and then small classes that calls functions in this helper class as well as contains some a couple of "inner methods" only needed for that specific test case.

A typical test case needs 10-20 "properties" for each element it uses (if a test case concerns one customer and one product there are 10-20 strings that describes the customer and 10-20 strings that describes the product).

I think I am looking for arguments for a system with decentralized test data. Basically I think I think there should be one physical file for each test case with the properties needed in that specific test case. There will very likely be a lot of duplicate data (e.g., we will probably use the same customer with the same address details for many test cases).

A disadvantage with such a "pattern" is that if you need to change the customer number you will need to do it in hundreds of physical files (but on the other hand, if this need ever arises, I think it would be better to change the data in the database and leave these property files as is). OTOH, an advantage with such a solution is that the tests are self contained. Everything you need is in one or two directories and if you modify something there it only risks breaking one test and you know exactly which test that is a risk. No inter-dependencies that is confusing and hard to track.

what is the best practice to implement an update ability (partial update may be) [on hold]

I want to develop my desktop application in a way that makes me able to provide update packages like visual studio does; in this way user shouldn't download the whole application and install it again to update just a bit of it.

to make it clear, I need some advice to guide me to the right direction, for example:

  • should I separate my application in to a lot of projects (.dll) to provide a partial update or what?
  • is there a specific design pattern or library or what ever that help me not to start from scratch?

I use C#, Wpf, Prism, and application has no database, it's just about some processing and presenting result to the user.

Validation of the form (three first characters different from the space)

I do not know how to enter the validation in the folmula. I want the first 3 characters to be different from the space (sign = "").Example:surname is "xyz"- error. surname is "aaa aaaaa" - correctly. surname is"aa aaaaaa" - error.My code with which I tried.

`<input type="text" name="surname" class="input-medium flat has- 
placeholder" required="required" id="surname" data-validation- 
rule="minLength" data-validation-value="2" pattern="[A-Za-z]{3,25}+[" "]+ 
[A-Za-z]" aria-required="true" placeholder="surname">`

Create a custom pattern in the Latex package "tikz"

I am working with "tikz" presently and found out is is possible to to fill areas with certain patterns, see p. 217 on https://www.bu.edu/math/files/2013/08/tikzpgfmanual.pdf

Now my question is: Is it possible to implement custom patterns? For example, i need to fill an area with the hatching of concrete, as you can see here: http://www.sema-soft.com/de/forum/files/schraff_886.jpg

Anyone of you tried that before?

Thanks for your help

lundi 28 janvier 2019

Is there a name for this C++ idiom in which a type vends a wrapper that expands its interface?

I have what is essentially a family of types that share a few common properties with each other. I could actually model this relationship fairly decently with C++ class inheritance. However, I also need to pass and store these objects all around my code, and keeping every instance as a polymorphic heap reference is a pain.

Here's the initial situation:

Enumeration type with values for all "subclasses":

enum class PhoneType {
    landline,
    cell
}

Type that's stored and passed around a lot:

class Phone {
public:
    static Phone landline(PhoneNumber number) {
        return Phone(PhoneType::landline, number);
    }
    static Phone cell(PhoneNumber number, optional<AppList> apps) {
        return Phone(PhoneType::cell, number, apps)
    }

    PhoneType type() { return _type; }
    PhoneNumber number() { return _number; }

private:
    PhoneType _type;
    PhoneNumber _number;
    optional<AppList> _apps;

    Phone(PhoneType type, PhoneNumber number) :
        _type(type), _number(number)
    {}
    Phone(PhoneType type, PhoneNumber number, optional<AppList> apps) :
        _type(type), _number(number), _apps(apps)
    {}
};

PhoneType enumerates different possible types of Phones, which all have a PhoneNumber and may or may not have an AppList.

The issue is how to go about giving the outside world access to a phone's AppList once the caller is sure that it's dealing with a cell phone. Note that I don't want to simply vend the optional type, as this pushes a lot of error checking code into the calling function(s), which is not what I want (in the majority of cases, the caller knows the PhoneType of the Phone it's being passed without even having to check, so vending an optional<> is just unnecessary pain).

I could just add the extra accessors to the Phone class, and document that they throw/crash/etc. if the receiving Phone doesn't represent a cell phone. However, in the real code there are many more such attributes that would require more accessors, and each of these accessors is not at all clear about its preconditions when read at a call site.

Long story short, after a bit of consideration I ended up with this idiom:

Before the definition of Phone:

class CheckedPhoneRef {
public:
    CheckedPhoneRef() = delete;

    Phone& phone() const { return * _phone; }

protected:
    Phone* _phone;
    CheckedPhoneRef(Phone* phone) : _phone(phone) {}

private:
    friend class Phone;
};
class LandlineCheckedPhoneRef : public CheckedPhoneRef {
public:
    using CheckedPhoneRef::CheckedPhoneRef;
};
class CellCheckedPhoneRef : public CheckedPhoneRef {
public:
    using CheckedPhoneRef::CheckedPhoneRef;
    AppList apps() const; // accesses private member of referenced Phone
};

In Phone's public section:

// (Comment above declarations in header):
// These assert that this Phone is of the correct PhoneType.
LandlineCheckedPhoneRef landline_ref() {
    assert(_type == PhoneType::landline);
    return LandlineCheckedPhoneRef(this);
}
CellCheckedPhoneRef cell_ref() {
    assert(_type == PhoneType::cell);
    return CellCheckedPhoneRef(this);
}
// (Plus const versions)

In Phone's private section:

friend LandlineCheckedPhoneRef;
friend CellCheckedPhoneRef;

Now it is rather clear what assumptions are being made at any given call site: if I say phone.cell_ref() then I'm clearly asserting that this phone is a cell phone, e.g.,

void call(Phone& phone) {
    if (phone.type() == PhoneType::cell) {
        if (has_facetime(phone.cell_ref())) ...
    } else {
        ...
    }
}

bool has_facetime(CellCheckedPhoneRef cell_phone) {
    return cell_phone.apps() ...
}

(Dumb example, but you get the point. I know I could use a visitation pattern here, but the real code isn't quite like this.)

I like this design for what I'm doing. Problem is, I don't quite know what to name the vended wrapper types. I'm currently using the pattern of LandlinePhoneLens, CellPhoneLens, etc., but I know that "lens" already has other meaning in programming. Perhaps this isn't a big issue, but I wanted to ask to be sure I'm not missing a more established naming scheme.

Is there an established name for this pattern/idiom in which a type vends a wrapper that expands its interface?

How to design internal methods access scope?

We have a small lightweight framework with around 20 classes, used by 50+ developers and semi-large code base. To keep the framework small, we've avoided creating too many interfaces, abstract classes, etc. This is a trade-off to speed up adaptation by new developers as well as keep code complexity low.

So we do not utilize internal/external interfaces or heavy use of factory classes. We rely on a few classes with public/private methods to define scope. However sometimes methods have to be public but only be accessible to the framework and not the developer.

Example:

public class Logger
    public boolean isDebugEnabled() {...}
    public void enableDebug() {...}

enableDebug is an "internal" framework method and is documented with "Do not use - Internal class". The method cannot be private nor at package scope due to framework structure.

Once in a while a developer will miss the javadoc and invoke an internal method which can produce unexpected results at runtime.

Example:

if (!Logger.isDebugEnabled) {
    Logger.enableDebug(); // screw the javadoc - i'm enabling debug logging
}

The framework team is thinking the best approach is to name them following a certain convention. This will not introduce compile-time safety, but decrease error probability.

Example:

public void enableDebugInternal() 

is more precise than

/**
* Internal method - do not use
*/
public void enableDebug() 

Can you recommend a better approach ? Preferably something that provides compile-time safety

Design - Alternative to Storing Executable Code in SQL

I'm working on a little browser game, and I've hit a design problem and the only solutions I can think of are bad.

Its a typical web-app - Angular2/HTML/JS front end, Java server with PostgreSQL DB, content hosted on nginx and Tomcat

Users can interact with various NPCs who all have custom behavior. I've genericized this logic, NPCs are stored in the DB as config rows, ID: 1 Name: Sam The NPC ImgURL: "http://bit.ly/2COdmca"

Accessing mygame.com/npc/1 issues a GET in JS to the backend API in Java to get that row from the DB and those values are bound and displayed. Storing these as config rows in the DB allows me to add new NPCs or edit existing ones without a redeploy of the server or the front end code.

So far so standard. However, I want Sam the NPC to be friendly, and visiting him increases the player's money. Another NPC, Steve, should be hostile, and remove money or items from the players inventory. Bob the NPC can, sometimes, unlock a quest for players.

This is where I'm stuck: Each NPC having totally different and arbitrary behavior means I need executable code per NPC.

My two options, as I see them, are both bad but in different ways.

  1. Each NPC gets his own Java class and is a first class entity in the server logic. All NPCs implement an interact() method and adding or changing NPCs requires a code push.

  2. Each NPC gets a new column in the DB with executable JS in, to be run via a script engine in Java. This is slightly dangerous, but also just a hassle. Writing JS that can invoke DB functions by interacting with the Java codebase and then saving it as a string in a database is kludgy.

I'm currently using option 2, but not too far in and wondering if there's an accepted way to handle something like this that's better.

Is it a good idea to use repository pattern in React application?

From what I've seen so far, the Repository pattern seems to be a great thing and is widely used in application logic in C# and Typescript environments. As far as I understand it, it's used for when we have a lot of data manipulation functionality and it's a good idea to abstract those functionalities, so that we avoid repeating the same logic for manipulating data throughout our app and also abstract the specific database communication, so that we can easily switch if needed.

Does it fit with the React ecosystem though and why does it seem that no one uses it in Javascript in general?

What would be more pythonic solution to this problem?

I have following structure for class.

class foo(object):
    def __class__(self,param1):
        pass
class bar(object):
    def __class__(self,param1,param2):
        pass

I have many classes of this type. And i am using this callable class as follows.

classes = [foo(), bar()]
for C in classes:
    res = C(param1) 
 '''here i want to put condition if class takes 1 argumnet just pass 1  
 parameter otherwise pass two.'''

I have think of one pattern like this.

classes = [foo(), bar()]
for C in classes:
    if C.__class__.__name__ in ['bar']:  
        res = C(param1, param2)
    else:
        res = C(param2)

but in above solution have to maintain list of class which takes two arguments and as i will add more class to file this will become messy.

I dont know whether this is correct(pythonic) way to do it.

  • On more idea i have in mind is to check how many argument that class is taking. If its 2 then pass an additional argument otherwise pass 1 argument.
  • Few things about this:
    • There are only two type of classes in my usecase one with 1 argument and one with 2.
    • Both class takes first argument same so params1 in both case is same argument i am passing. in case of class with two required parameter i am passing additional argument(params2) containing some data. Ps : Any help or new idea for this problem are appretiated.

Pattern to extend an enum in C++

I have a base class that defines some common states shared by all subclasses and subclasses may be able to add more specific states. As it is not possible to extend an enum in C++, i have this code :

class AbstractMachine
{
public:
    enum State {
        AbstractMachineState1,
        AbstractMachineState2,
        AbstractMachineState3
    };
    virtual enum State state() const = 0;
    // ..
};

class Machine : public AbstractMachine
{
public:
    // more specific states related to Machine
    enum MachineState {
        MachineState1,
        MachineState2,
        MachineState3
    };
    virtual enum State state() const = 0;
    virtual enum MachineState machineState() const = 0;
    // ..
};

class SpecificMachine : public Machine
{
public:
    // more specific states related to SpecificMachine
    enum SpecificMachineState {
        SpecificMachineState1,
        SpecificMachineState2,
        SpecificMachineState3
    };
    SpecificMachine();
    virtual enum State state() const;
    virtual enum MachineState machineState() const;
    virtual enum SpecificMachineState specificMachineState() const;
    // ..
};

The client code should be able to handle 3 levels of abstraction but then, to get the state of any SpecificMachine i need to call :

state()
machineState()
specificMachineState()

How is it possible to have the state of any SpecificMachine within one call to state() ?

Adding all states in the AbstractMachine enum would work but i don't like the idea to modify the base class every time we need to add a new SpecificMachine.

Thank you.

dimanche 27 janvier 2019

Real time message push to embedded devices

I'm designing firmware for the first time, and I've come across a pattern that I'm not sure how to solve. I need to be able to push arbitrary messages to embedded devices. The contents can be anything from octet stream to json. The embedded devices are not directly accessible over the network, however they can call out to the internet.

The obvious solution would be polling. But I'd like to use a push mechanism for more real time communication if possible.

Is there a scaleable way, for example, to open a socket from the client side (embedded device), and then hold it open to allow message pushes from the server side (cloud)?

Scala: how to avoid passing the same object instance everywhere in the code

I have a complex project which reads configurations from a DB through the object ConfigAccessor which implements two basic APIs: getConfig(name: String) and storeConfig(c: Config).

Due to how the project is currently designed, almost every component needs to use the ConfigAccessor to talk with the DB. Thus, being this component an object it is easy to just import it and call its static methods.

Now I am trying to build some unit tests for the project in which the configurations are stored in a in-memory hashMap. So, first of all I decoupled the config accessor logic from its storage (using the cake pattern). In this way I can define my own ConfigDbComponent while testing

class ConfigAccessor {
   this: ConfigDbComponent => 
   ...

The "problem" is that now ConfigAccessor is a class, which means I have to instantiate it at the beginning of my application and pass it everywhere to whoever needs it. The first way I can think of for passing this instance around would be through other components constructors. This would become quite verbose (adding a parameter to every constructor in the project).

What do you suggest me to do? Is there a way to use some design pattern to overcome this verbosity or some external mocking library would be more suitable for this?

Abstract factory design pattern and generics - Java

It's the first time I'm using this design pattern and I'm having some difficulties. Taking this image as reference:

enter image description here

I have two AbstractProduct that I would like to create a factory for, since they come in different "families". One of the products is a collection of the other.

public abstract class Frame{
    ...
}

public abstract class FrameMap<F extends Frame>{
    protected TreeMap<Integer, F> map;
    ...
}

Taking one family as an example (the one for App1) these are the concrete Product:

public class App1Frame extends Frame{
    ...
}

public class App1FrameMap extends FrameMap<App1Frame>{
    ...
}

Then I have created the AbstractFactory:

public abstract class ApplicationFactory{
    //Frame factory methods
    public abstract Frame makeFrame();

    //FrameMap factory methods
    public abstract FrameMap<? extends Frame> makeFrameMap();
}

And the ConcreteFactory for App1:

public class App1Factory extends ApplicationFactory{
    //Frame factory methods
    public Frame makeFrame(){
        return new App1Frame();
    }

    //FrameMap factory methods
    public FrameMap<App1Frame> makeFrameMap(){
        return new App1FrameMap();
    }
}

All of this compiles, but I'm not liking it very much because my Client cannot do something like:

ApplicationFactory factory = new App1Factory();
FrameMap<Frame> frameMap = factory.makeFrameMap(); //This doesn't compile!

which is, at least conceptually, the goal of the pattern, i.e. letting the client only use the abstract classes. In order to make it work, I have to do something like this:

App1Factory factory = new App1Factory();
FrameMap<App1Frame> frameMap = factory.makeFrameMap(); //This compiles!

which seems going against the purpose of using the design pattern.

Do you know any better way of implementing this pattern in a situation like mine, i.e. using generics in the AbstractProduct, in order to let the Client only use the abstract classes without knowing the underlying implementation?

Refactoring code with a good design pattern

Looking for a better design pattern to send messages between clients and server

Requirements:

  • Server S1 and S2 are different on-prem servers
  • Device D1 and D2 are different devices
  • A Device sends many messages in real-time to MessageClient
  • Each message contains a Name and Value fields which can be different between the devices
  • Once a message received to MessageClient, it should dispatch it to the MessageServer via REST API

enter image description here

// main program (will eventually be a dll)

namespace IoT.MessageProxy
{
    class Program
    {
        static void Main(string[] args)
        {
            // initialize Client Context
            MessageClient messageClient = new MessageClient() { DeviceType = DeviceType.Booster, DeviceId = "551221" };

            // invoke a single message
            messageClient.Dispatch(new Message() { Name = "temperature", Value = "40" });

            // invoke multiple messages
            messageClient.Dispatch(new List<Message>()
            {
                new Message() {Name = "temperature", Value = "42"},
                new Message() {Name = "humidity", Value = "76"},
                new Message() {Name = "pressure", Value = "5003"}
            });
        }
    }
}

// MeesageClient.cs

namespace IoT.MessageProxy
{
    public class MessageClient
    {
        public DeviceType DeviceType { get; set; }
        public string DeviceId { get; set; }

        public void Dispatch(Message message)
        {
            // Create a JSON file of as example:
            //
            // Message {
            //     "DeviceType": "Compressor",
            //     "DevieID": "3885",
            //     "Metrics": { "Name": "temperature", "Value": "42" }
            //}
            //
            // Dispatch the JSON to server to the server
        }

        public void Dispatch(List<Message> messages)
        {
            // Create a JSON file of as example:
            //
            // Message {
            //     "DeviceType": "Compressor",
            //     "DevieID": "3885",
            //     "Metrics":
            //       [
            //          { "Name": "temperature", "Value": "42" },
            //          { "Name": "humidity", "Value": "78" }
            //       ]
            //}
            //
            // Dispatch the JSON to server to the server
        }
    }

    public class Message
    {
        public string Name { get; set; }
        public string Value { get; set; }
    }

    public enum DeviceType
    {
        Compressor,
        Booster
    }
}

Any recommendation for a design pattern?

what is the best practice to implement an update ability (partial update may be) for desktop application

I want to develop my desktop application in a way that makes me able to provide update packages like visual studio does; in this way user shouldn't download the whole application and install it again to update just a bit of it.

and if I want to provide some feature packages (like visual studio does again) and even plug-ins what should I do in my design?

by the way, for extra information I use C#, Wpf, Prism, and application has no database, it's just about some processing and presenting result to the user.

Passing an abstract class as parameter in Room Database builder

I have seen this implementation in Room database.

There is an abstract class AppDatabase -

@Database(entities = {Task.class}, version = 1) 
public abstract class AppDatabase extends RoomDatabase {
    public abstract TaskDao taskDao();
}

But when you create an Object of this AppDatabase class, you do something like this -

AppDatabase appDatabase =  
Room.databaseBuilder(context, AppDatabase.class, "something").build();

My questions are -

  1. How can you pass an Abstract class directly like this without the Override methods defined ?

    Like, normally we don't use and pass abstract classes like that, if you do something like this in IDE, it throws an error.

  2. Which design pattern is this and how Room handles this type of things internally ?

samedi 26 janvier 2019

Definition of a variable load and its permanent use

I have to force these variables to rebuild on every one I want to use, which makes me hard. I need to create a class to define these variables and use them in the entire program. . How can i do that ?????

string RootFolderName = "Uplaod";
string ProductPictureFolder = "ProductPictureFolder";
string ProductMainPictureFolder = "ProductMainPicture";
string WebRootPath = _hostingEnvironment.WebRootPath;
string RootPath = Path.Combine(WebRootPath, RootFolderName);
string ProductPicturePath = Path.Combine(WebRootPath, RootFolderName, ProductPictureFolder);
string ProductMainPicturePath = Path.Combine(WebRootPath, RootFolderName, ProductPictureFolder, ProductMainPictureFolder);
string newPath = Path.Combine(WebRootPath, ProductMainPicturePath);

What software design pattern we can think of while using "|"(pipe) in *nix

While working on *nix terminal, I was curious about what software design pattern we can think of while using operator "|" (Pipe).
e.g

netstat -anep | grep "8080" | wc

Design / Architecture for many instances OOP (or another) implementation

We want to write an API (Python Library) which provides information about few systems in our company. We really aren't sure what is the best OOP approach to implement what we want, so I hope you'll have an idea.

The API will expose a series of tests for each system. Each system will be presented as a Class (with properties and methods) and all systems will inherit from a base class (GenericSystem) which will contain basic, generic info regarding the system (I.E dateOfCreation, authors, systemType, name, technology, owner, etc.) Each system has many instances and each instance has a unique ID. Data about each system instance is stored in different databases, so the API will be a place where all users can find info regarding those systems at once. These are the requirements:

  1. We want each user to be able to create an instance of a system (SystemName Class for example) and to be able to get some info about it.

  2. We want each user to be able to create multiple instances of a system (or of GenericSystem) and to be able to get info about all of them at once. (It must be efficient. One query only, not one for each instance). So we thought that we may need to create MultipleSystemNames class which will implement all those plural-approach methods. This is the most challenging requirement, as it seems.

  3. We want that data will be populated and cached to the instances properties and methods. So if I create a SystemName instance and calls systemNameInstance.propertyName, it will run needed queries and populate the data into propertyName. Next time the user will call this property, the data will be immediately returned.

  4. Last one, a single system class approach must be preserved. Each system must be presented as a sole system. We can later create MultiSystem class if needed (For requirement 2) but at it's most basic form, each system must be represented singly (I hope you understand what I mean).

The second and the fourth (2,4) requirements are the ones that we really struggle to figure out. Should we use MultiSystemNames class for each class and also for GenericSystem (MultiGenericSystems)? We don't want to complicate the user and ourselves.

Do you know any OOP (or another) best practice clean and simplified way? Have we missed something? I'm sorry if I added some unnecessary information but I really wanted to give you a feel about how we want things to be.

If you've reach so far or not, thank you!

Mess class design

I have a class design that looks like this one:

enter image description here

When Main receives an item, properties of other items can change based on some rules. For example, if Item1 has a red color, item2.level must be 3. Sometimes a value can change properties of multiple items. Implementing all rules in Main class is possible but it's a mess code.

So, I have implemented the Aggregate class that include all items. When Main.setItem(item1) is executed, I update Aggregate with Aggregate.setItem1 and run Rules.updateAggregate that updates items of Aggregate according to all rules.

It works, but Rules class is very inefficient. Because it doesn't know which item has updated, it apply all rules all times. Also, updateAggregate method is very large and difficult to test.

Is there any better design?

classic computer science books and Python

I am sort of hoping that before this gets flagged as subjective a senior programmer would let me know if "Design Patterns..." (Gamma et al., "gang of four") and "Refactoring..." by Martin Fowler will help with becoming an advanced modern Python programmer. I'm assuming the answer is a big yes but I'm sort of new and self taught so I just want to be sure that these really old books aren't at times (or largely) off topic for pythonic code. It is very hard for me to know from where I am now. I'm reading Code Complete by McConnell right now and that is kind of old and not "about" Python... but it is definitely helpful with writing Python practice programs. So I'm sort of assuming the same is true for the two I'm asking about... but the two I'm asking about are even older.

Polling Datawarehouse Design

I really need your help. I am currently working on a BI project for a polling institute. We have surveys that we do all over the world and I have to create a data warehouse that collects all these polls and analyzes them. The difficulty I encounter in modeling my datawarehouse is that I have a hundred measures. I've heard of a modeling in which we put measures as a dimension and we have measures like QTD, YTD. Would anyone have an example of this type of modeling ???

Thanks for your help

Write once the variables in the program and reuse them in the entire program

Hello friends .

I need to do this in one of my classes to access the folder for photos in any method. I want to do these things in another class. I need to define and value these variables and use them in the whole program. How should I do that?

    string RootFolderName = "Uplaod";
    string ProductPictureFolder = "ProductPictureFolder";
    string ProductMainPictureFolder = "ProductMainPicture";
    string WebRootPath = _hostingEnvironment.WebRootPath;
    string RootPath = Path.Combine(WebRootPath, RootFolderName);
    string ProductPicturePath = Path.Combine(WebRootPath, RootFolderName, ProductPictureFolder);
    string ProductMainPicturePath = Path.Combine(WebRootPath, RootFolderName, ProductPictureFolder, ProductMainPictureFolder);
    string newPath = Path.Combine(WebRootPath, ProductMainPicturePath);

vendredi 25 janvier 2019

Spring Prototype Beans are ugly. Do we have alternatives?

We do use Spring and Lombok.

Option 1 - No prototype beans

@Component @RequiredArgsConstructor(onConstructor = @__(@Autowired))
public class Consumer {
  private final SomeDependency iDontNeed; // Consumer class doesn't need
  private final SomeDependency2 iDontNeed2;

  public void method() {
    new Processor("some random per request data", iDontNeed, iDontNeed2);
  }
....
@Value @RequiredArgsConstructor
public class Processor {
  private final String perRequestInputData;
  private final SomeDependency iReallyNeed;
  private final SomeDependency2 iReallyNeed2;
}


Option 2 - Prototype beans

@Component @RequiredArgsConstructor(onConstructor = @__(@Autowired))
public class Consumer {
  private final Supplier<Processor> processorSupplier;

  public void method() {
    Processor p = processorSupplier.get();
    p.initializeWith("some random per request data");
  }
....
@Component @Scope("prototype") 
@RequiredArgsConstructor(onConstructor = @__(@Autowired))
public class Processor {
  private final SomeDependency iReallyNeed;
  private final SomeDependency2 iReallyNeed2;

  private String perRequestInputData; //wish I was final
  private boolean initialized; //wish I was not needed

  public void initializeWith(String perRequestInputData) {
    Preconditions.checkState(!initialized);
    this.perRequestInputData = perRequestInputData
  }
}


Which options is the lesser evil and why? Please give some guidance on this.

How much view-agnostic is a ViewModel supposed to be in MVVM?

Let's imagine a very simple UI, where there's a list of checkboxes. When you click on any of them:

1) if it's not selected, it should create a workspace with this checkbox name (and more logic then is available in that workspace, but that's irrelevant to the question). The checkbox naturally then becomes selected;

2) If it's already selected, it should turn unselected and should destroy the associated workspace.

The straightaway form of implementing this is to have the View look at the state of the clicked checkbox and depending on being already selected or not do a viewModel.createWorkpace() or viewModel.destroyWorkspace(). But then that means that this logic is in the View -- I get the impression it'd be better to have it in the ViewModel.

I've read that the ViewModel for diverse reasons should not know the View. But one thing is not having a physical dependency to the View (an object reference, for instance) and another completely different is not even being aware that the View may have checkboxes, as in this example.

It gives me the impression that actually there's really not big of a point in making the View and ViewModel that much different, and in fact, the closer the ViewModel is to the View, the easier it is to bind data between the View and ViewModel.

How should I deal with this situation and why?

Thanks

Duplicate code refactoring in Java with patterns

This isn't dropwizard specific and more so on Java but here it goes.

So I have two resources in Dropwizard CustomerResource.java ApiResource.java In CustomerResource.java there is a createCustomer method which basically creates a new customer. Now the ApiResource.java will also be creating a new customer when a third party invokes a method inside of it. So this got me thinking about duplicate code and the best way to resolve this. I have few approaches in mind but first here are the classes for better clarity.

@Path("/internal")        
public class CustomerResource{

    private DBDao dbDao;
    private AnotherAPI api;

    //constructor for DI

    public Response Create(@internalAuth CustomerPojo customerPojo) {

    //logic to validate customerpojo
    //logic to ensure user isn't a duplicate
    //some other validation logic
    //finally user creation/saving to DB
    Return response.ok(200).build();
    }
}



    public class ApiResource{
    private DBDao dbDao;
    private AnotherAPI api;

    //constructor for DI
    @Path("/external")
    public Response Create(@ExternalAuth PartialCustomerPojo partialCustomerPojo) {

    //logic to validate PartialCustomerpojo
    //supplement partialCustomerPojo
    //logic to ensure user isn't a duplicate
    //some other validation logic
    //finally user creation/saving to DB
    Return response.ok(200).build();
    }
}

So two main differences are that how the endpoint is called (authentication) and the payload provided.

Some ways I thought about how to remove duplicate code.

Create a new concrete class that takes common from both and each of these method instantiate a new class like this.

    public class CommonClass{
    private DBDao dbDao;
    private AnotherAPI api;

    //constructor for DI

    public boolean Create (CommonPojo commonPojo) {

    //logic to validate customerPojo
    //logic to ensure user isn't a duplicate
    //some other validation logic
    //finally user creation/saving to DB
    Return response.ok(200).build();
    }
}

And now inside CustomerResource.java and ApiResource.java I simply do this.

CommonClass commonClass = new CommonClass(dbDao, api);
//create a new instance customerPojo or CommonPojo and call 

commonClass.create(customerPojo);

Does this sound like a good strategy? or are there any other best practice around it? And no these two methods can't be inside same class either. Any best practice will be appreciated. thank you.

What are the examples of Decorator design pattern in JDK?

I want to know where Decorator Design Pattern is being used in JDK. I think below methods of java.util.Collections class are coming under that category..

  • synchronizedList()
  • synchronizedMap()
  • synchronizedSet()
  • unmodifiableSet()
  • unmodifiableMap()
  • unmodifiableList()

Please let me know some other implementation and correct if I am wrong.

Undefined reference to class using Prototype Patterns

Hello i want to implement a base type of Prototype Patterns in order to, in my case, clone the 2 clsses

I tried implementing the copy constructor on the 2 child classes, and the clone on the children and in the main class

class Persona {
   public:
      Persona();
      virtual Persona* Clone() = 0;
}

class Studente : public Persona {
   protected:
    string facolta;
    string corso;

   public:
    Studente();
    Studente(const Studente& s) {
        facolta = s.facolta;
        corso = s.corso;
    }
    virtual Persona* Clone(){
        return new Studente(*this);
    }
 }

class Docente : public Persona {
  protected:
    string corsi;
  public:
    Docente();

    Docente(const Docente& d) {
        corsi = d.corsi;
    }
    virtual Persona* Clone(){
        return new Docente(*this);
    }    
}

I tried to remove all the Clone() and it works, i tried to declare in the classes the return new Studente, without the parameter this, but gives the same error. I see online some example and do that similar, for the copy constructor i insert all classes variables/variable.

Thank you

Add new methods to interface or cast the object?

We have an interface like this?

public interface ILicense
{
   bool IsTrial { get; }
   bool IsTrialLicense { get; }
}

public class StandardLicense : ILicense
{
  public bool IsTrial { get { return true; } }
  public bool IsTrialLicense { get { return true; } }
}

But now new requirement came for new License (the name is ZLicense) which has additional methods.

  • GenerateActivationKey()
  • GenerateDeactivationKey()

So I have two options:

  • Add two new methods to interface (and make an abstract class)

  • Cast the interface and use new two methods

Usage can be used like this:

if(ILicense is ZLicense)
{
  ZLicense license = ILicense as ZLicense
  .. can use new methods lile license.GetActivationKey()
}

What's best practise approach here?

Interface segregation principle application

I'm wondering if the Interface segregation principle applys to my codebase.

Here's some example code:

First Class:

public class EntityGroup {
    public List<Entity> tests;

    //returns true if the EntityGroup is valid
    public boolean validate() {
        for (Entity test : tests) {
            if (!test.validateFieldA() || !test.validateFieldB()) {
                return false;
            }
        }
        return true;
    }

}

Second Class:

public abstract class Entity {

    protected String fieldA;

    public abstract boolean validateFieldA();

    public abstract boolean validateFieldB();

}

Third Class:

public class EntityChild extends Entity {
    private String fieldB;


    @Override
    public boolean validateFieldA() {
        if (fieldA.equals("valid")) {
            return true;
        } else {
            return false;
        }
    }

    @Override
    public boolean validateFieldB() {
        if (fieldB.equals("valid")) {
            return true;
        } else {
            return false;
        }
    }
}

Fourth Class:

 public class EntityChild2 extends Entity {

    @Override
    public boolean validateFieldA() {
        if (fieldA.equals("valid")) {
            return true;
        } else {
            return false;
        }
    }

    @Override
    public boolean validateFieldB() {
        return true;
    }
}

This is a greatly simplified example from my real codebase but I think it illustrates the problem well. My EntityChild2 class is forced to implement a method it does not need or want to know about.

I know that it would be more correct to have a Interface that would contain the validateFieldB() method and only have EntityChild implement that interface.

With the understanding that this would take a significant amount of effort to refactor into this solution, I'm having a hard time justifying the time it would take to implement this solution in my real code base.

What potential problems will I run into down the line by leaving my code this way?

What benefits will I gain from refactoring my code to have a separate interface for validateFieldB()?

tldr: Why is the Interface Segregation Principle so important?

jeudi 24 janvier 2019

Strategy pattern used in Factory pattern?

I am writing code with the factory pattern. In switch case, I am actually returning Class objects. Using this return class, I am going to call a method. Is this an example of strategy pattern?

using System;
using System.Linq;

namespace ConsoleApplication1
{
    public interface IVehicle
    {
          void Manufacture();
    }

    public class Car : IVehicle
    {
        public void Manufacture()
        {
            Console.WriteLine("Car Manufacturing");
         }
     }

     public class Bike : IVehicle
     {
         public void Manufacture()
         {
            Console.WriteLine("Bike Manufacturing");
         }
     }

     public static class factory
     {
         public static IVehicle GetVehicle(string name)
         {
            switch(name)
            {
                case "Car":
                    return new Car();
                case "Bike":
                    return new Bike();
                default:
                    throw new ArgumentException();
            }
        }
    }

    public class program
    {
        public static void Main()
        {
            Console.WriteLine("Please enter Car or Bike for manufacture");
            var vehicleName = Console.ReadLine();
            factory.GetVehicle(vehicleName).Manufacture();
            Console.ReadLine();
        }
    }

}

Can you clear my misunderstanding here? Is this code is an example of factory and strategy pattern both? Thank you in advance.

Should the 'main loop' of my bulk import be driven by the front end or backend?

Let me explain.

I'm building an app plugin which let's users bulk import records from CSV. I want to show a success or failure status in (close to) real-time as each record is imported.

The desired flow is that

  1. the user uploads a CSV of the records they want to import.
  2. See's a (paginated ?) webview of all the records parsed from the CSV
  3. User clicks confirm button on webview
  4. The plugin starts the import - creating the records by calling the apps rest api.
  5. a success or failure icon next to each record in the webview as it is processed by the back end.

The method I want to do, which I think would be the simplest, is to loop over the data in the front end, make a request to the backend, and update the UI with the result of the query.

but if I have a lot of records I don't want to upload a large CSV to the backend, send all the data back rendered in a template for the user to verify and then send each record back to the backend one by one. This won't scale well.

It seems like it would be better to have the backend handle the mainllop but then in this case I don't know how I would update the UI on the front end. - I can't use websockets due to client network constraints

How should I architect this? Please note, I'm looking for a simple solution as I am just trying to build a mvp to validate my idea for the plugin.

Edited for spelling and grammar

How to separate business logic from controller

so I created this project as a demo. I was told to seperate the buisness logic from the controller. How I can perfectly achieve this?

https://github.com/aallobadi/PizzaStore

Any tips?

What is the name of the design pattern to avoid chained field access?

There is a pattern or term that is used to avoid codes like

myObject.fieldA.fieldB.fieldC

something like this. I forgot what this term is called. Can anyone let me know about it?

Rails proxy design pattern

I have been doing rails development and I want to incorporate design patterns. My questions is, is it possible to use the proxy design pattern such that only specific classes may call functions from class b which makes changes to the model.

What I want to do is have a class which is protected with the proxy design pattern to mediate one of my models.

Would you recommend to implement a client-server architecture with client generating script code for the server to interpret? Are there pros and cons?

I am currently trying to implement a Java client (which is a java ee application running on wildfly 10 and is a server for a javascript front end client) to communicate with an instance of Rserve running on Ubuntu server.

The client is using REngine an API for Rserve and is therefore tightly coupled to the Rserve via the specific classes of this API. The communication is handled via a specific protocol see https://www.rforge.net/Rserve/ for further information.

Complex objects need to be created on the java side and assigned via a call of API functions, since they cannot simply be passed as R code to evaluate.

Since I found no solution for debugging the server via attaching to a running R session a colleague gave me the idea to let the java client generate the whole code (Parameters, functions via templates...) and pass it to the server to interpret it, so we can log the whole code that is executed on the server side.

My question is: Is this actually common practise and an accepted design pattern? Are there any resources on this? Are there any pros and cons other than the transparency gained and the extra work of parsing java objects to R code to let the assignment happen by passing a command as string instead of calling the API function?

PHP: Linking to static pages/resources using MVC

I am trying to figure out the best approach when linking to static pages using a loosely followed MVC design pattern.

I begin by rewriting all requests to the index.php which handles all request and break them down the url into the controller, action and parameters. However if i don't want to follow this url structure and just want to visit a static page such as 'http://example.com/home/' without having to call some action how would i achieve this without getting a php error caused by my router/dispatcher trying to request a file that does not exist?

I thought about setting up some switch statement or a if statement as shown below that checks if the url is set to something then uses a custom defined controller and action, or i wasn't sure whether to take the static resources out of the MVC directory and have it seperate and link to it that way?

<?php

class Router
{

    static public function parse($url, $request)
    {
        $url = trim($url);

        if ($url == "/")
        {
            $request->controller = "tasks";
            $request->action = "index";
            $request->params = [];
        }
        else
        {
            $explode_url = explode('/', $url);
            $explode_url = array_slice($explode_url, 2);
            $request->controller = $explode_url[0];
            $request->action = $explode_url[1];
            $request->params = array_slice($explode_url, 2);
        }

    }
}
?>

This works, but i'd rather not have a huge router setup for many different static resources as it feels tacky and that i am just patching together code. Would putting static pages in its own directory outside of MVC and linking to them in the views be a valid option? i'm relatively new to MVC so any guidance would be great.

Alternatives to the Pipes and Filters pattern

Modifying and tying to test the 7th filter out of a chain of 11 filters proves to be painful to test.

Each filter passes along the same object reference and they work on it. So for me, I have no idea what kind of state this object would be in when I receive it in the 7th filter that I'm modifying.

There isn't much documentation. So I don't really know what state I'm getting.

Are there any other ways to replace the Pipes and Filters pattern in general? I'm looking for a good way suitable for unit testing.

https://docs.microsoft.com/en-us/azure/architecture/patterns/pipes-and-filters

The way this programme that I'm working on is arranged seems like each filter relies on the output of the previous filter. And the filters are added in a specific order. The filters cannot be rearranged in a different order.

ElasticSearch in micro-services design

we have micro-services design and we have DocumentService and DocumentReportService.

DocumentsService - get documents, search documents in ELK.

DocumentsReportsService - generate reports in doc, export into PDF and e.g. and I want to use ELK as storage again.

Question: ELK for DocumentsService and DocumentReportService it is 1 ELK instance or 2?

HTML pattern regex at least one space between characters

I need an HTML pattern regex at least one space between characters and allowing more than one space in the field.

for example: 'XXXX XXXX' or 'XXXX XXXX XXXX' or 'XX XXX XXXX XXX'

I've tried pattern=".+/s" but it does not work in HTML5

Is there a better design pattern for this requirement?

However, more user types can be added is also the requirement. It is not suitable to add more elements in the visitor pattern. What design pattern should I choose instead? Thanks!

Hi, I'm dealing with a design pattern problem: In a library system, admin can grant the certain permission of user information management (e.g., creating or searching user info) to other departments or schools. So I tried to use the visitor pattern. Users like teachers and students are the subclass of User and the admin or other department is the visitor.

regex for alternate repetition of words [duplicate]

This question already has an answer here:

I want to find 'the phone' pattern but it's couting only one the phone in given line :

pat=r'\sthe\sphone\s'
line=' the phone the phone '

If I give input string with extra space ==' the phone the phone ' the only it will print expected output ['the phone' ,'the phone']

ssss=re.findall(pat,line,re.IGNORECASE)

print(ssss)

output [' the phone ']

I'm using python for this regular expression:

{pat=r'\sthe\sphone\s'

line=' the phone the phone '

ssss=re.findall(pat,line,re.IGNORECASE)

print(ssss)}

mercredi 23 janvier 2019

Event price to have a membership discount when events are unaware of membership

I have a bit of a design pattern issue. Say I have a module called "Events" which has the following class:

public class Event {
    public string Name { get; set; }
    public decimal Cost { get; set; }
}

Now say I have another module called "Membership" which has a dependency on this module. This is a basic membership module where if someone subscribes to a membership they will receive a discount of the cost of the events.

The problem I have is how do I get the correct event cost in the Events module taking into account the discount when the Events module has no knowledge of the Membership module.

One idea I come up with is to add a service in the Events module, e.g.:

public interface IEventCost {
    decimal GetCost(Event event);
}

Then I would implement this in the Membership module. However every time I display the event's cost I would then have to inject the service and call the GetCost method passing in the event. I'm not sure I like this idea and I was wondering if there was a design pattern to handle this scenario.

I'd really appreciate the help.

Is there a maximum number of windows?

Is there a maximum number of windows that an application can have?

silly question. Is there a maximum number of windows that an application can have in an iphone? I mean, if I want to design an application and I want to use 100 different windows, can I do that? I just want to know if the system allows it, not if it's not an intelligent way to work :)

Thanks.

Luis

What pattern or architecture can be applied to Repositories and several data clients (Mysql, Postgress, Elasticsearch, etc)?

my question is because I currently have several repositories working with a data system, specifically a DbalClient, which works with Postgress and Mysql, the question is that I want to implement something else like MongoDB or Elasticsearch and I would have to adapt my repositories, How can I abstract this?

Some example code

UserRepository {

   protected $client;

   public function __construct(DbalClient $client)
   {
      $this->client = $client;
   }        

   public function find($id)
   {
      $query = $this->client->createQueryBuilder();
      $result = $query->select('*')->where('user.id = :id')
         ->setParameter('id', $id);
         ->getResult($query);
      return $result;
   }

}

This is only serving me for DbalClient, What pattern could I use apart from interfaces?

What is a correct approach to manage test data using pytest?

I need to create automated tests for several related apps and faced one problem with test data management between tests. The problem is that same data must be shared between several apps and/or different APIs. Now I have next structure with pytest that working good for me but I doubt that use test data managment in conftest.py is correct approach:

Overall structure looks like:

tests/
    conftest.py
    app1/
        conftest.py
        test_1.py
        test_2.py
    app2/
        conftest.py
        test_1.py
        test_2.py
test_data/
    test_data_shared.py
    test_data_app1.py
    test_data_app2.py

Here is example of test data in tests/conftest.py:

from test_data.test_data_shared import test_data_generator, default_data

@pytest.fixture
def random_email():
    email = test_data_generator.generate_random_email()
    yield email
    delete_user_by_email(email)

@pytest.fixture()
def sign_up_api_test_data(environment, random_email):
"""
environment is also fixture, capture value from pytest options
"""
    data = {"email": random_email, "other_data": default_data.get_required_data(), "hash": test_data_generator.generate_hash(environment)}
    yield data
    do_some_things_with_data(data)

Its very comfort to use fixture for that purposes, because postconditions, scopes and other sweet things (note that apps have a lot of logic and relationship, so I cannot simply hardcode data or migrate it in json file for example) Similar things can be found in tests/app1/conftest.py and tests/app2/conftest.py for data that used in app1 and app 2 accordingly.

So, here is 2 problems: 1. conftest.py become a monster with a lot of code 2. as I know, using conftest for test data is a bad approach or I'm wrong?

Thanks in advance!

Should I store unique string into _id if the string too long in MongoDB?

I am implementing a crawler to get data from Youtube and I need to store the id (ex: UCZ0zEZe8pWhmNpPdzwfxx4B) of each channel into my database (using MongoDB 4.0). I want to store these id given the following conditions:

  1. The id field must be indexed
  2. Not use too much memory for indexing
  3. No need to hash the id into other shorter string (if possible)

Currently, I have 2 solutions:

  • Solution 1: store channel_id and set the index like following
{
   "_id": ObjectId("522bb79455449d881b004d27"),
   "channel_id": "UCZ0zEZe8pWhmNpPdzwfxx4B",
}
db.channels.createIndex({'channel_id':'hashed'})

  • Solution 2: store channel_id into _id and using default index of _id
{
   "_id": "UCZ0zEZe8pWhmNpPdzwfxx4B",
}

The solution 1 satisfy condition (1), (2), (3) but field _id seems useless because channel_id will be used like primary_key for this collection

The solution 2 satisfy condition (1), (3) and need more memory for indexing

I think solution 1 is better in this case but is there any pros and cons? What is the best practices to save the long unique string (with indexing) in MongoDB ?

Abstract Factory Desing pattern implementation in Python

I am rewriting my already working Python code in a OOP manner as I want to implement it in a modular way. I have a dataset that has been obtained using several parameters. I want to implement an Abstract Factory Pattern and with that instantiate different objects containing different datasets with different parameters. The ultimate goal is that with two different datasets I can calculate specific stuff and I don't know how to implement a method that applies to both concrete objects.

enter image description here

In the image that I'm sharing it can be seen both the abstract factory method and two concrete datasets called FompyDatasetHigh and FompyDatasetLow (I know the UML is not right but its only to show the structure). Then I want to implement a method called Dibl that applies to both datasets and returns a calculation. The implementation of the Abstract Factory method I understand, is at the method where I get lost.

So how would you write a method that applies to both Concrete Factory Objects

I hope the information I've given its enough if not I can try to provide something else.

Thanks!

A class is recursive - when this class gets implemented, the parent class becomes recursive

Take the following example:

class Foo {
    public int SomeProperty { get; }
    public IEnumerable<Foo> Children { get; }
    // ....
}

If another class (e.g. Bar) implements Foo, Foo becomes non-recursive and Bar instead becomes recursive.

class Bar {
    public Foo { get; } // At this point Foo.Children doesn't make sense anymore
    public IEnumerable<Bar> Children { get; } // How can I enforce this part
    // ...
}

Currently I need to write two versions of every class, one with Children and one without. Inheritance makes this slightly less tedious but I can't statically guarantee that the requirements will be implemented correctly. I was also thinking about some kind of monad pattern with a higher kinded type Recursive but I can't wrap my head around it (especially since I just started learning it).

Any ideas?