mardi 31 mai 2022

Thread safe singleton, locks

I have a Singleton class which is a thread safe, do I need to lock it methods?

        private static volatile JsonWriter instance;
private static final Object mutex = new Object();

ReentrantReadWriteLock lock = new ReentrantReadWriteLock();

private JsonWriter() {
}

public static JsonWriter getInstance() {
    JsonWriter result = instance;
    if (result == null) {
        synchronized (mutex) {
            result = instance;
            if (result == null) {
                instance = result = new JsonWriter();
            }
        }
    }
    return result;
}

do I need to lock each method like this to ensure thread safety?

    public void write(String filePath, ArrayNode content) throws IOException {
    lock.writeLock().lock();
    File file = new File(MASTER_DIR + "/" + filePath);
    mapper.writerWithDefaultPrettyPrinter().writeValue(Files.newOutputStream(file.toPath()), content);

}

Is it generally better to use an async static initializer instead of a public constructor? [closed]

In C#, as well as in other OO languages, calling a class's constructor directly (via new) has historically been the canonical method by which one instantiates a new instance...e.g.,

var emp = new Employee(<parameters/dependencies/etc.>);
// do something with emp:

Despite all that has been written about "new is glue" and the avoidance of tight coupling, I still see this pattern a lot. In my own code, I've started making my constructors private and replacing constructor calls with static initializers. e.g.,

public class Employee
{
    private Employee(<parameters/dependencies/etc.>)
    {
        // do something with inputs:
    }

    public async Task<Employee> CreateInstanceAsync(<parameters/dependencies/etc.>)
    {
        var emp = new Employee(<parameters/dependencies/etc.>);
        // asynchronous initialization logic goes here
        return emp;
    }
}

To me, it seems like a no-brainer. Static initializers have the following advantages over direct constructor calls:

  • They allow for asynchronous initialization logic - which is essential if your class needs to (for example) retrieve configuration settings from an Azure Key Vault or set up a DB connection before being used.
  • They make it easier to adopt the Factory pattern.
  • By constraining the manner in which a class may be instantiated, they give a user a guarantee that the newly-created object will be ready-to-use without needing additional initialization calls.

The only disadvantage I see is if you are using certain packages or patterns which require the existence of a public parameterless constructor (although there are ways to work around this).

What are your thoughts? Should this manner of instantiating class objects be the new standard? Should we keep constructors hidden from the user? Or are there legitimate reasons why one would continue to use public constructors and the old-fashioned new pattern today?

What is the meaning of breaking code while implementing new features?

I was reading a text about SOLID principles and Open/Close principle and it said that : "The main idea of this principle is to keep existing code from breaking when you implement new features"

what it means by breaking code?

lundi 30 mai 2022

Is it right to write DB Operations in a POJO or DTO Class?

Let's say we have a Class Customer

Class Customer
{
    String name, emailId;

    public void setName(String name)
    {
       this.name = name;
    }
    public String getName()
    {
       return this.name;
    }
  
    //Getter and Setter for Email ID

    public void addNewCustomer()
    {
        //DB Operations
    } 
}

Now I have to persist a new row to the Database table Customer.

Do I add a method addNewCustomer as above and access it as below ?

Customer customer = new Customer();
customer.addNewCustomer();

Or

I should have a separate Class say,

Class CustomerUtil
{
     public static void addNewCustomer(Customer customer)
     {
        //DB Operations
     }
}

Is there any standards that we could follow here ?

OOP: factory method in abstract parent class?

I have the abstract class ChordPrinter with several children implementing it ChordPrinterEnglish, ChordPrinterSpanish):

abstract class ChordPrinter
{
    abstract public function printChordInNotation($fundamental, $attributes);

    //(other non-abstract methods)
}

Until now, I'd create an instance of a particular printer through a factory method provided by my framework's (Silex) dependency container:

$this['factory.ChordPrinter'] = $this->protect(function ($printer) {
    $printer = Domain\ChordPrinter\ChordPrinter::class . $printer;
    return new $printer();
});

In my new framework (Laravel) there's no such a thing as factories in the dependency container, so I have to make a factory of my own. I've thought of making a static method in the parent abstract class ChordPrinter:

abstract class ChordPrinter
{
    abstract public function printChordInNotation($fundamental, $attributes);

    //Is this the right place for this?
    public static function factory(string $printer): self
    {
        $printer = ChordPrinter::class . $printer;
        return new $printer();
    }
}

From an OOP point of view, is this the abstract class ChordPrinter the right place for the factory method? Not using the dependency container makes unit testing more difficult (it was easy to inject a mocked version of the factory into the DC). Other alternatives:

  1. Make a new class ChordPrinterFactory with a strategy pattern creating the concrete ChordPrinter* instances. But no easy mocking.
  2. Make a Laravel facade ChordPrinterFactory. Easy mocking.
  3. Do not make a factory, but duplicate those 2 lines in factory() every time I need a concrete instance of ChordPrinter.

Design pattern for Java Spring data JPA projects [closed]

This is my current project design
Controller-> service -> Repository

Service layer contains the business logic, Repository contains SQL Native query. Now i am trying to understand which one layer i can add between service and repository for manipulation of data which I am getting from DB.

I am trying to understand :

  1. What layer(Name) i can create between Controller-> service if in case i need to have layer which can be composition of services.

  2. What layer I can create between service -> Repository .

  3. If i am having Repository Layer can i also keep DAO layer.

Many Thanks.

How and where to dispatch actions when multiple sibling components use the same response data

enter image description here

I'd like to make components stand-alone so instead of passing all data from top to bottom, I was thinking of making each component dispatching actions to make sure they have data they need, and also to pull data from store.

I had run in couple of problems with redux from begging:

  1. I've tried dispatching actions that make http requests from page and then I'd pass them down the three, but that approach was terrible, since all child components would seem stand alone, but would still be dependant on their top grand parent on dispatching actions and getting the data in store
  2. Second approach I've tried to make each component dispatch actions that would provide data that they need but I've run into a problem that if two child components use same state, from same request, request would be fired twice or more times.
  3. And finally, I've tried improving the second approach by "lifting the state up", where in case of 2 child components having a data from the same parent, I'd move dispatching and getting data from store to their wrapper "smart" parent and passing it down as props, but in that scenario I've also had a problem with UI. What if, lets say, components A & C had same data and would've needed the "smart parent wrapper" but in visual hierarchy their real parent would render them in order A -> B -> C? In that case B wouldn't need to inside the smart wrapper?

What are the common patterns to this problem?

Javascript: is categorizing class functions using objects a good design approach?

Let's say I have a component TaskList. It has functions such as addTask, removeTask, editTask, as well as functions like openList and closeList. Let's say I create an object for each category of functions, for example object tasks and object ui, and then I store the functions in their respective objects, like so:

class TaskList {
   constructor(){
       this.tasks = {
           addTask: function(params){
               //Code
           },
           editTask: function(params){
               //Code
           }
           //etc...
       }

       this.ui = {
           closeList: function(){
               //Code
           }
           openList: function(){
               //Code
           }
           //etc...
       }
       //etc...
   }
}

Then you would call each function like so: this.tasks.editTask(...)

Is this a good approach? If no, what are some better alternatives to effectively organizing class functions?

dimanche 29 mai 2022

Enforce the use of context manager?

I have a custom resource defined as a class and a context manager to manage that resource. This combination is working perfectly. Is there any way to enforce that the resource will be used through context manager only and if anything is there then is that Pythonic?

Remove switch in more generic way

I encountered this class:

public class CommandFactory
{
    private readonly Dictionary<string, ICommand> commands;
    private readonly IPrinterEmulator printerEmulator;

    public CommandFactory(IPrinterEmulator printerEmulator)
    {
        commands = new Dictionary<string, ICommand>();
        this.printerEmulator = printerEmulator;
    }

    public ICommand GetCommand(string cmdStr)
    {
        ICommand command;

        if (commands.ContainsKey(cmdStr))
        {
            command = commands[cmdStr];
        }
        else
        {
            command = GetConcreteCommand(printerEmulator, cmdStr);
            commands.Add(cmdStr, command);
        }

        return command;
    }

    private ICommand GetConcreteCommand(IPrinterEmulator printerEmulator, string commandStr)
    {
        return commandStr switch
        {
            "SetJob" => new SetJobCommand(printerEmulator),
            "GetJob" => new GetJobCommand(printerEmulator),
            _ => new NotReconizeCmd(printerEmulator),
        };
    }
}

I am wondering why the dictionary in class constructor wasn't prepopulated in fashion Dictionary<string,Func<ICommand, string>> selector, but rather using get command to gain reference to implementation?

I have feeling that there has to be more appropriate approach and I am sure that switch statement can be completely removed in this way. Your opinion?

Thank you in advance

How to draw letter R with SVG

I have a svg of letter B here is the code:

<svg id="logo" xmlns="http://www.w3.org/2000/svg" role="img" viewBox="0 0 84 96">
    <title>Logo</title>
    <g transform="translate(-8.000000, -2.000000)">
      <g transform="translate(11.000000, 5.000000)">
        <path
          d="M45.691667,45.15 C48.591667,46.1 50.691667,48.95 50.691667,52.2 C50.691667,57.95 46.691667,61 40.291667,61 L28.541667,61 L28.541667,30.3 L39.291667,30.3 C45.691667,30.3 49.691667,33.15 49.691667,38.65 C49.691667,41.95 47.941667,44.35 45.691667,45.15 Z M33.591667,43.2 L39.241667,43.2 C42.791667,43.2 44.691667,41.85 44.691667,38.95 C44.691667,36.05 42.791667,34.8 39.241667,34.8 L33.591667,34.8 L33.591667,43.2 Z M33.591667,47.5 L33.591667,56.5 L40.191667,56.5 C43.691667,56.5 45.591667,54.75 45.591667,52 C45.591667,49.2 43.691667,47.5 40.191667,47.5 L33.591667,47.5 Z"
          fill="currentColor"
        />
        <polygon
          id="Shape"
          stroke="currentColor"
          strokeWidth="5"
          strokeLinecap="round"
          strokeLinejoin="round"
          points="39 0 0 22 0 67 39 90 78 68 78 23"
        />
      </g>
    </g>
  </svg>

