samedi 3 juin 2023

A question regarding a class structure that will hold various types

I am creating a basic JSON string parser and I've run into a situation.

I've been using the following RFC.
RFC 8259:  The JavaScript Object Notation (JSON) Data Interchange Format.

In Section 3 – Values, it defines that a value is as follows.

value = false / null / true / object / array / number / string

And, Section 4 – Objects defines an object.

object = begin-object [ member *( value-separator member ) ]
         end-object

member = string name-separator value

Thus, in my code I created the following class structures.

private static class Value {
    private java.lang.Object object;

    @Override
    public String toString() {
        String string;
        if (object instanceof Boolean) string = (boolean) object ? "true" : "false";
        else if (object instanceof BigDecimal) string = ((BigDecimal) object).toPlainString();
        else if (object instanceof String) string = (String) object;
        else string = object.toString();
        return string;
    }
}
private static class Object {
    List<Member> list = new ArrayList<>();

    private static class Member {
        private String name;
        private List<Value> value;

        @Override
        public String toString() {
            return "{" + name + ": " + value + "}";
        }
    }

    @Override
    public String toString() {
        return list.toString();
    }
}

I am attempting to determine if there is a more logical way to do this.
Is there a better way to contain each of those types, and then capture their content accordingly.

I thought of just storing them all as String values, although an object has less precedence than a value.
Therefore, there would not be any difference in what I currently have implemented.

I feel inheritance would prove abstruse and lacking, since it won't ever scale beyond this.
The values will always have the forms described.

Essentially, I want to have the following pseudo-code as an end-point.
And, the error I encounter is that the user will have to decouple an array of JSON objects.
To provide them with Java Objects seems daunting,

parser.get("key").asString();
parser.get(0).asArray();
parser.get(1).asObject();
parser.findObject("key").asObject();
parser.findNumber(123).asNumber();

Is there some sort of concept, or design, that can be used to harness a set of uncorrelated values?
How can I offer the JSON object, or array, to the user, in a way that won't require them to cast a Java Object?

Classic circular dependency problem I run into with interfaces in golang, what is the idiomatic way to resolve this?

So I have,

package A

type a struct {}

func New() *a {
  return &a{}
}

func (A *a) Boo() {}
package B

type a interface {
  Boo()
}

type b struct {}

func New() *b {
  return &a{}
}

func (B *b) Foo(A a) {} // Dependency injection
package driver

type driver struct {
  // in here I want to have a field which has the method Foo(B b)
}

The problem is that I cannot define an interface with method Foo(B b) as b is an unexported interface in package B. If I make it exported it leads to circular dependency.

What is the idiomatic way to handle this problem in golang?

Of course I can export the struct B and directly use it in driver package but if possible I would like to use interfaces for better testability. Am I overengineering?

Should I implement factory pattern if one behaviour is common and rest are unique?

What problems are solved by factory design patterns?

I have studied Design Patterns: Elements of Reusable Object-Oriented Software but I still find difficulties to understand and implement it.

If I implement a factory design pattern and each object has one common behaviour and the rest are unique. So whether should I implement a factory design pattern for this or create a plain class?

vendredi 2 juin 2023

Is it acceptable to put std::promise-s into a container to be set by the thread?

There is a thread which is responsible for executing a certain task and acquire the result. To execute the task certain data is needed and it is being produced by multiple clients and the result must be returned to them. The solution that I am thinking about is to put the data into a thread safe execution queue along with a std::promise which its future is retrieved in the client code and will be kept to later get the result out of it. The worker thread then fetches the data and the std::promise, execute the task and set the std::promise's value. The client which is now waiting on the std::future gets its corresponding result. The implementation works technically but my question is that

  • Is there a better way to get the same outcome?
  • Is there any issue or performance penalty with this approach?
  • What are the best paractises for this kind of problem?

Thanks

The code below shows the method described:

std::condition_variable_any workerCv;
std::mutex workerMutex;
SomeThreadSafeQueue<std::pair<int, std::promise<int>>> threadSafeQueue;

