jeudi 31 décembre 2020

What does it mean by implementation of methods by a class using interface?

If we look at the definition of an "interface" it describes

Interfaces allow you to specify what methods a class should implement.

Now I came across the term "what methods a class should implement" using an interface. What does it mean?

A class also has some methods defined in it, then what is the meaning of "what methods a class should implement" using an interface?

OOP - Python - How to call function within class and avoid the error of missing arguments caused by self?

I am the beginner to the OOP practices.

I want to create a class which execute my query to database.

Here is my code:

class tools():
    def connect_db(self):
        cfg = ConfigParser()
        cfg.read('env.ini')
        sv_info = cfg['sv_info']

        db =  psycopg2.connect(
            host = db_connect['host'],
            user = db_connect['user'],
            password = db_connect['password'],
            database = db_connect['database'],
            port = db_connect['port']
        )
        return db


    def run_query(self, query):
        connection = self.connect_db
        do_the_query = connection.cursor()
        do_the_query.execute(query)
        do_the_query.fetchall()
        return do_the_query

    def find_locations(self,simple_query, latitude, longitude):
        return self.run_query(simple_query).format(latitude = latitude, longitude = longitude))

simple_query:

simple_query = """select * from a_function('{latitude}' , '{lontitude}')"""

My code to run it:

tools.find_locations(simple_query , '12.123456', '21.654321')

However, I keep receiving the error of:

TypeError: find_locations() missing 1 required positional argument: 'longitude'

According to my research, the argument self should not be taken to account (being ignored).

Anyway, would be nice if you guys can correct my code.

What is the name of the design pattern used by matterjs

the design seem to:

  • separate data into types
  • each type is associated with a class
  • methods are static, they do not get inherited by instanciated objects
  • instances of a class (type) can only be manipulated by the static methods provided by the class associated with their type

the classes purpose seem to only be namespacing the methods/procedures used by their instances

the approach seem procedural

const object = new TypeA();
TypeA.doSomething(object);
TypeA.doSomethingElse(object);

Does Bridge design pattern have only one abstract and interface Class in Java?

I am really difficult to think about abstract and interface Class in Java?

Here an example : We have 2 users which have the same and different action in School system Teacher : can add exercise and view the exercise Student : can view and submit exercise We have 2 different of user, different action and the same action. So how can we make it to one abstract class and interface?

Observer pattern - multiple reasons to observe a Subject

How could we implement the observer design pattern if a Subject is observed for multiple reasons? For example, a weather station is observed by a object that tracks the temperature and by another object that wants to be notified when the forecasts changes.

I would like to stay as close as possible to the UML diagram of the pattern presented in the gang of four's book.

enter image description here

Disabled attribute not working on pattern

I'm using matInput and pattern for numbers and dots only

 <mat-form-field>
      <mat-label>Table Number</mat-label>
      <input matInput placeholder="Enter Table Number"
      pattern="^\d+(\.\d+)*$"  [(ngModel)]="newStudy.tableNo">             
  </mat-form-field>
  
  
  <input type="button" class="body-popup-btn" value="Save" [disabled]="!pattern" (click)="onSubmitClick()" style="background: #1d5f93;">

But the button not getting enabled again even if the pattern is correct.

Need quick solution for this !!!!

Implementing delegation in decorator pattern

How can I delegate calls to the wrapped object - other than the functionality I changed:

class Base {
   function doSomething {}
   function doOtherSomething {}
   function doOtherSomething2 {}
}

class Decorator {
   constructor(wrapped) {
      this.wrapped = wrapped;
   }

   function doSomething { 
       console.log("doing more stuff");
       this.wrapped.doSomething()}
    }
}

How do I delegate the other functions to automatically be called on the Base class?

Vertical & Horizontal scroll interaction using Bootstrap?

How to add both vertical and horizontal scrolling in a web page using bootstrap and css. I wanted it to look something like below image.

Vertical & Horizontal scroll interaction

Recommended project structure for scalable multimodule project

I'm working on application that has to communicate like Restful client with Endpoint1, Endpoint2,...EndpointN calling methods let's say getAaa and getBbb. Every Endpoint has same methods and return the same context information but using own parameter list for calls and returning own response object structure. Till now I worked on prototype having only webapp project and 1 Endpoint like separate package in web project and it was quite simple to call methods and consume response or exceptions. Now I need to add Endpoint2, then expand further and I stuck to project design questions - how to have flexible structure and how to have unified response from all Endpoints calling methods in my ejb. Please point me to the right direction how to design Maven project structure and how to wire calls from ejb to different Endpoint using different parameter list and how to unify different response and catch exceptions to MyObject or MyExObject?

P.S.: I have full control of Endpoint Restful client code

enter image description here

Design pattern for Messaging system

In the College of Informatics Engineering, we want to build a system for the Diwan department to facilitate dealing with incoming and outgoing transactions and internal circulars so that we have the basic operations: Ward arrives at college. Send out of college. Circulating an internal memo within the college. It is required to draw a class diagram using the appropriate design model and with the help of the following: A.the content of this correspondence. B.Other related correspondence called "linked documents" what is design pattern for this question and Hw can i do it?

mercredi 30 décembre 2020

Architecture planning for a large scale REST API with front-end and database design

I've recently put together a domain & website monitoring tool, the product monitors website uptime, checks domain expiry and SSL expiry, the plan is to add features over time.

Project introduction

Right now, the project is split into a Laravel API, and a Nuxt JS front-end, completely decoupled, and interfacing with the Laravel API.

There's an account creation page on the front-end, and upon sign up, they're added to the users table, they can log in and manage their domains and monitors, a very typical flow of any web application.

Advice on scaling this...

At some point, I'd like to build some kind of management area to the front-end, and have it hosted on some kind of subdomain of my website...

But here's the the dilema...

  • Do I build the management feature as part of the same front-end project, keeping the front-end packaged up, because it would need to interface with the API and I just add some kind of "role" column to my database, and I can manually make myself an admin and then manually make other accounts admins, in which case an admin when they log in would see the management area?
  • Or, do I build out an entirely separate front-end project, without all the "website stuff" like landing pages and content pages.

Furthermore, is it okay to have one database with many tables for this? My users table right now is simply all of my customers, would it be okay to have admins and other management accounts listed in this table too?

How to decouple processing servers from database

I am building an application which takes in requests from users via web interface and then performs some processing and returns the result whenever available.

Here is a simple overview of the current architecture:

Architecture

The web application adds the request to multiple collections in MongoDB with the processed field set to False. Then there are processing servers for each collection, which poll their collections to check if there are any unprocessed entries. If yes, the servers then perform the processing which takes some time and also some cost (external API calls) and then save the result back in the database (output_data)and set processed to True.

Now, the problem I have:

  1. I am unable to scale up the processing servers for each module, because if I run two servers then there is a chance that the same entry is processed twice and would incur more cost for me.

  2. I also want to decouple the processing servers from the database, as I want to use the same processing servers with different databases too (ex: for different customers)

I do not know much about queues and pub/sub architecture. I think some sort of queue architecture would be useful in achieving the above, but not sure how to handle duplicate messages.

Please let me know what architecture would be useful in avoiding the problems above. I would prefer the solution to be cloud provider agnostic, but if really needed I would like to go with AWS.

Update: My current development stack is Python, Flask, MongoDB, Docker.

How can I maintain a list of objects that all inherit from base class, but access child methods after looking one up?

I am trying to figure out a way to maintain a list of objects that all inherit from a PlayerUpgradeData class and be able to access methods in their child classes.

In my game, given a string that corresponds with the property Name of one of these objects, I want to be able to look up the corresponding object either with LINQ or by dictionary key, and call a method Upgrade() in the child object. So, again, given a corresponding string I want to:

  • Lookup the object in a list, or dictionary.
  • Access the properties from PlayerUpgradeData.cs
  • Access the upgrade-specific Upgrade() method for the child class.

Here's a snippet of PlayerUpgradeData.cs:

public class PlayerUpgradeData : ScriptableObject
{
    public string Name;

    public string Description;
    
    public int Stacks;

    //More properties truncated...

    public virtual void Up()
    {
        Stacks++;
        UpdatePanel();
    }

    public virtual void Down()
    {
        Stacks--;
        UpdatePanel();
    }

    public void UpdatePanel()
    {
        //UI Update code that needs to be run each time this is upgraded.
    }

}

Here's a snippet of a given upgrade, PlayerUpgradeFanControl.cs:

public class PlayerUpgradeFanControl : PlayerUpgradeData
{
    //Data related to this upgrade

    public override void Up()
    {
        base.Up();

        //Logic for upgrading this item.
    }

    public override void Down()
    {
        base.Down();

        //Logic for downgrading this item
    }


}

And finally, an example of how I want to work this with data structure:

//Having a list of objects allows me to serialize it in my Unity Inspector
List<PlayerUpgradeData> UpgradeList = new List<PlayerUpgradeData>();

//Given a string, look up the object and run its upgrade logic.
UpgradeList.FirstOrDefault(x => x.Name == myString).SomehowRunChildUpgradeFunction();

A solution I've come up with is basically to create an interface property that all upgrades implement. Then, keep a list/dictionary of IPlayerUpgrade. Then when I look up, I'll certainly have access to the methods, but I no longer have access to the data within PlayerUpgradeData.

Hopefully, you see my issue... I'm storing a list of objects that all have their base class in common. But when I look up the corresponding object, I obviously can't cast it to a child object, so I have no way of accessing its upgrade logic.

I realize my data structure is inherently flawed, so I am hoping someone can explain to me a better way to structure this.

enter image description here

when refactoring using extract method, should you extract into a new class or into the current class?

I've been using extract method to make the flow of my code easier to understand, but now I have a load of these methods just dumped at the bottom of my class file. I've thought about creating individual classes for the methods or groups of them but I'm just worrying if that would be adding unnecessary complexity. Any tips for doing this elegantly would be appreciated.

Which Design Pattern is suitable for Hospital Management System in .net core 3.0?

I am developing web application for hospital, which have few modules like HR, Doctors, Patients, Medical Store, Admin. So which design pattern I can use for web app?