And here is how it looks

enter image description here

I just need to change letter B to letter R but i don't know the path and it should be centered in polygon

Unit of Work implementation on top of EF Core cleanly supporting explicit loading

I have implemented a Repository/Unit of Work on top of EF Core's DbContext:

public interface IUnitOfWork : IDisposable
{
  IUserRepository Users { get; }
  IRoleRepository Roles { get; }
  int Complete();
}

Obviously IUserRepository is a repository of User objects built over the corresponding DbSet:

public interface IRepository<D, E> where D : DbContext where E : class, new()
{
  E Get(long id);
  IEnumerable<E> GetAll();
  IEnumerable<E> Find(Func<E, bool> predicate);
  void Add(E entity);
  void Remove(E entity);
}

public interface IUserRepository : IRepository<MyDbContext, User>
{
  IEnumerable<User> GetCreatedInPeriod(DateTime startDate, DateTime endDate);
  IEnumerable<User> GetInactive();
}

My question is, is there a clean way to support explicit loading through such an implementation? For that, one normally uses the Entry API of DbContext, which is hidden behind the unit of work. One could expose Entry on the unit of work, but then one would be able to write queries starting from a specific entity (have queries leaked out of the unit of work). Since one of my goals is to only expose IEnumerable and not IQueryable (queries leaking), I wanted to ask the above question.

samedi 28 mai 2022

How to apply Interface segregation principle?

I have a public interface that creates a bunch of different specific objects by client, and the only thing in common is that they all need to be serialized as xmls.

Something like this:

public interface IBuildXmlService
{
    XmlObject1 BuildClient1Xml(CustomObjectWithClient1Data data);
    XmlObject2 BuildClient2Xml(CustomObjectWithClient2Data data);
    XmlObject3 BuildClient3Xml(string string1, int int1);
    XmlObject4 BuildClient4Xml(CustomObjectWithClient4Data data);
}

Now this interface started to get big, and I'm definitely sure this is not a good sign. Also every time I inject the interface into a client specific class, that client specific class has access to all the other object creation methods for other clients.

Now the first thing I thought about was to just move the object creation method as a private method in client specific class, but this results in quite some big files.

Then I thought to use the factory method pattern to create a IXmlFactory with a BuildXml method for the object creation part, but this doesn't seem to work since I have different objects to return.

Can anyone give me some advice about what design pattern should I look for?

vendredi 27 mai 2022

Python and Unix pipes

I have an interesting design problem and I wanted to ask the community for advice. I am designing a bunch of tools that deal with molecules, which are handled as a pickable class. The tools adhere to the KISS principle, so each is going to be specialized in one task only, and the idea is to allow to optionally combine them using Unix pipes to do something like this:

$> generator.py | filter.py [OPTS] | calc_properties.py

While each tool can be used independently, by allowing chaining multiple tools reduces redundancy and the amount of data to be saved and read at every step. Also, each tool can potentially generate more than enough data to saturate all the available RAM. I've looked around and while there is quite a lot of documentation about Python support for pipes, I can't find anything that tells me first if this is a good design pattern, and second what would be a good way to pass around pickable objects through the pipes.

Functional data processing in clojure

I'm looking for some architectural solution to the problem I'm facing. I am struggling with a huge pipeline that processes data (which is a very complex structure). Generally, it can be illustrated as:

(defn process [data]
  (-> data
    do-something-1
    do-something-2
    do-something-3
    do-something-4
    ...
    do-something-20
)

where each of the do-something-* functions might be similarly complex. My problem is that there is a lot of coupling between functions in such a processing chain. For example do-something-3add something to data that later is required by do-something-9 which adds something else required by do-something-18 and so on. So essentially data is enriched by all those functions when cascading down the threading macro. It's very hard to keep the track of what is happening and when. Holding the whole processing chain in my head is just too much of a cognitive load (or at least I have too little RAM in my head). How do handle such cases? I get that there is no silver bullet but maybe there is something I'm missing (I started to learn clojure few months ago).

What implementation should I use if I want to separate common parts of functions and keep interface without details [closed]

I have questions about design and what can C++ compilers do in those situations.

Q. What kind of approaches you use on situations where you want to separate common parts of multiple functions in order to gain perfomace boost, whilst keep client away from those details?

In detail:

  • Let me use pseudocode of mix of C++ and Python.
  • Assume that client is me. I want to have reusable functions as interface.
  1. Suppose I've written some statements.
client():
    commonExpression //This is used by A and B statements. Evaluated once
    statementOfA
    statementOfA
    ...
    statementOfB
    statementOfB
    ...
  1. Then I want to refactor this in order to gain readability and reusability in the future. In this case I implement those functions with individiual commonExpression in each of them. Hence, in client context, commonExpression is evaluated twise. This is what I want to give a client - a clean interface without implementation details
    client():
        doA() // uses one instance of commonExpression
        doB() // uses one instance of commonExpression
  1. If I want to use only one function, no problems
    otherClient():
        doA()
  1. But if I want to gain potential perfomance boost, I'd create something like this
    client():
        //commonExpression is evaluated once instead of 2 times
        commonExpression
        doA(commonExpression.result)
        doB(commonExpression.result)
  1. This seems very verbose for me, I'd rather use doA() whith commonExpression in it. Q. Isn't it better to give a client a clean function without some kind of injection, not related to OOP?
    otherClient():
        commonExpression
        doA(commonExpression.result)
  1. I can create wrappers, leading to overcomlicated interface:
    doAWrapper():
        commonExpression
        doA(commonExpression.result)
    doBWrapper():
        commonExpression
        doB(commonExpression.result)
    doAandBWrapper():
        commonExpression
        doA(commonExpression.result)
        doB(commonExpression.result)

C++ compiler optimizations and inlined functions.

  1. Q. Can compiler do this optimization at assembly level?:
    client():
        doA() // uses one instance of commonExpression
        doB() // uses one instance of commonExpression

Optimized by compiler. Compiler sees common parts:

    client():
        commonExpression
        statementOfA
        ...
        statementOfB
        ...
  1. Q. Are compilers smart enough to clamp 2 functions as one if I mark them as inline?:
    client():
        doA() // uses one instance of commonstatemet
        doB() // uses one instance of commonstatemet

As:

    client():
        commonExpression
        statementOfA
        ...
        statementOfB
        ...

Or they will unroll to:

    client():
        commonExpression1
        statementOfA
        ...
        commonExpression2
        statementOfB
        ...

Remark: When I was about to end previous lines, I remembered about singletones and flyweight patterns) I think this topic dive very deep. But I dont want to overcomlicate my code(hello KISS). There must be a simple way) And I'm asking you, expirienced ones, for advice

  1. Q. What kind of approaches you use on those situations?

Best way to create a generic handler for all return types in c#

I have a bunch of classes and I want to group them functionally leveraging generics.

Below are my interface and classes:

public interface IMessagePoster<TReceiptType> 
{
    TReceiptType postMessage(Message message);
}

public class FacebookPoster : IMessagePoster<FacebookReturnType> {}
public class TwitterPoster : IMessagePoster<TwitterReturnType> {}
public class InstagramPoster : IMessagePoster<InstagramReturnType> {}

I now am interested in creating a generic handler class that is able to return the appropriate return type based on the generic type provided.

public class SocialPostHandler<TSocialType, TPostReturnType>
 where TSocialType: IMessagePoster<TPostReturnType>, new()
{
    public TPostReturnType postMessage(Message message) => new SocialType().postMessage(message);
}

When I call it I have to pass in the class type as well as return type.

new SocialPostHandler<FacebookPoster, FacebookReturnType>(message);

Is there a better way to achieve this generic handler SocialPostHandler? Anything that would help me infer the type somehow would also help. Thanks!

jeudi 26 mai 2022

Are there tools for pattern mining?

I have a set of data that I'd like to search for patterns.

10 columns of 25 rows, with 5 different mutually exclusive values in each cell.

If no patterns are found, I'd like to explore a pattern of randomness, or employ something Markov related. What should I use to search for patterns?

The patterns are unknown.

Thanks!

mercredi 25 mai 2022

VBA QUESTION: How to use wildcards to catch a pattern as well as characters surrounding it

I’m running into some problems with VBA and I don’t know how to really work with wildcards well. Can’t use regex.

Say I’m looking for a pattern “cat” and just delete it, along with any spaces and commas around it.

Eg. “Catch” -> “ch”

“Cat in the hat” -> “in the hat”

“The boy loves his dog, Catherine too” -> “The boy loves his dogherine too”

Is it possible to just have one pattern with wildcards to detect all these cases or do I need multiple?

C# Pick one of two static class at runtime

C#. Basically I had one static class A, having multiple static properties a, b, c,d... I was able to access it as usual A.a or A.b.

Now I have another static class B with same set of static properties. At the runtime based on certain condition, its need to be decided which class (A or B) need to be picked.

any idea how to achieve it.

Pattern to control one object from different components

In a past few years on different projects I faced with some architecture issue which now I realize have something in common.

Issue 1: There is Error container on the top of the screen which can show only one error message in a time. Different independent application components can push errors into it. The issue is that it's difficult to identify which error is more importand. Or error which comes last overwrite previous one and user even can't see it.

Issue 2: There is camera positioned over the map. Camera shows a specific part of the map with some angle. Again, different components can change camera position according to own needs. The issue is that two-three components can set own position of camera concurrently. Thus, final camera position could be unexpected. Also, due to asynchronization each time the position of different components can be applied.

Is there some architectural pattern which can solve such issue?

c++: cross interactions within dual hierarchy

In a C++ application, I have two class hierarchies, one for Workers and for Stuff. I want each sub-class of Worker to interact differently with each sub-class of Stuff through a do_stuff function. I'm not sure how to do that without systematically down-casting both the worker and stuff inside do_stuff and have specific treatments for each possibility.

Moving do_stuff to be a method for either Worker or Stuff and overriding in the sub-classes removes the need for one down-cast, but not the other.

Is there a specific good pratice to handle similar cases ?

Code structure is as below:

class Worker;
class Worker1 : public Worker;
class Worker2 : public Worker;

class Stuff;
class StuffA : public Stuff;
class StuffB : public Stuff;

