mardi 2 mai 2023

What resource / topic should I study to get more knowledge in business logic development?

I'm interested in learning different ways available to develop the logic for a business application development.

For example. consider the design of an software for payroll system for a company which has multiple branches. How do I represent these branches logically in my application, such that an manager logging into the payroll system could belong to one or more branch but can keep only one branch active at a time for any type of payroll processing or reports? Can you suggest more than one ways the logic can be defined for this app?

I'm looking for material to read/study regarding this side of logic. I'm not familiar as to what it is called as System Design / Software Architecture / Design patterns? I couldn't find much details on web via search, maybe cause I didn't know what exactly to look for.

So far I've only developed CRUD apps that didn't have much logic applicable to it. Looking to get into more complex applications with learning techniques and guidelines to make them scalable, modular and efficient. Any help on this topic is appreciated. Thanks.

Did pretty detailed search on internet for examples of such business logic, Not sure where if i searched wrong or something else, couldn't find the answers i was looking for.

How to solve the problem of registered objects in a list that refer to registered objects

I have two model classes. The first class is Vector, the second is SequenceUnit. SequenceUnit stores different types of objects, to identify them there is a type property:

Vector.h

#ifndef VECTOR_H
#define VECTOR_H

#include <QObject>
#include <QPointF>
#include <QVariantList>

class Vector : public QObject {
    Q_OBJECT
    Q_PROPERTY(int index READ index WRITE setIndex NOTIFY changedIndex)
    Q_PROPERTY(QPointF point READ point WRITE setPoint NOTIFY changedPoint)

public:
    explicit Vector(QObject *parent = 0) {}

    int index() {
        return m_index;
    }
    void setIndex(int index) {
        if (m_index == index) {
            return;
        }

        m_index = index;
        emit changedIndex();
    }

    QPointF point() {
        return m_point;
    }
    void setPoint(const QPointF& point) {
        if (m_point == point) {
            return;
        }

        m_point = point;
        emit changedPoint();
    }

signals:
    void changedIndex();
    void changedPoint();

private:
    int m_index = -1;
    QPointF m_point = QPointF(0, 0);
};
#endif // VECTOR_H

SequenceUnit:

#ifndef UNITSEQUENCE_H
#define UNITSEQUENCE_H

#include "Vector.h"
#include <QObject>

class SequenceUnit : public QObject {
    Q_OBJECT
    Q_PROPERTY(QString type READ type WRITE setType NOTIFY typeChanged)
    Q_PROPERTY(QObject* unit READ unit WRITE setUnit NOTIFY unitChanged)

public:
    QString type() {
        return m_type;
    }
    void setType(QString type) {
        if (m_type == type) {
            return;
        }

        emit typeChanged();
        m_type = type;
    }

    QObject* unit() {
        return m_unit;
    }
    void setUnit(QObject* unit) {
        if (m_unit == unit) {
            return;
        }

        emit unitChanged();
        m_unit = unit;
    }

signals:
    void typeChanged();
    void unitChanged();

private:
    QString m_type;
    QObject* m_unit;
};

#endif // UNITSEQUENCE_H

The VectorController and LinkSequence controllers are responsible for creating objects in qml. VectorController for creating vectors. LinkSequence for creating unit objects:

VectorController:

#ifndef VECTORCONTROLLER_H
#define VECTORCONTROLLER_H

#include "Vector.h"

#include <QObject>

class VectorController : public QObject {
    Q_OBJECT

public:
    explicit VectorController(QObject *parent = 0) { };

    Q_INVOKABLE Vector* createVector() {
        return new Vector();
    }
};

#endif // VECTORCONTROLLER_H

LinkSequence:

#ifndef LINKSEQUENCE_H
#define LINKSEQUENCE_H

#include "SequenceUnit.h"

class LinkSequence : public QObject {
    Q_OBJECT

public:
    explicit LinkSequence(QObject *parent = 0) { };

    Q_INVOKABLE SequenceUnit* createUnit() {
        return new SequenceUnit();
    }
};

#endif // LINKSEQUENCE_H

I register all these controllers and methods through main cpp:

qmlRegisterType<Vector>("Model", 1, 0, "Vector");
qmlRegisterType<SequenceUnit>("Model", 1, 0, "Unit");
qmlRegisterType<VectorController>("Controller", 1, 0, "VectorController");
qmlRegisterType<LinkSequence>("Controller", 1, 0, "LinkSequence");

There are errors in main qml. The program crashes after 100 clicks:

import QtQuick 2.15
import QtQuick.Window 2.15
import Model 1.0
import Controller 1.0

Window {
    id: window
    width: 640
    height: 480
    visible: true
    title: qsTr("Hello World")

    Item {
        id: root
        width: window.width; height: window.height

        property var points: {
            [Qt.point(75.0, 0.0),
            Qt.point(150.0, 100.0),
            Qt.point(100.0, 200.0),
            Qt.point(50.0, 200.0),
            Qt.point(0.0, 100.0),
            Qt.point(75.0, 0.0)
            ]
        }
        property var handledPoints: {
            let newPoints = points.map((point) => Qt.point(point.x, point.y))

            const sequence = list
            for (let i = 0; i < sequence.length; ++i) {
                if (sequence[i] !== null) {
                    console.log(i, 'not null')
                    const vector = list[i].unit
                    for (let a = 0; a < newPoints.length; ++a) {
                        if (vector.index === (a % (newPoints.length - 1))) {
                            const point = vector.point
                            newPoints[a].x += point.x
                            newPoints[a].y += point.y
                        }
                    }
                } else {
                    console.log(i, 'null')
                }
            }
            return newPoints

//link model:
            property list<Unit> list

            VectorController {
                id: cntr
            }
        LinkSequence {
            id: link
        }


        Repeater {
            anchors.fill: parent
            model: root.handledPoints.length - 1
            Rectangle {
                id: circle
                x: root.handledPoints[index].x - height / 2; y: root.handledPoints[index].y - width/ 2
                width: 20; height: 20;
                radius: 20
                color: 'violet'
                MouseArea {
                    anchors.fill: circle
                    cursorShape: Qt.PointingHandCursor
                    property point pressedPoint; property point positionPoint
                    property var vector;  property var unit
                    onPressed: {
                        pressedPoint = circle.mapToItem(root, mouseX, mouseY)
                        vector = cntr.createVector()
                        vector.index = index
                        const unit = link.createUnit()
                        unit.type = 'vector'
                        unit.unit = vector
                        root.list.push(unit)
                    }
                    onPositionChanged: {
                        positionPoint = circle.mapToItem(root, mouseX, mouseY)
                        vector.point = Qt.point(positionPoint.x - pressedPoint.x,positionPoint.y - pressedPoint.y)
                    }
                }
            }
        }
    }
}

an error appears in the console - "TypeError: Cannot read property 'index' of null" and after one more click the program crashes.

I don't understand why it doesn't work. My task is to combine multiple models into one and then use it on another qml item. That is, get a model that will link to other models:

The model I want to get linkmodel

How do I combine multiple models into one model that will link other models in qml? And what could be the problem with the code?

source code: https://github.com/svirid132/qml-list-problem

Abstractions in React - HOC and hooks, possible or am I just hitting the limitations of React?

Say I have a create (POST) / update (PUT) endpoint for 10 (and growing) different resources.

All 10 of these resources implement the same popup form for create and update, design and flow wise.

Writing a CreateFirstForm UpdateFirstForm CreateSecondForm UpdateSecondForm is becoming super tedious. It's basically copy-pasta except the endpoint, fields and labels in the UI. They also all have "useCreateResource" and "useUpdateResource" hooks incorporated that are basically calls to react-query's useQuery (calls fetch and manages state for the incoming / outgoing data)

So, I think, let's write a higher order component, that's what they are for, to abstract away common logic.

I initially thought I could parse the id in the URL to discern whether or not the call is a POST vs PUT.

It was all going well, code-wise, until I hit the dreaded Hook is called conditionally issue. The hook in question is basically id ? useGetResource(id) : { } which determines the initial data a form should edit (existing vs blank).

Yes I understand I could separate this "upsert" flow into Create and Update flows starting with CreateForm and UpdateForm thereby bypassing all conditional hooks... but then it completely defeats my intention of abstracting away redundant code and I'm left with where I started at, 20 different form components for 10 different resources.

I realize this might be easier to understand with examples so here's some pseudocode with the interface of how I would like it to behave with one resource, a recipe.

// hooks
useGetRecipe = () => {}
useCreateRecipe = () => {}
useUpdateRecipe = () => {}
useUpsertRecipe = (id?) => {
  const recipe = id ? useGetRecipe(id) : {};
  const submit = // do the create vs update
  return {
    recipe,
    submit,
    ...
  }
}



// Components

// the Higher order component, takes in the form, the hook and edits the recipe in place. Submission will call submit with the updated data

const upsertResource = (FormComponent) => (hook) => () => {
   const id = useUrlParams('id') //presence or not should determine POST vs PUT
   const { recipe, submit } = hook(id);
   
   return <FormWrapper data={recipe} submit={submit}><FormComponent/></FormWrapper>
} 

//edits a recipe, mapping name attr to property in recipe

const RecipeForm = () => {
  return <Field name="name" />
}

// The top level component, which basically calls the HOC with the hook. All it would take for every resource if conditional hooks were allowed!

const UpsertRecipe = () => {
  const Upsert = upsertResource(RecipeForm)(useUpsertRecipe)
  return <Upsert><RecipeForm/></Upsert>
}

So using the above I should be able to keep 10 resources into 10 forms in which simply having "id" or not could determine a create vs update, but alas, hooks cannot be called conditionally.

Now, I started breaking up the "upsert" into create vs update.... but I just realized I'm back where I started, having 2 forms for each resource thereby making my HOC / custom hook pattern useless, which is fine, but I was wondering if there was a better way to do stuff like this or should I just toss it up to, "it's just UI... sometimes we write repeated code."

Thanks!

What design pattern should I use when a base class creates child classes?

I'm writing in c++, I have a base class let's call it base, that has 2 children classes. the requierements are:

  1. Singleton, also the base class can't be initialized as object
  2. the base class has a function to create an instance, which will choose on runtime what child object to create (not sure if this is a good logic, but the base class is responsible on choosing and initiating a child).
  3. The base class also holds multiple functions that the children share.
  4. Then there are multiple pure virtual funtions that only the children implement.

I'm thinking of some combination of singleton + factory patterns, but not sure how to use factory here.

lundi 1 mai 2023

How can we print a solid diamond inside of a hollow rectangle? [closed]

I'm stuck on this code . I can't seem to find a breakthrough as the right side of my hollow rectangle just won't print .

I tried loops and conditions . I was expecting to get the desired output of a solid diamond inside of the rectangle .

How I can mock a class marked as final?

I need to add unit tests to the class (SensorClient) that contains a pointer to the object of the class (VelocitySensor) marked as final. And what's important is that I can't modify the VelocitySensor class. Therefore, I can't change VelocitySensor methods to virtual... Also, I would like to avoid any "friend" classes or tricks with #define.

VelocitySensor class:

//sensor_service.hpp
#pragma once
#include <string>

namespace sensor
{
    class VelocitySensor final
    {
    public:
        VelocitySensor() : velocity(20), sensorName("VelocitySensor") {}

        double getVelocity() const
        {
            return velocity;
        }

        std::string getSensorName() const
        {
            return sensorName;
        }

        void calculateSomething()
        {
            const double time = 10;
            auto vel = getVelocity();
            auto distance = vel * time;
            //...
        }
    private:
        std::string sensorName;
        double velocity;
    };
}

SensorClient class:

//sensor_client.hpp
#pragma once
#include "sensor_service.hpp"
#include <memory>
#include <iostream>

namespace sensor
{
    class SensorClient
    {
    public:
        SensorClient() : sensor(std::make_unique<VelocitySensor>()) {}

        double getVelocity() const
        {
            return sensor->getVelocity();
        }

        void calculateNumOfTyres()
        {
            sensor->calculateSomething();
        }

        std::string getVehicleName() const
        {
            return sensor->getSensorName();
        }

    private:
        std::unique_ptr<VelocitySensor> sensor;
    };
};

I found three ways to solve that issue. Maybe there is another better solution (I hope so :))

  1. The first one is to templetize SensorCLient, and as a result, it should be quite easy to mock VelocitySensor during tests.