It is a good idea to have single design pattern throughout the app?

PS: I know design pattern is broad concept but a bit of guidance will helpful.

Separation of concerns for a API or Service accepting query filters

I always had this confusion which I couldn't reason more. Every time I think about it I go confused.

It is also hard to put in one line that's why the title is ambiguous.

All it is about where logic should go?

I have structured my backend architecture as below.

Router routes to controller and controller communicate with a Service Provider or Service.

i.e

For /zones router will route to ZoneController which loads off tasks to ZoneService .

Likewise, /banner-images router will route to BannerImageController which loads off tasks to BannerImageService

Fair enough!

Now, suppose I need to fetch banner images at a zone so banner-images?zone_id=2

Where the logic should go? Which controller? Which Service?

mardi 29 décembre 2020

How far should be the generalization of a class name and aggregation of similar behaviors?

The question may seem a little basic or entry level, but it is making me wonder a lot about how far should the generalization and function aggregation should go. Today I was reviewing code on my daily work and faced the following situation. Two classes named respectively EmailCancellationController and EmailConfirmationController were having their methods moved to a new class named UserAdministrationController. The last one end up with some methods and attributes which I think doesn't completely follows the SOLID principles.

Am I wrong on thinking that it doesn't fit the single responsibility principle? This class would need to handle Cancellation and Confirmation responsibilities. Or is it right, because it is handling only the user confirmation and cancellation, not another entity such as employee or student.

Apart from that, I think that someone else handling changes on this class could create a bad coupling while adding a method and using in both cancel and confirmation methods, or the class could grow more and more with more responsibilities such as EmailUpdateSomethingController.

My points here are:

  • Shouldn't class name be more specific than ?
  • Is there an approach on how classes should be named?
  • Should we generalize classes maintaining the SOLID principles?
  • When should we aggregate similar behaviors in a class?

Best way to combine different actions in python

Suppose there are n functions defined, each of which represents some action, and functions, whcich represent combinations of these actions:

def all_actions():
    action1()
    action2()
    action3()
    ...
    actionN()

def combination_of_1_and_2():
    action1()
    action2()

def combination_of_1_and_3():
    action1()
    action3()

def combination_of_1_2_and_3():
    action1()
    action2()
    action3()

.....

I don't want to write a separate function for each combination. Which is the best pattern in python to implement this functionality in more elegant way?

How do I make a complex UI layout with html/css grid?

I'm trying to make this complex layout shown below: enter image description here

Here's my code:

.item1 { grid-area: header; }
.item2 { grid-area: menu; }
.item3 { grid-area: main; }
.item4 { grid-area: posts; }

.grid-container {
  display: grid;
  grid-template-areas:
  'header header header header header header'
  'main main main main main main'
  'menu posts posts posts posts posts';
  grid-gap: 10px;
  background-color: #2196F3;
  padding: 10px;
}

.grid-container > div {
  background-color: rgba(255, 255, 255, 0.8);
  text-align: center;
  padding: 20px 0;
  font-size: 30px;
}
<div class="grid-container">
  <div class="item1">Navbar</div>
  <div class="item2">Small Picture</div>
  <div class="item3">Big Picture</div>  
  <div class="item4">Posts</div>
</div>

As you can see, I'm not even close. I'm not sure How I would get the small picture tab (shown in the picture) to be over the Tab Menu and the Big picture in my original layout design. Is this possible with CSS grid? If so, how would I do it?

If it's not possible or too difficult with CSS, what would you recommend I do instead?

Thanks in advance, I really appreciate any help I can get.

Passing injected dependencies to external functions

I have a NestJS application where I have some logic in regards to using AWS S3 buckets.