void do_stuff(Worker worker, Stuff stuff);

int main() {
    vector<Worker*> worker_vec = whatever;
    vector<Stuff*> stuff_vec = whatever;

    for(Worker* worker : worker_vec) {
        for(Stuff* stuff: stuff_vec) {
            do_stuff(*worker, *stuff);
        }
    }
    return 0;
}

How to correctly isolate states in React

I want my parent component state to be updated by its children independently, without the parent doing micromanagement and being aware of variables modified by its children. I'm abstracting these modifications with a single method onIssueDataChanged. The modified state object will then be transferred to GraphQL, so no need for the parent to know what's in it. My problem, is that children cannot call onIssueDataChanged in useEffect.

Here's the concrete problem:

I have a form IssueFieldsForm that handles the saving of an object called issue.

The object has a gallery of pictures included, the pictures can be added, removed or selected as the main issue picture. That logic is isolated in a separate component called GalleryComp, and the info is stored in a non-persistent issue field called attachmentsMeta.

My problem is that I want to isolate handling of the attachmentsMeta in GalleryComp and have in IssueFieldsForm a generic method I called onIssueDataChanged which takes only changed values and updates the issue variable state with it. That seems hard to do since I initialize an attachmentsMeta state in GalleryComp with the current attachments in the useEffect hook, but I cannot send that back to the issue state object in the parent.

export default function GalleryComp(props) {
    const {issue, onItemsChanged} = props
    const [attachmentsMeta, setAttachmentsMeta] = useState({
        images: [],
        attachmentsAttributes: {},
        mainAttachmentIndex: 0
    })

    useEffect(() => {
        const newAttachmentsMeta = {...attachmentsMeta}
        newAttachmentsMeta.images = []
        logger.debug('attachments cont before concat: ', newAttachmentsMeta.images.length)
        newAttachmentsMeta.images = unionBy(issue.attachments, issue.attachmentsMeta?.images, 'url')
        logger.debug('after concat: ', newAttachmentsMeta.images.length)
        newAttachmentsMeta.mainAttachmentIndex = issue.mainAttachmentIndex
        logger.debug('displaying attachments: ', newAttachmentsMeta)

        setAttachmentsMeta(newAttachmentsMeta)
    }, [issue?.attachmentsMeta])

That is a problem for me because if I don't do any change in the attachments, onIssueDataChanged will never be called to update the variable issue.attachmentsMeta with the initial attachments. Leading me to lose my original attachments on save (since they were not transferred to my single source of truth issue.attachmentsMeta).

On the other hand, if I initialize issue.attachmentsMeta in the parent component, I lose the elegance of having each component handle its own variables.

p.s: Obviously I cannot call onIssueDataChanged in the effect since it would trigger a state change and enter an infinite loop.

How would you do this?

mardi 24 mai 2022

What is the best way to let a child class communicate with the parent class

my question is, what is the best way to let a child class communicate with the parent class. For example: I have a main class simply called Main, and another class SomeClass. Now the Main class creates an instance of SomeClass, once the state of the SomeClass-object changes, the Main class should execute different code, depending on what changed. Yeah I know, that already sounds like the Observer design pattern, but how would I implement it with state changes treated differently? I'm currently writing an Android app with a database to make it more specific. In my project I have the main class, a class to connect, read from/write to the database and a GUI container class. (oversimplified, there are a few more) The main class creates an instance of both the GUI and database class. Now if I press a button A, it should write A-data to the database, if I press button B, it should write B-data to the database. As I think that a gui class shouldn't have direct access to the database, I tried other options, than just accessing the database from the gui-class Currently, I defined a placeholder abstract class with only one method, that I am just overwriting with the functionality. So right now I have to create a one-method-class A for the click of button A and a one-method-class B for the click of button B. It doesn't sound like the best way to me, I mean It's working, but I'd like to improve my code, so if you have any idea, please write your solution. :)

Which OO design pattern would best fit for a scheduled task?

I was thinking what would be a good design pattern for a certain task that needs to run periodically. I was thinking about a Singleton, so that the task doesn't run more than once at the same time. Would any other design pattern be more adequate to this kind of problem?

Identifying a Design pattern from a piece of C# code

I am trying to get a better understanding of the tech terms of design patterns, and in that case, im trying to guess the pattern from a piece of code.

I am a little stumpled with this one. What Pattern is this, and how do you know:

using System.Collections.Generic;

public abstract class Foo
{
    private readonly List<Bar> _list = new List<Bar>();

    public void Attach(Bar bar)
    {
        _list.Add(bar);
    }

    public void Detach(Bar bar)
    {
        _list.Remove(bar);
    }

    public void Notify()
    {
        foreach (var o in _list)
        {
            o.Update();
        }
    }
}

public abstract class Bar
{
    protected readonly Foo Foo;

    protected Bar(Foo foo)
    {
        Foo = foo;
    }

    public abstract void Update();
}

Any help or pointers would be appriciated :-)

Multiple views based on country

I have a react application. In that there will be different views based on country. For example there will be different table for different countries, filters will be different. Which design pattern will be the best for this use case? Also please share an example if possible.

lundi 23 mai 2022

Class behavior based on given data

I am receiving an IFormFile from a controller. What I want to do next is to process it and get its content. I expect to get .docx, .txt or .pdf file and I want a single class to process any of these files based on extension given. I created and made my class to do it like that:

{
    public static class DocumentProcessor // Should it be like this?
    {
        public static string GetContent(IFormFile file)
        {
            var result = new StringBuilder();

            switch (Path.GetExtension(file.FileName))
            {
                case ".txt":
                {
                    using(var reader = new StreamReader(file.OpenReadStream()))
                    {
                        while (reader.Peek() >= 0)
                            result.AppendLine(reader.ReadLine());
                    }
                    break;
                }
            }
            return result.ToString();
        }
    }
}

Anyway, I feel like it is an extremely bad solution just because it is static. I could use the strategy pattern, but how do I define what strategy context has to use? Should I create another class that returns a Strategy object depending on IFormFile object extension. But I feel it is also a bad solution I would like to know what is the best way to solve this problem

MVC approach in Flutter

I am starting to get into flutter development and wanted to implement an app using the MVC strategy.
In my case I wanted to use the MVC pattern especially to handle the http requests to the backend better.
My problem is, that I don't know if my following approach is correct:
GitHub Project
In the Project there is also an image of a plantuml diagram.

Especially that the Controller 'controls' the State Class is my worry.

dimanche 22 mai 2022

Symfony5 non-service classes - how to get services (like EntityManager)

The problem:

producer A produces 50 products

producer A sells its products through 300+ resellers across the world

each reseller demands the product sheets in a different structure/format/attributes etc.

Because:

I need 300+ methods to build each reseller's format, looped 50 times (for each product)

I guess that:

placing all 300+ methods in one class (in one 5000+ lines service class) is ugly, anti-design etc.

creating 300+ services (SellerX, each containing a method to create the product sheet) and auto-wiring them in the caller service __construct() is also no-go (the caller service being the one to loop the 300 methods 50 times)

Remaining option: strategy design pattern, with an interface class to be implemented 300+ times for each of the 300+ SellerX (to implement the method createProductSheet() in 300+ non-service classes). But how should the 300+ classes be built and used, in order to benefit from Symfony's EntityManager service and other useful Services that I need?

The big problem with this approach is that, in the calling code, I would somehow need to (first) instantiate a SellerX object with the NEW keyword (dynamic instantiation) AND pass each required service as argument (which would again turn ugly when tens of extra services are required in any of the createProductSheet() methods; furthermore, not all SellerX methods need all the services that would be passed as a bulk).

Whether the 300+ implementations of the method createProductSheet() are Singletons, static methods classes, or regular classes (non-singletons, non-static methods), the main problem is the same: I cannot use dependency injection.

Is there a way to access services like EntityManager from custom classes? From the Kernel? How?

Or, perhaps, is there any other possibility?

Observer design pattern java task

Observer is a behavioral design pattern that lets you define a subscription mechanism to notify multiple objects about any events that happen with the object they’re observing.

Implement methods:

newRepository - returns a Repository. It supports commits to various branches and merges between branches. Also, it supports WebHooks - observers that observes commit or merge events. mergeToBranchWebHook - returns a WebHook that observes merge events for a target branch. commitToBranchWebHook - returns a WebHook that observes commit events for a target branch.

I'm new to design patterns so can someone give a hint on how to implement these methods.

Webhook Interface

public interface WebHook {
String branch();
Event.Type type();
List<Event> caughtEvents();
void onEvent(Event event);}

Repository Interdace

public interface Repository {
void addWebHook(WebHook webHook);
Commit commit(String branch, String author, String[] changes);
void merge(String sourceBranch, String targetBranch);}

Commit Class

public class Commit{
private String author;
private String[] changes;

public Commit(final String author, final String[] changes) {
    this.author = author;
    this.changes = changes;
}

String author(){
    return author;
}

String[] changes(){
    return changes;
}

@Override
public boolean equals(final Object o) {
    if (this == o) return true;
    if (o == null || getClass() != o.getClass()) return false;

    final Commit commit = (Commit) o;

    if (!Objects.equals(author, commit.author)) return false;
    // Probably incorrect - comparing Object[] arrays with Arrays.equals
    return Arrays.equals(changes, commit.changes);
}

@Override
public int hashCode() {
    int result = author != null ? author.hashCode() : 0;
    result = 31 * result + Arrays.hashCode(changes);
    return result;
}

@Override
public String toString() {
    return new StringJoiner(", ", Commit.class.getSimpleName() + "[", "]")
            .add(author)
            .add(Arrays.toString(changes))
            .toString();
}}

Event Class

