mardi 31 décembre 2019

Sketch (SketchApp): When prototyping, is there a way to change the default animation?

When prototyping, is there a way to change the default animation from artboard to artboard?

By default I mean the animation Sketch gives by default to the transition.

Thanks!

Should functions that create structs return the struct or a pointer?

I'm learning C and this is one that I can't totally figure out. I have some code like:

typedef struct machine {
  char * name;
} machine;

machine create_machine(char * name)
{
  Machine machine = { .name = name };

  return machine;
}

But this means that the machine is on the stack. If the user wants it on the heap they have to create a machine themselves. So I'd need a function like this instead:

typedef struct machine {
  char * name;
} machine;

machine * init_machine(Machine * machine, char * name)
{
  machine->name = name;

  return machine;
}

The third option is to have create_machine create a machine and put it on the heap. Then also have a teardown function:

typedef struct machine {
  char * name;
} machine;

machine * create_machine(char * name)
{
  Machine *machine = malloc(sizeof *machine);
  machine->name = name;

  return machine;
}

void machine_teardown(Machine * machine)
{
  free(machine);
}

I'm leaning towards the 2nd pattern here. Have a create_machine that returns a machine, but then also provide an "init" function that can be called. This gives the consumer the option of putting it either on the stack or the heap.

Does this sound like a reasonable conclusion? What is the pattern that most libraries take here?

Design of a parser of a complex message structure

I'm working on a parser that is supposed to convert 1 type of a message from string to JSON, and another type of message from JSON to string.

The 2 types of messages can be expanded to more types further ahead, and have a common structure.

enter image description here

So far I've built the structure of the messages using OOP approach. It gives me the flexibility to add more types of messages in the future, and divides the responsibility for each part of the message between the different classes.

I created an interface called Parsable, which contains 2 static methods: json_build, and txt_build. The txt_build function takes a string as an argument, checks some of its format (the part which is relevant to the class), and returns an instance of the relevant class, with all the fields set to the contents of the message.

For instance, if I have a message like this one: "MESSAGE

MESSAGE_TYPE A

COMMON_FIELD1 SOME_VALUE

COMMON FIELD2 SOME_OTHER_VALUE

BODY

STOP"

Then txt_build with the message as an argument would return a MessageA instance with common_field1, and common_field2 set to SOME_VALUE, and SOME_OTHER_VALUE respectively.

The BODY contains fields which are unique to each type of message. I didn't mention it in order to simplify matters.

In addition, I would like to have an option to convert a JSON object from JSON to txt using the json_build method.

So that a json like this one:

{
    "type": "B",
    "common_field1": "SOME_VALUE",
    "common_field2": "SOME_OTHER_VALUE"
    "body": {
         ...
    }
}

Would also give me a MessageB instance with the fields set as above.

After having an instance of one class with all the fields set to their values, I can call the get_json(), or get_txt() methods in order to get the JSON representation or the string representation (according to some specified format I'm using) of the message.

I started to implement the part which build MessageA instances by strings and the code looks somewhat like this:

class Message:

@staticmethod
def txt_build(txt):
    parsed = ...  # code that parses the message

    common_field1, common_field2 = parsed['common_field1'], parsed['common_field2']

    msg_dispatch = {
        'A': MessageA,
        'B': MessageB
    }

    return msg_dispatch[parsed['msg_type']](common_field1, common_field2, msg_body)


class MessageA:
    def __init__(self, common_field1, common_field2, msg_body):
        super(MessageA, self).__init__(common_field1, common_field2)
        # code that parses the msg_body and init fields unique to MessageA


class MessageB:
    pass

The code works well for parsing text and initializing the fields. The problem is that I use the constructor of the sub-classes in order to give the body of the message (which is the only relevant part for each subclass), so I can't use it again for parsing JSON objects, at least not in a pretty way.

The only solution which I thought of, which answers good code practices (according to me, at least), is duplicating the entire message hierarchy so that the first one would parse JSON, and the other one would parse strings.

I would like to know if you have any other solutions, which would simplify things. Maybe I haven't noticed a much simpler solution, or didn't think of using some design pattern which is suitable in this case. I feel like I've made things complicated unnecessarily, and I don't have anyone to consult with.

I'd love to hear any suggestions or new ideas on how to do things differently, and I hope I made myself clear.

Thanks a lot :)

Can a variable be used in sqlite pattern match in python3

I have a very simple database that holds basic weather data, ie, date (yyyy-mm-dd), max-temp, min-temp and rainfall (date, max, min, rain). I'd like to be able to use input method to assign yyyy-mm to a variable that can be used in SELECT * FROM data WHERE date 'yyyy-mm%'. Is this possible? If so, could you point me to a good tutorial, please.

What is a good code design for button interaction similar to a radio button?

I would like to make an user interaction that works like radio button, hence only one item can be active in the list. Instead of a radio button graphics, I'd like to use the ListItem widget.

Hence, I'd like to:

  • ListItem A: On tap, 'activate' the list item.
  • ListItem B: On tap, 'deactivate' the current active and activate this ListItem.

What is the best algorithm architecture to do this?

I tried to use the architecture in the example below. The problem is that it does not track which list item is clicked, hence it change the 'state' of all the children of the parent at the same time.


//------------------------ ParentWidget --------------------------------

class ParentWidget extends StatefulWidget {
  @override
  _ParentWidgetState createState() => _ParentWidgetState();
}

class _ParentWidgetState extends State<ParentWidget> {
  bool _active = false;

  void _handleTapboxChanged(bool newValue) {
    setState(() {
      _active = newValue;
    });
  }

  @override
  Widget build(BuildContext context) {
    return Expanded (
            ListView.builder(
             itemCount: listOfBoxes.length,
             itemBuilder: (BuildContext context, int index) {
                 return TapboxB(
                     active: _active,
                     onChanged: _handleTapboxChanged,
                      ),
              }
            )
     )
  }
}

//------------------------- TapboxB ----------------------------------

class TapboxB extends StatelessWidget {
  TapboxB({Key key, this.active: false, @required this.onChanged})
      : super(key: key);

  final bool active;
  final ValueChanged<bool> onChanged;

  void _handleTap() {
    onChanged(!active);
  }