I have one module, which contains a service with a promiseWrapper function, to convert callback to async.

  private s3PromiseWrapper(action: string, params: S3ParamGetDTO): Promise<string> {
    console.log(params)
    return new Promise((resolve, reject) => {
      this.s3.getSignedUrl(
        action,
        {
          Bucket: params.bucketName,
          Key: params.key,
          Expires: params.expirationTimeSeconds,
        },
        (err: any, url: string) => {
          if (err) reject(err)
          resolve(url)
        }
      )
    })

No have another module, that needs to use the same function, so to not repeat the code I wanted to create a global function as a util function, but this requires me to pass the instance as an argument to the function.

  private s3PromiseWrapper(action: string, params: S3ParamGetDTO, s3Instance: S3): Promise<string> {
    console.log(params)
    return new Promise((resolve, reject) => {
      s3Instance.getSignedUrl(
        action,
        {
          Bucket: params.bucketName,
          Key: params.key,
          Expires: params.expirationTimeSeconds,
        },
        (err: any, url: string) => {
          if (err) reject(err)
          resolve(url)
        }
      )
    })

Is this anti-pattern in terms of dependency injection?

System design course for our "Ideas man" [closed]

I'm the lead developer at a new startup and we're having issues when it comes to feature requests in general and the Characterization of the product - it's a complete mess. My friend whom I consider as a genius have great ideas for our app but it's impossible to understand what he wants, he gives me drawings of "screens" and I need to figure out what is the user input, output, what the API and App should do when you press a button, how does the database looks like etc... in the end I find myself writing the code again and again, changing the database structure because there's something new there he didn't mentioned and just waisting precious time.

We're using Monday and I feel like he's not using it as intended, too much boards and complication. (I've worked with Monday before and I never got so frustrated) I'm looking for maybe a Udemy course or something that can teach him how to properly characterise, make a feature request, generally just bring him up to the standard I'm used to from other high-tech companies. just to clarify, I love designing the code structure, database and everything but the characterisations are just not enough for me to start with as a developer and I can't even estimate the time required for the developers to get things ready.

How to print this Pyramid filled with series of numbers upto the given input? [closed]

The output is attached in the link below, please go through it.

lundi 28 décembre 2020

Can a ActionListener class include other functionalities like driving the program?

I have 3 Java classes in my program that shows the user True or False questions using Swing GUI and gives the dialog if the answer is correct or not to the user. The questions and answers are in a single file.

1.a driver class TechTest that has the main method. In this method, it reads questions from file and populates the question and answer vector. public class TechTest {

static int numberOfQuestions = 0;
    
static int questionNum = 0;
static Vector  questionSet = new Vector();
static Vector answerSet = new Vector();
    
public static void main(String[] args) {
        // TODO Auto-generated method stub
        javax.swing.SwingUtilities.invokeLater(new Runnable() {
            public void run() {
                String questionAnsFileName = readQuestionAnswerFileName();
                
                
                parseQuestionAnswerFile(questionAnsFileName);
                if (!noFile) {
                    if (!questionSet.isEmpty()) { 
                        View view = new View();
                        System.out.println("run: " + "questionNum " + questionNum); 
                        view.display((String) questionSet.get((questionNum)));
                    

                   }
                   else
                      showErrorDialog("questions are missing. Check the javaQuestionAns.txt file");
                
                   }
            }
        });

    }
} 
  1. The second class is View public class View { /* Shows the Swing GUI. Registers events to event listener class TestEngine */ ..... .....

    TestEngine testEngine = new TestEngine(this);

    buttonNext.addActionListener(testEngine); answerList.addActionListener(testEngine);

}

  1. Third class is TestEngine.

public class TestEngine implements ActionListener { /* * Check the source of the event, and handle the event accordingly * Possible sources are the answerList Combo box or the Next Button */ @Override public void actionPerformed(ActionEvent e) {

    if (e.getSource() == View.answerList) {
      ...
    }
    if (e.getSource() == View.buttonNext ) {
        ...
    }
 

}

The Test Engine class needs many static variables of the TechTest class. Many static variables are defined in the TechTest class. There are references to these static variables within Test Engine class.

Is this a good design? Or is it better to combine the functionalities of the driver TechTest class into the Test Engine class itself? In this new design, the Test Engine will have the main method driving the program, the actionPerformed method(event handlers) and other application logic that determines the correctness of answers and display of dialog.

Is it OK to combine the Action Listener function with the driver functionality and other application logic?

Authentication with multiple services: Only one REST-call or multiple calls?

I have a question about using JWT in a webapp: An auth-service provides a JWT which gives me the information whether the user is known or not. Then another service will be called to check the user roles based on the JWT. It appends an API-key, the user roles and will call the real API. Now my question: What ist the best auth flow?

  1. Should the webapp do only one call: Calling the JWT-service which proxies the request to the auth service and this service proxies it to the real backend and all the way back?
  2. Or should it look like this: Webapp calls JWT-service. The JWT-service returns the JWT to the webapp and then the webapp will call the auth-service in a second request.

Unfortunately the JWT-service cannot check the userroles :(

Are there any advantages/disadvantages or BestPatterns?

I hope that is not too confusing:D

Best Lukas

dimanche 27 décembre 2020

Could anyone help explain Model Driven Development in few simple words?

I have been researching Model-Driven Development(Architect), however, after reading a lot of papers, I still cannot have a clear understanding of it. It seems so abstract. Ex:

  • What is its main idea?
  • What is exact the model (it means the diagram, right?).
  • MDD means we will design diagrams, then using the tool to convert to code???
  • How can I apply it to my system, what is the step to apply... ...

Anyone please help give me some explanations?

Thanks a lot.

What are the advantages and disadvantages of proxy design pattern?

What are the advantages and disadvantages of proxy design pattern?

How to use it in real scenarios?

What are the assumptions behind it?

Java Object Fields Value Depend on Other Fields - Best Practice Patterns?

I have a simple java object

 public class Order {
  private int quantity;
  private long price;
  private long totalPrice;
 }

I will only be storing quantity and price, and totalPrice field will be generated based on quantity * price.

Now i have method called populateTotalPrice() in Order class. But it seems that i am putting a logic inside an entity class which may be an anti pattern?

My other option, is to use a helper static method.

What is really the best practice for this type of behaviour?

What are recommended design pattern(s) to add functionality to a base class depending on how it's derived

I'm looking for feedback/recommendations/best-practices to accomplish the following architecture in the most elegant, expressive, and extensible fashion. I've tried a few approaches, including multiple inheritance and composition OOP as well as a "flat" classless C-like approach, but all require boilerplate and repetitive code which seems "smelly" to me. I'm convinced there should be a better way. What other design patterns should I consider? Ways to use templates and static typing? Other ways to achieve the necessary polymorphism?

Problem Statement:

"Device" objects can have different "Capabilities" which are supported depending on the concrete type of the device. Each type of concrete device's supported capabilities is known at compile time, so there is no need to assign different capabilities at run-time. Capabilities don't need to interact with other capabilities that any given device supports.

ConcreteDevices (A,B, & C in example below) inherit the BaseDevice class. BaseDevice contains functionality common to all devices. BaseDevice is also the interface class on which a client will invoke a DoCapability_N_() method, possibly without knowing the exact type of ConcreteDevice with which they are interacting (e.g. via a collection of devices stored in a std::list<BaseDevice*>). Run-time polymorphism required here.

If the ConcreteDevice has been "assigned" the N capability, the DoCapability_N_() method should be delegated to the associated ImplCapability_N_ class, otherwise the fallback DoCapability_N_() method from BaseDevice should be called, indicating that capability hasn't been assigned to this device.

The Capability implementations, ImplCapability (1,2, & 3 in the example below), inherit common functionality from the BaseCapability class. These implementations also need access to the BaseDevice's public members in order to perform their work.

Here is some basic "starter" code which isn't fully functional but expresses the basic class design. Comments indicate the missing pieces and possible approaches:

class BaseCapability {
public:
    void* mCapabilityHandle{ nullptr };
    int mBaseCapabilityData{ 0 };
};

class ImplCapability1 : public BaseCapability {
public:
    // QUESTION: how to make sure this method gets called if invoked via a device which has been assigned this capability?
    // QUESTION: how to make sure this method can access public members of BaseDevice? (dependency injection messy; not shown)
    void DoCapability1() { cout << "Doing Capability1!\n"; }

    ImplCapability1() { cout << "Capability1 assigned.\n"; }
};

class ImplCapability2 : public BaseCapability {
public:
    void DoCapability2() { cout << "Doing Capability2!\n"; }

    ImplCapability2() { cout << "Capability2 assigned.\n"; }
};

class ImplCapability3 : public BaseCapability {
public:
    void DoCapability3() { cout << "Doing Capability3!\n"; }

    ImplCapability3() { cout << "Capability3 assigned.\n"; }
};

class BaseDevice {
public:
    std::unique_ptr<ImplCapability1> Cap1Ptr{ nullptr };    // use for composition, construct in ConcreteDevice as necessary
    std::unique_ptr<ImplCapability2> Cap2Ptr{ nullptr };    // use for composition
    std::unique_ptr<ImplCapability3> Cap3Ptr{ nullptr };    // use for composition

    void* mDeviceHandle;
    int mBaseDeviceData{ 42 };

    // default functions to invoke if no capabilities have been assigned to the ConcreteDevice 
    void DoCapability1() { cout << "Capability not assigned.\n"; }
    void DoCapability2() { cout << "Capability not assigned.\n"; }
    void DoCapability3() { cout << "Capability not assigned.\n"; }
};

// QUESTION:  how to "assign" supported capabilities here to each type of concrete devices?...

class ConcreteDeviceA : public BaseDevice, public ImplCapability1, public ImplCapability3 {  // MULTIPLE INHERITANCE?
public:
    // needs Capability1, Capability3
    ConcreteDeviceA() { cout << "DeviceA constructed.\n\n"; };
};

class ConcreteDeviceB : public BaseDevice {
public:
    // needs Capability2
    ConcreteDeviceB() { 
        Cap2Ptr = std::make_unique<ImplCapability2>();      // COMPOSITION?
        cout << "DeviceB constructed.\n\n"; };
};

class ConcreteDeviceC : public BaseDevice {
public:
    // needs Capability1, Capability2, Capability3
    // .. some other method?
    ConcreteDeviceC() { cout << "DeviceC constructed.\n\n"; };
};

And desired use:

int main()
{
    // create devices
    std::unique_ptr<BaseDevice> DeviceA = std::make_unique<ConcreteDeviceA>();      // has capabilities: 1, 3
    std::unique_ptr<BaseDevice> DeviceB = std::make_unique<ConcreteDeviceB>();      // has capabilities: 1
    std::unique_ptr<BaseDevice> DeviceC = std::make_unique<ConcreteDeviceC>();      // has capabilities: 1, 2, 3
    std::cout << '\n';

    // test capability assignments by dereferencing pointer to base
    DeviceA->DoCapability1();           // should do Capability 1
    DeviceA->DoCapability2();           // should indicate not assigned
    DeviceA->DoCapability3();           // should do Capability 3
    std::cout << '\n';
    DeviceB->DoCapability1();           // should indicate not assigned
    DeviceB->DoCapability2();           // should do Capability 2
    DeviceB->DoCapability3();           // should indicate not assigned
    std::cout << '\n';
    DeviceC->DoCapability1();           // should do Capability 1
    DeviceC->DoCapability2();           // should do Capability 2
    DeviceC->DoCapability3();           // should do Capability 3
}

As for why I have a feeling that neither Multiple Inheritance nor Composition are the most elegant approach:

Composition:

  • having to write pass-thru functions which "wrap" the ImplCapability's DoCapability_N_() method within the BaseDevice's DoCapability_N_() method
  • having to explicitly check if a Capability has been assigned via testing if(CapNPtr != nullptr)...
  • passing of injected dependencies in constructors and correspondingly longer initialization lists
  • uses run-time polymorphism when compile-time should suffice for the ConcreteDevice to ImplCapability relationships

Multiple inheritance:

  • injected dependencies with lots of parent class constructors and correspondingly longer initialization lists
  • less extensible: what if in the future we wanted to give DeviceX two different Capability1's (with slightly different parameterization)? We would have to create a new "ImplCapability4" and copy a bunch of code.
  • uses run-time polymorphism when compile-time should suffice for the ConcreteDevice to ImplCapability relationships

To summarize:

What is the recommended strategy or design pattern to achieve this "assignment" of capabilities to devices? -> Multiple inheritance? Composition? Template-based approaches (mixins, CRTP), Other?

What is the recommended strategy to achieve the polymorphism that automatically selects the ImplCapability's DoCapability_N_() method if that capability has been assigned to the device?
-> Virtual functions & overriding? Templates? Overloading? Other?

What is the recommended strategy to insure the ImplCapability classes can access the BaseDevice members? -> Inheritance? Dependency injection? Other?

Creating objects with a type determined at runtime

I am writing a program that needs to save and load various objects from a file. The files are saved as XML, and I have therefore decided to create an interface called "XMLConvertible" for all the classes that can be converted to XML. When I read the file however, I need to create objects of different types depending on the contents of the XML file.

for example:

<Component></Component>
<Module></Module>

needs to first create an object of type Component, then an object of type Module.

the cleanest way I've encountered so far is to have a Factory with a static list of Builders for all the different classes that can be read from the XML file. Like this (some information has been left out for brevity):

public interface XMLConvertible {
    public void write();
    public void read();
}

public abstract class Factory {
    private static Map<String, Builder> xmlConvertibles = new HashMap<>();

    public static void addXmlConvertible(String key, XMLConvertible value) {
        xmlConvertibles.put(key, value);
    }

    public static XMLConvertible getXmlConvertible(String key) {
        return xmlConvertibles.get(key);
    }
}

public class Component implements XMLConvertible {
    ...
}

public class ComponentBuilder extends Builder {
    static {
        Factory.addXmlConvertible("Component", new ComponentBuilder);
    }

    public Component build() {...}
}

public class Module implements XMLConvertible {
    ...
}

public class ModuleBuilder extends Builder {
    static {
        Factory.addXmlConvertible("Component", new ComponentBuilder);
    }

    public Module build() {...}
}

the problem with this is that I have to create 2 classes for every new XMLConvertible class I add, an actual class and a builder. I would like to either have a way of forcing myself to add a builder so I don't forget, or ideally find a more clean way to implement something like this.

sorry for the long post, I tried to shorten it a bit. Hopefully it is still easy to understand what the problem is.

Keep getting the id from items in a list which is in a class

class EditorState:
    def __init__(self, content):
        self.content = content

class Editor:
    def __init__(self):
        self.content = ""

    def __str__(self):
        return f'{self.content}'

    def setContent(self, value):
        self.content = value

    def createContent(self):
        return EditorState(self.content)

    def restore(self, new_value):
        self.content = new_value

    def getcontent(self):
        return self.content

class History:
    def __init__(self):
        self.history = []

    def __repr__(self):
        return self.history

    def push(self, value):
        self.history.append(value)

    def remove(self):
        my_list = self.history
        my_list.pop()

        last_index = my_list[-1]
        return last_index

    def getvalue(self):
        my_list = self.history
        return self.history

I've learned how to use the Memento pattern in java, and I wanted to try the pattern with python. I does work but the problem is that when I'm returning the last item from my list in the history class, so it keeps showing me its id not the value. It's the same when I print the list using the getvalue() method.

I've tried to use the magic methods sush as str or repr but it did'nt work, also I've tried to set the attribut to a variable but no results.

Who should allocate channels, the caller of the callee?

I am trying to design a simple home automation program with Go. My bulbs return streams of messages when their state changes. This can be handled with a callback or may be better with channels in Go.

With callbacks, it is clear that the caller of the light bulb API implements a particular function signature and passes the function to the library. When a bulb changes state or communication error occurs the function will be called. The library will be allocating a done function to be called when the client is no longer interested in updates. For example

 type DeviceUpdate = func(Device, error)
 type Done = func()

 func (client *Client) ObserveDevice(deviceID int, deviceUpdate DeviceUpdate) (Done, error) {

Channels in my case seem to present a nicer abstraction as they can be merged easily, buffering can be added, middleware can easily be woven in etc. I struggle a bit with channel representation of the above declaration. What is the correct convention in Go for this case i.e. channel of data, channel of errors and done/close operation on the whole system.

I am thinking that channels should be allocated by caller similar to functions. This way the caller can instantiate the channel properly and wire middleware before activating the whole set up.

func (client *Client) ObserveDevice(deviceID int, data chan Device, done chan struct{}, err chan error) error {

On the opposite side having the light bulb library allocate channels seems much simpler for the consumer code - you just call a function and no need to allocate 3 channels. As well Go time module seems to go this route bravely e.g. https://golang.org/pkg/time/#After

In my case having the library allocate channels will result in signature like the following

func (client *Client) ObserveDevice(deviceID int) (data chan Device, done chan struct{}, err chan error) {

So what is Go standard practice for channel allocation? Is it caller vs callee or producer vs consumer?

Is the usual practice to have 3 channels when funneling updates from a network stream - data, err and done?

I did some digging in write-ups and videos about channels and concurrency with Go and could not find (perhaps due to laziness) documented best practice. I assume the caller allocating the channels is implied in the examples. See https://gobyexample.com/closing-channels, https://blog.golang.org/pipelines

Goroutine creation design pattern

When writing logic that should be run as part of a goroutine, should the method itself create the goroutine or the should that be the responsibility of the calling function? For example, which of the below would be preferable?

Creating the go routine within the method

func longrunning() chan Result {
    c := make(chan Result)
    go func() {
        // Business Logic Here
        c <- Result{}
    }()
    return c
}

func main() {
    c := longrunning()
    
    // Do additional tasks
    
    <-c
}

Leaving it up to the caller

func longrunning() Result {
    // Business Logic Here
    return Result{}
}

func main() {
    c := make(chan Result)

    go func() {
        c <- longrunning()
    }()
    
    // Do additional tasks

    <-c
}

How to print 4 pattern in horizontal way? [closed]

Photo I'm new in learning programming and I just learned about looping.This is my code but it keep print vertically. How to make the output just like in the photo? I try to display the output in horizontal way I have tried \t but it did not came out as expected. I think I need to add something but I don't know what.

package question3;
import java.util.Scanner;
public class Question3 {
public static void main(String[] args) {
int i,j,num,k;  
Scanner sc=new Scanner(System.in);
System.out.println("Enter an integer number line");
int line=sc.nextInt();
System.out.println("Pattern I");
for(i=0; i<line; i++)
{
   num=1; 
   for(j=0; j<=i; j++) {
   System.out.print(num);
   num++; }
   System.out.println() }
   System.out.println("Pattern II");
   for(i=line; i>0; i--){
   num=1;
   for(j=0; j<i; j++)
   {
   System.out.print(num);
   num++;
    }
   System.out.println();
   }
  System.out.println("Pattern III");
  for(i=0; i<line; i++){
   for(k=line-1;k>i;k--) {
     System.out.print(" ");}
  num=i+1;
    for(j=0; j<=i; j++){
     System.out.print(num);
     num--;}
     System.out.println();}
   System.out.println("Pattern IV");
  for(i=line; i>0; i--){
 num=1;
  for(k=line;k>i;k--)
   {
  System.out.print(" ");
 }
  for(j=0; j<i; j++)
  {
  System.out.print(num);
   num++;
  }

   System.out.println();}}}  

samedi 26 décembre 2020

Design pattern to reduce cyclomatic complexity


I have to send invoices to cutomers through the related customer's API.
Each customer chooses how to be contacted (email, fax, sms...).
My problem is that each time I add a new "contact type" I increase the cyclomatic complexity of my script.
Here is my code :
<?php

interface ExternalApi
{
    public function sendByEmail();
    public function sendByFax();
    public function sendBySMS();
    // more sending modes ...
}

class Api1 implements ExternalApi
{   
    public function sendByEmail()
    {
        echo __CLASS__." sending email<br>\n";
    }
    
    public function sendByFax()
    {
        echo __CLASS__." sending fax<br>\n";
    }
    
    public function sendBySMS()
    {
        echo __CLASS__." sending SMS<br>\n";
    }
}

class Customer
{
    public const EMAIL = 'email';
    public const FAX = 'fax';
    public const SMS = 'sms';
    public const EMAIL_AND_FAX = 'email_and_fax';
    public const PHONE = 'phone';
    public const PLANE = 'plane';
    public const BOAT = 'boat';
    public const SATELITE = 'satelite';
    public const CAB = 'cab';
    // more contact types...
    
    public ?string $contactType;
}

class Invoice
{
    public Customer $customer;
    
    public function __construct(Customer $customer)
    {
        $this->customer = $customer;
    }
}

class InvoiceSender
{
    private ExternalApi $api;

    public function __construct(ExternalApi $api)
    {
        $this->api = $api;
    }
    
    public function send(Invoice $invoice)
    {
        switch($invoice->customer->contactType) {
            case Customer::EMAIL :
                $this->api->sendByEmail();
                break;
            case Customer::FAX :
                $this->api->sendByFax();
                break;
            case Customer::SMS :
                $this->api->sendBySMS();
                break;
            case Customer::EMAIL_AND_FAX:
                $this->api->sendByEmail();
                $this->api->sendByFax();
                break;
            // more cases ...
        }
    }
}

$customer = new Customer();
$customer->contactType = Customer::EMAIL_AND_FAX;
$invoice = new Invoice($customer);
$api = new Api1();
$invoiceSender = new InvoiceSender($api);
$invoiceSender->send($invoice);

As you can see the switch statement of InvoiceSender::send is increased each time I add a new "contact type".
Do you know which design pattern could solve this problem ?

Need to get a uml diagram for the Bird and ToyDuck interface using adapter pattern

** I am confused as to how to design the whole diagram explaining the client, target, adapter and adaptee.

Suppose you have a Bird class with fly() , and makeSound()methods. And also a ToyDuck class with squeak() method. Let’s assume that you are short on ToyDuck objects and you would like to use Bird objects in their place. Birds have some similar functionality but implement a different interface, so we can’t use them directly. So we will use adapter pattern.

Need help asap! here is my code:**

// Java implementation of Adapter pattern 

interface Bird 
{ 
    // birds implement Bird interface that allows 
    // them to fly and make sounds adaptee interface 
    public void fly(); 
    public void makeSound(); 
} 

class Sparrow implements Bird 
{ 
    // a concrete implementation of bird 
    public void fly() 
    { 
        System.out.println("Flying"); 
    } 
    public void makeSound() 
    { 
        System.out.println("Chirp Chirp"); 
    } 
} 

interface ToyDuck 
{ 
    // target interface 
    // toyducks dont fly they just make 
    // squeaking sound 
    public void squeak(); 
} 

class PlasticToyDuck implements ToyDuck 
{ 
    public void squeak() 
    { 
        System.out.println("Squeak"); 
    } 
} 

class BirdAdapter implements ToyDuck 
{ 
    // You need to implement the interface your 
    // client expects to use. 
    Bird bird; 
    public BirdAdapter(Bird bird) 
    { 
        // we need reference to the object we 
        // are adapting 
        this.bird = bird; 
    } 

    public void squeak() 
    { 
        // translate the methods appropriately 
        bird.makeSound(); 
    } 
} 

class Main 
{ 
    public static void main(String args[]) 
    { 
        Sparrow sparrow = new Sparrow(); 
        ToyDuck toyDuck = new PlasticToyDuck(); 

        // Wrap a bird in a birdAdapter so that it 
        // behaves like toy duck 
        ToyDuck birdAdapter = new BirdAdapter(sparrow); 

        System.out.println("Sparrow..."); 
        sparrow.fly(); 
        sparrow.makeSound(); 

        System.out.println("ToyDuck..."); 
        toyDuck.squeak(); 

        // toy duck behaving like a bird 
        System.out.println("BirdAdapter..."); 
        birdAdapter.squeak(); 
    } 
} 

Share information between commands with Command design pattern [closed]

I'm building a little project in c++ that uses some commands, so I used a commands design pattern. I have a design problem, I have commands that need some information that other commands create. For Example, the first command is uploading a file. and the second command needs to do work on the file that uploaded in the first command. First, second, and all rest commands inherited from command interface that has the "execute" method. what design pattern should I use to share information between the commands? and please can you give me a little example?

Possible flaw in Iterator pattern?

Considering the following UML diagram: Iterator Pattern Image

If we add a method to addFriend() in Facebook class to add a new friend to a profile, the new friend doesn't reflect in the Facebook Iterator, and even if have a polling method in Facebook Iterator to check if any new friend has been added it would be a question of frequency and there can always be a corner case where the newly added friend didn't reflect.

I guess we can use Observer Pattern here but that would, in a way, imply that Iterator Pattern must always be used in conjunction with Observer Pattern.

I wanted to know if anyone thinks this is a legit issue, and how someone would go about tackling this

How to change color of Material Design Tab item when selected

I've got simple tabLayout:

 <com.google.android.material.tabs.TabLayout

        android:id="@+id/tab_layout"
        android:layout_width="match_parent"
        android:layout_height="wrap_content"
        app:tabMode="scrollable">

        <com.google.android.material.tabs.TabItem
            android:layout_width="wrap_content"
            android:layout_height="wrap_content"
            android:text="@string/home" />
        <com.google.android.material.tabs.TabItem
            android:layout_width="wrap_content"
            android:layout_height="wrap_content"
            android:text="@string/all_charts" />
        <com.google.android.material.tabs.TabItem
            android:layout_width="wrap_content"
            android:layout_height="wrap_content"
            android:text="@string/low_score" />
        <com.google.android.material.tabs.TabItem
            android:layout_width="wrap_content"
            android:layout_height="wrap_content"
            android:text="@string/big_score" />

When user select particular tab, it's color's changing, how can I change it? I've tried by implementing my own style like this:

   <style name="Widget.MyApp.TabLayout" parent="Widget.MaterialComponents.TabLayout">
    <item name="background">@color/white</item>
    <item name="textAppearanceCaption">@color/dark</item>
</style>

And then in main TabLayout:

 <com.google.android.material.tabs.TabLayout

        android:id="@+id/tab_layout"
        android:layout_width="match_parent"
        android:layout_height="wrap_content"
        style="@style/Widget.MaterialComponents.TabLayout"
        app:tabMode="scrollable">

This solutions is not working.

vendredi 25 décembre 2020

How to make objects interact each other in this example with the proper way?

I have an awkward question, a question from an amateur at designing reliable and flexible softwares. Let's say that i have an interface to specify Movable behaviour, named by IMovable as:

interface IMovable
{
    void MoveToDirection(string direction);
}

And a concrete class that movable two directions and implements the interface IMovable:

class TwoDirectionMovable : IMovable
{
    IMovement Forward;
    IMovement Backward;
    public void MoveToDirection(string direction)
    {
        if (direction == "Forward")
            Forward.PerformMovement();
        else if (direction == "Backward")
            Backward.PerformMovement();
        else
            throw new Exception("Can't move that direction!");
    }

    public TwoDirectionMovable(IMovement forward, IMovement backward)
    {
        this.Forward = forward;
        this.Backward = backward;
    }
}

As you can see, movements are specified by IMovement objects. IMovement interface and its abstract class, Movement Base, are like this:

interface IMovement
{
    bool Reached { get; set; }
    void PerformMovement();
}

abstract class MovementBase : IMovement
{
    public bool Reached { get; set; }

    public void PerformMovement()
    {
        if (!Reached)
        {
            PerformMovementImp();
        }
    }

    protected abstract void PerformMovementImp();
}

Assume there is a FastSlowMovement sub class:

class FastSlowMovement : MovementBase
{
    IMovement FastMovement;
    IMovement SlowMovement;
    public bool SlowDown { get; set; }

    protected override void PerformMovementImp()
    {
        if (SlowDown)
            SlowMovement.PerformMovement();
        else
            FastMovement.PerformMovement();
    }

    public FastSlowMovement(IMovement fastMovement, IMovement slowMovement)
    {
        this.FastMovement = fastMovement;
        this.SlowMovement = slowMovement;
    }
}

Somewhere in program, the SlowDown property becomes True while performing fast movement and object performs slow movement. Going back to TwoDirectionMovable, lets say that i instantiate object like this:

IMovable movable = new TwoDirectionMovable(new FastSlowMovement(movement1, movement2), new FastSlowMovement(movement3, movement4));

In this scenario, my movable object can go forward or backward and both movement is performed fast and slow. But the thing is, while moving forward direction, backward direction's SlowDown property must be false and same goes for moving backward direction, it sets forward direction's SlowDown property as false. And in future, TwoDirectionMovable may have another type of movement that doesn't have SlowDown property or may have one with SlowDown and one without it.

I thought that i can fire an event when one of those objects perform movement, subscribers can get their job done. But i couldn't figure where to do so. And i don't want to create objects for each possibility, for example: a composite object or a state machine with one FastSlowMovement and one with another type of movement etc.

Should i make objects subscribe events at the creational side of software? I mean, i will get that objects from a builder or factory. But i'm not sure if i have the knowledge to do so in the proper way.

I know it is a long, amateur-ish and an awkward question. Maybe the whole implementation is wrong, maybe i have to re-design with the proper way. I don't know, i am not sure. But i would be very appreciated if you'd answer.

Thanks to everyone, have a nice day/night.

jeudi 24 décembre 2020

Dynamic global variables in java

I am pretty new to java and while working on an FXML project I want an instance of class to be shared by multiple classes. That instance cannot be Static because i have to load that instance from a file and then call it in multiple classes. Static just gets unloaded when the scope changes. Any help on what should be done? Or is there a way arround other than static?

Separate logic from data in c#

In the first place let me explain what is in my mind :

A few days ago while I was reading an article regarding Builder design pattern , The point that drew my attention was the idea of separating logic from data that Builder pattern founded based on, Now its kind of confusing how to answer following questions:

1.What are exactly Logic and Data and how to differentiate between the two?

For example, you could consider my below pieces of codes that validate some specific classes:

  //Part 1
   var FailureAttr = step.GetType().GetCustomAttributes(typeof(KeepOperationInFailureAttribute), true).FirstOrDefault() as KeepOperationInFailureAttribute;
            var InitialStepAttr = step.GetType().GetCustomAttributes(typeof(InitialStepAttribute), true).FirstOrDefault() as InitialStepAttribute;
            var stepInfo = new StepInfoProps();
                stepInfo = new StepInfoProps()
                {
                    IsInitialStep = InitialStepAttr != null,
                    KeepOperationInFailure = FailureAttr != null
                };

            StepInfoList.Add(stepInfo);

        }
        var noInitialStep = !StepInfoList.Any(x => x.IsInitialStep);
        var moreThanOneInitialStep = StepInfoList.Where(x => x.IsInitialStep).Count() > 1;
        var DuplicateStepNames = string.Join(",", steps.GroupBy(x => x.PiplineStep).Where(x => x.Count() > 1).Select(x => x.Key).ToList());

//Part 2
        if (noInitialStep)
        {
            exceptions.Add(new Exception(Resources.InitialStepNotDefined));
        }
        if (moreThanOneInitialStep)
        {
            exceptions.Add(new Exception(Resources.MoreThanOneInitialStep));
        }
        if (!string.IsNullOrEmpty(DuplicateStepNames))
        {
            exceptions.Add(new Exception(string.Concat(Resources.RepeatedSteps, DuplicateStepNames)));
        }
        if (exceptions.Count > 0)
        {
            throw new AggregateException("Pipeline validation error , for more detail see inner exception.", exceptions);
        }
        return true;

Is it true to consider part 1 as data part and part 2 as logic part?

2.does a good structure should always separate these two parts?

template method design pattern - how to save and feed information into next step

I have an interface RequestProcessorInterface. There are different scenarios for processing a json request e.g. async vs synchronous request. I am trying to use template method pattern where the steps are like validate, preProcess, saveInDatabase, postProcess, etc


        ProcessingContext processingContext = validate(storeContentRequestContainer);
        processingContext = preProcess(storeContentRequestContainer, processingContext);
        saveInDatabase(storeContentRequestContainer, processingContext);
        return postProcess(storeContentRequestContainer, processingContext);

My ProcessingContext class has these attributes:

Map<String, String> errors;
String contentId;
String correlationId;
String presignedUrl;
String objectKey;
String bucketLocation;
DbEntity dbEntity; // Entity for database storage

When the json request is parsed, I assign values to 'processingContext' object. To keep the system flexible and not worry about what step might need the parsed information, I am encapsulating the extracted information in the context object.

Also I am passing the context object to every step so that in future, every step has this information readily available. I was going in the direction of most of the steps to be able to read the context and update some attribute and return the modified context , so the subsequent steps have access to attributes populated earlier.

I have a feeling that accepting context object (which is mutable) and modifying it and returning it is not a good idea. This context object is going to be in the method scope of a singleton class (spring boot). It will not be something lingering on forever and that should make it simpler.

How do I achieve this flexibility of multiple steps to be able to augment / update information in a context object? Will it make sense to make this context object immutable ?

Database schema and OOP model for sensors

Is there any design pattern for sensors? I'd like do collect data from various sensors. Some of them only measure temperature, others can measure temperature, humidity etc. I'm thinking about making a Sensor class which will contain 'name', 'description', 'location' (everything common for all sensors) and a collection of measurements. Data from this class will be stored in database in 'Sensor' table. This table will have so many rows as number of sensors. Column 'measurements' should point to next table with measurements. Every sensor will have its own table with measurements.

I'm not sure there aren't any "bad ideas" in my approach.

I'd like to use php, mysql and doctrine.

I would like to know if my approach is correct before I start writing the code. Maybe there is a better way?

How to design login viewmodel in android

I am building an android app by using compose, and I am stuck at how to write logic for my login button.

When that btn is clicked, I need first send request to the server with username and password wait for the response which contains code indicates if the username and password are correct. If the input is valid then I need to start the MainActivity with some data in response.

There are two approaches I think can work:

  • observe the databean livedata in viewmodel and determine if need to start MainActivity when livedata update(which indicates button been pressed and request been made). But I think this donot meets the design idea(click event->network request->start activity or not).
class LoginActivity : AppCompatActivity() {
    private val loginViewModel by viewModels<LoginViewModel>()

    override fun onCreate(savedInstanceState: Bundle?) {
        ...
        loginViewModel.loginBean.observe(this) {
            if (it?.code == 200) {
                startActivity(Intent(this, MainActivity::class.java))
            }
        }
    }
}

@Composable
fun LoginScreen(viewModel: LoginViewModel) {
    val context = AmbientContext.current
    Scaffold(
        topBar = { TopAppBar(title = { Text("LOGIN") }) }
    ) {
        LoginScreenContent(loginAction = { username, password ->
            viewModel.login(username, password)
        })
    }
}
  • pass the callback when invoke viewmodel login function and invoke the callback in network request. But this may cause memory leak because network request doesn't respect the lifecycle.
@Composable
fun LoginScreen(viewModel: LoginViewModel) {
    val context = AmbientContext.current
    Scaffold(
        topBar = { TopAppBar(title = { Text("LOGIN") }) }
    ) {
        LoginScreenContent(loginAction = { username, password ->
            viewModel.login(username, password){
                if (it?.code == 200) {
                    startActivity(Intent(context as LifeCycleOwner, MainActivity::class.java))
                }
            }
        })
    }
}

So which approach I should take or if there are some better way to do it.

How to correctly implement the repository pattern?

All examples on the internet have the basic 4 crud methods.

I am really confused how a big system will implement the repository pattern. Let's say I have a user which belongs to groups and has written books.

Sometimes I only need the user data, some times with his books data and sometimes with groups data. Do I implement a method for each of the usecases ?

And how to abstract updates? If I am using MongoDB then I have $inc, $pull and other awesome operators.

How do I actually abstract these types of updates if I need to combine them, for example $set with $inc. Do I need to have a separate method for each usecase of the system ?

mercredi 23 décembre 2020

What's the pythonic way of designing common class definitions in a package?

I'm coming from a C# background and have recently started to pick up Python 3. One thing that has lead to quite a bit of confusion so far has been how to structure modules in a package.

In C#, I would create a namespace MyLibrary.Model, in which all my different commonly used classes would reside, such as User, Employee, Customer, etc.. Each of these classes would be in their own file (e.g. User.cs, Employee.cs, etc.), since C# really doesn't care about files at all and only cares about which namespace a class belongs to. I would then import this in the various other bits of the library with using MyLibrary.Model, and all classes in that namespace would be available.

I have noticed that this is not how Python 3 likes to do things. Specifically, statements like "just import everything" seem to go against the design philosophy of Python, and instead, I am supposed to only import what I really need.

My question now is, how should I structure such common class definitions so it "makes sense" in a Python package?

What I have tried so far

One class per file

This most closely mimics the "one class per file" convention in C#, leading to a directory tree as follows:

main.py
mylib/
    __init__.py
    common/
        User.py
        Employee.py
        Customer.py
    controller/
        ...
    ...

Back in the main.py file, I would write something like this:

from mylib.common.User import User;
from mylib.common.Employee import Employee;
from mylib.common.Customer import Customer;

This works, but it seems like it has a lot of verbosity that it really doesn't need.

All classes in one file

This seems to work better with the import system as I have understood it. Instead of putting every class into its own file, I would instead put every class into one file. The file structure would then look like this:

main.py
mylib/
    __init__.py
    common.py
    controller/
        ...
    ...

Back in the main.py file, I would write something like this:

from mylib.common import User, Employee, Customer;

This seems much more succinct, but I feel like with a bigger project, this could mean a lot of class definitions in one file, and possibly lead to common.py becoming a bloated mess, containing a lot of classes that don't really have anything to do with each other.

How to solve coding challenges with design pattern instead of just practicing?

I am currently doing a lot of technical interviews and the technical coding rounds usually involves me solving coding problems.I am not a developer but an automation test engineer. I have a set of around 40 problems i practice but its kinda hit or miss for me. My question is how or where can i learn design pattern to implement them to solve this challenges instead of just practicing.Thank in advance.

SQS handle strategy using groupId and threadpool?

I am in process of designing sqs FIFO handling strategy, so trying to do it in right way. Faced with few fundamental questions.

For example i have in queue:

  • 100 messages with groupid "group1_100"
  • 5 messages with "group2_5"
  • 1 message with "group3_1"
  • 1 message with "group4_1"

Example of handle :

I requested 10 messages using longpooling :

1.1) Can i be sure that i'll receive 10 (max of requested) messages pre request on retrieve if there are more, than 10 messages of same group.

1.2) May sqs returns me 7 messages from group1_100, 2 from group2_5 and 1 from group4_1?

if yes :

1.2.1) for example, handling this 7 messages of group1_100 will take 10 seconds. So using thread pool 3 messages from group2_5 and group4_1 already handled in parallel - so i saying to sqs that they were handled so :

1.2.2) making another one request to sqs (to not wait until 7 messages from group1_100 finished). So

1.2.2.1) Is it possible, that i can receive messages from group1_100 (that should be handled after first 7 = in right order)? (assume, that no, because sqs guarantee us that it will be retrieved strongly in right order). Am i right?

In case if 1.2 is "yes" i need to control different "groupid" handle to prevent situation, when my processors will work only for "group1_100" even if they were first from "group/time" point of view, right? To prevent theoretic attack like "we are as a client will send you a lot of messages with one groupId, and you'll need to take us all your handle processors".

  1. So it may happen in case of single thread handling, right?

  2. And may it be resolved by next strategy? :

Making request to get 10 messages -> devide them to n groups (grouping by groupid) and starting handle them in parralel. When all messages from "group" handled - making "batch" notify to sqs about finishing -> in parralel start fetching another one pack of messages to handle (depending on/checking constant total_handling_messages_limit_at_time) and start handle them in same way syncing fetching to not make it too many times per second/minute.

So it will allow us to split handle inside one worker using threadpool, and not to stack with "long running" tasks with "one groupid".

Am i right in general, guys? Maybe i something missing here?

SQS handle strategy using groupId and threadpool?

I am in process of designing sqs FIFO handling strategy, so trying to do it in right way. Faced with few fundamental questions.

For example i have in queue:

  • 100 messages with groupid "group1_100"
  • 5 messages with "group2_5"
  • 1 message with "group3_1"
  • 1 message with "group4_1"

Example of handle :

I requested 10 messages using longpooling :

1.1) Can i be sure that i'll receive 10 (max of requested) messages pre request on retrieve if there are more, than 10 messages of same group.

1.2) May sqs returns me 7 messages from group1_100, 2 from group2_5 and 1 from group4_1?