public class Event {
private Type type;
private String branch;
private List<Commit> commits;

public Event(final Type type, final String branch, final List<Commit> commits) {
    this.type = type;
    this.branch = branch;
    this.commits = commits;
}

public Event() {

}

Type type() {
    return type;
}

String branch() {
    return branch;
}

List<Commit> commits() {
    return commits;
}

@Override
public boolean equals(final Object o) {
    if (this == o) return true;
    if (o == null || getClass() != o.getClass()) return false;

    final Event event = (Event) o;

    if (type != event.type) return false;
    if (!Objects.equals(branch, event.branch)) return false;
    return Objects.equals(commits, event.commits);
}

@Override
public int hashCode() {
    int result = type != null ? type.hashCode() : 0;
    result = 31 * result + (branch != null ? branch.hashCode() : 0);
    result = 31 * result + (commits != null ? commits.hashCode() : 0);
    return result;
}

enum Type {
    COMMIT,
    MERGE
}

@Override
public String toString() {
    return new StringJoiner(", ", Event.class.getSimpleName() + "[", "]")
            .add(type.toString())
            .add(branch)
            .add(commits.toString())
            .toString();
}}

What are the best design patterns, separations or structures which can be applied to ASP.NET MVC web applications?

I would like to know about the different types of desgin pattern/ structure/ speration can be used when developing asp.net mvc application. In this post I will summarize the tecnique used by me to further sperate asp.net application. I would like to know how to improve the current speration tecnique used in my projects. Further, I would like to know if there are any other desgin pattern/ structure or speration which can be applied when developing asp.net MVC applications. The level of speration recomnded to use is to keep the controller as clean as possbile from logical operation and data access layer. The architecture of my projects that I am working with is to call functions in the logical layer from controller. The logical layer classes do all logical operations than call functions in the data access layer. The data access layer then insert, update or return data. Also, I would like to find out if there are any other desgin pattern, sperations, or structure that I should apply to asp.net mvc projects. What are they, when to use them, when to use one over another and what are thier advtages. Further, should we always use desgin patterns, sperations, or structure to make functions reuseable even if these functions called once.

Javascript - Generalize similar function with different parameters

Imagine two type of content in an app: "Songs" and "Films".

I have two helper methods that are really similar:

/**
 * @protected <-- No need to validate arguments, as the method is "protected".
 * ...
 */
function fillRemainingSongsList(currentSongs, currentUserId) {
  const remainingSongs = MAX_LIST_SIZE - currentSongs.length; 
  const shouldFetchTrending = Math.random() < FETCH_TRENDING_PROBABILITY;
  const promises = [
    api.songs.getRandomSongs(), 
    shouldFetchTrending ? api.songs.getTrendingSongs() : undefined
  ];

  const [
    randomSongs = [],
    trendingSongs = [],
  ] = await Promise.all(promises);

  return [...currentSongs, ...randomSongs, ...trendingSongs];
}

and

/**
 * @protected
 * ...
 */
async function fillRemainingFilmsList(currentFilms, category) {
  const remainingFilms = MAX_LIST_SIZE - currentFilms.length; 
  const shouldFetchTrending = Math.random() < FETCH_TRENDING_PROBABILITY;
  const promises = [
    api.films.getRandomFilms(category), 
    shouldFetchTrending ? api.films.getTrendingFilms(category) : undefined
  ];

  const [
    randomFilms = [],
    trendingFilms = [],
  ] = await Promise.all(promises);

  return [...currentFilms, ...randomFilms, ...trendingFilms];
}

As you can see, there is code repetition in both functions. How can I do to generalize them more? Any design pattern? The problem I am handling is that both methods calls to different api methods, and have different parameters... but, in the other hand, I am trying to not repeat my self in the logic.

Javascript - Generalizing two functions where only numbers change

I have two similar methods:

function getFeedPizzasMinimumDate(startDate, totalPizzas) {
  // 2 weeks if there are less than 10 pizzas
  let numberOfDaysToDecrase = 14;

  // 3 days if there are more than 1k pizzas
  if (totalPizzas >= 1000) numberOfDaysToDecrase = 3;

  // 5 days if there are from 100 to 1k pizzas
  else if (totalPizzas >= 100) numberOfDaysToDecrase = 5;

  // 1 week if there are from 10 to 100 pizzas
  else if (totalPizzas >= 10) numberOfDaysToDecrase = 7;

  return substractDaysToDate(numberOfDaysToDecrase, startDate);
}

and:

function getFeedSpaghettisMinimumDate(startDate, totalSpaghettis) {
  // 3 weeks if there are less than 10 spaghettis
  let numberOfDaysToDecrase = 21;
    
  // 5 days if there are more than 1k spaghettis
  if (totalSpaghettis >= 1000) numberOfDaysToDecrase = 5;
    
  // 1 week if there are from 100 to 1k spaghettis
  else if (totalSpaghettis >= 100) numberOfDaysToDecrase = 7;
    
  // 2 weeks if there are from 10 to 100 pizzas
  else if (totalSpaghettis >= 10) numberOfDaysToDecrase = 14;
    
  return substractDaysToDate(numberOfDaysToDecrase, startDate);
}

As you can see, the code of both methods is really similar, only the numbers change.

Suppose that the numbers where calculates "heuristacally" (via suppositions, without any kind of formula).

Which pattern can I use to generalize both methods into one "getFeedPlatesMinimumDate"? Should I avoid generalizing code when code atomicity is as high?

Java Generics Compiler Error in Chain of Responsibility design principle

public abstract class AbstractExecutor<PARAM, RET> {

private AbstractExecutor<?, ?> nextExecutor;
    
public abstract RET execute(PARAM param);

public void executeAll(PARAM par) {
    System.out.println("Executing..");
    RET ret= execute(par);
     if(this.nextExecutor!=null){
         System.out.println("Executing.." + this.getClass());
            this.nextExecutor.executeAll(ret);
        }
}

public AbstractExecutor<?, ?> setNextExecutor(AbstractExecutor<?,?> next){
    this.nextExecutor = next;
    return this.nextExecutor;
}}

Can anyone help me with this code, why I am wrong here "this.nextExecutor.executeAll(ret);" ? I am getting "The method executeAll(capture#4-of ?) in the type AbstractExecutor<capture#4-of ?,capture#5-of ?> is not applicable for the arguments (RET)" but unable to understand whats wrong here? How to correct this ?

samedi 21 mai 2022

MVVM Service Layer?

Is it good practice to implement a service layer with MVVM?

In my case, I split my business logic into a service and a model. A service takes a model and a repository as a dependency and calls functions on each depending on what the ViewModel tells it to do. Instinctively, this reminds me of an Anemic Domain Model, but I believe it isn't as my Models don't have getters and setters, they have functions such as like() and unlike() to mutate its properties internally.

Example of what I am implementing:

class PostViewModel with ViewModel {
  final IPostService _service;

  PostViewModel(this._service);

  bool get isLiked => _service.isLiked;
  int get likeCount => _service.likeCount;

  void like() {
    _service.like();
    notifyListeners(); // update views
  }
}
class PostService implements IPostService {
  final PostModel _model;
  final IPostRepository _repository;

  PostService(this._model, this._repository);

  @override
  int get likeCount => _model.likeCount;

  @override
  bool get isLiked => _model.isLiked;


  @override
  Future<void> like() async {
    _model.like(); // tell model that this post was liked
    _repository.like(); // tell server that this post was liked
    // more complex logic will go in here in the future
  }
class PostModel {
  final String _id;
  ... other properties

  int get likeCount => _likeCount;
  bool get isLiked => _isLiked;

  void like() {
    _likeCount++;
    _isLiked = true;
  }
}

I like this implementation because it lets me plug in features to ViewModels whenever I need, so if I need to reuse this Post logic, I can do so easily. One downside though is that I have to write so many getters.

Code for Alternating 2 Box Pattern using if statements

I am trying to find a code that helps to create a pattern of:

Picture of Checkered 2box pattern

but the number of rows and columns are custom. Currently this is the code i have but it doesnt apply properly for all values. (labelseat.backcolour=color.red , refers to the red boxes) Thank you for your time:D and this is in C#

                                count =0;
                                if (Row%2==0)
                                   {
                                    count+=1;
                                   
                                    if (count==3)
                                    {
                                        labelSeat.BackColor=Color.Red;
                                    }
                                    else if (count==4)
                                    {
                                        labelSeat.BackColor=Color.Red;
                                        count=0;
                                        
                                    }

                                }
                                if (Row%2==1)
                                {
                                    count+=1;
                                    
                                    if (count==1)
                                    {
                                        labelSeat.BackColor=Color.Red;
                                    }
                                    else if (count==2)
                                    {
                                        labelSeat.BackColor=Color.Red;

                                    
                                    }
                                    else if (count==4)
                                    {
                                        count=0;
                                    }
                                }

vendredi 20 mai 2022

Which design pattern should I follow for a Nextjs application?(just frontend)

I am working on an E-commerce website that is developed using NextJs. My manager is telling me to use a design pattern like MVC or MVVM as our Android team is using MVVM. But I am not sure which design pattern will be better in my case. Can anyone give me any suggestion please?

Would a strategy pattern be appropriate for ETL?

Ive used this as my mental model https://refactoring.guru/design-patterns/strategy and can implement it without issues.

If I had this flow:

queue -> ETL -> opensearch <- service

Would ETL still follow a strategy pattern?

Navigate in object with a lot of nulls

I'm trying to implement a good design in my code. There is a Entity purchaseOrder and I need to navigate inside that object that has a list of stockOrder and each StockOrder has a list of StockOrderItem. There is no guarantee that a stockOrder or stockOrderItem exists so I needed to check a lot of nulls. Is there a elegant way to do that?

        PurchaseOrder purchaseOrder = purchaseOrderRepository.
            findByIdentifierAndBrandId(po.getPurchaseOrderIdentifier(), po.getBrandId());
        List<StockOrder> stockOrders = Optional.ofNullable(
            purchaseOrder.getStockOrders()).orElse(Collections.emptyList());
        for (StockOrder stockOrder : stockOrders) {
            for (StockOrderItem stockOrderItem : Optional.
                ofNullable(stockOrder.getStockOrderItems()).orElse(Collections.emptyList())) {
                InventoryDataLoad inventoryDataload = new InventoryDataLoad();
                inventoryDataload.setSku(stockOrderItem.getSku());
                inventoryDataLoadList.add(inventoryDataload);
            }
        }

Naming a subclass to store requirements of the parent class

I have the class Party and inside i have some restrictions to join that party.

Looking like this:

class Party {
    String id;
    String name;
    Instant date;
    Requirement requirement;
}

class Requirement {
    int age;
    String dressCode;
    boolean drinkIncluded;
    ....
}

My question is: How should i name the subclass Requirement? I came up with three options but i cannot tell what is the best naming convention.

