lundi 8 août 2022

Dependency injection and method restriction

I have a class that manages a WebSocket connection and provides the methods to subscribe to this WebSocket. An instance of this class may be passed to many child objects that subscribe to this WebSocket via these methods:

const client = new WebSocketManager();
await client.connect(); 

const objA = new ClassA(client);
const objB = new ClassB(client);

client.close(); // at a future point in time

The problem is that client exposes critical methods like connect and close. If objA calls close, objB would fail for no apparent reason. Those two methods should be private to the children, but public to the initiator of the parent object. Is there a pattern to solve this problem? Two methods are presented below. Are any of those two patterns acceptable or are there better solutions? I would like to hear your opinion.

Method 1: Define an owner of the parent object. Restricted methods require a reference to the owner.

class Parent {
    #owner;

    constructor(owner) {
        this.#owner = owner;
    }

    restricedMethod(owner) {
        if(owner !== this.#owner)
            throw Error('not authorized');

        console.log('restricedMethod called');
    }

    accessibleMethod() {
        console.log('accessibleMethod called');
    }
}

class Child {
    constructor(dependency) {
        this.dependency = dependency;
    }

    callAccessibleMethod() {
        this.dependency.accessibleMethod();
    }

    callRestricedMethod() {
        this.dependency.restricedMethod();
    }
}



const parent = new Parent(this);
// 'this' is the owner of 'parent'

const child = new Child(parent);

child.callAccessibleMethod();
// accessibleMethod called

try { child.callRestricedMethod(); } catch(e) { console.log(e.message); }
// Error: not autherized

parent.restricedMethod(this); // only the owner can call this method
// restricedMethod called

Method 2: Create a new parent object on the fly that only contains the methods that the child may access.

class Parent {
    restricedMethod(){
        console.log('restricedMethod called');
    }

    accessibleMethod(){
        console.log('accessibleMethod called');
    }
}

class Child {
    constructor(dependency) {
        this.dependency = dependency;
    }

    callAccessibleMethod() {
        this.dependency.accessibleMethod();
    }

    callRestricedMethod() {
        this.dependency.restricedMethod();
    }
}

class MethodSelection {
    constructor(object, methods) {
        for (const method of methods)
            this[method] = object[method];
    }
}



const parent = new Parent();

// select methods from parent object and create new object
const restricted = new MethodSelection(parent, ['accessibleMethod']);

console.log(restricted.accessibleMethod === parent.accessibleMethod);
// true

const child = new Child(restricted);

child.callAccessibleMethod();
// accessibleMethod called

try { child.callRestricedMethod(); } catch(e) { console.log(e.message); }
// TypeError: this.dependency.restricedMethod is not a function

parent.restricedMethod();
// restricedMethod called

Building a saas solution that lets companies keep their own data? [closed]

I'm figuring out how to build a saas where I can let companies keep their own database. For example, Slack for organizations don't have access to chats that are internal to the company. Similar to how Github works. What's the best way to design something so you can make updates but not directly access their database?

How to print this pattern in c [closed]

Write a program to print the following star pattern:

*
***
*
***
***
*
***
***
***
*
***
***
***
***

Please help some one to solve this c program to print this pattern

Visitor pattern for classes from external library

I want to use visitor pattern to extend functionality of classes from external library. The main problem that I can't add any new code to that library. Let's consider simple example.

External elements, which require functionality extension will be represented as tools for home work

public interface Tool {
    String name();
}

public record Saw(String name, String purpose) implements Tool {}

public record Screwdriver(String name, String nozzle) implements Tool {}

public record Wrench(String name, int size) implements Tool {}

And new functionality, which I want to add will be represented as workers

public interface Worker<T extends Tool> {
    Class<T> getToolClass();
    void doWork(T tool);
}

Saw worker

public class SawWorker implements Worker<Saw> {

    @Override
    public Class<Saw> getToolClass() {
        return Saw.class;
    }

    @Override
    public void doWork(Saw tool) {
        System.out.println("Sawing with " + tool);
    }
}

Screwdriver worker

public class ScrewdriverWorker implements Worker<Screwdriver> {

    @Override
    public Class<Screwdriver> getToolClass() {
        return Screwdriver.class;
    }

    @Override
    public void doWork(Screwdriver tool) {
        System.out.println("Tightens screw with " + tool);
    }
}

Wrench worker

public class WrenchWorker implements Worker<Wrench> {

    @Override
    public Class<Wrench> getToolClass() {
        return Wrench.class;
    }