if yes :

1.2.1) for example, handling this 7 messages of group1_100 will take 10 seconds. So using thread pool 3 messages from group2_5 and group4_1 already handled in parallel - so i saying to sqs that they were handled so :

1.2.2) making another one request to sqs (to not wait until 7 messages from group1_100 finished). So

1.2.2.1) Is it possible, that i can receive messages from group1_100 (that should be handled after first 7 = in right order)? (assume, that no, because sqs guarantee us that it will be retrieved strongly in right order). Am i right?

In case if 1.2 is "yes" i need to control different "groupid" handle to prevent situation, when my processors will work only for "group1_100" even if they were first from "group/time" point of view, right? To prevent theoretic attack like "we are as a client will send you a lot of messages with one groupId, and you'll need to take us all your handle processors".

  1. So it may happen in case of single thread handling, right?

  2. And may it be resolved by next strategy? :

Making request to get 10 messages -> devide them to n groups (grouping by groupid) and starting handle them in parralel. When all messages from "group" handled - making "batch" notify to sqs about finishing -> in parralel start fetching another one pack of messages to handle (depending on/checking constant total_handling_messages_limit_at_time) and start handle them in same way syncing fetching to not make it too many times per second/minute.

So it will allow us to split handle inside one worker using threadpool, and not to stack with "long running" tasks with "one groupid".