#pragma once
#include "sensor_service.hpp"
#include <memory>
#include <iostream>


namespace sensor
{
    template <typename T>
    class SensorClientTemplate
    {
    public:
        SensorClientTemplate(std::unique_ptr<T> _sensor = std::make_unique<VelocitySensor>())
            : sensor(std::move(_sensor)) {}
        virtual ~SensorClientTemplate() = default;

        double getVelocity() const
        {
            return sensor->getVelocity();
        }

        void calculateSomething()
        {
            sensor->calculateSomething();
        }

        std::string getSensorName() const
        {
            return sensor->getSensorName();
        }

    private:
        std::unique_ptr<T> sensor;
    };

    using SensorClient = SensorClientTemplate<SensorService>;
};

For me it looks quite good. But maybe there is another solution which doesn't require the use of templates.

  1. The second one is to use the Adapter Pattern.
#pragma once
#include "sensor_service.hpp"
#include <memory>
#include <iostream>

namespace sensor
{
    class ISensor
    {
    public:
        virtual ~ISensor() = default;

        virtual double getVelocity() const = 0;
        virtual std::string getSensorName() const = 0;
        virtual void calculateSomething() = 0;
    };

    class SensorAdapter : public ISensor
    {
    public:
        void calculateSomething() override
        {
            sensor.calculateSomething();
        }

