mardi 31 août 2021

Custom Search and Filter functionality VueJS

I was hoping I could get some feedback on something I'm working on. I'm building an application that is essentially a bunch of data tables. Part of my requirement is not to use any additional frameworks (vuetify) or any type of store (vuex).

Currently, my application is constructed as follows:

  • API call upon creation of app
  • That data get's passed into a component where I would like to do all my searching/filtering
  • From there the next component is built specifically for Pagination
  • Then to the component that builds the data tables.

My question is, since I have this top down approach, how do I build both the search and filter functionality to where I don't have to pass anything back up to the parent components?

I am using scoped slots to pass/inject data into child components. My first thought was that I would have a computed property that returns an array in the control component and then pass that down to the pagination component, which works, but how do I also use that same array if I want to be able to filter results and also search filtered and none filtered items? Essentially to be able to mock the functionality of some of the Vuetify tables.

Are creational design patterns useless in Dependency Injection environment ( like SpringBoot)?

Hi right now I am studing design pattern domain, and at one moment catched my self with ideea that most of creationla patterns like Factory, AbstractFactory are not so useful in scope of a dependency injection environment where we usualy didn't create objects with new keyword but "injecting" them from some context, I also understand that most probably I am wrong and I need a good explanion to make things clear if someone can provide it will be cool, thank you in advance.

Best practice for compatibility with 32-bit systems for softwares using version dependent data files?

In the easy case, when the program is independent of any external data-base, one could write something of the form:

#include <stdint.h>
#if UINTPTR_MAX == 0xffffffff
/* 32-bit */
typedef some_type_for_32_bit_version Type;

#elif UINTPTR_MAX == 0xffffffffffffffff
/* 64-bit */
typedef some_type_for_64_bit_version Type;
#endif

And continue to work with the desired type.

Now suppose the program reads some meta/data file at the beginning, some bit represents if the file is built for 32-bit or 64-bit (files built for 32-bit should work on 64-bit as well, files built for 64-bit should only work on 64-bit). The program may operate pretty much the same for both cases, but has subtle differences, e.g. some variable is uint32_t for 32-bit and uint64_t for 64-bit.

A bad solution would be to start by reading that bit, have different version of that variable and any struct/union/function that use it, and have a ton of unnecessary if statements.

I thought of having some loader program that reads that byte, writes to some #define in another file, runs a compiler and finally runs the generated program - but that seems too nasty and I'm not thrilled by the idea of having to suffer compilation time at every run.

Is there any general design for that? Something specific to c? c++?

Single responsability principle on complex process

I always had a question on how to assure the single responsability principle when the process I have to assure is quite complex.

I work with a 3 layers architecture Backend : Controller (my API endpoints) | Service (single responsability functions) | Data (access to the DB)

Let's say I have a process ProcessA that is composed by 4 tasks TasksA1, TasksA2, TasksA3, TasksA4.

If I have an endpoint exposed on my controller layer such as : POSTMethodProcessA

How should be composed my code in order to respect the single responsability principle on my service layer ?

The options I see :

Option 1 (the controller must know the process) :

class MyController {
  exports.processA = functions.https.onRequest(req, res) => {
    myservice.doTaskA1(); // single responsability on task1
    myservice.doTaskA2(); // single responsability on task1
    myservice.doTaskA3(); // single responsability on task1
    myservice.doTaskA4(); // single responsability on task1
  });
}

Option 2 (the service know the process and loose the Single responsability)

class MyController {
  exports.processA = functions.https.onRequest(req, res) => {
    myservice.doProcessA();
  });
}

//inside the service (the doProcessA method must be in charge of multiples tasks and loose the single responsability principle :
class MyService {
  function doProcessA() {
    this.doTasksA1();
    this.doTasksA2();
    this.doTasksA3();
    this.doTasksA4();
  }
}

This question is even more complicated to me if the tasks are composed themselves by multiple jobs : FirstJobA1, SecondJobA1, ThirdJobA1 ...

How those complexities layer should be handled on the code structure to respect the single responsability principle is something that always blocked me. Any insight would be a great help !

How to avoid repeat code when converting files?

Let's say I have a class whose function is to convert file types:

@dataclass
class Converter:
    data: Union[str, pd.DataFrame]

    def to_pickle(self):
        """Check the type of data. 

        Returns:
            a pickle file if the table exists, a string otherwise.
        """
        if isinstance(self.data, pd.DataFrame):
            return pd.to_pickle(self.data, "table_data.pkl")
        else:
            return self.data
        
    def to_csv(self):
        """Check the type of data. 

        Returns:
            a csv file if the table exists, a string otherwise.
        """
        if isinstance(self.data, pd.DataFrame):
            return pd.to_csv(
                self.data, "./table_data.csv", 
                index=False, 
                encoding="utf_8_sig",)
        else:
            return self.data

Since both methods will first check the datatype. If the data is a dataframe, both methods will apply pd.to_csv and pd.to_pickle. Otherwise, a string will be returned.

It seems that the only difference between to_csv() and to_pickle() is the convert type (i.e. pd.to_csv and pd.to_pickle). Is there any way to not repeat the code?

Better way to do it? [closed]

Need help with designing attendance display and update feature.
Currently have 2 components - one to display attendance and one to update it. Both components have a common parent.
I want to achieve update in display component without refreshing the page i.e. as soon as update component updates database, I want display component to be automatically updated.

Stack:
FrontEnd : React
BackEnd : Express
GraphQL Client

Code is something like this:

<Parent>
  <DisplayAttendance />
  <UpdateAttendance />
</Parent>

lundi 30 août 2021

Recursion - should the Package/Library do it, or the user?

So to give further context; I am creating a Golang package/module to front a REST API.

The rest API does pagination and page sizes.

As the module creator, I obviously want to return the results. Should I create a return all function which recursively goes through all pages and return the complete dataset, or essentially mimic then REST API and offer a function where the user passes the page number and limit, and they then create a recursive function on their end.

I've looked at the UNIX design philosophy and while there is no clear answer, it looks like I should lean towards providing a basic function, and letting the user create the recursion.

I would appreciate any input/opinions - thanks in advanced.

Why are there different ways to describe same design pattern using UML? What to trust?

I find it difficult to learn both Design Pattern and UML since there are different ways to describe the same pattern which make me unsure what is the single source of truth.

Take Iterator pattern for example, here are just a few diagrams that I saw from well-known sites:

1 WIKIPEDIA

https://en.wikipedia.org/wiki/Iterator_pattern

enter image description here

2 TUTORIALS POINT

https://www.tutorialspoint.com/design_pattern/iterator_pattern.htm

enter image description here

3 REFACTORING GURU

https://refactoring.guru/design-patterns/iterator

enter image description here

4 OODESIGN

https://www.oodesign.com/iterator-pattern.html

enter image description here

5 HOWTODOINJAVA

https://howtodoinjava.com/design-patterns/behavioral/iterator-design-pattern/

enter image description here

What confuses me the most is how arrow symbols are used to describe the relationship between these classes. Sometimes they are generalization, sometimes interface realization, directed association or dependency. Even composition is also used...

I wonder what would be the best way for me to get my head around all this.

How do I determine platform coverage for mobile devices in the U.S. & globally?

At some point in time, I had a link that showed a nice pie chart of all of the Android and iPhone models across tablets & mobile devices with their associated % market share and screen dimensions by country. I've lost the link sadly. =(

What mobile devices do I need to support 95% coverage of the U.S. market? Does someone have a resource for mobile devices with their associated % market share and screen dimensions by country?

Yes I have googled it and it's NOT the following link:

https://gs.statcounter.com/screen-resolution-stats/mobile/worldwide

I want to put constraint based on the extension only. I am trying to use the following -

<security-constraint>
    <display-name>XYZRole</display-name>
    <web-resource-collection>
        <web-resource-name>XYZRole</web-resource-name>
        <url-pattern>*.bear</url-pattern>
        <http-method>GET</http-method>
        <http-method>PUT</http-method>
        <http-method>HEAD</http-method>
        <http-method>TRACE</http-method>
        <http-method>POST</http-method>
        <http-method>DELETE</http-method>
        <http-method>OPTIONS</http-method>
    </web-resource-collection>

    <auth-constraint>
        <description>Access to XYZRole</description>
        <role-name>XYZRole</role-name>
    </auth-constraint>
    
</security-constraint>

The security.user.names.bear and security.user.roles.bear in defined in properties file. But it is not doing the whitelisting of valid Tenant.

How to put the extension URL pattern in <security-constraint>

Finding strings that do not include specific patterns in Lua