Am i right in general, guys? Maybe i something missing here?

Best methodology for an optimization algorithm

With the changes in the programming landscape I am at a loss on methodology and which is best for the problem I am working on. Principally, I work in C# and WPF but I can go pretty much anywhere. I am converting something from a legacy library I have where I have 2 versions - one in C (which itself was an upgrade from Assembly) and another in Delphi. Enough for context.

Question: I need a pattern given VS2019 (default config) that is all Microsoft that will allow me to start with a base object (complex), make conditional changes to that object and be able to, in code, compare the results of those changes. Paring down the original it did something like this:

Original Object: Scheduled work completes in 12 days
**Mod step 1**
Using Pete's changes: complete in 14 days - 10 if you double resource Y
Using Lora's changes: Complete in 11 days - 9 with 20% addition to resource X and Y
Using John's changes: complete in 16 days - resources balanced, 15% cost reduction

This worked by copying the original object and passing it through various functions and making comparisons along the path. The base object here is rather complex.

I have wasted a lot of time doing guess-and-check on my own and I am looking for an article, method, rock to look under that will get me thinking in the right way about the problem. Please help if you have worked on this kind of algorithm/model before.

I have something that works but it is a memory pig, overly complicated and horribly slow. As I am fond of saying - "there is too much code for it to be right"