        double getVelocity() const override
        {
            return sensor.getVelocity();
        }

        std::string getSensorName() const override
        {
            return sensor.getSensorName();
        }

    private:
        VelocitySensor sensor;
    };

    class SensorClient
    {
    public:
        SensorClient(std::unique_ptr<ISensor> _sensor = std::make_unique<SensorAdapter>())
            : sensor(std::move(_sensor)) {}
        virtual ~SensorClient() = default;

        double getVelocity() const
        {
            return sensor->getVelocity();
        }

        void calculateSomething()
        {
            sensor->calculateSomething();
        }

        std::string getSensorName() const
        {
            return sensor->getSensorName();
        }

    private:
        std::unique_ptr<ISensor> sensor;
    };
};

Now I have an issue with adding tests to the adapter class... I moved the issue with mocking VelocitySensor to a new class. I would like to take care of code coverage... So this is not a solution for me.

  1. Pimpl

I think I can use the Pimpl idom to hide implementation details (including a pointer to the VelocityObject) in the cpp file, and as a result, I should be able to mock the implementation (Now I don't need to mock VelocitySensor). But in that case, the implementation won't be covered by unit tests. :( I found something about using factories to solve that issue, but I'm not sure how I can use that in my case,

Am I bikeshedding + over-optimizing my database design by trying to account for duplicated data?

I am designing an RSVP-over-SMS system. An organizer user creates an event, and sends out SMS (text message) invitations to N amount of recipients. Each recipient will respond with a Yes/No type of answer and the system will mark their attendance accordingly.

In my database design, I have a table that holds all messages, as well as all responses. When the organizer sends a messages to User 1 of 50, the Messages table will be populated with single message record detailing the invite.

If an organizer sends a message to 50 users, should the table now include 50 message records? Every message record will contain the body of the message, which will be duplicated 50 times.

I have several ugly and un-elegant ideas in mind which solve the duplication problem, but ruin the simplicity of the schema.

My best solution so far is to create an "Invitations" table which every subsequent User response would reference through a "parent-invitation-id" field. I can foresee Organizers using the RSVP system as a simple messaging platform (i.e. sending a plain message to a user to communicate further details) and I don't think this use case fits in with my current solution.

I am confident our industry has encountered this problem before, but I am unable to trustworthy source of authority on design to consult over the competing suggestions.

I am curious to hear some input on my issue, and I'd be happy to elaborate further. Additionally, would anyone be able to point me to a trustworthy resource to consult for database design patterns, so that I could solve this kind of issue on my own?