  1. Requirements (in plural)

  2. Requirement (in singular)

  3. Requirements_configuration

Is there some design pattern that i am missing to solve this or i just can name it in plural in this scenario?

mercredi 18 mai 2022

Best practice for exposed fields in Kotlin

I have often the problem that I want to use a mutable class inside, but I don't want to expose the mutable interface. Here are two samples:

class Sample {
    val listData: List<Any> = mutableListOf()
    val liveData: LiveData<Any> = MutableLiveData()

    fun updateFields() {
        // update both fields above: The add() and postValue() methods are not visible here
    }
}

I'm casting the fields sometimes other times I use private extension functions/properties. In rare cases I also used two fields one private with the mutable interface and the public with the immutable interface. The first two options feel very hacky and look ugly the last one with the second property feels very redundant and like the "normal" java boilerplate.

Another option would be to define an interface where just the implementation has the mutable fields, but that is again boilerplate which I want to avoid. How do you handle this?

How to check the being unique of the model without sending the model to the update method in laravel?

this is method in UserRepository file:

public function update($request, $id)
{
    $new_request = (object)$request;
    $data = $new_request->all();
    $this->user::where('id', $id)->update($data);
    return http_response_code(201);
}

this is method in UserController:

public function update(UpdateUserRequest $request, $id)
{
    return $this->userRepository->update($request, $id);
}

this is UpdateUserRequest:

'username' => 'required|string',Rule::unique('users')->ignore($this->user),

but don't work and my error is: Attempt to read property "id" on string

Suggest Suitable Approach or Design Pattern for fallbacks in code

I have a below problem statement and seek better advice on Suitable Approach or Design Pattern for fallbacks in code

  • We have 3 database tables and 1 single node redis instance
  • If redis is down for any reason, We want to query directly from individual tables
  • If redis is up and does not have data from database, cache it

Our moto is application should not go down, depending on redis status and work fine.

I can write if / else logic to check redis status in all calls involved in fetching data from individual tables but it violates single responsibility principle and code duplication.

For a cleaner maintainable code, I am seeking better advice from community :)

Kindly let me know if you have trouble understanding my requirement

Is there a design pattern name for this code? [closed]

Can you tell me if this code is a named design pattern ?
I looked to many GOF patterns but I can't find one looking like this one. The closest pattern I found is "strategy" but "strategy" pattern runs only one service at runtime whereas here all services are running at runtime.

<?php

interface stuffable {
  public function doStuff(string $stuff): void;
}

class serviceA implements stuffable
{
  public function doStuff(string $stuff): void
  {
    echo "I am doing some $stuff\n";
  }
}

class serviceB implements stuffable
{
  public function doStuff(string $stuff): void
  {
    echo "I am doing some other $stuff\n";
  }
}

class stuffManager
{
  private $services = [];
  
  public function addStuffableServices(stuffable $service)
  {
    $this->services[] = $service;
  }
  
  public function stuffToDo(string $stuff)
  {
    foreach ($this->services as $service) {
      $service->doStuff($stuff);
    }
  }
}

$serviceA = new serviceA();
$serviceB = new serviceB();
$stuffManager = new stuffManager();
$stuffManager->addStuffableServices($serviceA);
$stuffManager->addStuffableServices($serviceB);
$stuffManager->stuffToDo('stuff');

the expected output is :

I am doing some stuff
I am doing some other stuff

mardi 17 mai 2022

golang regex match all that don't end with word [duplicate]

I have an issue where I'm limited to the regex variant from golang and want to match entries that don't end with a specific word, here an example:

fooend
foond
fooendfoo
footemp

Usually I would use such a pattern

^.+(?<!end)$

which does not work since golang regex doesn't support lookaheads...

Does anyone have an idea how to achieve my initial goal with that what golang regex provides?

Singelton pattern with multithread

I read about sigelton pattern with multithreads and I found that is implemented use synchronized .

my question is can I use wait() + notify() or notifyAll() instead synchronized ?? and if yes which better synchronized or wait()+ notifyAll() ???

Powershell - Search for Pattern and Copy

i have a bunch of *.CSV Files. Huge *.CSV Files. I try to search for a specific pattern in these Files called "Secure". If found, the script shall copy it to a folder.

It works, but it has one Problem i could'nt solve. In some files, the Word i'm looking for is present more than once. Now my script searches for the word, finds it and copies it. Then it searches in the same file again, finds the pattern again and copies again.

But it should copy after the first find of the word and then search in the next *.CSV file and not in the same again.

i tried a bunch of things "-SimpleMatch" or "-First 1"

the Code so far is :

Select-String -Path 'C:\Tools\Test\*\*.csv' -Pattern "Secure" | Select -first 1 | Copy-Item -Destination C:\Tools\Found -Verbose

can someone help me ?

Thank you!

Usage of @Stateless and @Transactional on a POJO class - when and why?

I have a developer in my team who uses both of the annotations @Stateless and @Transactional on POJO classes that do not need any of these to work correctly. Example:

@Stateless
@Transactional(Transactional.TxType.REQUIRED)

public class ObjektAnlegenService {

    public Home setImagesToHome(Home home, ImagesUploadHelper imgUpldHelper) {
        Objects.requireNonNull(home, "Home is Null!");
        Objects.requireNonNull(imgUpldHelper, "ImagesUploadHelper is Null!");
        String mainImage = null;
        for (Image savedImage : imgUpldHelper.getImagesSaved()) {
            if (savedImage.isMainImage()) {
                mainImage = savedImage.getSimpleFileName();
            }
            savedImage.setHome(home);
        }
        home.setHomeImages(imgUpldHelper.getImagesSaved());
        home.setMainImageTabl(mainImage);
        return home;
    }

    public String[] getPlzOrtDetails(String plzOrtInput) {
    
        int indexOfComma = plzOrtInput.indexOf(Constants.COMMA);
        indexOfComma = indexOfComma == -1 ? plzOrtInput.length() : indexOfComma;
        
        String[] plzOrt = PlzOrtUtils.getPlzOrt(plzOrtInput.substring(0, indexOfComma));
        return plzOrt;
    }
}

My questions:

1.) @Transactional only makes sence, when the POJO class (or its methods) shall work with a transactional datasource, such as database or a transactional web-service. Otherwise it only adds a load to the server, right?

2.) @Stateless only makes sence when we want the JEE server container to manage the CDI (context and dependency injection) of the POJO class. But @Stateless adds an additional load to the JEE Server, because @Stateless beans are insantiated, pooled and kept in JNDI, right?

Then: if a POJO can exist and work as a singleton (as is the case with ObjektAnlegenService above), isn't it better to design it as a singleton, instead of a @Stateless?

lundi 16 mai 2022

Want to parse a string only want specific parts in the string using regex

The string essentially must longer so I shortened it bit:

   String s1= ("henry2O|*|bob10|*|mark20|*|justin30|*|kyle15|*|95|*|henry3O|*|bob50|*|mark70|*|justin30|*|kyle25|*|1000|");

So essentially it follows this pattern and keeps repeating so I essentially want only want the parts with henry, mark, kyle, and all the numbers so in this case 95,1000 left. Not too sure of good way to use regex to achieve this.

Essentially I want my output to be:

(henry20,mark20,kyle15,95,henry30,mark70,kyle25,1000)

Extract text using regular expression

I'm trying to extract a case id from the string, Could someone help me with this

https://looney-tunes/review/case/CAAAAAAAAR-hw7QEAAAAMf___-A?caseGroup=12&queueId=52

I want to extract the portion after case/ and before '?'in the link. They're 27 characters in length.

Thanks in advance

Is splitting a class in two different class a good idea?

For a project I need to create report from Excel files.

But I have a big design question that I can't solve myself and I haven't found a solution online.

Here is what I'm trying to do :

  1. Read the content of an Excel file
  2. With that content initialize a new Report class
  3. Profit!

But the problem is that, the first time I wrote that, I put everything inside my Report class (by everything I mean reading the file, formatting the fields, etc ...) and I ended up with a big class.

I wasn't satisfied with that so I tried to do something better and created a ReportReader class that contain all my reading file stuff and also getters to init a Report class. It is a good idea or should I stick to one class ?

Also, could it be a good idea to create a createReport method inside ReportHeader instead of making public getters available ?

Thanks in advance for your responses.

public class ReportReader {
private final File file;
private final Sheet sheet;

public ReportReader(File file) throws InvalidFormatException, IOException {
 
}

public ArrayList<String> getFields() {

}

private String formatField(String input) {

}

public String getName() {

}

public Cell[][] getContent() {

}

public String getType() throws IOException {

}

}

public class Report {
private String name;
private String type;
private ArrayList<String> fields;
private Cell[][] content;

public Report(String name, String type, ArrayList<String> fields, Cell[][] content) throws IOException {

}

public void saveFieldsModel() throws IOException {

}

public String getFieldsAsCsv() {

}
}

A book/course for learning Programming with real understanding of all concepts

I am sorry If my question is inappropriate. I need your advice/recommendation. I don't know how to put it. I have been self-learning programming for 2 years through YouTube and Udemy. But I don't have any confidence. I feel like I have only barely scratched a surface, and memorized code snippets without understanding underlying concepts. During debugging I feel clueless. I think I am in "tutorial hell". I feel like I don't know the essential concepts, how things work, how software is interpreted, cache, memory allocation, stack etc.

Is there any book or source that teach not just how to quickly build something but essentials of computer science/programming.

How to zoom a picture while make it contained

my "wrapper" div is the most outlayer container. It consists of a picure and some text below. I want to use CSS (not yet learned JS...) method to realize the effect that, when mouse hovering over the picure area, the picure zoom-in a little, but still remain inside the shadowed box.

Below is my html code and css code. It did give me zoom-in effect, but the picture just ... stick out, how can I fix this (hopefully without using Javascript)

-- html code --

<!DOCTYPE html>
<html>
<head>
    <meta charset="utf-8">
    <meta name="viewport" content="width=device-width, initial-scale=1">
    <title>shadow block | link with graphics and info</title>
    <link rel="stylesheet" type="text/css" href="sectionlink_pic.css">