Additional note Thought of something else I should add. The base class definition here is Serializable and one thought I had was to simply serialize each version within a structure that held markers of what changes were applied and then Deserialize each instance and compare. This would allow me to surface the resulting set to users who could then compare (using something like LINQ as an inquisition method) and propose additional changes or take some other action.

Is it a good practice to avoid long line on the return statement?

For example, suppose I have this function:

    private int Example()
    {
        return something.ExecuteSomething<Type>(ClassName.MethodName("param", false)).Count();
    }

Is it better to write it like that?

    private int Example()
    {
        var count = something.ExecuteSomething<Type>(ClassName.MethodName("param", false)).Count();
        return count;
    }

Name of pattern

May be wrong place to ask (please direct) but:

I often use a variance of the Strategy pattern where I write like this:

interface IA
{
   bool CanHandle(T someParameter)
   void Handle(T someParamter)
}
class A1:IA {}
class A2:IA {}

I then have a class where IEnumerable<IA> is injected, the First/Single/All of the instances is found through CanHandle() and called on Handle().

IS there a name for this pattern?

Does DTOs comes under decorator pattern?

I have Entity and DTO classes defined in two different Entity and DTO packages as:

@Entity
@Table(name="Foo", schema="REF_DATA")
public class Foo extends BaseEntity {
 private Long fooId;
 private String fooName;
}


public class FooDto extends BaseDto {
 private Long fooId;
 private String fooName;
}

While returning values to the User, we are returning DTOs rather than Entity objects. For that we have declared the mapper and it's implementation as:

public interface DomainToDtoMapper<E extends BaseEntity, D extends BaseDto> {

   D mapDomainToDto(E domain);
}

public class FooDomainToDtoMapper implements DomainToDtoMapper<Foo, FooDto> {
    @Override
    public FooDto mapDomainToDto(Foo domain) {
        FooDto fooDto = new FooDto();
        FooDto.setfooId(domain.getfooId());
        FooDto.setfooName(domain.getfooName());
        return fooDto;
    }

}

And get list of all Foo objects call in the service layer looks something like:

@Override
public List<FooDto> getAllFoo() {
    return fooRepository.findAll().stream()
            .map(FooEntityDomainToDtoMapper::mapDomainToDto) // mapping entity to dto
            .collect(Collectors.toList());
}

My question is are we using Decorator pattern here? I know there is Data Transfer Object Pattern but since we are providing implementation for mapping, can we say it is decorator pattern? Or is there any other design pattern getting used here?

mardi 22 décembre 2020

java design - objects to be logically handled in similar way but might not have common members/ methods etc

I am writing a suite of java classes that will be doing network requests on the basis from the information produced from our application. Most likely there will be several of these kind of suites in the future -- sending out certain data to other platforms/clients/partners etc. The input for those suites will be the same set of data (will be provided at the integration point from our app and i have no control over it) But this input will be converted to different data objects before creating the requests from these data objects.