int process(int data) {
  // Create the promise
  std::promise<int> promise;
  // Get the future and keep it
  auto future = promise.get_future();
  // Move the promise along with the data into the thread safe queue
  threadSafeQueue.emplace({ data, std::move(promise) });
  // Notify the worker about the new data
  workerCv.notify_one();
  // Get the result
  return future.get();
}

void worker(std::stop_token stopToken) {
  while (!stopToken.stop_requested()) {
    
    // Construct the unique lock needed for condition variable
    std::unique_lock lock(workerMutex);
    
    // Wait for notification
    workerCv.wait(lock, stopToken, []() {return !threadSafeQueue.empty(); });
    // unlock since we don't need the lock for anything other than the condition variable
    lock.unlock();

    // Check for stop condition
    if (stopToken.stop_requested()) {
      break;
    }
    // Fetch the data and promise from the queue. This specific queue front method
    // moves the item out of the queue
    auto&& [data, promise] = threadSafeQueue.front();
    try {
      // Use the data to run some operation and set the result in the corresponding promise
      promise.set_value(someOperation(data));
    }
    catch (...) {
      // Set any possible exception into the promise
      promise.set_exception(std::current_exception());
    }
  }
}

void client(int start, int end) {
  for (int data = start; data < end; ++data) {
   
    try {
      // Call the process function that puts the data into the
      // thread safe queue and gets the result when it is ready
      // then use it
      useTheResult(process(data));
    }
    catch (const std::exception& exception) {
      // Handle the exception
      // Not thread safe but ok for demo
      std::cout << exception.what() << std::endl;
    }
  }
}

int main() {
  // Stop source for the worker thread
  std::stop_source stopSource;
  // Invoke the worker thread
  std::jthread workerThread(worker, stopSource.get_token());
  // Invoke the clients
  std::thread client1(client, 0, 10);
  std::thread client2(client, 10, 20);
  // Join the clients
  client1.join();
  client2.join();
  // Signal the worker thread to stop
  stopSource.request_stop();
  workerCv.notify_one();
}


As mentioned before the solution works as expected but I have never seen the same approach for using std::promise and std::future so I assume that there is some issue with it?

Is there a software design pattern for a "utility" class with only static methods?

In OOP, consider the example case of a global class like Math with methods like Math.abs(), Math.sin(), Math.floor(), or in general any kind of class that cannot be instantiated but provides a group of "utility" functions.

Such a class is often implemented as a "static" class with "static" methods that can be invoked directly from the class itself (this depending on the programming language).

In software design, is there a specific design pattern for this?

Any recommendations for learning how to reason about and create better automated tests with Cypress?

I create test automation tests using Cypress for a large scale application. I use POM and all the other best practices that are general ones and it is possible to find out online.

My issue is the test design architecture.

I have the written test cases with a lot of steps. I need to transform the test cases in a long e2e test using Cypress.

I am new to programming and I get code review comments that I do not think like a programmer, I do not do things like the programmer would create functions or reason about them.

Can you please share your thought process how you write long e2e tests and reason about them? What kind of design module should I use when writing tests? Should I follow a declarative programming pattern? Or how should I reason about the test?

How do you think?

I found one article regarding my issue called Creating an Architecture for Your Automated Tests in one of the QA blogs.

What books or things would you recommend to take into account or learn? Are there any good resources to see the code how other people reason about the long e2e tests and create functions or higher order functions, etc.

Thanks.

I have tried to Google and I found a couple of resources related to my issue

A blog article: Creating an Architecture for Your Automated Tests

A github repository: ui-testing-best-practices

I want to know if there any other resources to learn from or I could take into consideration.

jeudi 1 juin 2023

Bijectional mapping between two instance of different type

I have two class A and B. There is a bijection between every instances of these class.

class A {
    public:
        constexpr A() {}
};
class B {
    public:
        constexpr B() {}
}

// static delcaration of all pair of equivalent instances.

constexpr A toA(B);
constexpr B toB(A);


int main()
{
    A a;
    B b;
    a == toA(toB(a)); // always true
    b == toB(toA(b)); // always true
}

I need to find an elegant solution to solve this at compile and run time. I've tried many solutions like home-made bidirectional map, template variable etc but none of them matched my expectation.