</head>
<body>

        <div class="wrapper">
            <div class="image">
                <img src="https://images.pexels.com/photos/262508/pexels-photo-262508.jpeg?auto=compress&cs=tinysrgb&dpr=2&h=750&w=1260">
            </div>
            <div class="infocontent">
                <h3>Home Security Blog</h3>
            </div>
        </div>

</body>
</html>

-- css --

.wrapper {
    display: flex;
    flex-direction: column;
    width: 400px;
    justify-content: center;
    align-items: center;
    border-radius: 3rem;
    box-shadow: 0.6rem 0.6rem 1.2rem #d2dce9, -0.5em -0.5em 1em #ffffff;
    padding: 2rem;
    z-index: 100;
}

.wrapper:hover {
    text-shadow: 5px 5px 4px lightgray;
    transition-duration: 0.2s;
    cursor: pointer;
}

.wrapper .image img {
    width: 100%;
    object-fit: cover;
    border-radius: 2rem;
    cursor: pointer;

}

.wrapper .image:hover img {
    transform: scale(1.5);
}

.wrapper .infocontent {
    display: flex;
    justify-content: center;
    align-items: center;
    font-family: Consolas;
    color: #36187d;
    cursor: pointer;
}

body {
    background-color: #f2f3f7;
    padding-top: 90px;
    padding-left: 100px;
}

Is Spring Integration a good framework to implement the Transactional Outbox pattern?

I'm implementing Transactional Outbox pattern using Java. The Message Relay Service will poll the Outbox table for entries, and after an outbox message is found and processed, it will update the Outbox entry to be "processed". I'm using Spring Boot and ran into Spring Integration project and wonder if this is a good way for this pattern to handle the Message Relay polling and JPA updates to the Outbox table or are there better ways?

dimanche 15 mai 2022

best approach to implement subscription based features in our software [closed]

what would be the best approach to implement subscription based software. and what would be the implementing strategies? Company provides different type of subscription like free, pro, premium, enterprise etc.. with these subscription they have limited the service and features.

samedi 14 mai 2022

What is the best practice for solving the number of cases of N searches in Spring JPA?

What is the best practice for solving the number of cases of N searches?

There are 3 search conditions for me. There are search conditions of A, B, and C.

In this case, the number of possible cases is Search only A, search only B, search only C, Search only AB, search only AC, search only BC Search only ABC

In the above situation, there are a total of 6 cases like this.(3!)

To map the number of all cases without thinking

@GetMapping("/A/{A}/B/{B}/C/{C}")
public ReturnType MethodName(@PathVariable AClass A
                             @PathVariable BClass B,
                             @PathVariable CClass C) {
return service.findByAandBandC(A, B, C);

I have to create 6 controller methods like the one above.

With 4 search conditions, need 24 methods (4! = 4 * 3 * 2)

If there are 5 search conditions, need 120 methods (5! = 5 * 4 * 3 * 2)

As above, it grows exponentially.

Instead of making all cases a method, I wonder if there is a best practice.

If possible, any answer utilizing spring data jpa would be appreciated.

best regards!

How to rethink the architecture of my Python project containing multiple async interfaces

I'm developping a Twitch Bot for approximatively a year now. Over the time, the bot became bigger and bigger to add features. Now the bot can manage multiple interfaces including Discord, Twitch, Twitch API, Streamlabs... and have a web interface to receive all the callbacks from OAuth authentification APIs and to present some statistics on an HTML page to the streamer.

However, the bigger the bot gets, the more problems I experience. The fact is, I don't think my current architecture is good. This is how it's done currently :

First, I instantiate a Core class, this class will contain instance of all the bots and interface and store the variables shared between them. It also contains a global asyncio lock for the database (since the entire bot is running on a single async loop, I need to be sure only one interface is talking with the database at a same time).

class Core:
    def __init__(self):
        # Define session lock for database access
        self.session_lock: asyncio.locks.Lock = asyncio.Lock()

        # Store bots & API access
        self.discord_bot: Optional[discord.Client] = None
        self.twitch_bot: Optional[twitchio.ext.commands.Bot] = None  # Manage Twitch IRC chat
        self.twitch_api: TwitchApi = None  # Manage Twitch API
        # Other interfaces ...

        # Some shared attributes which are read by all interfaces ...

Then, I instantiate all my interfaces by passing them the core. Each interface will register into the core by itself when instantiated. This is an example of an interface initialization (Discord here) :

class DiscordBot(commands.Bot):
    def __init__(self, core: Core, **options):
        super().__init__(**options)

        self.core: Core = core
        self.core.discord_bot = self

And the instanciation phase in my main script:

core = Core()

discord_bot = DiscordBot(core)
twitch_bot = TwitchChatBot(core, os.environ['TWITCH_BOT_TMI_TOKEN'], [os.environ['TWITCH_CHANNEL_NAME']])

loop = asyncio.get_event_loop()
loop.create_task(twitch_bot.connect())
loop.create_task(discord_bot.start(os.environ["DISCORD_BOT_TOKEN"]))
loop.run_forever()

Here is a global diagram of my architecture and how it is managed :

enter image description here

This architecture is really convenient because it allows me to have a really simple bridge between interfaces. For example, if I want to post a message on Discord from my Twitch bot, I can simply call self.core.discord_bot.get_channel(...).send(). Same thing on the other direction.

But I feel like this architecture is no longer sustainable. Currently the Core class contains more than 5000 lines of code and more than 60 methods shared between all the interfaces. I would like to explode it in multiple file but it's a mess. Moreover, I increasingly think that running all interfaces on the same asynchronous loop is not a good idea in the long run.

I thought of solutions, like separating all the interfaces into different processes. But then how to manage the synchronization between these processes without doing something complicated (I take my example of posting a message on Discord from the Twitch bot). I also looked at solutions like Redis for the synchronisation but I don't really know if it could answer all my concerns... I also thought about using the python import module to directly import a Core instance (and thus not having to register the Core in each interface), but I'm not sure if it would work and if it's a good practice.

I take another example, in the Core class is instanciated a class processing the interactions between the bot and the community. It is used to vary the interactions with the users (a sort of primitive chatbot). This class MUST be shared between all my interfaces because I want the reactions of the Discord bot to react according to what is happening on Twitch.

Anyway, I would like your expert opinion on this. How would you have organized all this? Thanks :)

Which design pattern is useful to evaluate conditions and return Boolean value

I would like to know best coding practice or design pattern which I can follow to achieve following task in Java: I need to enable check box in UI based on certain criteria/condition to check if those are satisfied in business layer which is written in Java.

There are 3 conditions which I need to evaluate, but I don't want to write if-else block inside single method to determine it. Also one or two condition will be common which will be used at other place too.

As of now, I am thinking to create one abstract class and create various implemention of it for conditions. Then create a list of those conditions class and evaluate in for loop one by one. Is that correct approach?

can I use a façade design pattern with a factory design pattern?

I have an animal interface and subclasses like birds, cats..etc that extends from the Animal class and I have a factory class.. my question is can I use facade design with the factory class? and how?

vendredi 13 mai 2022

Alternatives to cyclic references in java design

I am currently working on a design that is quite processing-intensive, and processing happens in various phases which are also required to interact with each other. I have developed various ProcessingManagers for each phase and to keep them loosely coupled with each other, a StateMachine class is also designed which will act as an interface for various phase managers to interact with each other.

Below is the dummy code which I just wrote by imitating the design.

I feel some problems with this design -

  1. Exessive use of method reference
  2. cyclic references between StateMachine and PhaseManagers

My Questions:

  1. Please suggest what could be the major disadvantages of such cycle references
  2. If you could suggest an altogether different design for the same solution or any minor tweak to avoid cyclic references
  3. Is there any local message queue API (within the same JVM) that we can use for PhasesManagers and StateMachine to send signals to each other and cyclic reference can be avoided.

Code:

StateMachine class:

package com.vg;

public class StateMachine {
    private volatile Phase state;
    private volatile boolean backgroundCompletedFirstPhase;
    private volatile boolean firstPhaseCompleted;

    private final BackgroundPhaseManager backgroundPhaseManager;
    private final FirstPhseManager firstPhaseManager;
    private final IntermediatePhaseManager intermediatePhaseManager;
    private final SecondPhaseManager secondPhaseManager;

    public StateMachine() {
        state = Phase.FIRST;
        backgroundCompletedFirstPhase = false;
        firstPhaseCompleted = false;

        this.backgroundPhaseManager = new BackgroundPhaseManager(this::process, this::stateUpdater,
                this::setBackgroundCompletedFirstPhase);
        this.firstPhaseManager = new FirstPhseManager(this::setFirstPhaseCompleted);
        this.intermediatePhaseManager = new IntermediatePhaseManager(this::startSecondPhase);
        this.secondPhaseManager = new SecondPhaseManager();
    }

    private void stateUpdater(String message) {
        System.out.println("perform udate based on many conditions");
    }

    private void setBackgroundCompletedFirstPhase() {
        this.backgroundCompletedFirstPhase = true;
        startIntermediateIfApplicable();
    }

    private void setFirstPhaseCompleted(){
        this.firstPhaseCompleted = true;
        startIntermediateIfApplicable();
    }

    private void startIntermediateIfApplicable(){
        if(backgroundCompletedFirstPhase && firstPhaseCompleted){
            this.state = Phase.INTERMEDIATE;
            intermediatePhaseManager.process("do it");
        }
    }

    private void startSecondPhase(){
        this.state = Phase.SECOND;
    }

    private void process(String message) {
        if (Phase.FIRST.equals(this.state)) {
            firstPhaseManager.process(message);
        } else {
            secondPhaseManager.process(message);
        }
    }

    public void start(){
        System.out.println("pass background processing manager to an external system which calls its methods");
    }

    public static void main(String[] args) {
        new StateMachine().start();
    }
}

Phases Enum:

package com.vg;

public enum Phase {
    FIRST, INTERMEDIATE, SECOND;
}

BackgroundPhaseManager class:

package com.vg;

import java.util.function.Consumer;