Example pseudocode line

List(InputObjects) --> transformator --> List(RequestDTOs) --> requestcreator(creates and sends buch of requests based on DTOS).

I would like to encourage the future coders to use the same format for all the other suites. For ease of understanding and maintenance in the future.

So I would like to define interfaces/abstract classes etc. for "transformator" and "requestcreator". It would be easy to declare abstract superclass for RequestDTO and then let different suites extend it. But the thing is the RequestDTOs actually might have completely different fields with nothing shared. So one would make and abstract superclass with no members in this case. I do not like this idea much.

Would this be a good idea to mark RequestDTOs with annotation or marker (empty) interface?

Or could I just write the transformation as providing unspecified Collection as return type let the creator take in similar as input?

I would not like this latter idea I think -- I should the use Object as collection element type as trying to make generics for the elements would lead back to the problem that they might have not much in common except a certain "meta" logical position in the process flow that I would like the future users of the code to immediately recognize)

Any other ideas?

proxy design in java

I've got a question regarding proxy design.

So I've been asked to implement a proxy design in my project,

it asks of me to not directly create objects so my question is,

does that mean I shouldn't be doing this:

User user = new User (...);

company.add(user);

and instead i should be doing this:

company.add(new User (......));

or what does it mean?

enter image description here

How can I put an octagon inside of this octagon html

I'm not an expert with html so this is why I'm asking this question, so I could create an hexagon, but I need to create another one inside of the hexagon created, so this is why I'm asking if any of you guys could help me, thanks in advance!


<!DOCTYPE html>
<html lang="en">
<head>
    <meta charset="UTF-8">
    <meta name="viewport" content="width=device-width, initial-scale=1.0">
    <title>Document</title>
    <link href="https://cdn.jsdelivr.net/npm/bootstrap@5.0.0-beta1/dist/css/bootstrap.min.css" rel="stylesheet" integrity="sha384-giJF6kkoqNQ00vy+HMDP7azOuL0xtbfIcaT9wjKHr8RbDVddVHyTfAAsrekwKmP1" crossorigin="anonymous">
    <link rel="stylesheet" href="main.css">
</head>
<body>

<div class='octagonWrap'>
        <div class='octagon'></div>
        <div class="octagontwo"></div>
    </div>
    
</body>
</html>


here's the css


.octagonWrap {
    width:400px;
    height:400px;
    float: left;
    position: absolute;
    overflow: hidden;
    top: 30%;
    left: 20%;
}
.octagon {
    position: absolute;
    top: 0; right: 0; bottom: 0; left: 0;
    overflow: hidden;
    transform: rotate(45deg);
    background: rgb(255, 255, 255);
    border: 3px solid rgb(0, 0, 0);
}
.octagon:before {
    position: absolute;
    /* There needs to be a negative value here to cancel
     * out the width of the border. It's currently -3px,
     * but if the border were 5px, then it'd be -5px.
     */
    top: -3px; right: -3px; bottom: -3px; left: -3px;
    transform: rotate(45deg);
    content: '';
    border: inherit;
}



Memento Design Pattern - Real World Examples

Can someone give me some real world examples for Memento Design Pattern. I heard that Cart can be considered as one of the Memento Design Patterns. That kind of examples are preferred. Thanks in advance. :)

How to design a cli option combination handler in java?

I have the necessity to execute some functions based on a particular cli combination options (i use the apache commons cli library).

myprogram -a -b -c
myprogram -a -c
myprogram -d

To manage this situation, i have a very long list of "else if" based on a particular combination, all in my main function:

if (line.hasOption('a') && line.hasOption('b') && line.hasOption('c')){
   method1();
   method2();
 }
else if (line.hasOption('a') && line.hasOption('c')){
    method4();
 }
else if (line.hasOption('d')){
    method1();
    method4();
 }
....

There is a better way to design this? (by using some design pattern for example).

I'll appreciate any suggestions people have. Thanks.

Design pattern to limit access to a class's public members in C++

All of the code below is pseudo-code, for the sake of brevity.

Consider an event system, where have the following class:

class Event_dispatcher {
private:
    Listener_collection listeners;

public:
    void add_listener(Listener _listener) { ... }
    void remove_listener(Listener _listener) { ... }
    void post_event(Event _event) { ... }
};

I intend to have instances of Event_dispatcher in classes that are meant to send out events. However, I only want the events to be posted from inside the class, so that the user can only add or remove listeners, but never post events.
The simple solution would be to make Event_dispatcher a private member of the enclosing class, but then, I have to define add_listener and remove_listener as public members that forward the argument to the event dispatcher.
I am aware that two methods do not seem like a lot, but please bear in mind, this is just an example, I made it short on purpose. Imagine the same problem where I would have to define a significantly greater number of methods in a similar fashion.

I am trying to find out if there is a common or recommended way of solving problems like this. A solution that came to my mind would be to define an interface class like this:

class Event_dispatcher_interface {
private:
    Event_dispatcher* event_dispatcher;

public:
    void add_listener(Listener _listener) { event_dispatcher->add_listener(_listener); }
    void remove_listener(Listener _listener) { event_dispatcher->remove_listener(_listener); }
};

and make this a public member of the enclosing class. The pointer inside (*event_dispatcher) would point to the Event_dispatcher that's a private member of the enclosing class, so as to only allow for posting events from inside the class.

If there are other (better) solutions, I would appreciate any hints.

How to make an Object Factory maintaining the type

I have created the following object factory to instantiate implementations of all my interfaces:


interface SomeInterface {
    get(): string;
}

class Implementation implements SomeInterface {
   constructor() {}
   get() { return “Hey :D”; }
}

type Injectable = {
  [key: string]: () => unknown;
};

// deno-lint-ignore prefer-const
let DEFAULT_IMPLEMENTATIONS: Injectable = {
    SomeInterface: new Implementation()
};

let MOCK_IMPLEMENTATIONS: Injectable = {};

class Factory {
  static getInstance(interfaceName: string, parameters: unknown = []) {
    if (MOCK_IMPLEMENTATIONS[interfaceName])
      return MOCK_IMPLEMENTATIONS[interfaceName]();
    return DEFAULT_IMPLEMENTATIONS[interfaceName]();
  }

  static mockWithInstance(interfaceName: string, mock: unknown) {
    MOCK_IMPLEMENTATIONS[interfaceName] = () => mock;
  }
}

export const ObjectFactory = {
  getInstance<T>(name: string): T {
    return Factory.getInstance(name) as T;
  },

  mockWithInstance: Factory.mockWithInstance,
};

const impl = getInstance<SomeInterface>(“SomeInterface”);

As you can see, this Factory lets you instantiation and mocking of those interfaces. The main problem is that I have to call this function with the name of the interface AND the interface to keep the type in the assignments:

getInstance<SomeInterfaceName>(“SomeInterfaceName”)

I have seen this question, but I do not like the idea of using a Base interface. Moreover, that approach does not keep the type neither.

Ideally, I would want to use my approach but without having to use the interface, that is, use only the name of the interface.

how to implement feature - superuser shares data to subusers

Hi I'm trying figure out the best way to implement a feature where the superuser has some data (ex: contacts with name, phone number, etc) and can share it with designated subusers. A bonus would be superusers would have read/write access but the subusers would only have read access.

Wondering if this is a database, backend, or frontend problem.

Right now what I'm thinking is in the User Table, have a foreign key of superuser_id to establish superuser and subuser. Then I'm quite confused how to set up the data.

Also any common keywords or phrases used in the industry for this would be helpful for my google search. Thank you!

Why should we use decorator pattern?

I'm watching a course about Design Patterns and the example they used for decorator pattern is the Pizza and Toppings example ( you can find the example here as well). Please have a look at the link to understand my issue

What I don't like about this pattern as mentioned in the comments of the link I added is that a topping is not a pizza so why should it inherit the pizza class?

The solution I have in my mind is using an array of PizzaDecorators objects in a Pizza object and use that array to add or remove toppings from a pizza.

Isn't this solution much simpler than using the decorator pattern? Why should we consider using the decorator pattern in a situation like this?

Javascript return property instead of object during object initialization

is there way to change, what object actual is, when we manipulate with it? For exaple, if I have this class:

class Parent{
    child;
    contructor(){
        child = new Child();
    }
}
class Child{
    sayHello(){
        console.log("Hello");
    }
}

When I create instance of Parent class, I want to manipulate directly with its child property (which is actually reference to another object). I want to be able to do this:

let myObj = new Parent();
myObj.sayHello()

Sorry for silly/poor explanation, I really don't know right terminology for this.

Is there way to do what I want? Or any solution which give "similar" result to what I want? Notice, that what I really don't want is to solve it something like this:

let myObj = new Parent();
myObj.child.sayHello()

Thanks!

How to determine the right design pattern in combination with business logic

yes I know this question has been asked many times, but i need help with a 'concrete' example. However, I usually have the problem that it is not clear to me where the business logic comes into play.

The following example I have a list of object A. Based on object A an object B has to be calculated. Several complicated rules from the business logic apply here.

What is the appropriate design pattern? I thought of a (simple) factory.

Example:

public interface BFactory {
  public B createB();
}

public class BFactoryImpl implements BFactory { 

   public B createB() {
      return B.builder().exampleField(
      // methods fors business logic
      ).build();
   }

}

What do you think? I had also briefly considered using only the builder pattern, but I didn't think it would be nice to include the business logic there.

  1. Is that too much effort with the factory?
  2. Does the interface make sense?
  3. Or should I just use the builder with business logic?
  4. If this case is too simple for a design pattern, should I just write a method for it?

Thank you for your answers, unfortunately I am still a little inexperienced in the use of design patterns and would love to hear your thoughts on this

What design pattern to use for a common method with multiple implementations having different input parameter and different return type?

I am new to design patterns, and thus have a limited knowledge of what all is available. I am trying to implement a solution for a problem and request the user community to give some guidance on what design pattern to use and how it should be implemented.