  Widget build(BuildContext context) {
    return GestureDetector(
      onTap: _handleTap,
      child: Container(
        child: Center(
          child: Text(
            active ? 'Active' : 'Inactive',
            style: TextStyle(fontSize: 32.0, color: Colors.white),
          ),
        ),
        width: 200.0,
        height: 200.0,
        decoration: BoxDecoration(
          color: active ? Colors.lightGreen[700] : Colors.grey[600],
        ),
      ),
    );
  }
}```



How the client can have access to the concreteproducts in Factory pattern

When implementing the Factory Method in c#, I have several concrete products let's say ConcretProductA and ConcretProductB where every ConcretProduct has a public string Name. The problem I am facing is that I need to create a list of all the ConcretProducts' names. This list will be used for example to enable the user to select one product in a Combobox on runtime.

So I need the ability to read all the ConcretProducts' names, without instantiating instances for all the available concretProducts, read the name (i will have to make it static most probably) and store it in an enum for example. If not directly could the interface help me?

Could this work? or there is a better solution?

lundi 30 décembre 2019

How to implement Google Spreadsheet like application in browser? [closed]

Could you help me answer a few questions that I have regarding "Design Spreadsheet like app in browser"?

This is mainly from "browsers" perspective.

  1. How would you structure your data?

    2D Matrix: [["XYZ"],[]]
    A Hashmap like:
    {
        rowNumber: {
            colNumber: {
                data: "XYZ" 
            }
        }
    }
    
    In my opinion, hashmap would be great because it provides an easy access of O(1) and will save a 
    lot memory.
    

    What are some other ways to structure it?

  2. How will you implement/calculate formulas? Is using "Reactive programming" a good approach, or do I need to represent my sheet as a graph where each cell will be a vertex and their relations with other cells will be an edge? Like:

    {
        A6: [C9, D1, D3],
        c2: [d3, D1, A6]
    }
    
    C9, D1, and D3 are dependent on A6. So whenever the value of A6 changes,
    we need to update their values as well.
    
    Any other approaches?
    

    Finally, how will you calculate a value using the given formula?

  3. Will you store the entire data of the sheet locally or only the visible section?

Any help would be highly appreciated. Thanks for your time.

Command pattern - Commands that execute the task with a "weight"

I'm currently working on designing a base for future projects, more specifically I'm working on the input handling. I'm using the command pattern for handling the input, when creating an input context the programmer can bind a command to a key or mouse button through an invoker that executes the command depending on the different conditions of the application, key pressed, where the mouse is on the window and so on.

I ran into trouble when I got to the part of adding handling of the mouse when in an input context where the cursor is disabled, e.g. when controlling a 3D camera (This is actually the only situation I can think of where this would be useful).

The way I see this working, is the programmer binds a command, one that rotates the camera, to be activeated once an event is created that describes mouse movement. The command would hold a pointer to the camera object and call a function like camera->pan() when executed. This command would be executed when the mouse moved in the X-Axis. However if this was the case, the camera would always pan with a constant speed, no matter how fast or slow the mouse was moved. If the cameras function pan() had a parameter for specifying how much to pan, the Command object would need to have a value for this parameter when executing. If that value is specified on creation of the command and stored as a member, the problem would arise again, since the parameter would have the same value every time the function is called.

My proposed solution to this problem is to simply create a variant of the Command class called something like WeightedCommand that had a parameter in its execute() function. This parameter would be a "weight" passed on to the cameras pan() function. This would allow for the command to be executed with a differen "weight" everytime it's called, or the same "weight", it would be up to the programmer to decide.

For reference, this is an example of the Command pattern, from wikipedia.

class Light {
 public:
  void TurnOn() { std::cout << "The light is on." << std::endl; }
  void TurnOff() { std::cout << "The light is off." << std::endl; }
};


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

  virtual void Execute() = 0;
};

// The Command for turning on the light - ConcreteCommand #1
class FlipUpCommand : public ICommand {
 public:
  FlipUpCommand(Light* light) : light_(light) { assert(light_); }

  void Execute() { light_->TurnOn(); }

 private:
  Light* light_;
};

An example of the WeightedCommand:

class WeightedCommand
{
public:
    virtual ~WeightedCommand() = default;
    virtual void execute(double weight) = 0;
};

class PanCamera : public WeightedCommand
{
public:
    PanCamer(Camera* cam)
        : _camera(cam;
    {}

    void execute(double weight)
    {
        _camera->pan(weight);
    }    
private:
    Camera* _camera;
};

Can you see any flaws with this approach. Is there a better solution already available? I tried searching for solutions to similar problems, but couldn't find anything that really fit.

Is it right to make View bind on Instance of View from ViewModel

I am working on new version of application that takes big word file and parse its section to GUI , the current version is written in .Net , WPF framework and MVVM design pattern .

The current architecture which the code is following is like this :

  • View has a datagrid and the datagrid binds on instance of Model in ViewModel

  • ViewModel has an instance of Model

  • Model has List of object of supporter class

  • Supporter class has properties which mapped to columns of datagrid in View

This structure is illustrated in UML for more clarification

The implementation:

View

ViewModel

Model

Supporter

I suppose to build on the current architecture ; I feel that the current architecture is anti-pattern and it have a tight coupling issue because it is binding on view directly but by using indirect way.

I would like to know If I am right or it is okey to go with this architecture.


Is this actually the bridge pattern?

I am following the course Design Patterns on www.lynda.com. They discuss the Strategy pattern. Here is a still from their video. The strategy pattern

Is this actually the Bridge pattern? I am a little confused about it.

dimanche 29 décembre 2019

What is the difference between a template class design pattern and generic template class in a programming language like Java?

I am taking this basic course in design patterns that explains "Template-And-Hook Patterns" as an introduction by starting with the "Template Method Pattern" then goes a little bit complex into "Template Class Patterns" and finally the "Generic Template Class Patterns".

What still unclear to me is what the "Generic Template Class" really adds to this ?

Here is how it was explained:

enter image description here

Where do we exactly see the static generic expansion here ?

Can factory pattern be used for only one user defined class and no subclasses

I am trying to implement a basic factory pattern for a class which is user defined. For example a class of currencies which allows the user to enter the currency name, exchange rate, etc. Reason being that I would like to allow the possibility for future sub classes to be added.

I do not want to create a subclass for each possible currency as the details are entered by the user and these currencies may also be ficititous. I also do not have any other classes.

For example this is my code in which the user is expected to fill in the parameters of the class for a currency to be created. This is all done in a seperate class and they are placed in a list:

public String code;
public String name;
public boolean major;

public Currency(String code, String name, boolean major) {
    this.code = code;
    this.name = name;
    this.major = major;
}

I think I must be missing something but I cannot figure it out. It is possible that the factory pattern is not supposed to be used in this manner?

This is my first time using this design pattern as well in conjunction with dependency injection. Thank you for any help.

How to support multiple versions of server in one mobile app version?

This is pretty much duplicate of the following two questions which definitely do not have a certain or accepted answer yet.

Multiple Server Versions who needs to supported by one mobile App Version

Mobile strategy: How to handle this server-client version permutation?

So, the use case here is that the product is hosted on-prem by the customers and hence each customer can have different version of the product, like Customer A can be on version 1.0 of the server and Customer B can be on version 2.0 of the server.

Version 1.0 of the mobile app is developed with version 1.0 of the server and the plan is to update the mobile app version at least every time the server version upgrade happens. So, in a way version 2.0 of the mobile app will consume version 2.0 of the server which would have added features to version 1.0.

The mobile app version 2.0 in fact can have a different user experience altogether. The version of the server will be known to the mobile app only at runtime after the user authenticates (which will be first screen on the mobile app)

Now, some customers can still be on version 1.0 of the server as they might not want to upgrade due to many reasons. But the app on the devices of users/employees of the customers will be latest, that is, 2.0.

And it is not limited to just two versions. There can be as many as 10 different versions.

What would be the best way to handle such a client server problem at runtime? I want to ensure that version 2.0 of the mobile app works with version 1.0 of the server in the same way as version 1.0 of mobile app would work. Basically, mobile app becomes version 1.0 in terms of functionality and UI.

For iOS app, I am thinking of keeping separate targets in Xcode for each mobile app version. Each new target copies files from previous target and then adds its own new files or changes to copied files. That would solve the maintainability problem to some extent, in the sense that when we release this product as a SaaS solution, we just keep the latest target code.

However, I am not sure how I ensure that the version 2.0 of the mobile app selects files of version 1.0 when it finds server version as 1.0 after authentication happens.

I also got a hint of using Workspace as a possible solution. But not sure on how that would also help.

Any ideas will be appreciated, thanks in advance.

storing users' passwords theory

I'm writing backend service that authenticates users. So I must persist users' info including passwords. Let's say we have users manager

package userstorage


type User struct {
    Login     string
    Password  string
    Nickname  string
    FirstName string
    LastName  string
    Email     string
}

type Manager struct {
    users map[string]User
}

func New() *Manager {
    return &Manager{
        users: make(map[string]User),
    }
}

func (m *Manager) Add(user User) error {

    // some code
    return nil
}

func (m *Manager) Get(login string) (User, error) {

    var retUser User
    // some code

    return retUser, nil
}

It looks good to send User structure to Add() method. But when I do Get() it seems for me not good to return password. Instead it will be better to have method isPasswordValid(login, password string) bool that will allow class clients to check credentials without giving password.

This leads me to the idea that the User structure should not include password field. This means that I must have internal structure to persist all user's info. That looks redundant. So here's the question:

What is the correct class design in this case?

NB. Sure, passwords should be persisted hashed and salted. But anyway it doesn't look good to me to return user's password.

How to properly cancel an asynchronous and running method if it is invoked again and the previous invokation result is obsolete

I have a rather generic question but with a specific use case.

In my specific case I have a UI with an input text box and if the user is changing the text in that input box some recommendations are shown to what the user might want to type in eventually. In other words the input box uses an autocomplete feature. The recommendations are requested from a webservice, hence this process takes a significant amount of time in which the user might already changed the text again. Hence, I want to cancel or stop the process that is still acquiring obsolete data and only take the results of the most recent invokation of the method.

So imagine a method OnTextChanged in the View class that is calling the method GetRecommendationsAsync. My approach is to simply cancel the previous and obsolete invokation of GetRecommendationsAsync and then don't do anything in the UI if the method is canceled. Here some minimal code I just wrote up (so could contain errors) to show the concept:

public async Task OnTextChangedAsync(string newText)
{
    try
    {
        var recommendations = await GetLatestRecommendationsAsync(newText);
        ShowRecommendations(recommendations);
    }
    catch(TaskCanceledException)
    {
    }
}

private Task<Recommendations[]> GetLatestRecommendationsAsync(string text)
{
     _cancellationTokenSource?.Cancel();
     _cancellationTokenSource = new CancellationTokenSource();

     if (string.IsNullOrWhiteSpace(text)) return null;

     return GetRecommendationsAsync(text, _cancellationTokenSource.Token);
}

Now, my question is if this is a valid approach or does it have some shortcommings? Furthermore, I would like to know if there is a general known pattern to handle the generic case of cancelling a method that is obsolete because it was called again? Is an appraoch using a semaphore better? How would you approach this case? Is it guaranteed that the cancellation of the previous invokation is caught before the new invocation returns its results?

samedi 28 décembre 2019

Laravel 6 structure and pattern best practice

Just wanna check whether it is a good idea to use action methods (create, update, addRelation, etc) in self Model or create separate ModelService for that matter.

Abstract Factory Design and Linked List Issue C++

I am a newbie to C++ programming and abstract design patterns.

The program is meant to allow the user to select whether the data he wants to enter is for a management staff or Junior staff then save the parameters in the linked list and display them too using the Linked List.

I have used abstract factory design to implement the selection of type of data to enter but having challenges with the linked list.

Prior to this exercise, I have a working linked list that stores integers and displays integers which I modified for this exercise.

The AddNode and PrintList functions of the Linked list aren't working (StaffMain.cpp), no error message displayed, the program compiles but the created object is not displayed when I call the list display function.

I have five files for the program (Staff.h, Staff.cpp, StaffList.h, StaffList.cpp and StaffMain.cpp)

I am sharing the part of the program having issues -linked list and the abstract factory codes below.

Kindly provide an insight on how to pass the selected factory class object to the linked list and display them.

Thank you.

using std::cout;
using std::endl;


List::List() //default constructor for List
{
    head = NULL;
    curr = NULL;

}

void List::AddNode(StaffFactory* c) //function to add node
{
    List::Node* n = new List::Node;
    n->next = NULL;
    n->newstaffFactory = c;

    if (head == NULL) //check if the list is empty
    {
        head = n;
    }
    else

    {
        curr = head; //start of the list and iterates till next points to end of the list
        while (curr->next != NULL)
        {
            curr = curr->next;
        }
        curr->next = n;
    }
    cout << "New Node added" << endl;
}


void List::PrintList() //print nodes in the list
{
    curr = head;
    while (curr != NULL) //each node is printed till current pointer gets to end of the list
    {
        curr->newstaffFactory->staffDetails();
        curr = curr->next;

    }
    cout << "The linked list printed" << endl;
}
sing std::cout;
using std::endl;
using std::cin;



class StaffFactory
{
public:
    virtual Staff* staffDetails() = 0;

};

class JuniorStaffFactory :public StaffFactory
{
public:
    Staff* staffDetails()
    {
        return new JuniorStaff();
    }
};

class MgtStaffFactory :public StaffFactory
{
public:
    Staff* staffDetails()
    {
        return new MgtStaff();
    }
};

int main()
{
    List stafflist;
    int choice;
    cout << "Select type of staff: " << endl;
    cout << "1: Junior Staff" << endl;
    cout << "2: Management Staff" << endl;
    cout << "Selection: ";
    cin >> choice;
    cout << endl;


    StaffFactory* newStaffFactory;

    switch (choice)
    {

    case 1:
        newStaffFactory = new JuniorStaffFactory;
        break;
    case 2:
        newStaffFactory = new MgtStaffFactory;
        break;
    default:
        cout << "Invalid selection!!!" << endl;
        newStaffFactory = NULL;
        break;
    }

    if (newStaffFactory != NULL)
    {
        Staff* c = newStaffFactory->staffDetails();
        c->input();

        stafflist.AddNode(newStaffFactory);

        stafflist.PrintList();
    }

}

What is the best design pattern to build an object with different argument requirements depending on its creation?

I have a C++ program that renders 3D objects. Each object is represented by a mesh. To minimize the memory usage, I'd like to avoid identical meshes being loaded more than once and instead have objects regardless of material and other rendering parameters reference the same mesh in a mesh manager class. Mesh creation could be requested from the mesh manager class. Provided an identical mesh is not already created, a new mesh would be generated. However, meshes can be created any number of ways, either procedurally as primitives, such as spheres, cubes, planes, cones, etc., or loaded from various file types. The issue, though, is that each mesh creation option has its own unique argument requirements and mesh creation must be extensible for future scaling. A cone would require a radius of the base and height while a cube requires only a side length and for a file, a file location and/or file type to be loaded from. I have thought about factory and builder design patterns but examples of both are generally shown where each polymorphic creation has the same arguments. For this particular problem, what are the best design patterns or approaches?

Insert operation in two different classes with one post request

I want to insert mysql and redis databases in their classes at the same time. I tried to use the repository pattern, but laravel's bind method implements the interface to only one single class

The controller is as follows:

class PostController extends Controller
{
    protected $post;

    public function __construct(PostRepositoryInterface $post)
    {
        $this->post = $post;
    }

    public function store(StorePostRequest $request, PostRepositoryInterface $post)
    {
        return $post->create($request->validated());
    }
}

PostRepositoryInterface

interface PostRepositoryInterface
{
    public function all();

    public function get($id);

    public function create($param);

    public function update($id, $param);

    public function delete($id);
}

The question I want to ask is, how can I perform the insert operation in more than one class using this interface?

Generally speaking, what is a Domain folder? What does it mean/contain?

Lately I have been looking at a lot of different php frameworks and various php packages. Whenever I first look at project, like said frameworks or packages, I try to digest it's directory structure to get a clue as to its organization. I've noticed that there are often reoccuring themes, like an "app" folder, a "tests" folder, a "src" folder, a "var" folder and so on and so forth. Usually I understand what these folders represent or mean, however lately I have been coming across a folder I do not understand in project directories: a "Domain" folder.

What does a Domain folder represent? What kinds of logic or code are contained therein? Does it have any relation to an actual Domain name?

Any and all input would be greatly appreciated.

EDIT: To provide a specific example of what finally prompted me to ask this question, I was looking at the starter boilerplate that is generated by the php "slim" framework. You can generate this project by using php's tool composer and running:

composer create-project slim/slim-skeleton [app-folder]

Here is a link to the repo on github. Within the "src" folder of this project, there is a "Domain" folder. At least for this specific example, what does the Domain folder represent?

vendredi 27 décembre 2019

How to abstract types of transformations

I have an program that already transform POJOs to xml via JAXB and this is done by adding a the elements to a list in this form

List<JAXBElement<?>> elementsToTransform = new ArrayList<JAXBElement<?>>();

In other method I just transform and populate the elementsToTransform as xml, the firm of this method is something like this

private List<JAXBElement<?>> transform(Student student) 

Now I need to add a way to transform to Json via Gson and I want to abstract both declaration and method in order to support both formats but the implementation is pretty hardcoded to xml and I need to fit this solution as the way it is build with xml because this depends on other functionality that I do not want to modify so I would know if there is a way I can support both formats and which will be the better choice for this problem

At the end I would like to have something like this in the elementsToTransform list

JAXBElement(0)
JAXBElement(1)
JAXBElement(2)
String(3)(this will be Json)

How to synchronize block in method

I'm building an accounting application and one of the method has been written to save an invoice into the database (MongoDB). Before saving an invoice I must create a number (alphanumeric characters) incrementing the last saved invoice number. Basically, I have to read the last created invoice to get the number and reuse that number + 1 to save the new invoice. To keep the invoice number consistent, I have written the following method:

public synchronized void saveInvoice(InvoiceObject object){
   //Get the last invoice and increment the number
   //Save the InvoiceObject with the incremented number
}

So far so good, but since this application is used by multiple clients, each client has its own invoice numbering sequence so, instead of blocking all clients (threads) while saving an invoice (because of the synchronized), I would like to allow multiple clients accessing the method "concurrently" and queuing the requests of a same client (to keep increasing properly its invoice sequence).

To summarize, here is a diagram of what I want to achieve: Diagram

How can I achieve this?

Thanks :-)

Registering and injecting generic repositories into unit of work class with simple injector [closed]

I have a generic repository class which is being inherited from a generic repository interface. In the other hand I have a handful number of domain classes and because proper UoW & repository patterns imply that repositories must reside inside the unit of work class, I want all my repositories to reside inside the unit of work class. But I don't want to inject all those generic repositories into unit of work class one by one. Instead I have a GetRepository method in my unit of work class with the following signature:

IRepository<T> GetRepository<T>() where T : class , IEntity;

The problem is I'm using a RepositoryFactory class which actually is a wrapper around the container and I don't like it because it introduces service locator anti pattern.

Now what I want is to know how to register all of these generic repositories with a single registration command with a scoped lifestyle and also how to inject them as an IEnumerable of some type like IEnumerable<IRepository<IEntity>> into my unit of work's constructor, So later to be able to return the proper repository from the list with invoking unit of work's GetRepository() method instead of using RepositoryFactory service locator class?

All suggestions or code samples are much appreciated.

What approach to take to make my code more generic Java/ Spring?

In a SpringBoot application I have a service (in the Spring sense) that calls clients that themselves consume RestFul web services by calling a function that is identical to createXXX except that the nature of the object changes at the input of the method. To simplify, let's suppose that I model the creation of animals: with the objects CatDTO, DogDTO, HorseDTO as input of the web services. AnimaslDTO is an object composed of different types of animals (there is no inheritance relationship).

I make the three clients in the same manner let's take the cat's example

package com.animals.client;
import ...

@Service
public class CatClient {

    private static final String CODE_WS_CREATE_CAT = "createCat";
    /**
     * Call RestFul WS for Cat Creation
     * @param catDTO
     */
    public ResponseEntity<String> createCat(CatDTO catDTO)
    {
        // ... Call a RestFul WS in the same manner for each animal. Only the parameter change in each client
        // --> ie dogDTO in DogClient.createDog, HorseDTO in HorseClient.createHorse,
    }
}

In AnimalService implemented by AnimalServiceImpl I try to create the three animals Here is the code

package com.animals.service.impl;

import ...

@Service
public class AnimalServiceImpl implements AnimalService {

    @Autowired
    private CatClient catClient;

    @Autowired
    private DogClient dogClient;

    @Autowired
    private HorseClient horseClient;

    @Override
    public ResponseEntity<String> createAnimals(AnimalsDTO animalsDTO) {
        catClient.createCat(animalsDTO.getCat());
        dogClient.createDog(animalsDTO.getDog());
        horseClient.createHorse(animalsDTO.getHorse());
        .... 
    }
}

I want to know how to generify my clients in Spring or Java for the methods which are very similar as createXXX . What design pattern can I use ? What I've tried is to use Java generics but it doesn't fit well with Spring. I've tried to create a AnimalClient(T) class where T is the animal but I have problems in autowiring constructor with one argument.

Thanks by advance

Pattern for project roles in role based strategy

I want to differentiate between QA/Prod for example I have Jenkins projects by names 1)Ck-init-Prod 2) Mk-dir-Prod 3)CK-init-QA 4)Mk-dir-QA. I want to differentiate the jobs, I tried using (.*)Prod but it also shows me QA alone with Prod when I assign a user only Prod. can anyone help me fix this.

All objects in JavaScript are descended from Object why, for which purpose? [closed]

I know JavaScript is prototype based programming. It has only object. Creation of object is costly so we use object as prototype. I understand it gives hierarchy(links) for inheritance, from Object(global) for objects. but why there is one global object(Object)? What purpose does it achieve? Why such design?

Swift Protocol referencing itself and associated type

I have a classic implementation of Chain of Responsibility pattern with the following code:

protocol Request {

    var firstName: String? { get }
    var lastName: String? { get }

    var email: String? { get }
    var password: String? { get }
    var repeatedPassword: String? { get }
} 

protocol Handler {

    var next: Handler? { get }

    func handle(_ request: Request) -> LocalizedError?
}

class BaseHandler: Handler {

    var next: Handler?

    init(with handler: Handler? = nil) {
        self.next = handler
    }

    func handle(_ request: Request) -> LocalizedError? {
        return next?.handle(request)
    }
}

So I can create a PermissionHandler, LocationHandler, LoginHandler, a SignupHandler and combine them in chain. So far so good.

Now I want to create a Chain of Responsibility for other purposes, let's say a MediaContentPlayer CoR with different types of MediaContentHandlers and I thought to refactor and reuse the base code using generics.

So I started from the Handler protocol:

protocol Handler {

    associatedtype HandlerRequest
    var next: Handler? { get }

    func handle(_ request: HandlerRequest) -> LocalizedError?
}

but I get error "Protocol 'Handler' can only be used as a generic constraint because it has Self or associated type requirements".

Is there a way to reference the protocol inside the protocol itself when using associatedtype? Or another way to make the above code not dependent on a specific type?

callback from DLL functions

I have C++ console application which is statically linked to socket library to communicate with socket clients. My console application loads several DLLs(modules) and calls DLL functions. Assume I have 2 DLLs. 1st DLL will fetch available devices in the system along with device properties. 2nd DLL will fetch all installed applications and related information. Fetching these details may take little time. So I need to notify client about the status like fetching multimedia devices, storage devices, bluetooth devices, network devices and etc. Its kind of progress. Similarly for 2nd DLL. I have not linked my socket library to the DLLs so that I cannot update the status to client directly. As of now, my console application send information to client once dll function executed completely. Is there any way to update the caller from DLL function in between(before function execution complete). callback mechanism can be used here?

Type Erasure and the Return type

class Person
{
    String name;
    String add;

    Person(){}

    @Override
    public String toString() {
        return "Person{" +
                "name='" + name + '\'' +
                ", add='" + add + '\'' +
                '}';
    }

    public Person(String name, String add)
    {
        this.name=name;
        this.add=add;
    }
}


class PersonBuilder<E extends PersonBuilder<E>>{
    String name;
    String add;

    E addName(String name)
    {
        this.name=name;
        return (E)this;
    }
    E addAdd(String add)
    {
        this.add=add;
        return (E)this;
    }
    Person build()
    {
        return new Person(name,add) ;
    }
}

class Employee extends Person{
    String doj;

    @Override
    public String toString() {
        return "Employee{" +
                "name='" + name + '\'' +
                ", add='" + add + '\'' +
                ", doj='" + doj + '\'' +
                '}';
    }

    Employee(String name, String add, String doj)
    {
        super(name,add);
        this.doj=doj;
    }


}
class EmployeeBuilder extends PersonBuilder<EmployeeBuilder>{

    String doj;
    EmployeeBuilder addDoj(String doj)
    {
        this.doj=doj;
        return this;
    }
    Employee build()
    {
        return new Employee(name,add,doj);
    }
}

public class FluentBuilderRecursiveGenerics{
    public static void main(String[] args) {
 1.       EmployeeBuilder eb=new EmployeeBuilder();
 2.       Employee e=eb.addName("kamal").addAdd("dcd").addDoj("45").build();
 3.       System.out.println(e);

 4.       PersonBuilder pb=new PersonBuilder();
 5.       Person p=pb.addName("Kamal").addAdd("dlf").build();
 6.       System.out.println(p);
    }
}

I have two questions to ask in these lines of code. The lines of code are related to the Fluent(design pattern) Recursive Generics. First is as Line 1, 2, 3 are running that means the Return type of PersonBuilder method is EmployeeBuilder, but I have also studied that the type erasure replaces the type with the bounds, So it should be replacing with PersonBuilder(EmployeeBuilder) and the program should not be running. Because when in case of generics the input parameters of a function will be decided by the type Erasure. The other question is what type Erasure is going to do for the line Number 4,5,6. Can anyone explain?

Output:

Employee{name='kamal', add='dcd', doj='45'}
Person{name='Kamal', add='dlf'}

jeudi 26 décembre 2019

Validate when fields depend on one another

I am passing a request object name Person to controller. Lets say the object has 2 two fields. The following business rule apply:

  • If field age has a value < 18, the field sin should be left blank;
  • If not, it will produce exception with message the sin should be blank with age < 18 or another way is to set the field sin to empty string("").

What is the best way for me to validate those inputs when they depend on each other. My way to deal with them is to validate them inside the controller method. So it should look something like that

@GetMapping("/..."
public ResponseEntity<PersonResponse> getPersonResult(GetPersonRequest request)
{
    if (request.getAge() < 18)
    {
        if (request.getSin.length > 0)
            request.setSin("") 
    }
    PersonResponse response = callThirdPartyAPIToRetrieveInformationAboutThatPerson(request)
    return response ;
}

Is there any more elegant way to code ? Is it ok for the controller method to contain any validation logic like that ? am i violating the Single Responsibility in SOLID design ?

Java implementing business logic based on EnumType given as field of Object

I know my question title is not relevant to what I'm asking, but not getting any better title. But feel free to suggest title. (So it will be helpful for others as well)

Here is the scenario I'm having:

I've enum class as below

public enum CalendarBasis {
    FISCAL_YEAR,
    CALENDAR
}

This enum is used in multiple objects in project.

I want to know the best practice/design pattern to follow which will be helpful for having functionality based on value of enum. Today there are only two values in CalendarBasis but tomorrow there can be multiple values.

This is what I'm doing currently: Consider I've Object SpecificElement which has CalendarBasis enum parameter.

public class SpecificElement {
  private SpecificValue specificValue; //some object
  // few more Objects defined
  private CalendarBasis calendarBasis;

  //getters & setters
}

Following function do some operations on SpecificElement based on type of calendarBasis.

public Foo doCalculations(SpecificElement specificElement)
{

  if(specificElement.getCalendarBasis().equals(CalendarBasis.FISCAL_YEAR)){
    //do something based on fiscal & return.
  }
  if(specificElement.getCalendarBasis().equals(CalendarBasis.CALENDAR)){
    //do something based on CALENDAR & return.
  }

}

I want to know if I can have something like multiple class Implementations based on Enum values & do operations related to that enum inside implementation class. There are around 8-10 different functions as doCalculations which has business logic based on enum type.

The code structure I'm following doesn't seems to be good practice.

So it will be helpful if someone can give me light on structuring this kind of scenario.

ETL design - what Queue should i use instead of my SQL table and still be able to process in parallel

Need your help with re-design my system. we have very simple ETL but also very old and now when we handle massive amount of data it became extremely slow and not flexible

the first process is the collector process:

collector process- always up

  1. collector collect the message from the queue (rabbitMQ)
  2. parse the message properties (Json format) to java object (for example if the json contains field like 'id' and 'name' and 'color' we will create java object with int field 'id' and string field 'name' ,and string field 'color')
  3. after parsing we write the object to csv file as csv row with all the properties in the object
  4. we send ack and continuing to the next message in the queue

processing work-flow - happens every hour once

  1. a process named 'Loader' loads all the csv files (the collector outputs) to DB table named 'Input' using SQL INFILE LOAD all new rows have 'Not handled' status . the Input table is like a Queue in this design
  2. a process named 'Processor' read from the table all the records with 'Not handled' status ,transform it to java object ,make some enrichment and than insert the record to another table named 'Output' with new fields, **each iteration we process 1000 rows in parallel - and using JDBC batchupdate for the DB insert ** .

the major problem in this flow:

The message are not flexible in the existing flow - if i want for example to add new property to the json message (for example to add also 'city' ) i have to add also column 'city' to the table (because of the csv infile Load) , the table contains massive amount of data and its not possible to add column every time the message changes .

My conclusion

Table is not the right choice for this design.

i have to get rid of the csv writing,and remove the 'Input' table to be able to have flexible system , i thought of maybe using a queue instead of the table like KAFKA and maybe use tools such KAFKA streams for the enrichment. - this will allow me flexibly and i wont need to add column to a table every time i want to add field to the message the huge problem that i wont be able to process in parallel like i process today.

what can i use instead of table that will allow me process the data in parallel?

Java - How to swap a resource file path for a test file during unit testing?

I have a resource file which has some settings. I have a ResourceLoader class which loads the settings from this file. This class is currently an eagerly instantiated singleton class. As soon as this class loads, it reads the settings from the file (file path stored as a constant field in another class). Some of these settings are not suitable for unit tests. E.g. I have thread sleep time in this file, which may be hours for production code but I'd like it to be a couple of milliseconds for unit tests. So I have another test resource file which has a different set of values. My question is how do I go about swapping the main resource file with this test file during unit testing? The project is a maven project and I'm using testng as the testing framework. These are some of the approaches I've been thinking about but none of them seem ideal:

  1. Use @BeforeSuite and modify the FilePath constant variable to point to the test file and use @AfterSuite to point it back to the original file. This seems to be working but I think because the ResourceLoader class is eagerly instantiatied, there is no guarantee that the @BeforeSuite method will always execute before the ResourceLoader class is loaded and hence old properties may be loaded before the file path is changed. Although most compilers load a class only when it is required, I'm not sure if this is a java specification requirement. So in theory this may not work for all java compilers.

  2. Pass the resource file path as a command line argument. I can add the test resource file path as command line argument in the surefire configuration in the pom. This seems a bit excessive.

  3. Use the approach in 1. and make ResourceLoader lazy instantiated. This guarantees that if @BeforeMethod is called before the first call to ResourceLoader.getInstance().getProperty(..), ResourceLoader will load the correct file. This seems to be better than the first 2 approaches but I think making a singleton class lazy instantiated makes it ugly as I can't use a simple pattern like making it an enum and such (as is the case with eager instantiation).

This seems like a common scenario, what is the most common way of going about it?

How to combine and maintain multiple applications that do the same thing using sound engineering principles?

I currently have around 15 automation applications I have adopted that are all doing similar things, but they are written by different people. Almost all of the code is copy-pasted over a 3 year period. A new automation would need to be created, and whoever was responsible for making it, would copy the most recent project, and modify it. I also have new projects coming up that do similar things, and would like to avoid what has happened in the past.

I'm trying to combine the identical functionality in some way and looking for ideas about the best way to do this so these projects will be easier to maintain and fix bugs in. First, I will describe what these automation programs do. They are all C# console applications that are run from the task scheduler at set times of day on a couple machines. However, they are currently all being moved to the same machine. Ideally, I think we should assume they will not be on the same machine. They can loop around and wait, but all are supposed to complete their execution by end day (23:59:59 local).

They all retrieve files from a source, and copy them to a working directory. This working directory is usually the local machine, but not always. Some transfer the source to working directory via ftp, some via UNC path, and probably other ways as well. The retrieved source files are in different formats, sometimes JSON, XML, or CSV. Sometimes there is pre-processing that needs to be done, because the source files are malformed XML, or CSV files with bad records, and so on; I am responsible for fixing or removing bad entries. From here, depending on the type of data in these files, we send the data off to different sources for more processing, sometimes combined with our own internal data. So for instance, the source file might contain addresses, but this specific automation will also need information in our internal databases along with files located in an image server.

This is the most varied part of each of the applications, but is limited to about 6 different places the data can go to (ie 6 different formats going out). Each destination has a different format the data we compile will need to be in, but each current automation application has a different way of handling this. After we send the formatted source out, we sometimes get it back and send to another source.

This can be complicated. Lets say we have initial data D0 that has been preprocessed (removed bad entries, combined with internal data), and 2 external file processes A,B. We format D0 for A, call it D1. D1 is sent to A and we get back D2 in a different format. D2 needs to be in a new format to be processed by B, so we create D3 for B, which gives us back D4. D4 will then go through some finalization specific to the automation usually.

After the data has been fully processed, we move the files to a final location and update necessary values in databases, generate reports, and send emails to people who need them. Along the way, errors are tracked and written to logs, and error emails are sent out when a critical part of the process fails.

My intuition tells me a shared and versioned library is the way to go for most of this, so that when we make a change or fix, we can deploy it to every app by updating the configs. My colleagues are resistant to this and want to go a web service route, so I'd like any points/counterpoints to bring up in discussions.

The next part I would like suggestions for is the different data formats we use in formatting. My initial thoughts on this are to make a large class that contains all the data from our internal data and the data we collect from sources, and perhaps even data that can come back from external processing. Call our monolithic class format M, and our external processing input and output format classes Ai, Ao, Bi, Bo, ... I'd have to have a M->Ai, Ao->M for every external process. Sometimes we need to do M->Ai, Ao->M, before we can do a M->Bi though, because process B relies on data from A processing. Not sure if its better to do M->Ai->Ao->Bi->Bo->M, or something like M->Ai->Ao->M->Bi->Bo->M. It seems like converting every external process format to another format might be an impossible task, because it grows exponentially with additional external sources. I'm leaning towards some system that tracks which external processes have been applied to the monolithic data in M.

Thank you and I'm looking forward to hearing any suggestions.

Design pattern for subclass-like structure

My goal is to represent a set of types with a similar behaviour in a elegant and performant manner. To achieve this, I have created a solution that utilises a single type, followed by a set of functions that perform pattern matching.

My first question is: is there a way how to represent the same ideas using a single type-class and instead of having a constructor per each variation to have a type that implements said type-class?

Which of the two approaches below is: - a better recognised design pattern in Haskell? - more memory efficient? - more performant? - more elegant and why? - easier to use for consumers of the code?

Approach 1: Single type and pattern matching

Suppose there is a following structure:

data Aggregate a
  = Average    <some necessary state keeping>
  | Variance   <some necessary state keeping>
  | Quantile a <some necessary state keeping>

It's constructors are not public as that would expose the internal state keeping. Instead, a set of constructor functions exist:

newAverage :: Floating a
  => Aggregate a
newAverage = Average ...

newVariance :: Floating a
  => Aggregate a
newVariance = Variance ...

newQuantile :: Floating a
  => a                     -- ! important, a parameter to the function
  -> Aggregate a
newQuantile p = Quantile p ...

Once the object is created, we can perform two functions: put values into it, and once we are satisfied, we can get the current value:

get :: Floating a
  => Aggregate a
  -> Maybe a
get (Average <state>) = getAverage <state>
get (Variance <state>) = getVariance <state>
get (Quantile _ <state>) = getQuantile <state>

put :: Floating a
  => a
  -> Aggregate a
  -> Aggregate a
put newVal (Average <state>) = putAverage newVal <state>
put newVal (Variance <state>) = putVariance newVal <state>
put newVal (Quantile p <state>) = putQuantile newVal p <state>

Approach 2: Type-classes and instances

class Aggregate a where
  new :: a
  get :: Floating f => a f -> Maybe f
  put :: Floating f => 

data Average a = Average Word64 a
data Variance a ...

instance Aggregate Average where

instance Aggregate Variance where

instance Aggregate Quantile where

The obvious problem here is the fact that new is not parametric and thus Quantile can't be initialised with the p parameter. Adding a parameter to new is possible, but it would result in all other non-parametric constructors to ignore the value, which is not a good design.

Is undo operation supported in bloc pattern?

I have recently learned the bloc design pattern in flutter development. I found it a bit similar to redux, which made me wonder:

  • Should MapEventToState function be pure like in redux? I saw some tutorials but no one mentioned if this function has to be pure or not.

  • If it is, does that mean we can implement undo operation using bloc pattern?

iOS determine which design patterns should i use based on the specification?

I have been doing IOS for several years and I have learned a lot but now I am interested how should i determine which design patterns should i use based on the specification? I mean MVC, MVVM, MVP, VIPER.

mercredi 25 décembre 2019

How to capture the essence of an object-oriented API "ideally"?

I'm confused as to how best to organize the fields/properties of an object. Specifically, the graphic sprite. These are some of the ways you can create the object:

{
  width: 10,
  height: 10,
  marginTop: 2,
  marginRight: 3,
  marginBottom: 4,
  marginLeft: 5,
  alpha: 0.5,
  red: 200,
  blue: 200,
  green: 200
  // ...
}

Or a million ways in between. Or this for example:

{
  size: {
    width: 10,
    height: 10
  },
  margin: {
    top: 2,
    right: 3,
    bottom: 4,
    left: 5
  },
  color: {
    red: 200,
    blue: 200,
    green: 200,
    alpha: 0.5
  }
}

One reason you might want to have these nested objects vs. the flat structure, is for type-checking. You would have clear objects with specific types which could be used elsewhere. But the reason for the flat structure is potentially performance in accessing the properties. But, you loose some of the conceptual relations which the nested object provides. So I am confused.

I am confused because in HTML you are essentially at this strucure:

{
  type: 'div',
  width: 10,
  height: 10,
  style: {
    margin: {
      top: 2,
      right: 3,
      bottom: 4,
      left: 5
    },
    color: 'rgba(200, 200, 200, 0.5)'
  }
}

Or perhaps the width and height are moved into the style object. But we just showed you can have a flat list of properties in the first example. And why the need for the nested style object. Why is "margin" (a pixel value for sizing) separated into style while width/height are delegated to the element? I'm not actually wondering why HTML did it this way, or if there are other ways of viewing it. I am just using this as an example to demonstrate that there are potentially many various ways of doing the same thing. Having nested or flat objects in various configurations and combinations.

I could imagine having a div be like this too:

{
  vector: [10, 10],
  marginVector: [2, 3, 4, 5],
  colorVector: [200, 200, 200, 0.5]
}

Needless to say, there's unlimited ways of organizing the code, with tradeoffs in every direction.

But what I want to know is if there is some notion of an "ideal representation" of an object. Is one way better than the other in the end? Specifically in terms of being generic.

A related example is how list iteration works. If you worry about implementation details of lists, like if it is using pointers vs. a dynamic language, or if you have complex data structure implementations of lists, etc., then you have to write a custom implementation of each list iteration algorithm.

iterateThisListType
iterateThatListType
...

This creates the problem of that you now don't have a "generic list iteration algorithm", like those you learn in school. Each list iteration algorithm can be totally different depending on architecture-specific/etc. implementation details.

This problem can be solved by using the concept of "iterators". Passing an iterator to the list algorithm allows you to have a very simple, single list iteration algorithm.

for (item in iterator) {
  ...
}

Not something that doesn't resemble list iteration at all (just making this up):

let something = *another;
while (true) {
  if (something->else > 10) {
    complicated....
  } else {
    complicated...
  }
}

That doesn't capture the "essence" of list iteration like the iterator does.

In the same light, I am wondering how do we capture the "essence" of a DOM node? It makes total sense on some level to group everything under style, or to make color all one object, etc. But at the same time, it also makes sense to have a top-level red and blue, etc. rather than nesting it in an object. So how can we do similar to the list-iteration example and capture the essence of the DOM node? (Or any other relatively complex structure)

It only gets more complicated when you start to think more in terms of graphics and effects. In graphics, like in sound production, you have all kinds of "effects" that are applied to the main object, our sprite in the graphics example. Some effects are "drop shadow", "blur", "reflection", "old film", and many others. Often times (in the graphics case) the effects are simply modifying existing lower-level properties on the object. So like blur might just modify the pixels attribute (where each pixel has a color of some sort). (Just making this up). Effects (or you could call them "filters"), could also be like regular properties it seems. Grayscale, for example, could be a top-level boolean:

{
  grayscale: true
}

Or it could be an effect:

{
  effects: [
    { type: 'grayscale' }
  ]
}

Well if you are doing this, then why not just make "width" and "height" into effects too! I mean, they are effects of the object as well, "giving them a size".

{
  effects: [
    { type: 'grayscale' },
    { type: 'width', value: 10 },
    { type: 'height', value: 10 }
  ]
}

Well now we are seeing that effects could then just be thought of as attributes in this simple case, and we can go back to the flat top-level attribute example. But some other effects seem to be layers on top of lower-level "effects/attributes", sort of forming a graph of processing on some "fundamental" attributes. So I don't know! I am wondering, is there an "ideal" approach to this? Is there a way to "capture the essence" of the graphics sprite? To make it so that every algorithm that used it could be written in one way (like the iterator)? So in one case we don't have top-level flat attributes, and another nested, and another effects, etc. Which one is right? How do we arrive at the ideal?

That was just for demonstration.

My question is about the DOM node. Not specifically the DOM node API and how it works or why it is like that, but about the philosophy behind it. How can we capture the essence of the DOM node attributes in this way?

Another quick example... It seems you could nest things pretty deeply if you wanted to.

{
  type: 'animal',
  body: {
    organs: {
      skin: {
        mesh3d: {
          texture: {
            color: '#ff0000'
          }
        }
      }
    }
  }
}

Rather than just doing:

{
  type: 'animal',
  color: '#ff0000'
}

You might have a really complicated mesh which is has a color on the texture. But then you want to just think about it as "the animal has a color". So I am confused on what to do.

Is It a Good Idea to Make Singleton's getInstance() Method Asynchronous by Making It Returns an Observable

I have a singleton that takes some time to instantiate. So I'm planning to make the getInstance() method asynchronous. Is writing the following code a common practice?

public class Singleton {

    private static volatile Singleton instance;

    public static Observable<Singleton> getInstance(Params params) {
        return Observable.fromCallable(() -> {
            synchronized (Singleton.class) {
                if (instance == null) {
                    instance = new Singleton(params);
                }
            }
            return instance;
        });
    }

    // ...
}

If not, why isn't it and what's the better solution?

Autofac Container Update and Mock dependencies

As part of integration testing I would like to wrap a registered class with Autofac so that I can track what happens on that class and redirect the operations to the original implementation.

In the following example, I create a first container which the real app container and then create a spyContainer.

The spyContainer should reuse the registeredInstance of NameRetriever as well as the WorldLogger but the WorldLogger should be injected a HelloLoggerSpy which itself should have been instanciated with the original IHelloLogger.

public class NameRetriever
{
    public string GetName()
    {
        return "linvi";
    }
}

public interface IHelloLogger
{
    void Hello();
}

public class HelloLogger : IHelloLogger
{
    private readonly NameRetriever _nameRetriever;

    public HelloLogger(NameRetriever nameRetriever)
    {
        _nameRetriever = nameRetriever;
    }

    public void Hello()
    {
        Console.WriteLine("Hello " + _nameRetriever.GetName());
    }
}

public class WorldLogger
{
    private readonly IHelloLogger _helloLogger;

    public WorldLogger(IHelloLogger helloLogger)
    {
        _helloLogger = helloLogger;
    }

    public void World()
    {
        _helloLogger.Hello();
        Console.WriteLine("Welcome in this world");
    }
}

public class HelloLoggerSpy : IHelloLogger
{
    private readonly IHelloLogger _sourceHelloLogger;
    public bool Called { get; private set; }

    public HelloLoggerSpy(IHelloLogger sourceHelloLogger)
    {
        _sourceHelloLogger = sourceHelloLogger;
    }

    public void Hello()
    {
        _sourceHelloLogger.Hello();
        Called = true;
    }
}

static void Main()
{
    var containerBuilder = new ContainerBuilder();
    // This is normal container creation
    containerBuilder.RegisterInstance(new NameRetriever());
    containerBuilder.RegisterType<HelloLogger>().As<IHelloLogger>();
    containerBuilder.RegisterType<WorldLogger>();

    var realContainer = containerBuilder.Build();

    // This is something that would be invoked during tests
    // to override the A behaviour
    containerBuilder.Register<IHelloLogger>(context =>
    {
        var realA = context.Resolve<IHelloLogger>(); // recursive as IA is not yet reusing the previous one
        var aSpy = new HelloLoggerSpy(realA);
        return aSpy;
    });

    var spyContainer = containerBuilder.Build(); // cannot build twice

    var b = spyContainer.Resolve<WorldLogger>();
    b.World(); // should have called  HelloLoggerSpy.Hello()
}

Anyone knows how to achieve this here and how will this be possible in the future?

Not able to view react native storybook stories on web

I am trying to use storybook for building design system library for react-native.
I have installed react-native through react-native init and configured storybook through npx -p @storybook/cli sb init
On running storybook server, i am able to view default stories on mobile device but web shows some thing like this attached image(showing loaders instead of stories)
web view of stories Since i want to share the design stories with others and viewable on site (final deploy)
What is the process for this?
I have gone through this below issues and tried configuring but does not help and i need some proper configuration even after future update of sb
one
two
three
Please advise on this situation.
Below version
"react": "16.9.0",
"react-native": "0.61.5",
"@storybook/addon-actions": "^5.2.8",
"@storybook/addon-links": "^5.2.8",
"@storybook/addons": "^5.2.8",
"@storybook/react-native": "^5.2.8",
"@storybook/react-native-server": "^5.2.8"
storybook version :- 5.2.8

Spring Boot Microservices

So I have been asked to design a microservice from scratch which in future will basically act as a source of data to be displayed on a website. Data would be like prices of a phone, size, camera, etc and within a phone it can be that there are 2-3 sizes available. And later on maybe new properties are added. I am thinking of using NoSQL. Could you guys recommend which would be better SQL or NoSQL. And any other design thing to keep in mind while designing a microservice. Thanks.

Where should repetitive logic be placed, in an Express.js app?

Let's say our API has some functionality, that might be consumed identically from different endpoints/controllers/routes. For example, we might wanna perform a login procedure, from different places. Perhaps both post(/login) and post(/register) will eventually log the user in.

So it would make sense, to put this procedure in a different module. For instance, i have this function, in a services/UserLogin class:

/**
     * 
     * @param {String} email 
     * @param {String} password 
     * @return {Promise<Object|false>} Resolves with a User object on success, false on failure.
     */
    static login(email, password) {
        return new Promise((resolve, reject) => {

            db.query('SELECT * FROM `user` WHERE email = ? AND password = ?', [email, password], async function (error, results, fields) {
                if (error) {
                    reject(error);
                }
                console.log(results.length)
                if (results.length > 0) {
                    // const id = results[0].id/
                    const user = results[0];

                    resolve(user);
                } else {
                    resolve(false);
                }

            });
        })

    }

So i named this class a "service". I'm wondering though, whether a service is the correct terminology here. I didn't manage to find a clear definition of this term, in the context of modern web applications. Is it possible, this UserLogin class should better be referred to as a "facade"?

I'm sure all of us have found ourselves wondering where to place such functions, and which terminology to use. Can someone shed some light on the issue?

mardi 24 décembre 2019

Implementing a design pattern in a Database project

I'm at my last year at the university and working on my final project with a group of friends. I'm responsible on implementing the database (using google firestore in java) and i'm trying to implement it using a design pattern. I found the adapter quiet useful, as I can create an interface called: GenericDB, which contains all the methods the database needs to use. A concrete class, let's call her FirestoreDB which implements it, and an Adapter, which also implements the GenericDB, and holds an Instance Of GenericDB as a variable, so I can choose at run time which db I will want to use (maybe in the future the db would change) Here is some basic code:

public interface GenericDB {

boolean add(String... args);

boolean delete(String... args);

boolean get(String... args);

boolean changePassword(String... args);

}

public class FirestoreDB implements GenericDB {
private final Firestore db;
public FirestoreDB() {
    FirestoreOptions firestoreOptions =
            FirestoreOptions.getDefaultInstance().toBuilder()
                    .setProjectId(Constants.PROJECT_ID)
                    .build();
    this.db = firestoreOptions.getService();
}

public boolean add(String... args) {
    return true;
}

public boolean delete(String... args) {
    return false;
}

public boolean get(String... args) {
    return false;
}

public boolean changePassword(String... args) {
    return false;
}

}

public class Adapter implements GenericDB {

private GenericDB db;
public Adapter(GenericDB db){
    this.db = db;
}
public boolean add(String... args) {
    return this.db.add(args);
}

public boolean delete(String... args) {
    return db.delete(args);
}

public boolean get(String... args) {
    return db.get(args);
}

public boolean changePassword(String... args) {
    return db.changePassword(args);
}

}

public class DatabaseCreator {
    public GenericDB getDB(DATABASE database) {
        switch (database) {
            case FIRESTORE:
                return new FirestoreDB();
            default:
                return null;
    }
}

}

    DatabaseCreator database = new DatabaseCreator();
    GenericDB db = database.getDB(EXTRA.DATABASE.FIRESTORE);
    Adapter ad = new Adapter(db);
    System.out.println(ad.add("1"));

Is this a good use of the adapter pattern?

2D matrix with Flyweight Design Pattern

I produce 2 square matrices A and B both of size 8192x8192 filled with complex numbers. I want to calculate the Discrete Fourier Transform of A+B. But it’s not as simple as that. I have access to multiple cores and I can do parallelize for this process. But I can't create 2 square matrices A and B both of size 8192x8192 because of java.lang.OutOfMemoryError. How can to handle with Flyweight design pattern and threads? How can i solve this solution? I couldn't find a way out to enlarge memory.

Design help for kind of a gird type view without pictures, see image & description attached

I need a design suggestion. So the screenshot below is my app (I've blanked out any sensitive information) but basically the blue text is a clickable "question" and the black text below is the "answer". This is basically a list so imagine more of these "questions" below each other.

They want to pop and im really not that good with html designs. They also don't want images.

Is there any code pen, fiddle, or template out there that would make this look better? I searched many websites like Freefrontend, bootsnipp, codepen, etc but all I have been finding are cards with images on it. Thank you for he help.

P.S. My UI stack is Angular 8

My App

How to use builder pattern when the resulting product requires different input

Let's say I want to create builders for ModernCar and FlintstonesCar, but they requires different materials for example

class ModernCarBuilder
{
    BuildEngine(Steel);
    BuildDoor(Steel);
    BuildTire(Rubber);
}

class FlintstonesCarBuilder
{
    BuildEngine(Wood);
    BuildDoor(Wood);
    BuildTire(Stone);
}

How can I create a common interface between the 2?

One way I can think of is like below, but it seems anti-pattern to me

class ModernCarBuilder
{
    ModernCarBuilder(Steel, Rubber); // constructor
    BuildEngine();
    BuildDoor();
    BuildTire();
}

class FlintstonesCarBuilder
{
    FlintstonesCarBuilder(Wood, Stone);
    BuildEngine();
    BuildDoor();
    BuildTire();
}

Splitting a string using multiple Lua patterns

So essentially I want to split a string using non fixed amount of lua patterns.

I'm currently working on a layouting system that involves parsing some sequences of characters such as :this: for example. For rendering the layout I have components that can be chunk of texts, images, or font modifiers for example. These components are the reason why I need to split/explode a string using multiple patterns. Because the patterns can match significantly different texts, and that lua patterns do not support "or" I've been stuck for a while on this problem.

I have tried messing with the string.gmatch function without success, any help is greatly appreciated.

Java: How to structure or pattern a class so that we can map composed Object during Runtime?

Consuming a rest api which is returning json which has some fixed format and other change per endpoint. I am using gson library which maps incoming json to java classes.

So I have following abstract Resource:

@Getter
@Setter
public class AbstractResource {
    @SerializedName("Meta")
    @Expose
    private List<Meta> meta = null;
    @SerializedName("Body")
    @Expose
    private List<AbstractBody> body = null;

AbstractBody has following contents:

public class AbstractBody {
    @SerializedName("Body")
    @Expose
    private Computer computer = null;
    @SerializedName("Links")
    @Expose
    private List<Link> links = null;

AbstractResource is common for all endpoints but In Abstract body, It returns Computer in one endpoint and in other endpoint it returns Licenses and other Endpoint returns Clusters. All comes in Body field of json.So everytime AbstractBody gets changes.

Currently i have to make both classes again and again in different packages. So in main things goes like.

 ComputerResource agreement = gson.fromJson(json, ComputerResource .class);

I want to make common package for both abstractresoource and abstractbody and at run time it should decide which class it should get into.

How can i modify above structure to do that?

lundi 23 décembre 2019

Is there a way to avoid passing all the parameters to a function [duplicate]

This question already has an answer here:

Suppose i have something like this:

createSettings(a = null, b = null, c = null, d = 50) {
}

I would really like to avoid calling my functions like this:

createSettings(null, null, null, 60)

I know one way is to accept an object instead of a multiple parameters:

createSettings(settings) {
}

And then i would call it in this way:

createSettings({d: 60})  

But the problem with this approach is that i lose the advantage of knowing what i should pass to the function!, meaning the function only says pass a setting, it doesn't say the setting can accept a, b, c, d !, which is kinda important because it helps me understand how to use a function, and my functions usually are complicated and knowing what to pass is really important as well.

So here is my question, is there a way to combine these two approaches and have a function:

createSettings(a = null, b = null, c = null, d = 50) {
}

And then called it like this?:

createSettings(...{d: 50})  

Any solution or suggestion is much appreciated.

Design of Python conditional imports

I'm new to conditional importing in Python, and am considering two approaches for my module design. I'd appreciate input on why I might want to go with one vs. the other (or if a better alternative exists).

The problem

I have a program that will need to call structurally identical but distinct modules under different conditions. These modules all have the same functions, inputs, outputs, etc., the only difference is in what they do within their functions. For example,

# module_A.py
def get_the_thing(input):
    # do the thing specific to module A
    return thing

# module_B.py
def get_the_thing(input):
    # do the thing specific to module B
    return thing

Option 1

Based on an input value, I would just conditionally import the appropriate module, in line with this answer.

if val == 'A':
    import module_A
if val == 'B':
    import module_B

Option 2

I use the input variable to generate the module name as a string, then I call the function from the correct module based on that string using this method. I believe this requires me to import all the modules first.

import module_A
import module_B

in_var = get_input() # Say my input variable is 'A', meaning use Module A
module_nm = 'module_' + in_var
function_nm = 'get_the_thing'

getattr(globals()[module_nm], function_nm)(my_args)

The idea is this would call module_A.get_the_thing() by generating the module and function names at runtime. This is a frivolous example for only one function call, but in my actual case I'd be working with a list of functions, just wanted to keep things simple.

Any thoughts on whether either design is better, or if something superior exists to these two? Would appreciate any reasons why. Of course, A is more concise and probably more intuitive, but wasn't sure this necessarily equated to good design or differences in performance.

Mediator pattern [UML]: how to connect to the rest of the code?

Context: I am programming an app (for trading/brokers, with Python or Java) and was asked to include the Mediator, Observer, Adapter and Facade design patterns. But I am having trouble understanding the Mediator pattern and designing it in UML. Mainly I have 2 questions. First the UML:

enter image description here

1) how to connect it (the Mediator block at the end) to the rest of the code? Is it correct for the GUI and AsyncActions (in other controllers package) to connect to the concret Mediator through an association or dependency? I have seen examples connecting trought the abstract Mediator but that don't make much sense to me.

There are some examples on the internet but they only have abstract ones, without full integration on a code-base, so I can't find one Mediator in the context of full code.

Examples from refactoring.guru and sourcemaking.com: enter image description here

And:

enter image description here

Both great examples but out of context of the rest of the code :(

2) My second questions is related with the 2 examples above: in the second one there is an abstract Component and it connects to the abstract Mediator. In the 1st example there is no connection bettween the abstract Mediator and the components (because there is no abstract component). The connection between the abstract Mediator and abstract components is mandatory? I don't understand it fully, why it is needed. In my UML I made it, but I can't see the utility in the code (because the concret mediator always tracks the mediated elements already from what I understood, so I don't understand the need for that connection).

Thank you very much in advance.

Good code design in C++ when objects interact with shared pointers holding data

I'm writing a C++ class say Class Foo that contains objects of Person class as well as a shared pointer of Data class, that holds a bunch of data for all Persons that can be accessed by personID.

I instantiate my Person objects as follows:

Person(uint32_t personID, std::shared_ptr<Data> data)

My Data class has a bunch of functions where I can access the Data by person ID.

The Data is set by class Foo and then I ensure that I call operations on that data after fresh data has been written to the Data class.

I'm pretty sure that this is bad design, but I'm not sure if there is a design pattern that turns this into good design.

Design pattern to avoud circular references

I want to build an emulator in rust and currently try to find a good design pattern for the following problem: My emulator right now aims to consists of two structs: The CPU and the RAM. Since multiple other components will follow, I dont want the CPU to reference the RAM directly. Instead, there is a Bus struct that will tie everything together:

struct CPU;

impl CPU {
    pub fn clock() {
        // read data from RAM, do stuff..
        unimplemented!();
    }
}

struct RAM;

impl RAM {
    pub fn read_byte(addr: u16) -> u8 { unimplemented!() }
}

struct Bus {
    pub cpu: CPU,
    pub ram: RAM,
}

impl Bus {
    fn clock() {
        self.cpu.clock();
    }
}

Now for the CPU to read some memory from the RAM, it needs to get a reference to the Bus. However, this would lead to a circular reference because the Bus already holds the CPU. Now imagine another component added: the GPU, which also wants to access features of the Bus. Now both (CPU and GPU) will require a mutable reference to the Bus which is also not possible because we can only have one.

I can't think of a good design pattern to resolve this in rust. In C++ I would instantiate the CPU, store it in the Bus, and then set a pointer to the Bus in the CPU. But in Rust, this does not work. What's a good design pattern to implement this in Rust?

dimanche 22 décembre 2019

Design pattern suggestion/implementation using java 8

I have to process requests in a series of steps.

For example: if request 1 comes, then I have to apply step1, step2, step3 and finally step4 which will persist the processed request into the database.

I thought of implementing Template design pattern, as it solves a similar problem.

When I started implementing the design pattern, I suddenly found it hard to implement, because of the logical complexity.

Let me explain the requirement:

Request -> Controller -> run()

The request will contain List.

Inside the run method, a series of operations will be fired.

 request.parallelStream()
.map(step1 -> executeStep1.apply(step1))
.map(step2 -> executeStep2.apply(step2, action))
.map(step3 -> executeStep3.apply(step3, rules))
.map(step4 -> executeStep4.apply(step4))
.collect(Collectors.toList());

Function<String, List<PersonDto>> executeStep1= person-> {
    return metaData.getMetaDataPerson(person);
};

BiFunction<List<PersonDto>, String, TransTemplateDTO> executeStep2= (metaData, action) -> {
    return temlate.createTemplate(metaData, action);

};



Now, as we can see I am passing the first element of request as an input to step1(), and then processing it and further passing the output as an input to subsequent steps.

Problem 1: Till this point, there was no problem. But suddenly the requirement changed and now I have to add rules logic in the step3 i.e. executeStep3.apply(step3).

step3 is taking 2 parameters, one is the output of step2 and second is List rules.
Step3 should apply all the rules and return the results equal to the rules.
For ex. If there are 3 rules, then step3 should return a List of 3 objects. Let's assume step3 received List of PersonDto with 10 items and List of rules of 3 items, then step3 should return 10*3 = 30 records. Also for each person rules will vary as per the command.
**Problem 2:** In step 3, I need the request object, so that I can make use of values. something like this:
**.map(step3 -> executeStep3.apply(step3, rules, request))**



Please help.

Differences between Sidecar and Ambassador and Adapter pattern

I confused between Multi-Container Pod Design patterns.
(sidecar, adapter, ambassador)

What I understand is :
Sidecar : container + container(share same resource and do other functions)
Adapter : container + adapter(for checking other container's status. e.g. monitoring)
Ambassador : container + proxy(to networking outside)

But, According to Istio -Installing the Sidecar, They introduce proxy as a sidecar pattern.

Adapter is container, and Proxy is container too.

So, My question is What is differences between Sidecar pattern and Adapter&Ambassador pattern?

Is the Sidecar pattern concept contain Adapter&Ambassador pattern?

C++ function design

I came across the following question in multiple occasions this year but I don't have a clear answer to it: say I want to design a function that accumulates or in general builds something. I would need to declare the initial accumulator value (or an empty object in general), the problem is that whether I should initialize this value or object inside the function arguments with default value or should I initialize this thing inside the function body?

An example would be the following piece of function that split an sequential container into N equal size pieces (precondition: the pieces are splittable). Is it a okay to write it in the following form

template <typename T, std::size_t N>
array<T, N> equal_split(const T& x, array<T, N> result = {}) {
  for (int i = 0; i < N; ++i)
    std::copy(begin(x) + i * size(x) / 3, begin(x) + (i + 1) * size(x) / 3, std::back_inserter(result[i]));
  return result;
}

or is it better to write it as

template <typename T, std::size_t N>
array<T, N> equal_split(const T& x) {
  array<T, N> result = {};
  for (int i = 0; i < N; ++i)
    std::copy(begin(x) + i * size(x) / 3, begin(x) + (i + 1) * size(x) / 3, std::back_inserter(result[i]));
  return result;
}

what is wrong with the logic that i am using?

theres a logic error , for the code i m trying to do ,

  *
 **
***
 **
  *

so this is the pattern , what my code is running is this

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

there seems to be logic error for the printing of stars , i just wanted to know what logic should i use. heres the code :-

#include<iostream>
using namespace std;
int main()
{

    /*

       *
      **
     ***
      **
       *

    */
    int i,rows;
    cout<<"Enter number of rows :"<<endl;
    cin>>rows;
    for(i = 1; i <= ((rows/2)+1) ; i++)
    {
        for(int j = (rows  - i); j >= 1; j--)
        {
            cout<<" ";
        }
        for(int k = 1; k <= i; k++)
        {
            cout<<"*";
        }
        cout<<endl;
    }
    for(i = ((rows/2)+1) ; i <= rows; i++)
    {
        for(int j = 1; j <= i; j++)
        {
            cout<<" ";
        }
        for(int k = (rows/2); k >= 1; k--)
        {
            cout<<"*";
        }
        cout<<endl;
    }


    return 0;
}

Knex/Objection relation "One to Many"

I have a product that has a category relationship. Each product can have multiple categories.
The problem: I need to design a relationship to include the case when a product has "All Categories" relation. I can add relations to all categories but if the category list will be updated "All categories" will be corrupted. product:

id | name
1  | product1
2  | product2
3  | product3

product_categories:

id | product_id | category_id
1  |  1         |   1
1  |  1         |   2
1  |  2         |   2
4  |  3         |   3

categories:

id | name
1  | one
2  | two
3  | three

Objection product relation mappings:

static relationMappings = {
    categories: {
      relation: Base.ManyToManyRelation,
      modelClass: path.resolve(__dirname, 'Category'),
      join: {
        from: 'products.id',
        through: {
          from: 'product_categories.product_id',
          to: 'product_categories.category_id',
        },
        to: 'categories.id',
      },
    },

samedi 21 décembre 2019

What class design will be change in case of promotion of roles in employee class hierarchy

I am building the simple object-oriented inheritance class for the employee management system, but I found one issue if some employee gets promotions then how we can handle such scenario.

/* This code represents the employee class hierarchy using inheritance relation */

#include <iostream>

using namespace std;
/* This is Employee Class */
class Employee
{

private:
    string empname;
    int empid;
    float salary;
public:
    int getSalary();

};
/* This is Manager Class  Derived from Employee */
class Manager: public Employee
{
       public:
            int getSalary(); // This will return salary of manager
};
/* This is Clerk Class  Derived from Employee */
class Clerk: public Employee
{
public:
    int getSalary(); // This will return salary of clerk
};
/* This is Accountant Class Derived from Employee */
class Accountant : public Employee
{
public:
    int getSalary(); // This will return salary of Accountant
};
/* This is Accountant Class Derived from Employee */
class Developer: public Employee
{
public:
    int getSalary(); // This will return salary of Developer
};
// Now if some employee gets a promotion or demotion how to handle such scenario
// Suppose someday Developer becomes Manager then how to manage those changes in c++ classes

Why does PHP consider a value of -1 to be true? Why isn't that "false" just like 0? [duplicate]

This question already has an answer here:

These both print "true":

$test = 1;

if ($test)
    echo 'true';
else
    echo 'false';

And:

$test = -1;

if ($test)
    echo 'true';
else
    echo 'false';

Only this one outputs "false":

$test = 0;

if ($test)
    echo 'true';
else
    echo 'false';

Why is "-1" considered "true"? If always forces me to do:

$test = -1;

if ($test > 0)
    echo 'true';
else
    echo 'false';

Which is very unintuitive to me, and uglier in many cases compared to if ($test).

Also, I'm pretty sure that this is some kind of standard behaviour which also happens in C and other languages, so I'm wondering in general about this design choice.

What's the best Object Oriented design for this job interview problem (Java)? [closed]

I failed a job interview because my solution to the given Java problem wasn't object oriented. I was able to solve the problem but it's more of a procedural design than Object oriented.

The problem was something like: Create a java program for a restaurant that will read a CSV file with the given format: Name|Cellphone Number|Number of Seats|Time Period|Status

Status could be: Confirmed, No Show, Cancelled Time Period is between 8:00 - 16:00 with every two hours duration. E.g. 8:00 - 10:00, 12:00 - 14:00, 14:00 - 16:00

The program should generate a report file based on the reservations with the following information: 1. Total number of seats with Confirmed reservation. 2. Total number of seats with No Show reservation. 3. Total number of seats with Cancelled reservation. 4. Time Period with highest Confirmed reservation 5. Time Period with highest No Show reservation. 6. Time Period with highest Cancelled reservation.

Know that I'm thinking of making a more OO solution, there are a lot of solutions I can think of. What do you guys think of the best design to solve this problem? No need to go through the code just the design to the solution would be a big help.

vendredi 20 décembre 2019

Implementation design pattern for html javascript on script tag

I'm fairly new to javascript and web dev. I'm making a simple template formatting web app. It's pretty much going to have forms where a user can fill in personal info such as name, age, gender, etc and using javascript I'm going to output a personal paragraph with the users submitted info. I'm using template literals on this and I know how to do it, I'm just confused as how to design the javascript code within the script tag, as in the design patterns? Is the standard similar to OOP with classes such as initializing the object and parsing the forms? Any advice and suggestions are really appreciated!

Here is some sudo code

//not real code, but you get the gist
class Template:
   var name = html.InnerElement
   var age = html.InnerElement
   var food = html.InnerElement

   const paragraph = () => {
   //template literal
    paragraph = 
   `Dear ${this.name},
    Happy Birthday! You're turning ${this.age today}.
    This is a big accomplishment, we must celebrate. Are you free next week for some ${this.food}?`

   return paragraph

   }

Allow authenticated users only to access any activity using Firebase Authentication in Android

I am developing an app by using Firebase Authentication. In my app all activities should be accessed by an authenticated user only. To do this I have this portion of code in all my activities:

firebaseAuthStateListener = new FirebaseAuth.AuthStateListener() {
            @Override
            public void onAuthStateChanged(@NonNull FirebaseAuth firebaseAuth) {
                // If user is logged out, bring him to LoginActivity
                final FirebaseUser user = FirebaseAuth.getInstance().getCurrentUser();
                if(user == null){
                    Intent intent = new Intent(ConnectionsActivity.this, LoginActivity.class);
                    startActivity(intent);
                    finish();
                }
            }
        };

I realize that this is not a good way to do it since my code is not DRY anymore and I'm having to copy paste this portion to all my activities. I am thinking of implementing a singleton class, but I'm not sure how it will work in Android framework. Is there a better way to make the user to be authenticated without repeating this code?