public class BackgroundPhaseManager {
    private final Consumer<String> consumer;
    private final Consumer<String> stateUpdater;
    private final Runnable finishFirstPhase;

    public BackgroundPhaseManager(Consumer<String> consumer, Consumer<String> stateUpdater,
                                  Runnable finishFirstPhase) {
        this.consumer = consumer;
        this.stateUpdater = stateUpdater;
        this.finishFirstPhase = finishFirstPhase;
    }

    public void supply(){
        consumer.accept("my-message");
    }

    public void changeStatus(){
        stateUpdater.accept("new-State");
    }

    public void finishFirstPhase(){
        finishFirstPhase.run();
    }
}

FirstPhseManager class:

package com.vg;

public class FirstPhseManager {
    Runnable phaseCompleteMessanger;

    public FirstPhseManager(Runnable phaseCompleteMessanger) {
        this.phaseCompleteMessanger = phaseCompleteMessanger;
    }

    public void process(String message){
        System.out.println("Extensive processing involving multiple threads, " +
                "hand-shakes, retries, failure recoveries, and takes-time " +
                "and lastly calls back to done function");
    }

    private void done(){
        phaseCompleteMessanger.run();
    }
}

IntermediatePhaseManager class:

package com.vg;

public class IntermediatePhaseManager {

    Runnable phaseCompleteMessanger;

    public IntermediatePhaseManager(Runnable phaseCompleteMessanger) {
        this.phaseCompleteMessanger = phaseCompleteMessanger;
    }

    public void process(String message){
        System.out.println("Extensive processing involving multiple threads, " +
                "hand-shakes, retries, failure recoveries, and takes-time " +
                "and lastly calls back to done function");
    }

    private void done(){
        phaseCompleteMessanger.run();
    }
}

SecondPhaseManager class:

package com.vg;

public class SecondPhaseManager {


    public void process(String message){
        System.out.println("perform extensive processing");
    }
}

Covariant return type on Eigen Matrix for base class method

Suppose that I have two different solvers that both will be called at run time.

  • I want to call solvers' api and get resulted Eigen matrix through the base class pointer.
  • The solved matrix size are selected from a few known values depending on some runtime variable. I need to use compiled time fixed size matrix in this case.

The solver derived class definitions are as follow.

template <int VarSize>
class SolverA : Solver {
 public:
  SolverA() {}

  bool Solve() override {
    // SolverA specific implementations.
  }
  const Eigen::Matrix<double, VarSize, 1>& solution() override {
    return solution_;
  }
 private:
  Eigen::Matrix<double, VarSize, 1> solution_;
}


template <int VarSize>
class SolverB : Solver {
 public:
  SolverB() {}

  bool Solve() override {
    // SolverB specific implementations.
  }
  const Eigen::Matrix<double, VarSize, 1>& solution() override {
    return solution_;
  }
 private:
  Eigen::Matrix<double, VarSize, 1> solution_;
}

Now the problem is how I can write the base class solution() method to get the resulted Eigen matrix, since the template parameter VarSize are not known in the base declaration.

class Solver {
 public:
  virtual bool Solve() = 0;
  // not covariant type, won't compile.
  // virtual const Eigen::VectorXd& solution() = 0;
}

constexpr int kEasyProbSize = 5;
constexpr int kHardProbSize = 20;

int main() {
  Solver* solver;

  if (GetComplexity() > 30) {
    solver = &SolverB<kHardProbSize>();
  } else {
    solver = &SolverA<kEasyProbSize>();
  }
  solver->Solve();
  std::cout << solver->solution() << std::endl;
}

Some thoughts:

  • Eigen::Matrix<double, VarSize, 1> does not derive from Eigen::VectorXd so it cannot override.
  • I also cannot use const Eigen::MatrixBase<Derived>& since there is no that derived information and virtual method won't allow template.
  • I need to call from base class pointer so I cannot make the base class a template class.
  • The solved solution_ is already allocated and doesn't make sense to return a copy or converted to a dynamic size matrix.

Is this fixed size matrix getting from base class pointer even possible?

How to Dynamically Switch API providers in case one provider is not available

I am working on a project where I want to be able to use any available API. For example, a mobile app needs to display the weather information to a user by obtaining weather data from the backend API and there exist 2 weather APIs(API_1, and API_2) interfaced by my backend. I would like to get the weather information from API_2 in case there is a network error in API_1 and vice versa.

I thought of using if statements but it won't help that much if in the future I decide to add API_n. I appreciate Any guide or link that can help me design a solution for this problem. Thank you

Inappropriate Intimacy in factory

My Factory has dependency on Repository. It calls many methods from Repository. Lets say something like this:

class CarFactory {
    private Repository repository;

    Car create() {
        detail = repository.findSomeDetail();
        if(detail.large()) {
          anotherDetail = repository.findAnotherDetail();
          return new Car(detail, anotherDetail);
        } else {
          anotherDetail = repository.findYetAnotherDetail();
          if(anotherDetail.expensive()) {
              cheapDetail = repository.findCheapDetail();
              return new SecondHandCar(cheapDetail);
          } else {
              smallDetail = repository.findSmallDetail();
              return new SmallCar(smallDetail);
          }
    }
}

It is hard to test, I need to mock lots of Repository methods. One problem is that Repository takes a lot of time to find something, so I can not find everything and then pick whatever I need. I need to call its methods only after certain criteria was met. Repository manages only single entity type, so I don't think it is a God Object. I tried to use Builder and ended up with:

class CarFactory {
    private Repository repository;
    private CarBuilder builder;

    Car create() {
        detail = repository.findSomeDetail();
        return builder.buildBasedOn(detail);
    }
}

However, it introduces new dependency in CarFactory and there is still problems inside Builder itself.

jeudi 12 mai 2022

Database and Buisness Layer Design for Python App

I am trying to understand how to design a python app using UML class diagrams. Take the following database design as an example.

enter image description here

Now I am having troubles understanding how to create class diagrams out of this, specifically in the context of separating the Data layer (SQLAlchemy Models??) from business layer.

Would the data access layer be something like a SQL alchemy model for each table that inherits from some Base model with create, update, delete methods? What other sort of methods might I include in each model? Im assuming some high level function like send_message() would be in a separate class in a higher layer? Something like:

class UserModel(BaseModel):
    __tablename__ = 'user'
    username = Column(String(50), nullable=False)
    password = Column(String(200), nullable=False)


class ConversationUserModel(BaseModel):
    __tablename__ = 'conversation_user'
    user_id = Column(ForeignKey('user.id'), nullable=False)
    conversation_id = Column(ForeignKey('conversation.id'), nullable=False)
    unread_messages = Column(Integer)


class ConversationModel(BaseModel):
    __tablename__ = 'conversation'


class MessageModel(BaseModel):
    __tablename__ = 'user'
    text = Column(String(50), nullable=False)
    sender_id = Column(ForeignKey('user.id'), nullable=False)
    conversation_id = Column(ForeignKey('conversation.id'), nullable=False)

Where BaseModel contains attributes: created_at, updated_at, and methods: create, update, delete.

Now the part that confuses me even more, is how to create a business layer. Is this a completely separate set of classes with business related functions such as create_user(), send_message(), add_user_to_convo() etc.. Would these classes be separated by each individual entity (conversation, user, message)? And how would they instantiate the models? something like?:

class User:
    def __init__(self, user: UserModel = None):
        self.user = user
    
    def create_user(username: str, password: str, encoded_photo: str):
        # handle password hashing, photo storage, etc..
        pass

    def send_message(text: str, convo_id: int):
        # utilize MessageModel, ConversationModel to send a new message
        pass


class Conversation:
    def __init__(self, conversation: ConversationModel = None):
        self.conversation = conversation
    
    def add_user_to_convo(user_id):
        # do stuff
        pass

Or maybe this doesn't really make sense because its not based on what each entities actions are (eg. A user sends a message, but a user does not necessarily create a user. Likewise, a conversation does not add a user to a conversation, but instead a user adds a user to a conversation). If thats the case wouldn't the user class have almost all of the functions, as most of the actions of an application are invoked by a user. Then something like a Message class might not make sense since there is nothing that a message does.

On a related note, take this UML diagram for example, which is similar to almost every UML diagram I am trying to learn from: https://miro.medium.com/max/1200/1*Srh6QviwDT6LFFdSnyzelA.png. This UML diagram to me seems to squash the business and data layer together, as all the data exists as attributes of the class, and high level functions are also associated with each class. If thats the way I am supposed to implement some design given to me, how would that translate into code?

Separate request building and execution

I have a few kinds of requests that have different payloads (or no payload at all). I want to separate request building from its execution, so I have RequestFactory that produces abstract Request and RequestExecutor that has method execute(request). The problem is that logic of request execution is coupled with its type, so I would need to have cases like this:

if(request instanceof SomeTypeOfRequest) ((SomeTypeOfRequest) request).getPayload()

Another approach is to have execute method inside Request but that leads to having all of RequestExecutor dependencies inside RequestFactory as I need them to build a request. What other options do I have?

What is the best practice to construct an object depending of external calls?

I am trying to build an object that gets its data from external APIs. I will try to explain it with an example:

First of all, I get a POST body in my API to create an object:

class CarRequestBody {
    private String colorId;
    private String engineId;
    //Constructors, etc.
}

Then with this info I need to build a detailed instance of the Car. Feeding the data from external services:

ColorDetails color = colorApiClient.getColor(colorId);
EngineSpecifications engine = engineApiClient.getEngine(engineId);

And finally I build my Domain Object with all this info.

So i would like to know what is the best practice in order to build the instance. I have thought in 3 different ways:

1 - A method in CarService like this:

public Car createCar(CartRequestBody body) {
    ColorDetails color = colorApiClient.getColor(body.getColorId);
    EngineSpecifications engine = engineApiClient.getEngine(body.getEngineId);
    Car car = new Car(color, engine);
} 

2 - Feed the data in the constructor:

public Car(CarRequestBody body) {
    this.color = colorApiClient.getColor(body.getColorId);
    this.engine = engineApiClient.getEngine(body.getEngineId);
}

3 - In the getters of the domain class:

class Car {
    private ColorData color;
    private EngineSpecifications engine;
    //Constructor