Task : Implement central mapping factory that takes some input x and converts it to some output y. New implementation can be added in future.

  1. Input parameter is different for each implementation
  2. Ouput parameter type is different for each implementation

So far I have implemented factory pattern but I am doubtful on following points:

  • Warning in MapperFactory Raw use of parameterized class MappingUtil
  • In the service class when I use factory mapperFactory.getMappingUtils("A").mapData(a) I have to cast the output since each implementation has it's own specific outputformat

Is this the correct approach to the problem or am I following any anti-pattern in the implementation

public interface MappingUtil<X, Y> {
    Y mapData (X value);
}
 
@Component
public class A implements MappingUtil<Input A, OutputA> {

    @Override
    public OutputA mapData(Input A){
    // Perform some logic and convert InputA to OutputA and return Output A object
    }
   }

@Component
public class B implements MappingUtil<Input B, OutputB> {

    @Override
    public OutputB mapData(Input B){
    // Perform some logic and convert InputB to OutputB and return OutputB object
    }
   }

@Component
public class C implements MappingUtil<Input C, OutputC> {

    @Override
    public OutputC mapData(Input C){
    // Perform some logic and convert InputC to OutputC and return OutputC object
    }
   }
}

Factory Class

@Component
public class MapperFactory {

private final static Logger LOGGER = LoggerFactory.getLogger(MapperFactory.class);
private static Map<String, MappingUtil> mapperStrategyMapping;

private final A a;
private final B b;
private final C c;

@PostConstruct
void init() {
    mapperStrategyMapping = new HashMap<>();
    mapperStrategyMapping.put("A", a);
    mapperStrategyMapping.put("B", b);
    mapperStrategyMapping.put("C", c);
}

@Autowired
MapperFactory(A a,
              B b,
              C c) {
    this.a = a;
    this.b = b;
    this.c = c;
}

public MappingUtil getMappingUtil(String mapperCode) throws Exception {
    if (mapperCode != null) {
        return mapperStrategyMapping.get(mapperCode);
    } else {
        LOGGER.error("Empty mapper code received");
        throw new Exception("Empty mapper code");
    }
}

Usage of Factory :

@Service
public class XyzImpl implements Xyz{

    private final MapperFactory mapperFactory;

    @Autowired
    XyzImpl(MapperFactory mapperFactory){
        this.mapperFactory = mapperFactory;
    } 

    public void doFunction1(Input a , Input b){
        OutputA outputA = (Output A) mapperFactory.getMappingUtils("A").mapData(a);
        OutputB outputB = (Output B) mapperFactory.getMappingUtils("B").mapData(b);
        // Perform some logic on Output A Output B
    }

    public void doFunction2(Input c){
        OutputC outputC = (Output C) mapperFactory.getMappingUtils("C").mapData(c);
        // Perform some logic on Output C
    }
}

lundi 21 décembre 2020

LOGSTASH GROK PARSING

We are loading access logs data into elasticsearch using logstash.log file data look like below.

2020-12-14 05:19:27.441 10.20.20.198 - narayana.sathya [14/Dec/2020:05:19:27 +0000] "GET /zoomdata/api/groups/5c9349a029a3fa0700a243ae HTTP/1.1" 200 5552 "https://ift.tt/3h98wK9" "Mozilla/5.0 (Windows NT 10.0; Win64; x64) AppleWebKit/537.36 (KHTML, like Gecko) Chrome/87.0.4280.88 Safari/537.36 Edg/87.0.664.60" 315

Could anybody help me to get GROK pattern for above file , i have written below GROK patten in logstash configuration file but getting error.

grok { match => [ "message", "%{DATESTAMP_12H:timestamp} %{NUMBER:ip} %{WORD:user} %{DATESTAMP_12H:timestamp} %{WORD:api_details} %{NUMBER:responce_type} %{NUMBER:type} %{WORD:dashbaord} %{GREEDYDATA:daemon_message}" ] }

Telegraf parsing “grok” patterns out to prometheus

I have been trying to ingest data into influx from a log file. The structure is as follows

2020-12-20 09:03:33.867 [http-nio-8080-exec-1] [] INFO  FCPROCESS_WEB_DIGEST - (process.IndexController.index,/api/index,Y,0ms),

I have used this pattern

[[inputs.logparser]]
   files = ["/etc/telegraf/example/fcprocess1.log"]
   from_beginning = true
   [inputs.logparser.grok]
      measurement = "fcprocess1"
      patterns = [ "%{COMBINED_LOG_FORMAT}", "%{TIMESTAMP_ISO8601:date:tag} \\[%{NOTSPACE:thread:tag}\\] \\[\\] %{NOTSPACE:level:tag}  %{NOTSPACE:filename:tag} \\- \\(%{NOTSPACE:handler:tag}\\.%{NOTSPACE:controller}\\.%{NOTSPACE:path}\\,%{NOTSPACE:msg:tag}\\,%{NOTSPACE:flag:tag}\\,%{NOTSPACE:cost:tag}\\),"]
   [inputs.logparser.tags]
       value = "1"

Can I get help regarding formulating the pattern ? thank you

parse: match in the middle part of a string

I am using the parse package to extract some information from strings. I have a pattern like:

pattern = compile("hello {}")
s = "I am Jack, hello Mike, hello Tom! nice to meet you."
pattern.parse(s)

I want to extract 'Mike', 'Tom' out of s, no matter what's before and after the matched patterns in the string. How should I modify my pattern?

Android MVVM design pattern not showing empty values in logcat but when calling api to set data it is showing size of arraylist in repository class

IN THIS CLASS WHEN I AM CALLING API I AM GETTING SIZE OF THE LIST IN LOGCAT UNDER getFromApi() METHOD BUT EMPTY SIZE IN getIMAGES() METHOD I AM NEW ON MVVM DESIGN PATTERN CAN SOMEONE HELP ME OUT THANKS

public class ImagesRepositoy {
private static ImagesRepositoy instance;
private ArrayList<Images> dataset = new ArrayList<>();
private RequestQueue queue;
private static Context mCtx;
private StringRequest request;

public ImagesRepositoy() {
}

public ImagesRepositoy(Context context) {
    mCtx = context;
}

public static ImagesRepositoy getInstance() {
    if (instance == null) {
        instance = new ImagesRepositoy();
    }
    return instance;
}

public MutableLiveData<List<Images>> getIMAGES() {
    getFromApi();
    MutableLiveData<List<Images>> data = new MutableLiveData<>();
    data.setValue(dataset);// here I am getting empty array size
    Log.e("DATA",data.getValue().toString());
    return data;
}

private void getFromApi() {
    Log.e("YUPP", "HANN");
    request = new StringRequest(Request.Method.GET, ImageApi + "APIKEY&limit=25", new Response.Listener<String>() {
        @Override
        public void onResponse(String response) {
            Log.d("responsefromserv", response + "null");
            try {


                JSONObject jsonObject = new JSONObject(response);
                JSONObject images, original, jsonObject3;
                JSONArray jsonArray = jsonObject.getJSONArray("data");
                Log.d("DATAATA", jsonObject.getJSONArray("data") + ".");


                for (int i = 0; i < jsonArray.length(); i++) {
                    Images Imgs = new Images();
                    images = jsonArray.getJSONObject(i);
                    original = images.getJSONObject("images");
                    jsonObject3 = original.getJSONObject("original");
                    Imgs.setUrl(jsonObject3.getString("url"));
                    Log.e("JSONE3", Imgs.getUrl() + "");
                    dataset.add(Imgs);   // HERE I AM GETTING 25 size

                }


            } catch (JSONException e) {
                e.printStackTrace();
            }
        }

    }, new Response.ErrorListener() {
        @Override
        public void onErrorResponse(VolleyError error) {
            Log.e("error", error.toString());
        }
    });
    queue = Volley.newRequestQueue(mCtx);

    queue.add(request);

}}

VIEW MODEL CLASS ALSO SHOWING EMPTY ARRAY HERE ALSO

  public class HomeViewModel extends ViewModel {
private ImagesRepositoy repositoy;
private MutableLiveData<List<Images>> url;


public void init() {
    if (url != null) {
        return;
    }
    Log.e("INIT","OK");
    repositoy = ImagesRepositoy.getInstance();
    url = repositoy.getIMAGES();
}

public LiveData<List<Images>> getIMAGES() {
    Log.e("UUUU",url.getValue().toString());
    return url;
}}

THIS IS HOME FRAGMENT CLASS WHERE I AM FILLING RECYCLERVIEW AND WHEN I LOG THE VALUE IT ALSO SHOWING ME THE EMPTY ARRAY I DON'T KNOW WHY I HAVE TRIED MANY SOLUTION ON S.O. NONE OF THEM WORKED

 public class HomeFragment extends Fragment {

private List<Images> imagesList = new ArrayList<>();
private RecyclerView recyclerView;
private RequestQueue queue;
private MyGifAdapter myGifAdapter;

public View onCreateView(@NonNull LayoutInflater inflater,
                         ViewGroup container, Bundle savedInstanceState) {

    View root = inflater.inflate(R.layout.fragment_home, container, false);
    recyclerView = root.findViewById(R.id.my_recycler_view);
    HomeViewModel homeViewModel = new ViewModelProvider(this).get(HomeViewModel.class);
    new ImagesRepositoy(getActivity());
    homeViewModel.init();
    homeViewModel.getIMAGES().observe(getActivity(), new Observer<List<Images>>() {
        @Override
        public void onChanged(List<Images> s) {
            myGifAdapter.notifyDataSetChanged();
        }
    });
    GridLayoutManager gridLayoutManager = new GridLayoutManager(getActivity(), 3);
    recyclerView.setLayoutManager(gridLayoutManager); // set LayoutManager to RecyclerView
    Log.e("VMMM",homeViewModel.getIMAGES().getValue()+".");     //THIS IS GIVING EMPTY ARRAYLIST
    myGifAdapter = new MyGifAdapter(getContext(), homeViewModel.getIMAGES().getValue());
    recyclerView.setAdapter(myGifAdapter); // set the Adapter to RecyclerView
    //fetchGifs();

    return root;
}