(Sorry if the title is vague, I couldn't figure out a way to summarize this properly even though the problem itself is easy).

Say I have a Lua string like this: s = "dog frog bag bog cat shop hog" and I want to get a substring from it that only includes those words that do not include the letter "a". How would I go about doing this?

What generic constraint to use in C# for all basic types like int float string etc?

I am trying to implement an Observer pattern in C#, specifically in Unity. I want to make it such that whenever any flags or values change, I want events to fire. So far I have following:

public interface IObservable<T> : IDisposable where T : object
{
    public void Subscribe(Action<T> callback);
}

public class Observable<T> : IObservable<T> where T : object
{
    private Action<T> onValueChanged;

    private T _value;

    public T Value
    {
        get
        {
            return _value;
        }
        set
        {
            _value = value;
            onValueChanged.Invoke(_value);
        }
    }
    public Observable(T newVal)
    {
        _value = newVal;
    }
    public void Subscribe(Action<T> callback)
    {
        onValueChanged += callback;
    }

    public void UnSubscribe(Action<T> callback)
    {
        onValueChanged -= callback;
    }

    public void Dispose()
    {
    }
}

I want this to work on basic types like floats, strings, int, etc, possibly on custom classes too. But currently I am facing this error:

Constraint cannot be special class 'object'

I understand that every class is ultimately a child of object which is why the error is showing. But if I do change the generic constraint to class, I can't use them on basic data-types because they are not reference types, which doesn't work too.

How do I go about doing that, I can't seem to wrap my head around it! Any leads or hints would be greatly appreciated!

How to implement pb message polymorphism like c++

In C++, I have a class T, it's constructed like:

class T {
public:
    T(X* x) { // X is pb message 
     .....
    }
    // some func use x
    .....
};

Then, a class A which uses T like:

class A {
    void funcA(X* x) { // X is pb message 
        T* t = new T(x);
        ....
    }
};

And now, a new class B wants to use T, but this class use message Y. Message Y and X are similar. But it was already used by other service, so I can't just change it to X. (So does X.)

class B {
    void funcB(Y* y) { // y is pb message, which is similar with x. 
        T* t = new T(y); // error
        ....
    }
};

Copy T and make a new class T1 can solve this problem, but it's weird, not a good design.

class T1 {
public:
    T1(Y* y) { // y is pb message 
     .....
    }
    // some func use y
    .....
};

If X, Ys were common C++ class, I could make them inherit from Z, and change T(X* x); to T(Z* z); But they are both pb message, is there any solution? Maybe change T constructor to a template func?

Please help me. Thank you!

dimanche 29 août 2021

Python pass parameters/variables between two files

It is hard to describe but I will try my best. What i want is similar to this scenario. in main.py file:

var = None
while true:
    var += 1
    time.sleep(1)

in my anotherpythonfile.py

I want to access the var, but in every 5 second or whenever i want and check the current value. is there any design pattern for it?or any method?

samedi 28 août 2021

Could there be caused any problem creating a modal component using observer pattern like this?

Okay I've never looked into design patterns and so far what I've been doing I've created a modal component that takes children and in every component that I used it I was creating a state to check if I should show modal or not like this:

const Modal = ({...someOtherProps,children})=>{
   
return(
  <div>{children}</div>
)
}

and in every single component where I needed to show modal I was doing like

const Component1 =() =>{
const [showModal,setShowModal] = useState(false);
  

return (
<div>
<button onClick={setShowModal.bind(null,true)}>Add Data</button>

{showModal && <Modal>
<AddDataForm/>
</Modal>
</div>

)

}

I knew this is not the best way of doing it and I looked up at design patterns as soon as I saw the Observer Pattern I thought that this would solve this problem, how I changed it now is like this:

I created a class that will act as the Observable

class ModalObservable {
  constructor() {
    this.open = false;
    this.child = null;
    this.subscriber = null;
  }

  setSubscriber(sub) {
    this.subscriber = sub;
  }

  subscribe(child) {
    this.child = child;
    this.open = true;
    this.notify();
  }

  unsubscribe() {
    this.child = null;
    this.open = false;
    this.notify();
  }

  notify() {
    this.subscriber(() => ({ ...this }));
  }
}


export const modalObservable = new ModalObservable();

const Modal = () => {
  const [modal, setModal] = useState(null);
  console.log(modal);
  useEffect(() => {
    modalObservable.setSubscriber(setModal);
  }, []);
  return modal?.open ? <div>{modal.child}</div> : null;
};

const Component = () => {
  return <div>This is a modal child</div>;
};

and now whenever I have to use it in a component I Just do

const MyComponent = ()=>{

return (

  <button onClick={()=>{
modalObservable.subscribe(<AddDataForm/>)
}}>Add Data</div>
)
}

I am wondering if there could be any down side to this?

designing python code, use var from one method within another

I am having a code where I run several checks, like

def run_checks():
  check_on_color()
  check_on_size()

normally all the checks are independent, but in a very few cases, it would be good to use a value within one of these checks and use it within another. What would be the best pythonic way to do this? Is it ok to define a global var then, or should I rather return the value like:

def run_checks():
  one_var = check_on_color()
  check_on_size(one_var)

I don't like returning var so much, because its not the actual task of the method to return something, its more a byproduct. But using a global var to transfer a value from one independent method to another also seems quite quirky.

Design pattern to execute multiple sequential functions as a unit of work and support rollbacks

I have a complicated review application submission process that does several steps.

ReviewService.CreateReview()

  • CheckReservedTimeslotIsAvailable
  • ProcessPayment
  • CreateMeeting
  • InsertReview
  • UpdateFinancialJournal
  • FinalizeDocuments
  • Notify

All these steps are coded inside the CreateReview() method and is becoming un-readable, hard to manage. Also the current implementation doesn't have the support of rollbacks.

So the idea is to create an Orchestrator class and build the sequence of steps. The orchestrator ensures a successful review is created if all steps are completed. If any of the step fails to complete then all of the completed preceding functions are rolled back to ensure data integrity. This is pretty much the same as Saga pattern (Orchestrated) but with slight change the steps are not micro services.

Is this the right pattern to use? Or Command pattern would be a good option? Please advise.

vendredi 27 août 2021

Powershell -match with variable in pattern

Hoping an experienced coder could explain why a variable create from contents of a text file and added to a match pattern does not work...but a variable with a static string does?

$computer = "TYMXL-F3MC012WV"

$s_01 =  (Get-Content $path\source_files\pascodes.txt -Raw).replace("`n","|") #F3MC|FRSE|FGTS
$s_02 = "F3MC|FRSE|FGTS"

$computer -match "^(TYMX|MPLS)(W|L|T|V)-($s_01)([a-zA-Z0-9]{1}).+$" #false
$computer -match "^(TYMX|MPLS)(W|L|T|V)-($s_02)([a-zA-Z0-9]{1}).+$" #true

diamond pattern with odd numbers only [closed]

Print the following pattern for the given number of rows. Note: N is always odd.

Pattern for N = 5

The dots represent spaces. enter image description here

What is the best design for scheduling regular API calls?

I have a small(ish) MongoDB collection of 100 documents. Each of these has some fields, which are used in the API call (location, timezone, etc.). Each of these belongs to a profile based on their expected volume, and would dictate how often the API should be called, for that specific item, for example:

  • Profile A: API call every 5 minutes if current local time is between 0700 and 1900, otherwise every 30 minutes
  • Profile B: API call every 15 minutes, if 0700-1900 as above, otherwise every 30 minutes
  • Profile C: Every 30 minutes

During testing, I would call the API for each of these, but now I want to be more specific. What would be an efficient way of doing this(if this were to be hosted on the cloud, I don't want it to loop constantly multiple times per second)?

  • Easiest would be a loop that constantly checks
  • My gut is telling me to use the python scheduler? Example below:
def update_one(id):
    make_api_call(id) #gets the data based on the id specified
    process_response(id) #do whatever needs to be done with the information
    current_local = get_local_time(id) #get the local time for this place
    #find the next time this location is to be polled in the API
    next_task = get_next_call(id,current_local) 
    add_to_queue(id,next_task)

Or, should I rely on existing tools from cloud providers to schedule these things?

Good solutions for heirchical and type-based data in java

I am struggling with how best to approach a complex filtering system.

The idea is to let the user define a filter on certain objects and then to search/send notifications based on that filter.

The objects are of the same archetype and but can have different fields between them and some fields can have a set of predetermined values that are allowed.

Just as an example: A filter that can be of type PC or type Laptop, some fields are similar (like os and price range) and some are not (like inch for a laptop).

The filters also need to be saved inside a JSON-type database.

To maintain the set of fields we thought about creating a Conventions class with a hierarchy of static classes that each hold final static int values each corresponding to a certain field and their possible corresponding values as integers (basically a static dictionary).

To save this kind of filter object we thought of using JSON, and ultimately.

The solution seems kinda clunky however and messy to implement or maintain so I've been wondering if there's any clever design pattern to tackle this issue in java.

Choosing an Online payment Processor

This is not so much a coding question but more of an architectural/advice question. Im working on a project and need to integrate with a payment processor. The two options I was thinking is Stripe and Braintree.

My Requirements are as follows:

  • Monthly recurring payments.
  • One time payments on top of recurring payments. (For upselling products)
  • Must have native experience, no leaving the app to pay bill.
  • Should be able to use ACH or Credit cards.

I have been reading through the documentations and neither companies really talk about the native experience, but DO talk alot about no code solutions, which require clients to leave the site. I am not confident which one has a better native experience, but they must have it since you dont leave the site in Lyft or Airbnb.

For recurring payments, both have built in subscriptions services, but was thinking it might just be easier for me to implement my own subscription service by using a daily cron job to check if its their billing date and simply do one time charges.

Would love to hear some advice from the community. Thanks!

Abstract Factory create objects based on different json format

We need to create a few types of dynamic metadata base on different json format, for example: metadata1

"metadata1": [{
        "item1": "address1",
        "date": "Jan -Jun22",
        "tag": true,
        "itemurl":"item url"
      }]
}

metadata2

{
    "amount": 100,
    "item3": {
        "amount:" 1200,
        "currency": "AUD"
      }
    "item4": [
        "blabla",
        "yaliyada"
      ],
    "flag": true,
    "count": 2
}

And we have those metadata id, I'm thinking the following implementation

public static IMetaData RetrieveMetaData(string metadatDetails, string metadataId)
        {
            switch (metadataId)
            {
                case "metatdata1":
                    return JsonSerializer.Deserialize<MetaData1>(metadatDetails);
                case "metatdata2":
                    return JsonSerializer.Deserialize<MetaData2>(metadatDetails);
                case "metatdata3":
                    return JsonSerializer.Deserialize<MetaData3>(metadatDetails);
                default:
                    return null;
            }
        }

Is there any better implementation using abstract factory? I'm not too familiar with design pattern. I'm thinking to remove switch block, not sure if it's possible. Thanks for advance.

jeudi 26 août 2021

Builder pattern with struct

I'm trying to implement a builder patter in C++. That what i got by now:

struct Person {
  std::string name;
  uint32_t age;
  std::vector<std::string> pet_names;
};


class PersonBuilder {
public:
  PersonBuilder& SetName(std::string name) {
    person_.name = std::move(name);
    return *this;
  }

  PersonBuilder& SetAge(uint32_t age) {
    person_.age = age;
    return *this;
  }

  PersonBuilder& SetPetNames(std::vector<std::string> pet_names) {
    person_.pet_names = std::move(pet_names);
    return *this;
  }

  Person Build() {
    return Person(std::move(person_));
  }

private:
  Person person_;
};

int main() {
  auto person = PersonBuilder()
      .SetName("John")
      .SetAge(23)
      .SetPetNames({"rax", "rbx", "rcx"})
      .Build();

  return EXIT_SUCCESS;
}

I'm a little worried about unitilized uint32, and std::move(person_) inside a Build method. Am i doing it right or there is a better way, with a struct constructor for example?

What is the best practice for Dependency Injection in Django/Python?

I work on a Django-based product that works as a proxy between an enterprise ERP and some mobile clients. So it supposes to have scalability and easy maintenance in long run.

One challenge I'm facing right now is the ability to have multiple versions both on API I expose to clients, and also API I consume from the ERP.

I have my business logic in a separate module in each app named *_usecase.py, essentially I should implement versioning by having a base UseCase class and override methods for each version and provide the right class instance to view through DI based on request/response header values.

So I've reached this package python-inject. It has pretty neat decorators to inject instances based on configuration you have and type annotation for method parameters. something like:

# in view.py
@inject.autoparams()
def send_notification(
    request, 
    use_case: SendNotificationUseCase, 
    # as many type annotated parameters you required
):
    pass

# in binder.py
class AppNameBinder(BaseBinder):
    def __call__(self, binder, *args, **kwargs):
        binder.bind_to_provider(
            SendNotificationUseCase, 
            self.provide_send_notification_use_case
        )
    def provide_send_notification_use_case(self):
            # some check and logic to evaluate appropriate version
            return SendNotificationUseCaseV1() # v1 implementation of usecase

So this package does the job eventually, although I had some minor issues with it here and there but, since it doesn't have that many stars and I haven't seen its usage anywhere in the community, I want to know if you guys have better/more pythonic solution for Dependency Injection in Django/Python and also for this versioning challenge I mentioned.

mercredi 25 août 2021

How to avoid fatty jobs in Rails, or even better, How to avoid Active Jobs at all in Rails?

Have you ever seen a code like this using an Old Resque technology?

NOTE: Some details were removed to avoid making any references to a production code like this

# frozen_string_literal: true

class MySuperDuperNotificationsCount < Retryable
  @queue = :integrations

  class << self
    def perform
      # Validating if Notification exist
      return unless msg_type.present?

      # This job will check if doctors have the electronic prescriptions service Notifications and will send
      # a notification per Doctor to each manager
      doctors.each do |doctor|
        send_managers_notification(doctor) unless notifications_empty?(doctor.prescription_notifications)
      end
    end

    private

    def msg_type
      @msg_type ||= MessageType.find_by(group: 'electronic_prescriptions', name: 'doctor notifications count')
    end

    def doctors
      # We need to reduce as much as possible the amount of records to iterate
      # TODO: While this shortens the search there might be other things
      # that we could add like last login time
      @doctors ||= User.with_electronic_prescriptions_enabled
        .enabled_users
        .doctors
        .where.not(prescription_notifications: nil)
    end

    def notifications_count(notifications)
      MyApplicationNamespace::ElectronicPrescriptions::NotificationHelper.notifications_count(notifications)
    end

    def notifications_empty?(prescription_notifications)
      # While the query (doctors) already checks for nil values,
      # due to the way prescription_notifications is build, it can have values
      # but that doesn't mean it has notifications
      # Examples:
      # "[]" No partnerships
      # "[{:clinic_id=>1}, {:clinic_id=>2}]" Two partnerships but no notifications
      # So we need to cover/validate that here

      # This verify if any of the notification types has notifications
      !MyApplicationNamespace::ElectronicPrescriptions::NotificationHelper.has_pending_notifications(
        # At this point prescription_notifications is separated by partnerships
        # So we need to count the total of notifications by type
        notifications_count(prescription_notifications)
      )
    end

    def send_managers_notification(doctor)
      # As required, this will send a Notification to all managers telling them
      # that a specific doctor has pending rcopia notifications
      # 1 Notification per Doctor per manager
      # TODO: Managers for Organization returns staff (including owners)
      # So we need to call managers again (for Users) to scope to Managers only
      doctor.organization.managers.managers.each do |manager|
        # Here we check only for in app notifications settings,
        # if user has the notification enabled we can send the notification,
        # currently this doesn't care aout email settings as the email is not implemented
        notification_enabled = manager.notification_settings.find_by(
          notification_type_id: notification_type.id
        )&.send_in_app

        return unless notification_enabled

        MyApplicationNamespace::Notifications::Manager.queue_notification(
          user_id: manager.id,
          notification_type_id: notification_type.id,
          notifiable_type: doctor.class.to_s,
          notifiable_id: doctor.id,
          payload: notifications_count(doctor.prescription_notifications)
        )
      end
    end
  end
end

And you are running that code every 15 minutes?

What architecture you are following to avoid that?

Well, In this guide we are going to review how to become from that to turn into something great like this:

        ServiceEnqueuerJob.enqueu(
          'GoogleApis::AppointmentCalendarEventCreator',
          'create_event_from',
          appointment_id
        )

or at least like this If you are still using Resque but not Sidekiq

class GoogleCalendarDeleteEventJob
  @queue = :notifications

  class << self
    def enqueue(appointment_id)
      Resque.enqueue(self, appointment_id)
    end

    def perform(appointment_id)
      AppointmentCalendarService.delete_event_for(appointment_id)
    end
  end
end

So you can call it in any place you need it, like in a controller

def create
  if AppointmentEvent.persist_values(params)
    GoogleCalendarDeleteEventJob.enqueue(appt_event.id)
    ...
  else
    ...
  end

Are you interested in the details?

two project that needs the same library

so I have this project that I decided to create an external controls library for, until now I've been creating controls inside the main project but its getting cramped up in that project, and a library could be useful for future projects, but I still need bootstrap in the main project.

the thing is I am mainly using ng-bootstrap for the controls, if I do separate the controls into a controls library is there a way to provide ng-bootstrap to the controls library, from the main project, and if so, how can I do that ?

if not what is the best practice for this ?

and is installing ng-bootstrap in both project a good idea ? It doesn't feel right to do so.

Create loop and save output in .txt or .fasta file

I have an data set with 7754 obs. and 5 variables

name    protein     mutation_CDS    mutation_nonCDS     seq
B*07    02                01               01           ATGCTGGTCATGGCGCCCCGAACCGTCCTCCTGCTGCTCTCGG
B*07    02                01               48           ATGCTGGTCATGGCGCCCCGAACCGTCCTCCTGCTGCTCTCGG
...
B*18    153               NA               NA           ATGCGGGTCACGGCGCCCCGAACCCTCCTCCTGCTGCTCTGGG
B*18    155               NA               NA           ATGCGGGTCACGGCGCCCCGAACCCTCCTCCTGCTGCTCTGGG
...

Within the "name" variable I have 36 different names with different numbers of rows having this name "B07" "B08" "B13" "B14" "B15" "B18" "B27" "B35" "B37" "B38" "B39" "B40" "B41" "B42" "B44" "B45" "B46" "B47" "B48" "B49" "B50" "B51" "B52" "B53" "B54" "B55" "B56" "B57" "B58" "B59" "B67" "B73" "B78" "B81" "B82" "B83"

My idea was, to create a loop within R in which I take the whole data set with its 7754 obs., look for the unique name ("B*07") and store all rows (including columns) having this name and stored it in a new data set with the lable "B07" OR directly create a .txt (or .fasta) file.

I would end up with separate files, for example a file called B07 containing only the B*07 information (620 obs. and 5 variables)

name    protein     mutation_CDS    mutation_nonCDS     seq
B*07    02                01              01            ATGCTGGTCATGGCGCCCCGAACCGTCCTCCTGCTGCTCTCGG
B*07    02                01              48            ATGCTGGTCATGGCGCCCCGAACCGTCCTCCTGCTGCTCTCGG

and a file called B08 containing only the B*08 information (X obs. and 5 variables)

B*18    153     NA      NA          ATGCGGGTCACGGCGCCCCGAACCCTCCTCCTGCTGCTCTGGG
B*18    155     NA      NA          ATGCGGGTCACGGCGCCCCGAACCCTCCTCCTGCTGCTCTGGG

In simple words, I want to split the 7754 observations in their parts referring to a certain name pattern

"B*07" 620 of 7754

"B*08" X of 7754

"B*13" X of 7754

etc.

does anyone have an Idea how to do that?

How to print this pattern in java? [closed]

            1
       2    0    2
   3   0    0    0     3
4  0   0    0    0     0    4

I want to know the condition how zero is printed.

How can I implement the observer-pattern for REST API with ASP Net Core?

I am looking for a way to implement Observer patterns via Rest API, because I have a server (ASP NET Core and C#) and several clients (in Python) (the number of which may vary). In Spring 5, for example, there is WebFlux.

Is there also something like that for ASP NET Core ?

How do I build my R package such that I can quickly adjust some style changes (e.g. main colors/font size)

I am working on my own R package. I am at the point where I want to write some functions that will visualise my data. I want to be able to quickly adjust the style of all my functions when I'm not happy with some configurations. Examples of this will be:

  • Font size
  • Primary/secondary colors
  • Green/Orange/Red colors

Because, suppose I have graphs.R:

graph_a <- function(font_size = 9, primary_color = "#ffffff") { ... }

graph_b <- function(font_size = 9, primary_color = "#ffffff") { ... }

graph_c <- function(font_size = 9, primary_color = "#ffffff") { ... }

It would be a hassle to change all the pre-defined values if I want to increase my font size a bit. I was thinking of using a global constant, but cannot find anything on this on Google, and using a config file seems not the proper tactic as well. The first thing that comes to mind is add the following at the first line of graphs.R:

FONT_SIZE <- 9
PRIMARY_COLOR <- "#ffffff"

But what if I want to use these across my package?

mardi 24 août 2021

Are there any common strategies for choosing an object type to create based on the type of another object

Imagine I have an object that could be any of a number of different types that all derive from a single base type. I want to create a second object which is related to the first object in the sense that its type is dependant on the type of the first object. The type of the second object will however always derive from a second base class.

My go to solution would be to have the first object create the second object through a virtual method.

In this particular situation however, we do not want the two classes to be coupled at all. Neither object should have any existence of the other object.

This means there must be some kind of third-party mediator object creating the second object based on the first objects type.

My next chosen solution would therefore be to have this mediator be a factory which looked specifically at the type of the first object and instantiated the second object based upon it.

To me this works, but seems not an ideal solution. If a factory is creating the first object then whenever a new derived type is added two factories must be updated and a new connection made.

Are there any common design patterns that could help with this and make the code cleaner?

Factory concurrent access

when coding factories there's a thing I always do:

final class FooFactory implements FooFactoryInterface 
{
  /**
   * @var array<string=>mixed> - constructor argument names to values
   */
  private array $constructorArguments = [];

  public function withBar(BarInterface $bar): static
  {
    $factory = clone $this;
    $factory->constructorArguments['bar'] = $bar;

    return $factory;
  } 
}

When calling a method of a factory (could be for entity hydration too), I always add it in a new factory to avoid concurrent accesses, always did it by safety, but can the problem even occur ?

Does all clients use the same factory, the object in memory ? I tend to say each request triggers the creation of all objects, which are then destroyed, but i'm not 100% sure the no-cloning version is safe.

Having a void return type would help with code comprehension, in C functions returning the same string they take as arguments are confusing, and if fluent pattern can be avoided I'll take it. Plus, the interface can't enforce affectation has to be done to get the new state of the factory given by the implementing class, which is a problem to me, interface should say it all.

So, to clone or not to clone ? That's the design question.

Detecting candlestick pattern

I have a question about a simple box drawing algorithm done in a chart.

A box should be drawn over 3 certain candlesticks. The three candlesticks are classified like: the highs and lows of the left and right candlesticks are biggger/lower than the high and the low of the middle one. So the left and right candlestick cover the middle one.

If this pattern is detected, a rectangled (dashed) box should mark that pattern with top box of the highest high and the lowest low of the three candlesticks.

Thank you!

Is it possible for a visitor in c++ to operate over multiple projects?

I'm trying to add a visitor to an existing library. The visitor must be able to visit some classes from separate projects.

Let's say my solution have the following projects: ProjectA, ProjectB and they contain 1 class each respectively: NodeA, NodeB. Since the visitor is only an implementation of a class member outside of the class, I think its dependency won't allow it to be placed at another project. So if I want to create a visitor which can visit both NodeA and NodeB objects, I can't use a simple visitor.

Is this assessment correct?

I was thinking about a couple of solutions to overcome this.

  1. Move one the classes to the other projectand implement visitor there (this isnot a feasible solution).
  2. Add an extra indirection. Create a class for the visitor implementation for each project. And create a "head visitor" which would use these implementation objects.

Am I missing something? Is there a better way to do this?

Please find my visitor implementation below. Please note that I removed header guards for the sake of simplicity.

/// --- Node.h in project A ---
class Visitor;

class Node {
  public:
    Node() = default;
    virtual ~Node() = default;
    virtual void accept(Visitor & v) = 0;
};

/// --- NodeA.h  in project A ---
#include "Visitor.h"

class NodeA : public Node {
public:
    void accept(Visitor & v);
};

/// --- NodeB.h  in project B ---
#include "Visitor.h"

class NodeB : public Node {
public:
    void accept(Visitor & v);
};

/// --- Visitor.h ---
#include "Node.h"

class NodeA;
class NodeB;

class Visitor {
  public:
    Visitor() = default;
    virtual ~Visitor() = default;

    virtual void visit(const Node & node) = 0;
    virtual void visit(const NodeA & node) = 0;
    virtual void visit(const NodeB & node) = 0;
};

// --- Visitor.cpp (includes B.hpp and C.hpp) ---

#include "Visitor.h"
#include "NodeA.h"

void Visitor::visit(const Node & node)
{
   // implementation
}

void Visitor::visit(const NodeA & node)
{
   // implementation
}

void Visitor::visit(const NodeB & node)
{
   // implementation
}


Subset dataframe filtered by specific name

Hi guys I'm new here so it's my first post, be gentle :D

I'm working with DNA sequences and after I have imported the .fasta file (using "readDNAStringSet") and converted the names & sequences into a separate R object with 7754 obs. & 2 variables (names, seq), I want to extract specific rows according their names into a new dataframe. As and example of what I mean, I have 10 names starting with "B07:" and 5 names starting with "B38:", I want to extract from these 15 names only those starting with "B*07:" and save them as a new dataframe for later saving into new .fasta file.

Does anybody have an Idea how I could achieve that?

lundi 23 août 2021

Why Parameterless factory methods are Leaky Abstraction?

I'm reading a book which says:

// code smell
public interface IProductRepositoryFactory {
   IProductRepository Create();
}

The Dependencies created by an Abstract Factory should conceptually require a runtime value, and the translation from a runtime value into an Abstraction should make sense. By specifying an IProductRepositoryFactory Abstraction with a parameterless Create method, you let the consumer know that there are more instances of the given service, and that it has to deal with this. Because another implementation of IProductRepository might not require multiple instances or deterministic disposal at all, you’re therefore leaking implementation details through the Abstract Factory with its parameterless Create method.

I'm a little bit confused here, what does "more instances of the given service" mean, does it mean that you call a concrete Factory's Create method multiple times? what's wrong with that? even if you have factory methods that does have parameters as:

public interface IProductRepositoryFactory {
   IProductRepository Create(string type);
}

and if you call a concrete Factory's Create method multiple times there will be multiple instances too. so what's wrong with parameterless factory methods? what does it leak?

Does Global Access to Imported Variables in Functions Violate the Black-Box Paradigm?

In Python, is it always advisable to access import-ed variables without going through the parameters of a function? Doesn't this violate the black-box paradigm?

For instance: given the statement from collections import deque, I wouldn't expect that one would instantiate a deque object to be passed as a parameter along with every function. Instead, I would expect that a deque would be instantiated as needed.

Suppose, though, that the imported object didn't belong to the canonical libraries in Python. Would it be preferred to access such an object through the parameters of a function, or through the global scope?

Edit: To help illustrate what I mean, take for instance the code below:

from collections import deque

def my_func():
    # this seems to be OK
    nodes = deque()

On the other hand, suppose that we had some other kind of object. Would this be encouraged in Python?

from my_module import SomeClass

def my_func():
    # SomeClass accessed through global scope
    instance_of_some_class = SomeClass()

Doesn't the above violate black-box coding? Alternatively:

from my_module import SomeClass

def my_func(some_class):
    # SomeClass accessed through local scope
    some_class.do_a_thing()

def main():
    # I suppose SomeClass() is being accessed globally here...but this is the crux of my question nonetheless.
    instance_of_some_class = SomeClass()
    my_func(instance_of_some_class)

I realize that as a matter of design, this may be open to opinion; mainly, I was curious if there is a prescribed recommendation in Python.

Using multilevel IntDef for describing a fixed structure of data for efficiency

I'm trying to find a convenient and proper way to support a hierarchical data structure that describes hierarchical data for backend tasks (like comparing and building an object according to the values we get in the hierarchical data). I know that I can use a JSON object (or in fact Hashmap of Hashmaps) or Enum, but maybe using hierarchical IntDef is a better option?

Something like this -

@IntDef({OPTIONS.OPTIONS_A.AA,
        OPTIONS.OPTIONS_A.AB,
        OPTIONS.OPTIONS_A.OPTIONS_AA.AAA,
        OPTIONS.OPTIONS_A.OPTIONS_AA.AAB,
        OPTIONS.OPTIONS_B.BA})

public @interface OPTIONS {
    public @interface OPTIONS_A {
        int AA = 0;
        int AB = 1;

        public @interface OPTIONS_AA {
            int AAA = 10;
            int AAB = 11;
        }
    }

    public @interface OPTIONS_B {
        int BA = 2;
    }
}

Is it make sense at all? Maybe there is a better way or design pattern you are familiar with for representing hierarchical data structure for these kinds of backend tasks? The structure of the data I receive is fixed and only the values can change.

Multi actions API best Practice / Design Pattern

I have an API with a multi actions POST function.

It is structured like that :

exports.myFunction = functions.https.onRequest((request: any, response: any) => {
    const action: 'a' | 'b' | 'c' = request.body.action;
    switch(action) {
      case 'a':
        doProcessA();
        break;
      case 'b': 
        doProcessB();
        break;
      case 'c': 
        doProcessC();        
        break;
    }
    response.send('done');
});

I cannot split this function into 3 exposed functions. Regarding this contraint, is my code clean, or is there any better practice / Design pattern to handle such situation ?

In an MVC-type architecture, where should a Builder class go? Model or Controller?

Suppose you have the following Architecture, and the following definitions of MVC (I know this may not be totally conformant to the "original" MVC as described by Martin Fowler):

  • Model: Responsible for direct data access (not especially for actually holding the data, but for accessing it (for example accessing a database or processing HTTP requests). Exposes some kind of interface to the data for the Controller to work with that data.

  • Controller: Contains the actual business logic, processes data coming from the Model and gives it to the views. Also processes data coming from the user and gives it to the Model to store it.

  • View: Responsible for displaying the Data (and other relevant Information) to the user, for example in the form of some GUI.

I know I am probably mixing up stuff here that isn't really supposed to be mixed in the way I do, but I am still interested in your assessment of this situation:

I have a class (in the model part of my application) that is rather complicated (multiple different fields, some are other object types as well, the value of some of those depends on other values) to actually instantiate in a sensible way. Since I figured that the Model isn't supposed to hold any real logic apart from basic getters, setters and maybe some minor input validation (although everything that makes its way to the Model should already be processed by some Controller); it seems logical for me to introduce a Builder class that takes care of the complicated creation of this object I am speaking of.

Intuitively, I would put this Builder in the Controller layer, but there could also be valid points for putting it in the Model layer. My rationale for Controller is the following:

Even though a Builder isn't especially containing actual "business logic", it may still need to access other data which it then uses in the creation process of the object it is supposed to build. For example there might be some value that the user can supply but that will just be set to a default value if the user doesn't supply it. Or the builder may have to get references to other objects for duplication checking some input from the user. I may just have a wrong understanding of the MVC architecture here, but in my mind, the Model shouldn't make ANY requests to other model classes, but should purely communicate to some underlying data storage like a database, and the Controller classes.

dimanche 22 août 2021

HOW CAN I PRINT ALPHABETICAL PATTERN IN PYTHON? [closed]

import string
from string import *
alp=list(string.ascii_uppercase)

for i in alp:
    print(i,end=' ')
print()

output:

A B C D E F G H I J K L M N O P Q R S T U V W X Y Z

Desired output:

A P Q R \n
A B Q R\n
A B C R\n
A B C D

samedi 21 août 2021

Pine Script for "Kiano-Pattern" in tradingview

I found the Kiano Pattern in the book written by Orkan Kuyas and as a strong buying signal I would like to identify automatically by tradingview.com. Here is the image from his book: Kiano Pattern

The pattern consist of 3 candlesticks

  1. There is an hammer (green arrow)
  2. Two bars before the hammer is an outside bar
  3. The outside bar is followed by an inside bar

Optional, but stronger signal: The pattern is found at a new low

In short: low - outside bar - inside bar - hammer

As my experience with pine is on a very basic level I would like to hear your input.

How to create an instance of a child class with a factory builder using generics?

I am trying to create an instance of a class using factory builder from the parent.

The use case is basically a library that contains series of classes that inherit from the same class. The main goal was to reduce the amount of code in those classes.

I have an interface that contains two values, IDualValues<T>.

public interface IDualValues<T>
{
    public T FirstValue { get; }
    public T SecondValue { get; }
}

This is an example of what all the classes will look like (changing the method name).

public class Foo : IDualValues<string>
{
    public string FirstValue { get; }
    public string SecondValue { get; }

    public Foo(string firstValue, string secondValue)
    {
        FirstValue = firstValue;
        SecondValue = secondValue;
    }

    public static Foo Create(string firstValue, string secondValue)
    {
        return new Foo(firstValue, secondValue);
    }
}

My point is that I want to use the FactoryBuilder to do Foo.Create instead of a new instance directly in the client application.

The ideal scenario will have a parent class that contains all the logic:

public class DualValuesBuilder<T, CreatedType> : IDualValues<T>
where CreatedType : class, IDualValues<T>
{
    public T FirstValue { get; init; }
    public T SecondValue { get; init; }

    private DualValuesBuilder(T firstValue, T secondValue)
    {
        FirstValue = firstValue;
        SecondValue = secondValue;
    }

    public static CreatedType Create(T firstValue, T secondValue)
    {
       //Creation here
    }
}   

and the other classes will be empty classes just implementing that one:

public class Foo : DualValuesBuilder<string, Foo>
{
}

Notice that I am sending the class itself as a generic parameter to the "builder".

To Achieve my goal, I created a "helper" class to build a class that inherits from IDualValues<T>.

public class DualValuesBuilderHelper<T> : IDualValues<T>
{
    public T FirstValue { get; init;}
    public T SecondValue { get; init; }

    private DualValuesBuilderHelper(T firstValue, T secondValue)
    {
        FirstValue = firstValue;
        SecondValue = secondValue;
    }

    public static IDualValues<T> Create<ReturnType>(T developerK8SClusterValue, T octopusValue)
    where ReturnType : IDualValues<T>
    {
        return new DualValuesBuilderHelper<T>(developerK8SClusterValue, octopusValue);
    }
}

and then I updated the Create method in the class DualValuesBuilder to look like the next:

public static CreatedType Create(T firstValue, T secondValue)
{
    return (CreatedType)DualValuesBuilderHelper<T>.Create<CreatedType>(firstValue, secondValue);
}

But that is giving me an error on the casting: System.InvalidCastException: Unable to cast object of type 'DualValuesBuilderHelper1[System.String]' to type 'Foo'.`

Here there is a fiddle with the code: https://dotnetfiddle.net/IUrgr1

Yes, if I do the following works, but is not what I am trying to achieve.

Foo foo = new Foo()
{
    FirstValue = "f1",
    SecondValue = "f2"
};

note: Using the construtor also works, but I need to make it work with the Create.

Even if I create an explicit (or implicit) operator, the casting still happening.

Am I overthinking, and there is a simple way of accomplishing what I am trying to do? Or is it not possible to do?

Thanks.

Am I using the Repository pattern correctly in NodeJS?

I use Sequelize to work with the database.
In my project, I encountered code duplication, and decided to study the repository design pattern, which will separate the work with the database and data output from the business logic. Having studied the information on the Internet, I decided to consolidate the material and check with more experienced programmers. I use the repository pattern correctly? controller/user.controller.js

const userService = require('../services/user.service');

exports.userCreate = async (req, res, next) => {
 try {
   const user = await userService.userCreate(req.body);
   return res.status(201).json(user);
 } catch (e) {
   return next(e);
 }
}

services/user.service.js

const ApiError = require('../utils/error');
const userRepo = require('../repositories/user.repository');

exports.userCreate = async (data) => {
  if (!data) throw ApiError.badRequest('Bad');

  const { login } = data;

  if (!login) throw ApiError.badRequest('Bad');
   
  const password = 'hash';
  const user = await userRepo.userCreate({login, password});
  
  return user;
}

repositories/user.repository.js

const User = require('../models/User');

exports.userCreate = async (data) => {
  const { login, passowrd } = data;
  const user = await User.create({login, password});
  
  return {
    login: user.login,
  }
}

models/User.js

const { sequelize, Sequelize } = require('../config/db');

const User = sequelize.define('users', {
 id: {
   type: Sequelize.INTEGER,
   autoIncrement: true,
   allowNull: false,
   primaryKey: true,
 },
 login: {
  type: Sequelize.STRING,
  allowNull: false,
 },
 password: {
  type: Sequelize.STRING,
  allowNull: false,
 }
});

module.exports = User;

vendredi 20 août 2021

Java - How to handle Long running requests

I am having a java web application which has a component to hit an external system through REST API, bring the data, do some joins with few tables and then show that information to the user on the screen. All the while the system hits the external system, the user has to wait on the screen looking at the loading button. Hitting the API and doing the data transformation which can be shown to the user takes 30secs currently. This means, the user has to wait till 30secs to see the data on the screen.

What are the best design ways to handle the above scenarios? Even though this question is specific to a java web application, I am curious to know what are the best designs in other platforms as well.

Sorry that this question sounds more of a design problem.

Building a all time top-k score leaderboard

Suppose we are building a module for game which keeps track of the all time top scores. Whenever players complete a game, a service will publish the player's score.

Whenever we call our service, it should return the top 5 scores (along with names) of the players.

How can I approach this?

I was just thinking of implement Top K algo using min heap.
But drawbacks are
1. Single host - not scalable
2. No support for streaming data, we should have the data ready
3. Not processing parallelly

For loop nested Pattern in Javascript

I have been trying to get a progress bar representation that looks like this: The user has to enter an input, and as of the input, the loop will run and get to a 100%.

Enter State: 70

[####### ] 70 % [######## ] 80 % [######### ] 90 % [##########] 100 %

Here is what I have ade so far, but I am stuck now:

let hashtag = "";
for (let i = 1; i <= 3; i++) {
  hashtag += "#";
}

console.log(
  "[" + hashtag + " ",
  " ",
  " ",
  " ",
  " ",
  " ",
  " " + "]" + " " + "30%"
);

Any ideas of how to solve this problem? I a a total beginner, please go easy on me" :)

jeudi 19 août 2021

How has chalk.green.bold("Some Text") and chalk.bold.green("Some Text") been coded in the background in the npm package chalk

I was recently using the chalk package while learning node. I tried using both chalk.green.bold() as well as chalk.bold.green() and got the same result. I like how it has been implemented where green is being used as both an object as well as a method. So to simplify my question how can you have a variable named say var and have the same output for

    var.x.y.z()
    var.y.x.z()
    var.z.x.y()
    ...

all of these without explicitly defining functionality for them all? What design pattern is used(if any is used in this case)?

INotifyPropertyChanged best practices: How do you specify which properties notify?

Firstly, if I have a class that implements INotifyPropertyChanged, what is the best way to communicate which properties do, or do not notify when changed? Or should the pattern be that every public property with a getter in a class that implements INotifyPropertyChanged, should notify?

In my case I'm actually creating an interface, with a bunch of properties, that I've made dependent on INotifyPropertyChanged as I want to communicate that implementations of the interface notify when some of the properties change.

Is a comment in the summary block of each property the best way to communicate this? or maybe an attribute?

eg:

interface IMachine: INotifyPropertyChanged 
{
     Color StatusLED {get;} // does notify when value changes
     bool Busy {get;} // does NOT notify when value changes (because doing so would be too hard, so needs to be polled or whatever.
}

Design help for execution flow of a java method

I'm stuck in a tricky situation here and not able to figure out how I can design this flow. Below is the sample code of what I'm trying to do.

class Service {
 
    private boolean wait = true;
    private boolean result;

    public void doSomething() {
        callExternalRestAPI()  // This API will send a callback to my app which will be received in the controller 
        while(wait) {} // Pause execution flow until callback is received
        print(result); // Execution will resume here 

    }

    public void callbackReceived(boolean result) {
        this.result = result;
        wait = false;
    }

}

class Controller {

    private Service instance; // Don't know how to initialize this instance

    @GetMapping("/{isInternalUser}")
    public void getCallback(@PathVariable("isInternalUser") boolean isInternalUser) {
        instance.callbackReceived(isInternalUser);
    }
}

I understand I need to send the current instance of the Service class to the Controller class but I am not sure how I can do this. If anyone has any suggestions that would be really appreciated.

should subject have collection of observers

I am new in design patterns , i just wonder

should subject has collection of observers although that I need only one observer because every diagram or application I see uses observer pattern has many observers is it called observer pattern if it has only one observer

Alternative C# Design Pattern [closed]

I've come up with a design pattern that's a mix of other patterns like Mediator, Repository, Factory.
The idea is that instead of passing a specific object like a UserViewModel from the UI to the BL the UserViewModel is wrapped in a transaction object. By doing this the UserViewModel becomes a property of the wrapper class along with other info like number of records, a user id for auditing, a response status etc;

Will this be maintainable for a DB that has 100+ entities?

This is some bare-bones sample code:

class Program
{
    static void Main(string[] args)
    {
        string loggedInUserId = "55541";
        
        IBaseService baseService = new BaseService();
        
        var requestModel1 = new SystemTransactionModel<IEnumerable<UserViewModel>>(loggedInUserId);

        var responseModel = baseService.GetObjects(requestModel1, a => a.USER_ID == "65412");

        if (responseModel.Successful)
        {
            Console.WriteLine("USERS");
            foreach (var item in responseModel.ResponseObject)
                Console.WriteLine($"{item.UserId} - {item.FirstName}");
        }

        var requestModel2 = new SystemTransactionModel<IEnumerable<RolesViewModel>>(loggedInUserId);

        var responseModel2 = baseService.GetObjects(requestModel2, a => a.ROLE_ID == "1002");

        if (responseModel2.Successful)
        {
            Console.WriteLine("ROLES");
            foreach (var item in responseModel2.ResponseObject)
                Console.WriteLine(item.RoleName);
        }
    }
}

Business Logic

public interface IBaseService : IBaseFactory<SYS_USERS, UserViewModel>,IBaseFactory<SYS_ROLES, RolesViewModel>,
{
    //place any one-off items here
}

//base component that manages requests from the UI to the BL
public partial class BaseService : IBaseService
{
//get some data from the DB 
//EntityModel = SYS_USERS 
//ViewModel = UserViewModel
    public SystemTransactionModel<IEnumerable<UserViewModel>> GetObjects(SystemTransactionModel<IEnumerable<UserViewModel>> requestModel, Expression<Func<SYS_USERS, bool>> query) => new BaseFactory<SYS_USERS, UserViewModel>().GetObjects(requestModel, query);
    
    public SystemTransactionModel<IEnumerable<RolesViewModel>> GetObjects(SystemTransactionModel<IEnumerable<RolesViewModel>> requestModel, Expression<Func<SYS_ROLES, bool>> query) => new BaseFactory<SYS_ROLES, RolesViewModel>().GetObjects(requestModel, query);
}

Service Factory

public interface IBaseFactory<TEntity, TModel>
{
    SystemTransactionModel<IEnumerable<TModel>> GetObjects(SystemTransactionModel<IEnumerable<TModel>> requestModel, Expression<Func<TEntity, bool>> query = null);
}

//generic factory that manages transactions between ViewModes and EntityModels
public class BaseFactory<TEntity, TModel> : IBaseFactory<TEntity, TModel> where TEntity : class
{
    public SystemTransactionModel<IEnumerable<TModel>> GetObjects(SystemTransactionModel<IEnumerable<TModel>> transactionModel, Expression<Func<TEntity, bool>> query)
    {
        //data from db context
        //Repository/UnitOfWork 
        IQueryable<TEntity> source = context<TEntity>().Where(query);

        //AutoMapper map the data results into an view model
        var destination = iMapper.Map<IQueryable<TEntity>, List<TModel>>(source).AsEnumerable();

        if (destination != null)
        {
            transactionModel.ResponseObject = destination;
            transactionModel.Successful = true;
        }       
        return transactionModel;
    }
}

Transaction wrapper

//this class is the object that is sent to and from the UI (ASP.NET MVC) and the backend (Services  that manage the any custom BL and mapping between ViewModels and EntityModels)
public class SystemTransactionModel<T>
{
    //example of an auditing paramater
    //to track who sent the request
    public string UserId {get;set;}
    
    public bool Successful { get; set; } = false;
    
    public T ResponseObject { get; set; }
    
    public SystemTransactionModel(string userId){
        UserId = userId;
    }
}

View/Entity Models


//ViewModels
public class UserViewModel
{
    public string LastName { get; set; }
    public string FirstName { get; set; }
    public string UserId { get; set; }  
}
public class RolesViewModel
{
    public string RoleId { get; set; }
    public string RoleName { get; set; }
}

//Entity Models
public class SYS_USERS
{
    public string USER_ID { get; set; }
    public string USER_FIRST_NAME_MI { get; set; }
    public string USER_LAST_NAME { get; set; }
}

public class SYS_ROLES
{
    public string ROLE_ID { get; set; }
    public string ROLE_NAME { get; set; }
}

Singleton CRTP with meyers singleton

i am tring to implement a Singleton template that using meyers singleton inside:

#include <bits/stdc++.h>

template <typename T>
class Singleton {
public:
    static T& instance() {
       static T _instance; 
       return _instance;
    }
protected:
    Singleton() = default;
    ~Singleton() = default;
    Singleton(const Singleton & s) = delete;
    Singleton& operator=(const Singleton & s) = delete;
};


class Foo : Singleton<Foo> {
public:
    void print() {
       std::cout<<"from the foo singleton count : " <<count++<<std::endl; 
    }
private:
    int count = 0;

};

int main () {
   Singleton<Foo>::instance().print();
   Singleton<Foo>::instance().print();
   Singleton<Foo>::instance().print();
   return 0; 

and it seems to work : link

but now i want to be able to using it like this :

Foo::instance().print();

is there any way to do it ?

Is there a better way to implement a singleton pattern, using Node.js?

I'm working on a (pseudo) game engine to be used with Foundry.js. The intention was to create a scaffolding that can be reused to quickly create different game systems. To make the final product easier to read and troubleshoot, I decided to use Node.js and a very modular system. (I'm not sure if any more context is needed, but please ask if it is.)

Is there any obvious issue with my implementation?

Note: I'm an 2nd year medical student and self-taught over the past summer --> a lot of what I do might look weird so...

Note: the file and object names were removed, along with extemporaneous code. I added some fillers so that the general idea would still be conveyed

core file: singleton which contains all engine modules within its instance

const Module_A = requires('./modules/module_a.js');
const Module_B = requires('./modules/module_b.js')

module.exports = (function(){
        var instance;
        
        function createInstance(){
            var o = Object.create({
                Module_A: Module_A,
                Module_B: Module_B,
                // etc.
            })
            return o;
        }
        return {
            getInstance: function(){
                if(!instance){
                    instance = createInstance();
                }
                return instance;
            },
            Module_A: function(){
                if(!instance){
                    instance = createInstance();
                }
                return instance.Module_A;
            },
            Module_B: function(){
                if(!instan ce){
                    instance = createInstance();
                }
                return instance.Module_B;
            }
        };
    }())

an abstract class declaration

module.exports = (
    class {
        constructor(){}
        static getType = function(){
            return entityConfig.type;
        };
        static entityConfig = {
            type: 'Object.(Engine.Entity)'
        }
    }
);

a concrete class declaration

const Entity = requires('*./entity.js');

module.exports = ( 
    class extends Entity {
        static requiredParameters = () => {throw `incomplete code at ${new Error().lineNumber}`};
        static optionalParameters = () => {throw `incomplete code at ${new Error().lineNumber}`};
        static docData = () => {throw `incomplete code at ${new Error().lineNumber}`};
        /* ------------------------------------ */
        /* CONSTRUCTOR                          */
        /* ------------------------------------ */ 
        constructor(){ 
            arguments.forEach(arg => {
                if(!arg.includes(requiredParameters) && !arg.includes(optionalParameters)){
                    throw console.error(`ERROR: unknown token; ${arg}\n${docData}`);
                }
            });            
            this._data = args.data;
            this.data = this._data;
        }
    }
);

ASP.NET MVP Composition

i just read the article below : https://www.c-sharpcorner.com/UploadFile/vendettamit/simplest-example-of-mvp-design-patter-of-Asp-Net/

I found the idea pretty and i would try to adopt this MVP pattern in a ASP.NET project (unfortunaltely the MVC option is not suitable for my team). But i am not sure how to handle composition, usually with the ASCXs components i can "define" my custom user controls, and so reuse code.

Not clear to me how to achieve this with MVP pattern

What should the driver class contain in a usual program? [closed]

The driver class(main method) is sort of like the starting point of any application. Since we have tons and tons of design patterns pertaining to object oriented design principles. I was thinking if there was any pattern or best practice which is followed while implementing the driver function.

A usual program being a simulation of any system. For example a banking system where the entities are a clerk a manager and so on. Each having their own packages with their own classes segregated according to the single responsibility principle.

mercredi 18 août 2021

Any ideas related to the techniques for building the content aggregators' architecture?

I am working on thesis that is about content aggregation systems' architecture. The research focuses on techniques for building their architectures. Could you please share your ideas on that?

What do you think is the most actual problem in building the content aggregation systems? I mean, content aggregators as the distributed highload systems, of course.

What are the patterns for the evolutionary development of such systems, from a small project to the a large distributed system?

Thanks in advance. Any help and your thoughts are appreciated.

Symfony interface extends another interface instead of implement

I'm working with symfony, and I'm trying to apply SOLID principles and practicing Design Patterns for Code refactoring.

I have 2 questions :

  1. what design patterns should i always use when using Symfony or other php framework
  2. Why an interface extends another interface instead of implementing it ?

For example :

<?php

namespace Doctrine\Bundle\DoctrineBundle\EventSubscriber;

use Doctrine\Common\EventSubscriber;

interface EventSubscriberInterface extends EventSubscriber
{
}

namespace Doctrine\Common;

/**
 * An EventSubscriber knows himself what events he is interested in.
 * If an EventSubscriber is added to an EventManager, the manager invokes
 * {@link getSubscribedEvents} and registers the subscriber as a listener for all
 * returned events.
 */
interface EventSubscriber
{
    /**
     * Returns an array of events this subscriber wants to listen to.
     *
     * @return string[]
     */
    public function getSubscribedEvents();
}

Why i can't just implement the interface or extends a class or abstract class instead of an interface ?

Design pattern - Singleton pattern in JavaScript

I'm following this article. I understood what singleton pattern is but I'm not be able to understand the code.

let Singleton = (function(){
    let instance = null;

    function createInstance() {
        let obj = new Object("I am the new instance");
        return obj;
    }

    return {
        getInstance:function() {
            console.log(instance);
            if(instance === null) {
                instance = createInstance();
            }
            return instance;
        }
    }
})();

function test() {
    let instance1 = Singleton.getInstance();
    let instance2 = Singleton.getInstance();
    console.log(Object.is(instance1,instance2));
}
test();

why instance1 and instance2 are same, we are always initializing the instance to null whenever we call Singleton.

Python Multiple Inheritance & configuration files

I've been looking through design patterns and trying to figure out how to solve this problem:

class dependency diagram

I have an application that is composed of multiple classes and each class inherits at least one other class. Each class in each layer has a required configuration file. This is proving to be challenging. I can manage to pass the configuration files to the objects I am instantiating from classes within the "Application." But passing configuration files to subsequent objects is proving to be difficult.

I would appreciate some feedback on how I should approach this problem and on design patterns.

How to design RESTful API URI when you can't have user ID on the URI

Make-up scenario:

Let's say I am building a RESTful Web API backend for managing the payment plans for members:

  • It's for members so you would have to register with us. Each member would have a member ID internally.
  • There are various payment plans: 0% interest for 6 months, 0% interest for 12 months, etc. Each payment plan would have an ID internally.
  • The relationship between member and payment plan is many-to-many.
  • Each member also would have 1 active plan at a time. You can change it, but there is only 1 active plan allowed for a member.

Now if I want to design an API endpoint to return the information about the member active payment plan, I would normally do something like:

/members/{member-id}/plans/active

I understand that it might be a bad idea to put state on the URI (I had a separate question for that matter), but please bear with me.

Now here is the tricky part: the company's policy states that I can't have the member ID in the URI. They will have some kind of tokens in HTTP header, which is required in order to access the RESTful API endpoints, that contains the member ID.

My API application, which is ASP.NET Core Web API by the way, has no problem creating a filter to parse that token and transform it into member ID, in the code. It's just that my API URIs can't have the member ID anymore.

How would you design the URI in this case?

Without the member ID on the URI, mine would look like

/plans/active

And the data now would be all driven/filtered by that member ID, securely inside the API backend. Is this normal?

Allocate customers based on their expenditure moving average

I would like to ask your support in a case I am working. I have a dataset around 80.000 lines from January to July where I have the customer expenditure and the moving average of expenditure based in 3 months. I need to check customer behaviour month by month to check if is increasing, decreasing or being stable and report in a new column in what group the customer is.

The problem here is that I have much oscillation between the periods which makes hard to classify the customer. I would like to have a measure to tell if the expenditure variation between the months is significative in a general way.

I have checked the moving average control chart, however it can give me only an ideia about who is consuming within a limit(customer with stable consume), however it is just a part of the problem.

I have also checked about some tests in time series cenario for stationary series.

Thank you !

Golang extension interface pattern in multiple packages

I am trying to apply the extension interface pattern in Go, but I am running into an issue of cyclical imports.

I have a base class A, where I would like to 'override' some of the methods, while still maintaining access to the old ones as well. For this reason I have introduced a new class B, which is helping me to choose the right instance (C or D in this example). As C or D can be quite complicated, I would like to keep them in separate packages for ease of testing. In this current setup, I will run into an issue of cyclical imports, because package A is referring to package C, which is pointing again to A. How could I solve this problem? Thanks!

package A


type A interface {
   Create(input string) error
   Delete(input string) error
}


type B interface {
    A
}


func newTypeB(base A) B {
  switch base.type {
    case "C":
        return c.New(base)
    case "D":
        return d.New(base)
    default:
        return base
  }
}


///////////////////
package c


type C interface {
    B
}


func New(base A) C {
    return C{A}
}

func (c *C) Create(input string) error {
    c.B.Create(input)
    // do other stuff
    return nil
}

// similar implementation for D in a separate package
......

how to rewrite this code to avoid switches/casting

Simplified example to give you an idea, hope it's be clear.
I've already added inheritance for Service class to avoid switches I'm having now

class Config {}

class ConfigA extends Config {}
class ConfigB extends Config {}

// service class - different implementation for configA and ConfigB
// normally it would look like
class ServiceA {
    public String run(ConfigA configA) {}
}

thus next then I need sth like

class ServiceRunner {
    public String run(Config config) {
        // if or switch doesn't matter now
        if (config  instanceof ConfigA) {
            return serviceA.run((ConfigA)config);
        }
    }
}

// main
Config config =  configFactory.create(...) // returns ConfigA or ConfigB
String result = serviceRunner.run(config);

Is there a better way to code it I mean without casting? The only solution I can see is:

interface Service { String run(); }

@RequestScope
class ServiceA implements Service {
    private ConfigA  config;
    public ServiceA(ConfigA configA) {this.configA = configA}

    public String run() {
        ...
    }
}

but I'm not convinced it's a good idea to implement service beans as state beans and I'm using CDI (quarkus actually) for DI which it seems doesn't support assisted injection via constructor

C++ best way to pass a message higher in class structure

I am currently implementing a program that realizes TCP communication between PC program and external devices in QT. The problem I have is more general, but I will use this one as an example.

My class hierarchy looks like this:

            Program
           /       \
      Server_A <--> Server_B <--- External system
          |
       Sockets[]
       /        \
  Commands      Confirmations
                /     |     \
         Interf1   Interf2    Interf3

I can get a command from device (Socket), my command gets into Confirmation class, realizes any Interface job, and returns confirmation back to Socket, which sends it back to device.

The problem occurs when I want to have a command send from an external system, which I also have to confirm.

  1. I get a message on Server_B and pass it to Server_A with information about: socket to send command to and command to realize.
  2. I pass a command to a particular socket
  3. Socket sends a command to Commands, as there is logic for an External System commands.
  4. Commands prepares a message, runs logic, and sends(through socket) message to device
  5. Socket waits for response
  6. Socket gets the response, understands that it was a response to an external system command, and passes it back to Commands
  7. Commands realizes its logic.

Here it would all be fine, but the next step is:

  1. Commands need to confirm the success(or failure) to external system.

So basically, what I have to do is pass a message from Commands to Server_B this way: Commands->Socket->Server_A->Server_B. For all these classes, I would have to create an unnecessary method just to pass this one information. Is there a way to somehow solve this problem? During my programming, it often occurs that I have to pass something to the higher layer of my class structure, and it looks redundant to realize it through additional methods that only passes information further.

I have provided a sample pseudocode for this problem:

class Program
{
    ServerB serverB;
    ServerA serverA;
}

class ServerB
{
    void send(QString msg);
}

class ServerA
{
    QVector<MySocket*> sockets;
}

class MySocket
{
    Commands commands;
    Confirmations confirmations;
}

class Commands
{
    void doLogic();
    void sendToExternalSystem(QString message); //How to realize it?
}

My program is much bigger, but I hope it will give you a clue what I am trying to achieve. The simplest solution would be to add a method void sendToExternalSystem(QString message) into Sockets, Server_A and Server_B, aswell as providing a pointer for each parent during construction (commands will have access to sockets, sockets will have access to server_a, and server_a will have access to server_b)

mardi 17 août 2021

Is there a design pattern like this? [duplicate]

In a class inheritance, base class's protected member is not available to outside but is available to derived class.

Like this, I wanted to make derived class's public member not available to outside but available to base class.

I got an idea that if derived class's member function has parameters which is base class's inner class, then it'll behave like reverse-protected member while it's still public.

I adjusted this idea writing singleton class with CRTP pattern.

template <typename T>
class Singleton
{
public:
    static auto& getinst()
    {
        static T inst = no_constructor_call{};
        return inst;
    }
    Singleton(const Singleton&) = delete;
    void operator=(const Singleton&) = delete;
 
protected:
    struct no_constructor_call {};
    Singleton() {}
};

I made a singleton backbuffer for draw image via double-buffering with winapi.

#define BackBuffer _BackBuffer::getinst()
class _BackBuffer : public Singleton<_BackBuffer>
{
public:
    void Draw(HDC h_dc)
    {
        buf_dc = CreateCompatibleDC(h_dc);
        HBITMAP bit_buf{ CreateCompatibleBitmap(h_dc, client.right, client.bottom) };
        SelectObject(buf_dc, bit_buf);
        BitBlt(h_dc, 0, 0, client.right, client.bottom, buf_dc, 0, 0, SRCCOPY);
        DeleteObject(bit_buf);
        DeleteDC(buf_dc);
    }
    operator HDC() { return buf_dc; }
 
    _BackBuffer(Singleton<_BackBuffer>::no_constructor_call) {}
 
private:
    HDC buf_dc;
};
  • _BackBuffer(Singleton<_BackBuffer>::no_constructor_call) {}
    

this line made class _BackBuffer's constructor is not available to outside code but available to the Singleton base.

So I could create the _BackBuffer object in Singleton class while preventing other code creating _BackBuffer objects.

If I made the constructor private, it couldn't have created in it's base class.

And If I made the constructor perfectly public, it could have created in other code so it's not guarantee as singleton.

Now I'm regarding it can expandable to when you are wanting some public member function to be not available except some regions.

Is there a design pattern like this already existing?

Task vs Pattern

Few days ago I've been asked in an interview for this question: What's the difference between Task and Pattern. Cant relate one thing to another, what kind of answer are they expecting?

Multi Tenancy with nodejs and mongoDB database

recently I'm trying to implement Multi Tenant Application with in nodejs and mongoDB database, I'm also going to use redis as a caching layer for the application. Multi Tenancy here is going to defined as: A single database for a client (organization, company) for better security and data segregation. What are the best practices and design patterns should I apply to this project. I should also mention that we are going to have lots of users and organizations and scalability and maintainability means really really lot for me

Design pattern for combining separate branches into common structure

I've got applications that consist of a data loader and a data transformer. Each loader and each transformer are subclasses of an abstract base loader and an abstract base transformer, which I'll omit in the example below. There is a 1:1 mapping between the concrete loaders and transformers, i.e. is known which loader and transformer belong together.

Say we have two loaders and two transformers, handling data

class Data1: ...

class Data2: ...


class Loader1:
    def get_data(self) -> Data1: ...

class Loader2:
    def get_data(self) -> Data2: ...


class Transformer1:
    def transform_data(self, data: Data1) -> None: ...

class Transformer2:
    def transform_data(self, data: Data2) -> None: ...

These classes could now be combined into applications

class App1:
    Loader = Loader1
    Transformer = Transformer1

class App2:
    Loader = Loader2
    Transformer = Transformer2

with an accompanying factory

from typing import Union, Type

def make_app(use_app1: bool) -> Union[Type[App1], Type[App2]]:
    if use_app1:
        return App1
    else:
        return App2

This is how I'd like to use the above

def main(use_app1: bool) -> None:
    app = make_app(use_app1)
    loader = app.Loader()
    data = loader.get_data()
    transformer = app.Transformer()
    transformer.transform_data(data=data)

However, mypy complains:

error: Argument "data" to "transform_data" of "Transformer1" has incompatible type "Union[Data1, Data2]"; expected "Data1"  [arg-type]
error: Argument "data" to "transform_data" of "Transformer2" has incompatible type "Union[Data1, Data2]"; expected "Data2"  [arg-type]

Is there some way to convince mypy that the branches Loader1 -> Data1 -> Transformer1 and Loader2 -> Data2 -> Transformer2 are separate and will not be mixed?

Is there an alternative pattern that could be used for this use case?

lundi 16 août 2021

In python, Two functions calls some same workflows, how to distinguish the origin function at bottom?

I have two python functions A() and B(), they both call f1(), and f1() calls f2()... In f4(), I want to get the origin function name(A or B), Is there any smart way? I thought I can add a param for each functions, but it makes my codes quite ugly. These functions are in different files and some start in new Thread, I also read some doc about context but I'm not sure if it works here.

def A():
    f1()

def B():
    f1()


def f1():
    f2()

def f2():
    f3()

def f3():
    f4()

def f4():

    if call_from_A:
        print(123)
    else:
        print(456)

Can my JSON editor web app design be simplified? [closed]

My aim is to build an app for personal use which provides an editor that saves / loads an encrypted JSON file from the server. The editor should have syntax highlighting and the decryption key should remain on the client since the webserver might be controlled by a third party. The app should be accessible from any device that has a web browser

After doing research, I have found the following -

  • Server side framework - express.js / node
  • Authorisation - express-session / connect-redis
  • Embedded JSON editor - ace.c9.io
  • Front end symmetric encryption - aes-js

My main concern is that the above solution is overly complex for these requirements. Could it be simplified?

Good example of Singleton usage

Recently I've read a lot about the Singleton pattern. As far as I'm concerned singleton objects should be used only if there is no sense to have more than one, and when there is a need to access them from all over the program. My question is fairly simple and for educational purposes. When making a board game simulator such as Monopoly or Catan is it correct to create Dices (throwable board game dices) as a singleton class?

"Target class [Modules\\Admins\\Controllers\\AdminController] does not exist."

I'm developing an e-commerce website using Laravel 8, And I tried to change on Laravel folders structure I've put views folder inside new path modules/admins which works fine, and I've also created a Models folder in the modules/admins path which works fine, however, I am having trouble with the controllers folder.

I still have the app/http/controllers/Controller.php, but now I've created a folder called Controllers inside the modules folder, and in it I have a controller called AdminController

error message: "Target class [Modules\Admins\Controllers\AdminController] does not exist."

AdminController file


namespace Modules\Admins\Controllers;

use App\Http\Controllers\BaseController;
use App\Http\Traits\ApiDesignTrait;
use Illuminate\Http\Request;
use Illuminate\Support\Facades\Auth;
use Illuminate\Support\Facades\{
    Hash, Validator
};
class AdminController extends BaseController
{
    public function test()
    {
        return true;
    }
}

route.php

use Illuminate\Support\Facades\Route;
use Modules\Admins\Controllers\AdminController;

Route::post('/test',  [AdminController::class, 'test']);

BaseController.php


namespace App\Http\Controllers;

use App\Http\Controllers\Controller;


class BaseController extends Controller
{

}

Controller.php


namespace App\Http\Controllers;

use Illuminate\Foundation\Auth\Access\AuthorizesRequests;
use Illuminate\Foundation\Bus\DispatchesJobs;
use Illuminate\Foundation\Validation\ValidatesRequests;
use Illuminate\Routing\Controller as BaseController;

class Controller extends BaseController
{
    use AuthorizesRequests, DispatchesJobs, ValidatesRequests;
}

Is this approach good in project design node js?

In my API projects - I use the Controller -> Service -> Model pattern. In simple projects enough, describe all the functions in one file.
user.controller.js

const ApiError = require('../error/ApiError');
const yup = require('yup');
...

exports.login = (req, res, next) => {...}
exports.signup = (req, res, next) => {...}
exports.getInfo = (req, res, next) => {...}
exports.changePassword = (req, res, next) => {...}

But when the project develops, the code grows accordingly, and it becomes inconvenient to store everything in 1 file. For example, when a file consists of 500 lines of code and you need to change somewhere 1 line of code, you have to scroll down, which is very inconvenient. I decided, what if each function is divided into sub files and in the end everything is included in index.js

controllers/user/
- index.js (Единая точка входа для всех функций);
- login.js;
- signup.js
...

and it turns out something like
controllers/user/login.js

const ApiError = require('../error/ApiError');
const yup = require('yup');
...

module.exports = (req, res, next) => {...}

controllers/user/index.js

const login = require('./login');
const signup = require('./signup');
...

module.exports = {
 login,
 signup 
};

Now it is more convenient to edit functions, and they are all stored at one point.
Do you think my approach to design is normal or is there something similar?

C++ QT terminate to parent

I am looking for a nice way to stop running instructions of different classes methods(called from, let's say, manager) and return to manager in case of an error in these classes methods.

What I have built is a structure consisting of manager class, which runs methods of different workers classes, these workers classes sometimes have their own workers, workers of workers can have their own workers (typical tree structure, but there's a point why I call them workers), etc.

So let's say we have this type of structure, where each class delegates part of their job to different classes, while also doing something on their own. All workers work on, let's say Message structure with fields text and error, as if an error occurs, they have to report what type of error it is, and if possible provide a text explanation of this error. (in case of success, the error is NO_ERROR and text is filled with the work they have done)

Manager->WorkerA->Worker_B->WorkerC->WorkerD

So, in case of an error in WorkerD, which will prevent all supervisors from finishing their jobs, we would have to:

  1. Check for error in WorkerD - there is an error!
  2. Change message.error from NO_ERROR to ERROR, change message.text if it is necessary
  3. Return message //here begins the part I would like to omit somehow:
  4. WorkerC has to check after WorkerD has finished, if there's an error, if there is, immediately return(workerC shouldn't continue his work)
  5. WorkerB has to check after WorkerC has finished, if there's an error, if there is, immediately return(workerB shouldn't continue his work)
  6. WorkerA has to check after WorkerC has finished, if there's an error, if there is, immediately return(workerA shouldn't continue his work)
  7. Manager checks the error after WorkerA has finished. If there is no error, he does some additional job, if there is - he just passes the message with text and error further.

I am looking for a simpler way to omit steps 4-6, so once there is an error in any worker job, he fulfills the error and text, and returns this message through all the intermediate methods up to the Manager. Something like return, but also return parent functions.

I know it can be done with exceptions, but is there a way to NOT do it with exceptions and still reducing the need to constantly add 'do func1(), if there is an error, stop working and return this error'?

Example pseudocode:

manager, worker1, worker2

manager.work{
//do something
switch(delegate_to) {
case worker:
 message=worker1.work
case accountant:
 message=accountant1.work
case differentworker:
 message=differentworker.work
}
if(message.error=NO_ERROR)
   all_ok
else
   not_all_ok
}

worker1.work
{
message=do_something()
if(message.error) //this is what I am trying to omit
   return message;
//some work
message=worker2.work
if(message.error) //this is what I am trying to omit
   return message;
//some work

return message;
}

And a part of my program (I am looking for a solution to skip this as I have this type of instructions on multiple layers)


    // lots of code
    out << getOperators(controlList[2], &msg); 
    if(msg.error!="") return msg;
    out << getProductDetails(controlList[3], &msg); 
    if(msg.error!="") return msg;
    //lots of code
    return msg;