    public ColorData getColor() {
        if (color == null){
            return colorApiClient.getColor(colorId);
        }
        return this.color;
    }
    ....
}

Is there some design patter for this scenario?

Should we use a DAL and BLL when working with cloud?

I am new to cloud technologies, and I am designing an API which talks to the azure cloud storage account.

I want to decouple the cloud interaction and I was thinking if it would be a good way to have a Data Access Layer where the data from storage account will be accessed.

And then having the Business Logic Layer for doing any manipulation with the data before the API service will receive it.

Is this a good approach ? If not, please help with any suggestions.

Best regards !

Using adapter pattern to plug multiple file types into single interface

I'm trying to build a program to compare data in various file formats (e.g., CSV, JSON and XML). I want to be able to use a single interface that can handle different file formats and is easily extendible with additional file formats.

The main interface should be able to compare two files with different formats (e.g., CSV and JSON). This will require a step to extract and convert the data into a dict for example.

It seems the object-oriented adapter pattern is perfectly suited for this. Unfortunately, I am not familiar with this design pattern and do not fully understand how to implement it.

I have created a small outline, but cannot understand how to integrate the parts:

class DataComparer:

    def __init__(self, source, target):
        self.source = source
        self.target = target

    def compare(self):
        # do comparison


class CSV:
    
    def __init__(self, csv_file):
        self.csv_file = csv_file

    def extract_convert(self):
        # extract and convert


class JSON:

    def __init__(self, json_file):
        self.json_file = json_file

    def extract_convert(self):
        # extract and convert


class XML:

    def __init__(self, xml_file):
        self.xml_file = xml_file

    def extract_convert(self):
        # extract and convert

Does anyone know how to approach this problem with the adapter design pattern? Suggestions for other design patterns are also welcome. Your help us much appreciated!

mercredi 11 mai 2022

Python Adapter pattern class takes no arguments error

I am learning the Adapter pattern using a straightforward example, I am facing a TypeError: ElfAdapter() takes no arguments when I am trying to add Class as an argument. WHY...? any ideas?

class Elf:
    def null_nin(self):
        print('Elfs says: calling the overlord ...')

class ElfAdapter:
    def __int__(self, elf):
        self.elf = elf

    def call_me(self):
        self.elf.null_nin()

if __name__ == '__main__':
    minions = [ElfAdapter(Elf())]

    for minion in minions:
        minion.call_me()

Create many class objects with little repetition

I'm working on a Python wrapper for a REST API. The API has many types of endpoints, like Users, Participants, Payments, Calendars, Periods, etc...

Many of these endpoints have the same set of, or a subset of, methods, like: create, create_versions, get, get_versions, list, delete, delete_versions, update and update_versions.

Some of the endpoints do not support versioning, so in those the *_versions methods need to be left out. Other do not allow create or even delete. Finally there are two special cases that need there own implementation entirely.

So far, I've implemented a Client class to store the session and handle the get, post, put, update and delete requests. And an Endpoint class to define the methods above, with a reference to the Client.

Inheriting from the Endpoint class enables all of the methods by default. Not very user friendly.

What is a good design-pattern to implement this use case?

.NET/C# Unit of work pattern with generic repositories

Im creating unit of work with generic repository, the question is about a performance in two approaches:

First - creating singleton unitofwork instance and whenever getting a request for any repo usage, check if its already created - then use it, or if not - create one:

public class UnitOfWork : IUnitOfWork
{
    public Dictionary<Type, object> _repositories = new();
    private readonly Context _context;

    public UnitOfWork(Context context)
    {
        _context = context;
    }

    public IRepository<T> Repository<T>()
    {
        if (_repositories.ContainsKey(typeof(T)))
            return _repositories[typeof(T)] as IRepository<T>;

        var requestedRepositoryType = new Repository<T>(_context);

        _repositories.TryAdd(typeof(T), requestedRepositoryType);

        return requestedRepositoryType;
    }
}

Second: just simply create unitOfWork as in 99% existing examples with scoped injection like eg here https://medium.com/codex/generic-repository-unit-of-work-patterns-in-net-b830b7fb5668

Im wondering if using my approach wouldnt have better performance because we can just simply use one implementation of unitofwork and repositories (only first use when they are created will cost us). Have anyone more experienced can mayby give me a quick explanation of that topic?

Best regards and thanks in advance.

mardi 10 mai 2022

Replacing borland VCL library with visual studio 2019 supported UI libary

I have a project which use Borland v6 VCL UI libary and I want to migrate my code base to Visual Studio 2019, can u share an equivalent libary that I can use for UI level ? I dont want to pay for cross platform sw (QT framework), if you know a free libary that l can use, can u add them as a comment? The application is a desktop app, and I want to isolate UI level with business logic and want to implement MVC design pattern, is there a libary that will full fill that requirment?

Thanks Ben

lundi 9 mai 2022

Specification pattern vs Always valid domain model

Let's say we have two aggregates:

public class Order : IAggregateRoot
{
    public Address Address { get; private set; }
    
    public int? BuyerId {get; private set}

    public OrderStatus OrderStatus { get; private set; }

    public string Description {get; private set;}
}

and

public class Buyer : IAggregateRoot
{
    public string IdentityGuid { get; private set; }

    public string Name { get; private set; }

    public IEnumerable<PaymentMethod> PaymentMethods => _paymentMethods.AsReadOnly();
    
    public bool IsActivated { get; private set; }
}

and we want to allow only activated user to create an order. Should this logic be inserted in domain service or in specification pattern like this (and how this will affect always valid domain model state):

interface ISpecification {
    bool IsSatisfiedBy(Offer offer);
}
public class OrderSpecification : ISpecification {
    private Buyer _buyer;
    public OrderSpecification(Buyer buyer) =>
        _buyer = buyer;

    public bool IsSatisfiedBy(Order order) => buyer.IsActivated 
...
}

and then in order

    public Order(..., ISpecification spec) {
        // field initialize and then 

        if (!spec.IsSatisfiedBy(this))
            throw new OfferConstructionDomainException(...);
    }

Any way to set a hook to a variable?

I'm designing a new functionality that would override or take control of some variables' value that have been preloaded into memory during boot.

For instance, system has preloaded some bin files and parsed their contents into memory. And we have some C++ classes, say CBinaryParam, to represent them. What I am supposed to achieve is that user can set new values, by providing a setting file or by keyboard input. And when such situation happens, the new value is supposed to "override" the one in CBinaryParam. Since CBinaryParam is composed by other team, and the code is auto-generated, hence it's not convenient to change implementation of CBinaryParam, let alone it's not easy to achieve.

Hence I'm looking for a trick/solution/design pattern, that would allow me to kind of set a hook between user input and preloaded binary parameters, and if user input is present, its value would automatically "override" corresponding binary parameters, otherwise original binary parameters will be used, without changing internal implementation of CBinaryParam.

Does the Observer Design Pattern Work For Food Delivery Status Updates?

I've recently been learning about the Observer design pattern and understand canonical examples like newspapers notifying their subscribers like so:

public class NewsPaper implements Publisher{
    List<Subscriber> subscribers;

    @Override
    public void register(Subscriber s) {
        this.subscribers.add(s);
    }

    @Override
    public void unregister(Subscriber s) {
        this.subscribers.remove(s);
    }

    @Override
    public void update(String type) {
        this.subscribers.forEach(subscriber -> subscriber.update()));
    }
}

I was thinking about how something like this would translate to a food delivery notification service where each delivery needs to be notified separately. For example the delivery status would send updates when the order is "on the way", "arriving", ect. Is there a way to apply the observer problem (or another design pattern) to notification services like food delivery?

A map could be used to map each delivery order to the subscribers, but this seemed inefficient since it most likely would be a one -> one relationship.

What is the difference between the ViewModel class and the Repository class?

Inside my application, There are more than 25 fragments and now it is very hard to add new features and fix bugs because reading the code became harder (I feel like I've lost control of the code)

I studied the MVVM pattern 1 week ago and I want to apply this pattern to all fragments, But I still don't understand the difference between the ViewModel class and the Repository class.

I know the ViewModel class can secure the precious data from external conditions but why I should create a Repository class? Why I don't put everything in the ViewModel class?

Please don't link me with external questions because I read everything

Explain like I'm five

What kind of design pattern is MVC

There are three types of design patterns: behavioral, structural and creational.

MVC is also a design pattern, but I can't find what category it belongs to.

samedi 7 mai 2022

Is it acceptable to rethrow Exception's cause?

Sometimes I would want to throw an exception with more information to the user, so they can easily see why the method failed.

My method would look like this:

public myPublicMethod(...) throws Exception1, Exception2 {
  try {
    doSomething(); // this throws OtherException
  }
  catch (OtherException e) {
    Exception cause = e.getCause()
    if (cause instanceof Exception1) {
      throw (Exception1) cause;
    }
    if (cause instanceof Exception2) {
      throw (Exception2) cause;
    }
    throw new IllegalStateException("some other type of exception occurred", cause);
  }
}

Is this design acceptable?

vendredi 6 mai 2022

The best way to implement override data state from parent class

I'm facing a really hard problem. I want to create a wrapper class that can do something like "override" the state of the child without affecting them. Quite hard to understand, I know.

Let's see some minimal code below:

class State{
    key: string; //Unique key
    //This is really complex, nested, array, etc state.
    value: number | string | State | State[] | any
}

class Child{
    state : State;
}
class Wrapper{
    overrideState: State;
    child: Child;
    
    constructor(child: Child){
        this.child = child;
    }

    getFinalState() : State{
        //This will return the new State (or not), that is the final state
    }
}

A function to call them:

function client(){
    let child = new Child();
    child.state = new State();
    child.state.value = "original";

    let parent = new Wrapper(child);
    parent.overrideState = new State();
    parent.overrideState.value == "overrided"

    console.log(parent.getFinalState().value); //It should be `overrided`, simple
}

The problem is State class is really complex.

Actually, I have almost done with the getFinalState function by using looping, checking type, Lodash.cloneDeep,...a ton of code. And I think it's really complex to maintain, hard to read, and maybe has some risk.

I don't think my way is right, I try to research some design patterns but am still stuck. If you have any ideas, keywords, or something. I really appreciate that. Thank you