    @Override
    public void doWork(Wrench tool) {
        System.out.println("Tightens bolt with " + tool);
    }
}

And main class to start the show

public class Main {
    public static void main(String[] args) {
        List<Tool> tools = List.of(
                new Saw("hand saw", "for gardener"),
                new Saw("chainsaw", "for forester"),
                new Screwdriver("torque screwdriver", "line"),
                new Screwdriver("powered screwdriver", "cross"),
                new Wrench("open-end wrench", 12),
                new Wrench("combination wrench", 32));

        Map<Class<? extends Tool>, Worker> workers = Stream.of(
                new SawWorker(),
                new ScrewdriverWorker(),
                new WrenchWorker()
        ).collect(Collectors.toMap(Worker::getToolClass, Function.identity()));

        tools.forEach(tool -> workers.get(tool.getClass()).doWork(tool));
    }
}

What do you think about such implementation of the pattern? Is it possible to upgrade this solution with use of java8 lambdas? And will it look easier and clearer?

Designing an event mechanism where an entity can be both listener (for some events) as well as generator (for some events) in C++

I am trying to create a basic design in c++ for an event mechanism which could have multiple event generators and listeners. The caveat here is that an object can behave as a listener (for some events) and a generator (for some other events). I am having a hard time figuring out the correct design for the same. Any suggestions please..

dimanche 7 août 2022

Swift Repository Design Pattern Quetion

Good Morning, I'm trying to implement Repository Design Pattern In my application as an iOS SWIFT developer.

I wonder if my way of implementation is good practice in software engineering ( trying to be better and better )

I use Generic programming in the repository and don't use a Manager for every model, it's a single manager that takes ownership of all basics CRUD database operations, so let's stop talking and see the code.

Database Manager that owns all operations

Main Database Manager Definition

Example Of Database Manager Functions

Code Inside Main Database Manager Class

My Way to use in Presenter ( Using MVP for this project )

Definition of the Database Manager with the type I need

Example of functions use cases in Presenter

Use Case of database manager in presenter

Example of functions used by another presenter

Use Case of database manager by another presenter

Receive add password Event from another view Controller in the main Presenter without the need to refresh the passwords list and re-fetch from the database (Look at picture number 4)

Function add, in another Presenter

I hope the question is clear.

How to use the Java type system to create classes handling network messages, which determine their proper handler using a field in the message?

I have a lot of classes implementing a "common" interface called Setter.

public interface Setter {
  Result set(Config config, int entityId);

  enum Result {
    HANDLED, HANDLING_ERROR, REJECTED
  }
}

An example of an implementation looks like this, it sets in the world a 'number' value for a given 'entity' distinguished by its entityId:

public class NumberSetter implements Setter {

  private World world;
  private Assets assets;

  public NumberSetter(World world, Assets assets) {
    this.world = world.
    this.assets = assets;
  }

  @Override
  public Result set(Config config, int entityId) {
    if (config instanceof NumberConfig numberConfig) {
      world.passNumber(entityId, numberConfig.number);
      return Result.HANDLED;
    } else {
      return Result.REJECTED;
    }
  }
}

Please do notice, that the Config object is cast to a specific NumberConfig, otherwise the Setter implementation signals it didn't handle the argument.

I am using a Set of these Setters in a network-enabled class, where it tries to match a super-type Config object against one of these Setters from the Set. (The naming might be subject to change lmao.) The code below handles a network package by passing it to all of the Setters in the Set and checks if there were any errors or if no Setter handled the package. If the check passes then the package wasn't handled properly and the Handler returns a NOT_HANDLED which later crashes the program because I'm still at the development stage.

public class ConfigNetworkHandler implements NetworkHandler {

  private final Assets assets;
  private final Set<Setter> setterSet;

  public ConfigNetworkHandler(
      Assets assets,
      Set<Setter> setterSet
  ) {
    this.assets = assets;
    this.setterSet = setterSet;
  }

  @Override
  public boolean handle(WebSocket webSocket, int worldEntity, Component component) {
    var configId = ((ConfigId) component).getId();
    var config = assets.getConfigs().get(configId);
    var setterResults = setterSet.stream()
        .map(setter -> setter.set(config, worldEntity))
        .toList();
    var anyErrors = setterResults.stream().anyMatch(HANDLING_ERROR::equals);
    var wasHandled = setterResults.stream().anyMatch(HANDLED::equals);
    if (anyErrors || !wasHandled) {
      return NOT_HANDLED;
    }
    return FULLY_HANDLED;
  }
}

I don't like it how I am not using Java's type system properly. I don't know how to do it otherwise, without manually providing a Map between ConfigId's and the Setters, which I would rather not do, because the ConfigIds aren't known at compile-time. The NetworkHandler-type-stuff is kind of similar but there are a lot less of them and they will probably be refactored in a similar way (there is also a lot fewer of them, so it's not a practical issue).

I like the current solution because it allows me to add and remove Setters without worrying about the other ones and also I don't need to change the implementation of ConfigNetworkHandler, because it's provided a Set. I don't like it, because it requires list traversing, doesn't seem "idiomatic" for Java, returns weird Results instead of just not being called because it doesn't accept the type, and FEELS like there should be something else.

Do you have an idea how to approach this differently?