samedi 30 septembre 2023

Analyzing approaches to handling optional arguments in multiple interface implementations: what are the pros and cons of each method?

I have a question regarding the code. The code is an example to illustrate the problem. I have an interface named MembershipInterface and I created a new implementation for this interface called MembershipExternalServiceAdapter. I also have a class MembershipApiSwitch which is used to decide which interface implementation should be called based on conditions. The problem is that in the new MembershipExternalServiceAdapter interface, some arguments which are present in these methods are not needed because they are unused or will be different.

How to solve this properly?

Set default values - and in one implementation ignore these arguments? Create a new interface that will inherit from MembershipInterface and override the methods? Use the strategy pattern - introduce separate strategies for these methods for different implementations and inject them as needed? Which method do you recommend?

Sample code:

interface MembershipInterface {
    fun validate(memberID: String, passphrase: String): MembershipValidationDto
    fun getMembershipData(membershipID: String, showRewards: Boolean): MembershipDataDto
    fun getMembershipData(productList: List<Item>, shopCode: String, membershipID: String): MembershipDataDto
    fun isMemberIDCorrect(memberID: String): Boolean
}

@Component
@Primary
class MembershipApiSwitch(
    @Qualifier("API1_MembershipFacade")
    private val api1Membership: MembershipInterface,
    private val membershipSettings: MembershipSettings,
    @Qualifier("API2_MembershipFacade")
    private val api2Membership: MembershipInterface,
    private val tokenHandler: TokenHandler,
    private val membershipIntegration: MembershipIntegration
) : MembershipInterface {

    If the condition is met, call the methods from `api1Membership`; otherwise, call from `api2Membership`.
}

@Component("API1_MembershipFacade")
class MembershipDatabaseAdapter(
    private val databaseClient: DatabaseClient
) : MembershipInterface {
    override fun validate(memberID: String, passphrase: String): MembershipValidationDto {
        return databaseClient.validateMember(memberID, passphrase)
    }

    override fun getMembershipData(membershipID: String, showRewards: Boolean): MembershipDataDto {
        return databaseClient.getMembershipData(membershipID, showRewards)
    }

    override fun getMembershipData(productList: List<Item>, shopCode: String, membershipID: String): MembershipDataDto {
        return databaseClient.calculateMembershipPoints(productList, shopCode, membershipID)
    }

    override fun isMemberIDCorrect(memberID: String): Boolean {
        return databaseClient.isMemberIDExists(memberID)
    }
}

@Component("API2_MembershipFacade")
class MembershipExternalServiceAdapter(
    private val externalServiceClient: ExternalServiceClient
) : MembershipInterface {
    override fun validate(memberID: String, passphrase: String): MembershipValidationDto {
        return externalServiceClient.validateMember(memberID)
    }

    override fun getMembershipData(membershipID: String, showRewards: Boolean): MembershipDataDto {
        return externalServiceClient.getMembershipData()
    }

    override fun getMembershipData(productList: List<Item>, shopCode: String, membershipID: String): MembershipDataDto {
        return externalServiceClient.calculateMembershipPoints(membershipID)
    }

    override fun isMemberIDCorrect(memberID: String): Boolean {
        return externalServiceClient.isMemberIDExists(memberID)
    }
}

Sample method call: membershipApiSwitch.validate(memberID, passphrase)

I provided some sample code and several variants of solving this problem. I am seeking opinions on which approach seems most sensible.

vendredi 29 septembre 2023

How can I apply the strategy pattern to a set of derived classes?

I have been learning about the strategy pattern. I have seen it as a technique that allows you to write extra code for an existing class with minimal changes to the original class.

I would like to apply this technique in my code, but my code has a set of derived classes that I want to implement strategies for.

To make a concrete example. Let's say I have an empty Shape class, and two subclasses Rectangle (int width, int height) and Circle (int radius).

I would like to implement a serialization strategy pattern that can write a Shape out as a simple TOML file.

I can do it like this for a single shape:

class Rectangle; 

class SerializerStrategy {
public:
  virtual std::string serialize(const Rectangle& rectangle) = 0;
};

class TomlSerializer : public SerializerStrategy {
public:
  std::string serialize(const Rectangle& rectangle) override {
    return "[Rectangle]\n"
           "width = " + std::to_string(rectangle.getWidth()) + "\n"
           "height = " + std::to_string(rectangle.getHeight());
  }
};

But I cannot find any solution which would enable me to, for example, iterate over a vector of Shapes that may be rectangles or circles and serialize each one.

I have tried reading through a lot of related questions on stack overflow. I've written my own simplified example code out as an experiment. I have watched video lectures on C++. I have asked claude AI for example code. I didn't find a solution from any of these attempts.

jeudi 28 septembre 2023

How do I use objects to represent data from my relational database without making an excessive number of database queries?

I'm trying to design my first complex object-oriented PHP application and I'm confused about how to use objects to represent data from my database. More specifically I'm confused about how to combine multiple objects without making a huge number of database queries.

A simple example: let's say I have two database tables:

products: - product_id
          - manufacturer_id
          - name
          - price

manufacturers: - manufacturer_id
               - name
               - factory_address
               - factory_zipcode
               - factory_country
               - // [50 additional columns]

I represent these using two classes:

class Product {}
class Manufacturer {}

Now let's say I want to create a page which lists 1000 products.

I create an array of 1000 Product objects using a ProductFactory class or similar, something like this:

class ProductFactory {
    function allProducts() {
        $results = db_query("SELECT * FROM products");
        foreach ($results as $result) {
            $product_objects[] = new Product($result);
        }
        return $product_objects;
    }
}

That's fine. That's only a single database query and now I have all the product data - great!

But what if I want to create a slightly different page which also displays 1000 products, but also includes data from the manufacturers table?

Sure, I could change my query to use a JOIN to return columns from the manufacturer table as part of my product query, but that doesn't seem very flexible to me, because:

  1. I might not always need manufacturer data, so loading it in the ProductFactory seems wasteful if I only use it on a single page and nowhere else.
  2. The manufacturer data might be very extensive, and I don't want 50 extra columns bloating my query result when all I need is the manufacturer's name.
  3. If I fetched product and manufacturer data in a single query I don't see how I could elegantly create two separate objects (Product and Manufacturer) from the query results without it being super messy.

I guess I could add a second method to my ProductFactory class, something like:

function allProductsWithManufacturerData() {
    // SELECT * FROM products JOIN manufacturers...
}

But that seems hacky and inflexible. People using my code would not know that they need to specifically call this method if they want to include manufacturer data in the Product objects.

Alternatively I could load the manufacturer data only when it's explicity requested:

echo $productObject->getManufacturer()->name;

That seems like a fairly flexible approach to me. But in my example above, that would result in 1000 extra queries (one for each product on the page) which would be horrible for performance.

So it seems like I'm being forced into a choice:

  1. Choose to fetch all the data you could ever possibly need (using a single JOIN query)
  2. Or... choose to fetch the bare minimum data and then use extra queries to fetch data as required.

Are these my only choices or am I missing something? Is there a design pattern I don't know about that I can use to leverage more flexibility here?

To print a pattern in python using nested for loops

Ok I am a begginer in python The pattern to be printed w/ nested loop:

1@
1#3#
1@3@5
1#3#5#7#

(For loop preffered) thx

The code I tried:

n = int(input("Enter no:"))
for i in range(1, n + 1):
    for j in range(1, 2 * i):
        if j % 2 == 0:
            print("#", end="")
        else:
            print(str(j), end="@")
    print() 

OUTPUT:

Enter no:7
1@
1@#3@
1@#3@#5@
1@#3@#5@#7@
1@#3@#5@#7@#9@
1@#3@#5@#7@#9@#11@
1@#3@#5@#7@#9@#11@#13@

"@" seems to come every line and "#" is not printed every 2nd line

Is there a recommended pattern to follow for conditional formatting in React?

I was currently in the process of developing a React component library. Depending on the variant specified by the user, different props are available for customization.

Presently, we utilize if conditions to determine the variant provided by the user and render the component accordingly.

I'm seeking advice and recommendations regarding a more effective approach. Specifically, one that accommodates varying props for different variants and allows us to render the component accordingly without the need for extensive if conditions.

Presently we are following the below approach

if(variant === 'A' || variant === 'B'){
  const {A, B, C, D, E} = props
  //Code block
  return (<ComponentA/>)
} 

if(variant ==='C' || variant === 'D' ){
  const {F, G} = props
  // Code block
  return (<ComponentA/>)
}

mercredi 27 septembre 2023

My right angle pattern is incomplete, why am I missing a few bottom rows or columns?

I am close to figuring out this code but it keeps resulting in a missing bottom line.

The pattern is supposed to be like this:

🐟
🐟🐟
🐟🐟🐟
🐟🐟
🐟

My code:
def get_right_arrow_pattern(max_cols)
    emoji = "🐟"
    result = ""
    max_rows = max_cols
    for row in range(1, max_rows+1):
        for column in range(1, max_cols+1):
            result = "" + result
        result += str(emoji)
        print(result)
    return emoji

Output:
🐟
🐟🐟
🐟🐟🐟
🐟🐟🐟🐟
🐟
None

The trick is I can't use print() within the function or for loop but it's giving me a semi-result of what I need. Any suggestions?

What does the phrase "hide the implementation from the user" mean when doing composition in Java when the user won't see your code anyway? [closed]

I am currently learning Java, and have recently started composition, yet every now and then I hear or read the phrase "hide the implementation from the user" when using different design patterns, what does this mean? Isn't the developer the only individual able to see the code? What does it mean to hide the implementation from the user? I've recently learnt interfaces so maybe interfaces could be referenced for any answers to help me understand what this means, thanks.

generate a pattern dataframe using R

I wish to make a dataframe as below. and I wish to have 3 parameter x,y,z,

x is number of "a" (number of "b" = column number, at first column, number of "b" is 1),

y is number of column,

z is number of row,

if x=2, y=5, z=16, then enter image description here

this is my code, I can't solve this problem. 
1. how to fill the empty space.
2. how to rename the column ([x]to[column number])
I need help.

library(dplyr)


x <- 2
z <- 16
w <- 5

df <- data.frame(matrix("", nrow = z, ncol = w))

for (col in 1:w) {
  a_count <- x
  b_count <- col
  
  df[1:a_count, col] <- "a"
  df[(a_count + 1):(a_count + b_count), col] <- "b"
}

print(df)


  X1 X2 X3 X4 X5
1   a  a  a  a  a
2   a  a  a  a  a
3   b  b  b  b  b
4      b  b  b  b
5         b  b  b
6            b  b
7               b
8                
9                
10               
11               
12               
13               
14               
15               
16              



lundi 25 septembre 2023

what do i need to modify in the code to make my desired output?

A B C D E D C B A 
A B C D   D C B A   
A B C       C B A     
A B           B A       
A               A

make this pattern using the code below:


n = int(input('\nEnter the No. of rows : '))
n=n//2+1

print('\n')
# this is a never ending loop
r=n
i=-1
s=chr(64+1)

while r>=n:
 c=j=1
 while c<=n*2-1:
  print(s if c<=r else ' ',end='')
  if c==n: j=-1
  c=c+j
 print()
 if r==1: i=1
 r=r+i
 if i==1 and r>n:
   break

previously i also made and succeded in making hollow diamond inscribed in rectangle so here it is:

n = int(input('\nEnter the No. of rows : '))
n=n//2+1
print('\n')

r=n
i=-1
while r<=n:
 c=j=1
 while c>=1:
  print('*' if c<=r else ' ',end='')
  if c==n: j=-1
  c=c+j
 print()
 if r==1: i=1
 r=r+i

print()

i have tried many ways but the code isnt working. i only want in this format so please understand and edit the code

i was expecting this:

A B C D E D C B A 
A B C D   D C B A   
A B C       C B A     
A B           B A       
A               A

but i am unable to make this.

What is the best choice (while or for loop) for iteration through string's characters?

I am new to programing, and still learning the basics and figuring out best practices for C language. For iterating through string's characters i know of two ways, which is better and why?

int letters = 0, i = 0;
while (text\[i\] != '\\0')
{
if (isalpha(text\[i\]))
{
letters++;
}
i++;
int letters = 0, i = 0;
    while (text[i] != '\0')
    {
        if (isalpha(text[i]))
        {
            letters++;
        }
        i++;
    }

I tried both methods and both worked, but not sure which works better.

Which design pattern should I use to have a "context" in my app?

I am developing an app with an ActionController. It handles a Queue, which stores Action objects. All it does is dequeue an Action, execute it, then execute the following Action etc. If there are no Action instances, it waits for one to queue.

These actions do not know themselves, so I would need a pattern to keep track of the higher level stuff, such as knowing where the program is in a process, which is composed of actions.

Actions should have access to this Context object to update it.

I have read about the Context Pattern, but I don't think it fits my needs because the Context object will have some logic, checking program state and alter actions in the queue.

A Singleton may be a solution, but I would like to have the cleanest architecture possible.

What are your thoughts?

Thanks

I read about Design patterns, specifically Context Object and Singleton but I don't think they fit my needs or are the cleanest way to organize my program.

Is it good practice to define a inner memeber accessor operator overload for CRTP template?

This occurs to me that I can add

template<typename T>
class ISock {
    public:
    Message Recv()  {
        return static_cast<T*>(this)->Recv();
    };
    ~ISock(){
        static_cast<T*>(this)->~ISock();
    };

    // use the following complementary...
    T* operator->(){
        return static_cast<T*>(this);
    };
    void Other override {
        (*this)->Other();
    }
};

This allows more flexibility in function definition and reduce boilerplates, for example, if I have

class MockSock : ISock<MockSock> {
     public: 
     ...
     void peculiarFunction(int){
     ...
}

Then I may use the peculiarFunction in defining fn(ISock<MockSock> m) or even with if constexpr for specialization. I am wondering whether it's a good practice to

  1. provide a .inner() method
  2. to overload it as operator-> for simplicity in coding.

dimanche 24 septembre 2023

Explain the usage of hook (); method in Template Method design pattern

Explain the usage of hook (); method in Template Method design pattern with the sample code examples

What are the usages of hook (); method in Template Method design pattern. What is the purpose to use hook(); method

Write a code example to demonstrate the Template Method design pattern

Conditional `@abstractmethod`

What's a good design-pattern / solution for the following problem?

Context: I want to write a Protocol "IVP_Generator" for classes that represent initial value problems. These classes must provide a function solve_ivp that solves the IVP for some time interval. Now, in the by far most common case, one defines a system and uses an off-the-shelve solver. So I want the protocol to look something like this:

class IVP_Generator(Protocol[T]):
    """T some array-type."""

    @property
    def system(self) -> Callable[[T, T], T]:
        """Represents the vector field f(t, x(t)), if applicable."""
        return NotImplemented

    def solve_ivp(self, t: T, y0: T) -> T:
        """Return solution y[t] of the IVP."""
        if self.system is NotImplemented:
            raise NotImplementedError
        return default_solver(self.system, t, y0)

Now, I don't really want to make system an @abstractmethod because there are some cases I want to cover where the dynamics are not given by an ODE. In these cases, solve_ivp should be overwritten by the subclass appropriately.

So really the behavior I want is:

  • If a subclass does not implement system, it must implement solve_ivp
  • If a subclass implements system it can choose to implement solve_ivp or not.

Is it possible to make @abstractmethod conditional this way? Or should I do something else altogether? I'd rather like to avoid having multiple Protocols.

How to arbitrarily stop goroutines from operating on input?

Let's say i am building a little script that brute forces paths on a url for pentesting purposes (like legal stuff :)), and i am building it like the code snippet below, however i would like to make a change in this code such that when a url starts to respond with 429 status codes (too many requests) which means we're being rate limited, i would like it to stop sending requests to that specific host and resume bruteforcing the rest of the other hosts what is the optimal way of doing this such that i reduce (or better yet, completely eliminate) the number of requests send to a host once it returns 429 status code?

a possible solution i thought about would be setting an array or urls that i should stop bruteforcing and access that array from the gorountines via a mutex, and before each request in the goroutines loop, access that array and only send the request at hand if the url if not in that array.

The reason i don't like this approach is that given a url will start with responding with 429, it will allow many requests to be sent before we can access the array via the mutex and append it to it.

Is there a better approach ? I'm also fine with changing the design pattern used for the concurrency here if it leads to a better solution.

urls := make(chan string)
for i := 0; i < concurrency; i++ {
  wg.Add(1)
    go func() {
      for url := range fileNamesChan {
        sendRequest(url)
      }
      wg.Done()
    }()  
}

for _, url := range inputURLS {
  for _, fileName := range fileNames {
    urls <- url + fileName
  }
}

close(urls)
wg.Wait()

I tried the solution suggested above, but like i said given a url will start with responding with 429, it will allow many requests to be sent before we can access the array via the mutex and append it to it.

samedi 23 septembre 2023

How to correctly apply the Decorator pattern (C++)

I am currently working on a simple WYSIWYG project to exercise my skills with design patterns. Basically, the program lets the user create, move and resize basic shapes, like rectangles or triangles. Now, I am trying to implement a mouse selection feature using the Decorator pattern, but I am facing a hard time with it. My main problem is that the decorator object must have acess to member variables in the derived shapes to draw the selection on screen. If I follow the canonical examples in the textbooks, I would have to inject those variables in the decorator by reference, but that would not be sustainable, the more member variables I introduce in the derived shapes later on.

class Shape {
public:
virtual void Draw(Window* window) = 0;
};

class Decorator : public Shape {
private:
Shape* shape;
public:
Decorator(Shape* shape) : shape(shape) {}
void Draw(Window* window){shape->Draw(window);}
};

class SelectionDecorator : public Decorator {
private:
RECT& rect; //SelectionDecorator needs a reference to RECT to draw the selection border
public:
SelectionDecorator(Shape* shape, RECT& rect) : Decorator(shape), rect(rect){}
void Draw(Window* window) {
//draw selection
}
};

class RectangleShape : public Shape {
private:
RECT rect;
public:
void Draw(Window* window) {
//draw rectangle
}
};

Duck typing would avoid the variable duplication. My biggest concern with this strategy is the fact that, if I wish to use the Visitor pattern to send messages to the decorator, I would have to treat it as a generic Shape or I would have to declare a different Visit algorith in the Visitor interface for each type of Shape I use, which contradicts the whole pattern purpose.

class Shape{
public:
virtual void Draw(Window* window)=0;
};

template <typename T> class SelectionDecorator : public Shape {
private:
T shape;
public:
Decorator(T shape) : shape(shape) {}
void Draw(Window* window){shape->DrawDecoratedShape(window);}
};

class RectangleShape : public Shape {
private:
RECT rect;
public:
void Draw(Window* window) {
//draw rectangle without selection
}
void DrawDecoratedShape(Window* window) {
//draw rectangle with selection
};
};

Another BIG question I have is where I should store the pointers to the decorators I create. If, for example, I declare a class Document, that contains a list of Shapes I want to display on screen, everytime I select a shape with a mouse click, I have to create a decorator object and replace the pointer to the basic shape in Document by the decorator pointer. I highly doubt that's how the selection feature concretely works in real life programs, since it represents, in my opinion, a contradiction to the Open Clode principle.

I am starting to think that real programs do not use the Decorator pattern for selection purposes. Instead, they may add a boolean member variable to each object to store the selection state (which is a very ugly solution) or use the Strategy pattern as a replacement to the Decorator. Is that really so?

Does anyone know why the screen part looks like that? [closed]

The screen doesn't look very nice. looks very weird I don't know why but the bottom part and the whole calculator container looks fine.

enter image description here

Here's what its meant to look like.

enter image description here

here's my code

.calc-screen {
    align-items: center;
    justify-content: center;
    display: flex;
}


.calc-buttons-container button {
    box-shadow: 2px 2px 5px rgba(0, 0, 0, 0.2); /* 3D-like box shadow */
    color: white;
    font-size: 35px;
    border: none;
}

.calc-container {
    box-shadow: 2px 2px 5px rgba(0, 0, 0, 0.2); /* 3D-like box shadow */
    width: 70vh;
    height: 95vh;
    background-color: white;
    margin: auto; /* This is the key property for centering horizontally */
    position: absolute; /* Centering vertically */
    top: 0; 
    bottom: 0; 
    left: 0; 
    right: 0; 
    border-radius: 10%;
    background-color: #7E6767;
    display: flex;
    flex-direction: column;
}

.calc-buttons-container {
    box-shadow: 2px 2px 5px rgba(0, 0, 0, 0.2); /* 3D-like box shadow */
    background-color: #3B3232;
    display: flex;
    border-radius: 10%;
    width: 90%;
    height: 65%;
    position: relative;
    left: 35px;
    top: 30px;
}

Facade Design Pattern With Possible Use Cases

Recently I was interviewed and discussed a bit on the design pattern Facade with the interviewer. My understanding on this in terms of C# is - There will be a base class library under which each facade or classes would be isolated with it's functionalities. Something as follows:

public class Facade
{
    public Facade()
    {
 
    }
    
    public void MethodA()
    {
        Console.WriteLine("Method A");
    }
 }

Interestingly the interviewer asked me if there are two different forms say Customer Registration and Order form, in that case will there be one Facade or two? What I said and in my opinion, there would be different facades and under the class library there would be two different facades or classes as those are two different features to be implemented. So my code snippet was something as follows:

Facade1:

public class Facade1
{
    public Facade1()
    {
 
    }
    
    public void AddCustomer()
    {

    }

    public void GetCustomer()
    {

    }
}

Facade2:

public class Facade2
{
    public Facade2()
    {
 
    }
    
    public void AddOrder()
    {

    }

    public void GetOrder()
    {

    }
}

Though the interviewer didn't ask me anything after showing the code snippet. But my question is the approach I did, is it the convenient one? After getting through an hour of session, I was thinking on the design pattern as I had a little experience on that and was wondering it was correct enough to provide the above example. Any clarification would be much appreciated.

vendredi 22 septembre 2023

Is there a design pattern I can use to implement this Jenkins pipeline code?

I want to write Jenkins pipeline code (Groovy) to deploy Docker containers in ECS. Say I capture this behavior in the following classes, with each concrete class representing a Docker container to be deployed to ECS. Depending on the container, I need to run certain tasks (or none at all) before deploying to ECS, then common tasks to actually deploy to ECS, then certain tasks post deployment to ECS. All files are in the com.somepath class path.

package com.somepath
abstract class EcsService {
  runPreDeployTasks() {throw new Exception("Implement in sub-class.")}
  runDeployTasks() { println "Do something common to all sub-classes" }
  runPostDeployTasks() {throw new Exception("Implement in sub-class.")}
}

package com.somepath
class AdminService extends EcsService {
  AdminService() {}
  def runPreDeployTasks() {
    println "runPreDeployTasks: ${this.getClass().getSimpleName()}"
  }
  def runPostDeployTasks() {
    println "runPostDeployTasks: ${this.getClass().getSimpleName()}"
  }
}

package com.somepath
class ProcService extends EcsService {
  ProcService() {}
  def runPreDeployTasks(final boolean singleSvc=false) {
    println "runPreDeployTasks: ${this.getClass().getSimpleName()}"
  }
  def runPostDeployTasks(final boolean singleSvc=false) {
    println "runDeployTasks: ${this.getClass().getSimpleName()}"
  }
}

Then this is the API to Jenkins

package com.somepath
import com.somepath.EcsService
import com.somepath.AdminService
import com.somepath.ProcService

class Deployer {
  Deployer() {}

  def deployServices() {
    def obj = new AdminService()
    svcList.add(obj)
    obj = new ProcService()
    svcList.add(obj)

    svcList.each { svc ->
      svc.runPreDeployTasks()
      svc.runDeployTasks()
      svc.runPostDeployTasks()
    }
  }

  List<EcsService> svcList = []
}

Then the Jenkins pipeline

@Library('share-lib') _
import com.somepath.Deployer

node("node1") {
  def obj = new Deployer()
  obj.deployServices()
}

Is there a better way to do this using a classic design pattern? Thanks.

How to create a polymorphic behavior when sub-classes have extra fields, compared with base-class?

Let us assume we have the following hierarchy:
(It's worth mentioning that the example uses Person-Student case just for the sake of simplicity)

class Person
{
   public string Name;
   public int Age;

   public abstract void SayHello();
}

class Student : Person
{
   public double Grade;
   public string SchoolName;

   public override void SayHello()
   {
      Console.WriteLine("Hi! I'm a student.");
   }
}

There might be a lot of other classes which sub-class Person.
From the methods point of view, the Liskov principle is 100% satisfied. Wherever in the code I create an instance of Student (or other sub-class of Person), the appropriate SayHello() method will be called.
From the fields point of view, the Liskov principle is not satisfied at all.
The following piece of code is not working and it looks to me as a bad code design.

Person onePerson = new Student();

Console.WriteLine(onePerson.Name);       // OK
Console.WriteLine(onePerson.Age);        // OK
Console.WriteLine(onePerson.Grade);      // NOT OK - Person does not have a Grade field
Console.WriteLine(onePerson.SchoolName); // NOT OK - Person does not have a SchoolName

My question is: How can I redesign this code to achieve some sort of a polymorphic behavior ? It makes totally sense for the sub-class to contain Grade and SchoolName, but this destroys the Liskov principle. I cannot access the fields from the sub-class as I tried in the above code. The only solution is to downcast, but this is really a bad practice.

I tried to search for different design patterns, but nothing really fits in my case. I also read about Inheritance vs. Composition, but I didn't find anything helpful.

In the context of inheritance in C++, how can a function in the derived class be invoked before the execution of the base class constructor?

this is an example program to demonstrate adapter pattern.
In the context of inheritance in C++, how can a function in the derived class be invoked before the execution of the base class constructor?

AdapterInterface(int d, double r) : LegacyInterface(_w, _h)

I was looking for a solution to execute diagToRectConverter before LegacyInterface(_w, _h) call.

#include <iostream>
#include <cmath>

// Desired interface (calculate rect based on diagonal and ratio)
class NewInterface
{
public:
    NewInterface() { std::cout << "NewInterface ctr" << std::endl; }
    virtual void draw() = 0;
};

// Legacy component (Adaptee)
class LegacyInterface
{
public:
    LegacyInterface(double w, double h) : _w(w), _h(h) { std::cout << "LegacyInterface ctr" << std::endl; }

    void oldDraw()
    {
        std::cout << "--LegacyInterface--" << std::endl;
        std::cout << "Width    : " << _w;
        std::cout << "  Height   : " << _h << std::endl;
    }

private:
    double _w;
    double _h;
};

// Adapter wrapper
class AdapterInterface : public NewInterface, private LegacyInterface
{
public:
    AdapterInterface(int d, double r) : LegacyInterface(_w, _h)
    {
        std::cout << "AdapterInterface ctr" << std::endl;
        std::cout << "--New Interface--" << std::endl;
        std::cout << "Diagonal : " << d;
        std::cout << "  Ratio    : " << r << std::endl;
        diagToRectConverter( d,  r);
    }

    void diagToRectConverter(int d, double r)
    {
        // Calculate the square of the diagonal
        double D_squared = double(d * d);

        // Calculate the width and height
        _w= std::sqrt(D_squared / (1 + r * r));
        _h = r * _w;
    }

    void draw() override
    {
        LegacyInterface::oldDraw();
    }

private:
    double _w;
    double _h;
};

int main()
{
    int d;
    double r = 1.7778;
    std::cout << "Enter Diagonal: ";
    std::cin >> d;
    NewInterface *adapter = new AdapterInterface(d, r);
    adapter->draw();

    return 0;
}

I'd like to find an alternative approach that avoids calling diagToRectConverter twice in the constructor initialization of LegacyInterface within AdapterInterface for the given d and r values.

AdapterInterface(int d, double r) : LegacyInterface(std::get<0>(diagToRectConverter(d, r)), std::get<1>(diagToRectConverter(d, r)))

jeudi 21 septembre 2023

What would be the correct naming for a method that creates and returns an object?

I have a SectionBuilder class that creates a Section as follows

public class SectionBuilder {
    public static func make(…) -> Section {
        return Section(…)
    }
}

Since the class name is Builder, should I rename the make() method to build()?

I didn’t want to do so since that’s not actually a builder that has other methods to set values.

What do you guys think?

mercredi 20 septembre 2023

Log to database with local buffer

What are the best practices to log data to a central entity/database that may be unavailable for some time while logging?

I'm loggging data from a desktop application. The data should be stored in an sql database that may be unavailable for some time (may be days). The database is never read from the desktop application.

What I'm currently doing works, but it feels like a hack: The desktop application simply writes to a local sqlite database. Every table of the database has a 'modified' column that is updated by triggers on updates and inserts. A second application then polls the sqlite database, checks for modified rows and tries to write them to the sql server. If the rows were successfully written, the modified flags are updated.

Alternatives I have thought of so far:

  • A send-queue that buffers data that should be sent to the server until the server is available again. It seems like kafka offers something similar. An issue that could arise: if the system that runs the desktop application (or the application itself) crashes unexpectedly , the data is lost - which I would like to avoid

  • Try to write directly to the sql server. If that fails, write the data to a local database. Every now and then try to write rows from the local database to the server and delete them on success. This is quite similar to the alternative above but it ensures that the data persists on crashes (The local database is now basically the send-queue).

Design Pattern for handling the many components of a locomotive

In C#, I'm creating a locomotive management system. My issue is that I have various components, such as a bogie carrying Axles, Axles holding multiple Wheels and Breaks, and all of these parts degrade on a timer. I'd like a system in which the wheels can update the basic components holding them, such as the bogie (chassis), and I'd like the components (Axle, Wheel) to be more independent rather than being stored into lists. Is there a design pattern that can meet these requirements? My code is included below.

public abstract class LocomotiveComponent 
{
    public string Name;
    public string Description;
    public List<LocomotiveComponent> Components;
    public float Health;

    protected LocomotiveComponent(string name) 
    {
        Name = name;
        Health = 100f;
    }

    public abstract void Update();

}

public abstract class Bogie : LocomotiveComponent
{
    public Bogie(string name) : base(name)
    { }
}

public abstract class Axle : LocomotiveComponent
{
    public Axle(string name) : base(name)
    {}
}

public class Axle4Wheeled : Axle
{
    public Axle4Wheeled(string name) : base(name)
    {
        Components = new(4);
    }

    public override void Update()
    {
    }
}

public class Axle6Wheeled : Axle
{
    public Axle6Wheeled(string name) : base(name)
    {   
        Components = new (6); 
    }

    public override void Update()
    {
    }
}

public class Wheel : LocomotiveComponent
{
    public Wheel(string name) : base(name) 
    {}

    public override void Update()
    {
        Health--;
        if(Health < 10f)
        {
            //update bogie of low health
        }
    }
}

I tried the composite pattern for various components holding others.

Message passing vs memory manipulation

My app consists of different decoupled modules and usually the output of one module is the input of the next module. However for a specific use case I want to collect data across all modules and print it out in the end. I see two options:

  1. Message passing: Passing a container object through the different modules which fill it with data. This is how I would usually do it since the hardcoded dependencies make the code very clear and understandable. However, refactoring really becomes annoying, since I often need to change the arguments and return-values of the call hierarchy. Also, I'm not sure if just passing a "container/collector object" and filling it without explicitly returning it is a good design approach.
  2. Memory manipulation: Injecting the container object at all places where I need to collect data data. Inject the object also at the place where I need to retrieve the data. Allows for quick refactoring since I just need to inject the collector/container object at the specific places. However, it feels like the code becomes hard to understand, since i don't have a call hierarchy to understand where the information is coming from.

Are there reasons to prefer one option over the other in my scenario or in general?

mardi 19 septembre 2023

convert multiple lines into single seperated by comma

have a json file with tons of records as follows . I need to extract 4 fields and put them in one line of output as show below

{,
"address": "122.22.33.33",
"ipv6_prefix_bits": "0",
"protocol": "IPV4",
"network": "10.118.121.11/14",
"hostname": "abcd.net",
"state": "active"
.....
},
{,
"address":......
...
...
},

OUTPUT 
"hostname": "abcd.net","protocol": "IPV4","network": "10.118.121.11/14","state": "active"
"hostname":.....
,

I tried JQ however I need to do this in a production server where we dont have JQ and so might have to use AWK or SED .

Is there any design pattern to solve the problem of long running code that uses a lot of integrations?

Let's say you need to write a REST microservice with a single GET request method.

The only function of this method is to receive and aggregate data from different legacy systems through different types of communication channels. These legacy systems are black boxes for us; we cannot change any of them.

As the number of such systems increases, the execution time of the method also increases. And in some cases, the execution time reaches too long values ​​(seconds and tens of seconds).

Hence the question - is there some kind of design pattern or accepted approach for optimizing such services?

Of course, caching can be a solution to the problem. But what if we only have one highly unique input parameter, such as ID? There is no point in making a cache, since the probability of repeating input parameter is very small. What can be done in this case?

Access Tokens or alternatives with microservices for determining User Access to Database resources

Hi I have following structure :

Client App (layer 1) Business logic Services ( Layer 2)

Business Logic layer consists of many microservices . Access token can be created and passed from APP layer to business logic layer. Business logic layer could validate the access token and allow access to required operations.

But Scenario is : user A logged in can access Resource 1 but not Resource 2 ( here resource means Individual records in database ) . How would I manage this situation ? These checks to resource is quite expensive and ideally would require to be done once.

However, Should each of my business layer microservices cross check always if user can access resource ? Or Should there be a separate access token created when user tries to open each resource and pass to business logic layer so that it can trust and allow?

How to properly design a desktop application managing a small database?

I have to develop a small Desktop application in Java/Swing managing a small SQLite database.

The example described here is largely stupid but it fairly accurately represents my question.

enter image description here

I need to perform CRUD operations on all tables.

The basic DAO pattern produces, for the "software" table, a POJO including the language_id foreign key, which means nothing for the user.

I want the user to be able to enter the language with a ComboBox including all the languages present in the "language" table. If the user wants to add or modify a language, I want him to also be able to enter the paradigm with a ComboBox including all the paradigms present.

Similarly, ActiveRecord and UpdatableRecord patterns are associated with one table, not multiple tables.

Is there a pattern that aggregates objects from different tables?

I don't want to use an ORM.

Are there any books or source codes that describe how to develop a Java Desktop application to manage a database, without using web technologies?

"SQL Server Database Programming with Java: Concepts, Designs and Implementations" by Ying Bai (https://link.springer.com/book/10.1007/978-3-031-06553-8) covers this topic but I found it very difficult to read and I couldn't find the code and the database presented in the book: I have to re-enter everything!

"Database Programming with JDBC and Java" by Georges Reese (https://www.google.fr/books/edition/Database_Programming_with_JDBC_and_Java/oPbGi0l0ZHEC) is interesting but does not use modern patterns.

Software by Mateus Vargas (https://github.com/mateuscardoso99/controle-academico) can help, it is well structured, but it is a very small application.

lundi 18 septembre 2023

Head First Design Patterns in p.543, What is The last question's answer? -> Design pattern to separate Model and View perfectly [closed]

I am reading chapter 12 "Compound patterns (MVC)" in Head First Design patterns second edition. On p.543, there is a Q&A, the last question of which is

Q: The view is not supposed to manipulate the model; however, I noticed in your implementation that the view has full access to the methods that change the model's state. Is this dangerous?"

the author writes

You are correct; we gave the view full access to the model's set of methods. We did this to keep things simple, but there may be circumstances where you want to give the view access to only part of your model's API. There's a great design pattern that allows you to adapt an interface to provide only a subset. Can you think of it?

I can't think of that design pattern. Can anyone tell me what it is?

Given the structure of this document, it should always be one of the following patterns. Observer Decorator Factory Singleton Command Adapter and Facade Template Method Iterator and Composite State Proxy

Huu... Adapter pattern?

Designing a scalable front-end for network interfaces

I want to provide different mobile network functionalities with an agnostic approach in C++, that is hiding which adapters are used to achieve them (WPA socket, Netlink communication to WiFi chip...). Each functionality is implemented using one of available adapter, but the client code is not aware of which one has been used. Provided network functionalities could grow in time and so also new adapters could be required to implement them (so maybe Network Manager via DBus, ioctl...).

My idea is to:

  • Use Bridge pattern to provide an high level abstraction to client code and decouple from low level implementation. Bridge is mainly used to send commands from client to low level implementation side and it is providing basic functionalities.
  • Use Command pattern to encapsulate request to perform actions on network interfaces. So client code is not calling functions, but creating commands and sending via the Bridge abstraction.
  • Chain of responsibility pattern (CoR) to pass command to proper adapter that can handle the execution.

Assuming that it is a good design, I am not sure how to manage the following things:

  • How I can check (in CoR) if an adapter can handle a command without using switch or downcast?
  • What if command execution provide a result or generate and event? Should I add a getter function for those specific command and then client code should call it or it would be better using a Visitor pattern to trigger a callback to manage the result/event?

dimanche 17 septembre 2023

How to create multiple front-end websites with the same structure?

I want to create multiple distinct front-end landing page that share the same layout, logic, and back-end but can customize content and CSS for each site.

How can I efficiently and conveniently create a new site each time? I'm using Vue 3 for the front-end.

My idea is to create a template for the interface, and each new website will be built from that template. However, it may take a lot of time for customization, so please give me some ideas on this matter.

create a search functionality for at most 500k items [closed]

Hey I wanted some guidance, I would be glad if someone could show me the right direction, or shed some light on my problem I wanted to make a semi optimised search functionality (semi optimised cause i can't deal with very complicated things also i have 500K items i wanted to search through not 10M items) so i want to be able to fuzzy find items, and be able to do something like spell checking (like if they press 2 or 3 keys wrong it could still match) also i have to make it scalable

the items i have is just strings and i am planning on making the search on 1 column of items (so if i have like a student table i am planning on making the search only for the first name, not something like it would search through name and address) i am planning on it but later if possible, i want to be able to do 2 or 3 columns search on a single search, so if i could do that now without that much more effort i would like to that

the strings i would be searching through would be mostly 1 continuous string maybe some with 2 strings with a "-" concatenating them. I haven't decided how many items i wanna have with 1 search but i think i would need at least 50 results as quick as possible and then get more later somehow ...

I wanted everything there is to it (mostly everything) i don't mind crunching through blog posts and/or videos for 4 days straight (yeah, i would be sane upto 4 days only) by everything i mean if i should handle the data in a database or in the server itself (not doing anything on the client side we decided all this would be in server side ) so if its database what kinda database or what kinda database engine should i use also what kinda optimisation i would have to do like indexes and everything else i don't know about or if its in a server what kinda data structure would i have to do or a combination of both, i wanted to know it until i have those figured out (i hope i don't have to reinvent a wheel many times and there are known ways to do it)

so anything you could link would be a great thanks

I am looking through postgres's full text search and also found an article about fuzzy string matching I would like to know anything else that would help me make an informed decision.

samedi 16 septembre 2023

How does singleton instance implementation in C++ does not leak memory?

I'm studying about singletons in design patterns and I saw this singleton implementation and I tested it with fsanitize=address, because there is no delete keyword even though there is a new keyword being use I suspect that this is an incomplete implementation and therefore has memory leak, but after running the program it doesn't seems to have one? why is that? we are allocating new memory for *singleton so it should be a dangling pointer?


class Singleton {
    public:
        static Singleton& instance() {
            static Singleton* singleton = new Singleton();
            return *singleton;
        }

        void set_data(int value) { data = value; }
        int get_data() { return data; }
    private:
        Singleton() : data(0) {}
        ~Singleton() {}
        int data;    
};

How come this singleton implementation does not leak memory in C++?

If I rewrite this singleton class into something like this:

class Singleton {
    public:
        static Singleton& instance() {
            static Singleton* singleton;
            
            if (singleton == nullptr) {
                singleton = new Singleton();
            }

            return *singleton;
        }

        void set_data(int value) { data = value; }
        int get_data() { return data; }
    private:
        Singleton() : data(0) {}
        ~Singleton() { delete this; }
        int data;    
};

What would be the difference?

Name of the pattern that pyunit uses to identify test cases and test methods

pyunit works by looking for classes subclassing unittest.TestCase and methods starting with the string test.

What is that pattern called? Is it a form for the decorator pattern? Discovery? Introspection? Enumeration?

I know other systems use similar as well. For example, I think JavaBeans uses a similar naming pattern for exposing what they can do, rather than having to explicitly call a method for a list of stuff.

How to validate POJOs that extend antoher POJO

this is more a theoretical question than technical.I am wondering what is the best way to implement some method(or methods ?) to work on different POJOs that extend the same POJO. In the sample app that I created I want to validate with jakarta some POJO. Here you can find the complete sample app zoo repo, anyway i will describe the main feature here.

I am focusing on a SpringBoot app.

I have a rest controller that accepts as input a List:


@RestController
@RequestMapping(value = "/api/v1", produces = MediaType.APPLICATION_JSON_VALUE)
public class AnimalController {

        AnimalService service;
        
        @PostMapping("/validate")
        @ResponseStatus(value = HttpStatus.OK)
        public List<ValidationErrorDTO>  validateCollection(@RequestBody List<AnimalDTO> request)
                                                        {
            return service.validateCollection(request);
        }
        
        
        public AnimalController(AnimalService service) {
            super();
            this.service = service;
        }
        
        
}

In the AnimalDTO class i added some jakarta annotation on the properties and in the method implementation of the service I get the errors:

@Component
public class AnimalServiceImpl implements AnimalService{

    
    
    @Override
    public List<ValidationErrorDTO> validateCollection(List<AnimalDTO> collection) {
        
        List<ValidationErrorDTO> validationErrorList = new ArrayList<>();
        //instantiate the validator
        ValidatorFactory factory = Validation.buildDefaultValidatorFactory();
        Validator validator = factory.getValidator();
        
        //for every record of the collection, validate the record and add errors to the error list
        for(int i= 0; i<collection.size();i++) {

            int k =i;
            //get single record errors
            Set<ConstraintViolation<AnimalDTO>> violations = validator.validate(collection.get(i));

            violations.forEach(v -> validationErrorList.add(new ValidationErrorDTO(k, v.getPropertyPath().toString(), v.getMessage())));
        }
        
        return validationErrorList;
    }

}

Now, I have two POJOs DogDTO and CatDTO that extend AnimalDTO and i would like to reuse the same method, or anyway apply the best pattern in this scenario, to validate the input list.

What are my options?

I did not to try any coding since this is not a tech issue but I am convinced i'm missing something. Maybe I am overthinking and the best way is just to use another method?

vendredi 15 septembre 2023

How do you approach OO Design and OO Programming with GameObject and Components in UPBGE?

How do you approach OOD with GameObject and Components?

I’m trying to better understand things in a deeper sense. I usually have something like:

class Player(KX_GameObject)

and then I have several

class Movement(KX_PythonComponent)
class UI(KX_PythonComponent)
class Animations(KX_PythonComponent)

Is this a sound way of doing it? I feel like I’ve been learning a ton about OOD, OOA, OOP and I’m struggling to implement it in my code using Components and GameObjects and Properties inside of UPBGE.

I want to better understand the relationship between a GameObject and a PythonComponent. When I create a Cube and create a KX_GameObject with it and also a KX_PythonComponent. I notice that the KX_GameObject has access to the Component class through a self.components list. Giving you access to all the attributes and methods inside your Component Classes associated with that same object in your scene.

I also just realized that in the Game Object there is no self.object like in the Component Classes. But in KX_GameObject self is the object. And something cool is all the methods I create inside of my KX_GameObject class are passed down to my Component classes like Inheritance.

I want to design a game using sound design and OO principles. Does anyone have any experience with this especially using the classes that are special and not exactly "classes" like in any other python program. (I mean Player(KX_GameObject) and Movement(KX_PythonComponent) both don't have an init() method but they have a start() that act's like an init(), they also have to have a update() method that is called every frame.

Should I be using a service method (which relies on an observable) to do calculations in a component?

This is a pattern I frequently find myself in and I'm not sure why or what the right way to achieve my goals is.

I need a number value which many calculations are dependent upon, but this value needs to be retrieved from an observable.

I'm using a get method in the service that my component can call upon, but I always struggle to find the correct pattern to achieve this.

My service method:

getMarketCap(company: Company): number {
    combineLatest([
      this.getPrevDayClose(company.ticker),
      this.getCurrDayLastPrice(company.ticker),
      this.getWsLastPrice(company.ticker)
    ]).pipe(
      tap(([prevDayClose, currDayLastPrice, wsLastPrice]) => {
        if (wsLastPrice) {
          this.price = wsLastPrice;
        } else if (currDayLastPrice) {
          this.price = currDayLastPrice;
        } else {
          this.price = prevDayClose;
        }

        return this.price * this.getSharesOutstanding(company);
      })
    );
  }

This won't work because the return which includes the value I want is inside the tap.

My component is a list of companies and I simply call this.service.getMarketCap(company) in ngOnInit() for each one. Is there a simple way to get the value of this.price out of there after being set, so it can be consumed by other calculation methods in the service?

I've done something like this before with component methods, but I was able to set a variable at the component-level since it was only ever setting for one company at a time.

Is the service the wrong place for this logic?

jeudi 14 septembre 2023

Name for technique of running two versions of code to ensure they are compatible?

I am looking for a name to call this pattern that I have seen when maintaining legacy codebases.

Short version:

Run two versions of a function side-by-side, to ensure that changes to the new version remain compatible with the old version.


Question: Is there a well-known name for this pattern?


Long version:

  • We need to change the internal implementation of some server function foo. For example, this could be for better performance, or to connect to a different database.
  • We must not change what the function returns i.e. the function still does the same job, but with some change to how it is implemented.
  • The function is in a production server environment, and must remain available at all times.
  • There are no dev environments, unit tests, or well-defined requirements, and creating them is well outside of our budget.
  • The change is simple enough that it is within our budget.

(I acknowledge that in this situation, many best practices have been overlooked. The pattern I describe is a pragmatic solution.)

So we do these steps:

  1. Make two copies of foo, call them foo_v1 and foo_v2.
  2. Change foo so that it calls both foo_v1 and foo_v2, and returns the result of foo_v1. From the outside, the only change is that it got slower, due to running 2 versions.
  3. Change foo so that it compares the results of foo_v1 and foo_v2. If they are different, this is logged.
  4. Change foo_v2 to do whatever the new requirement is, e.g. a performance improvement.
  5. Because we are comparing the results of running both functions with real data, we can be confident that both versions do the same thing.
  6. After some time has passed without detecting any differences, we copy the implementation of foo_v2 into foo, and then delete foo_v1 and foo_v2.

The key is that at all times the results come from a version of the function that we know is good.

I have used this pattern on a small scale when optimizing PHP functions which were making too many SQL queries. This Stripe blog post describes a large project with some similarities. They used a Ruby library named Scientist.

Is it up to the caller or called to ensure to make sure the arguments exist?

This question should be language agnostic, but for simplicity, I will provide an example in python.

Suppose that I have a pandas dataframe with some columns and I have a getter that gets one of the columns:

def get_dataframe_column(dataframe, column_name):
  # should I check that the column exists here

I'm wondering what is best practice. Should the get_data_column function itself check to make sure the column exists, or should the caller know what they're doing and make sure they're using it correctly?

I feel like when it comes to python, they have more error checking than a language like C++, so maybe the question does become language dependent?

C++ refactor common method/logic without polluting interface

  • I have an interface:
class FooInterface {
  virtual void Method1(bool method) = 0;
};
  • I have multiple derived classes which implement this interface which all have common logic/method [Method1]:
class BarClass1 : FooInterface {
  void Method1(bool method) final {
    if (method) {
      Method2();
    } else {
      Method3();
    }
  }
    void Method2() {// BarClass1 logic};
    void Method3() {// BarClass1 logic};
};

class BarClass2 : FooInterface {
  void Method1(bool method) final {
    if (method) {
      Method2();
    } else {
      Method3();
    }
  }
  void Method2() {// BarClass2 logic};
  void Method3() {// BarClass2 logic};
};
  • I want to refactor out the common logic without polluting my interface.

Does it make sense to move the common logic into a AbstractClass or is there a more optimal design pattern?

class FooAbstractClass : FooInterface {
  void Method1(bool method) final {
    if (method) {
      Method2();
    } else {
      Method3();
    }
  }

  virtual void Method2() = 0;
  virtual void Method3() = 0;
};

class BarClass1 : FooAbstractClass {
    void Method2() final {// BarClass1 logic};
    void Method3() final {// BarClass1 logic};
};

class BarClass2 : FooAbstractClass {
    void Method2() final {// BarClass2 logic};
    void Method3() final {// BarClass2 logic};
};

Intended usage:

BarClass1 bar1;
bar1.Method1(true);

BarClass2 bar2;
bar2.Method1(false);

Embedded C++: how to develop a good structure for programs [closed]

I am writing some embedded C++ code. Currently I only interface with a uart, some leds and some general IO.

My question comes here, what's the best way to structure the code?

My current approach: Each peripheral has a separate source, header and class. Then all the classes are instantiated in a class called Env.

// main.cc
int main()
{   
    Env env;
    
    while(1)
    {
        env.leds.allOn();
        util::counter(100000);
        
        env.leds.allOff();
        util::counter(100000);
    }
}

Then within the environment the rest is instantiated.

// Env.h
class Env 
{
public:
    Env();
    ~Env();
    
    UartPC pc;
    DebugLeds leds{&pc};
    GenIo gio{&pc};
    
private:
    
};

I got to this point where I am constantly passing a reference to the uart to the rest of the classes (this is because the classes will print some "Init successful" message).

Is this good/bad practice? Is there a good book / webpage describing how to structure code?

Thanks.

mercredi 13 septembre 2023

Single-Machine Distributed Graph Processing EDU: Use Existing Storage or Implement Custom Solution?

I need to design and implement a distributed system for graph processing for edu purposes. The primary objective is to develop distributed algorithms for traversing graphs and collecting information from them.

I'm facing a challenge in selecting the right level of granularity for the implementation. I have only one machine, and I need to simulate process failures as node failures in a distributed system. Additionally, I need to somehow simulate the distributed placement of data on a single disk.

Two questions arise:
  • How should I implement distributed processing? Would it be better to use an existing storage solution and build a layer on top of it using its API, or should I implement my own simple storage system to showcase my methods?

  • If I choose to implement my own simple storage system, how can I simulate that the data is located on different nodes (in my context, processes, as it's on a single machine)?

create a pattern program in that you create box and middle value of box is empty [closed]

I want to below pattern program without using third loop in javascript.

1
2 2
2 2
3 3 3
3 _ 3
3 3 3
4 4 4 4
4 _ _ 4
4 _ _ 4
4 4 4 4
5 5 5 5 5
5 _ _ _ 5
5 _ _ _ 5
5 _ _ _ 5
5 5 5 5 5

Note:underscore represent empty place here.

Please help me to find out this problem solution and Thank in Advance.

I tried 2D Array and store the result 2D array but it doesn't work for me.

mardi 12 septembre 2023

How can polymorphism be achieved in data-oriented design without the use of OO? [closed]

I'm trying to bridge the gap between the OO and FP paradigms, and I'm looking into data-oriented design. I've found that there aren't many agreed-upon best practices or architectural patterns that I can just lift from.

One common problem in the C++ domain is trying to do polymorphic extension. This can be done very easily in OO using virtual methods and inheritance.

What would be a suitable, equivalent pattern to use in the data-oriented design paradigm?

Angular related Architectural decision

Architectural decision

I am currently developing an Angular application and facing a crucial architectural decision. To provide you with more context, let's consider that I have three main components: "education," "education-item," and "education-form."

enter image description here

Architectural components

Education-Form

The "education-form" component is responsible for gathering all the necessary information related to a user's education record. This component is triggered when a user clicks the "Add Education Record" button within the "education" component.

Education-Item

The "education-item" component represents an individual education record. It features two buttons for editing and removing education records.

Education

The "education" component serves as the page where all education items are displayed and includes an "Add" button, which reveals the "education-form" component for adding a new education record.

Upon analyzing these three components, it becomes evident that they all require access to a list of education records. This list is essentially the central element that undergoes continuous modification throughout the application's operation.

Component Roles / Usage
education-form adds education records to the list
education-item edits or removes elements from the list
education displays the list using the "education-item"

Services

Education-Service

The "educationService" will manage this list of education records. This service provides methods for adding, updating, deleting, and retrieving records and is injected into all three components. Note that this data is persisted in the backend.

Api-Education-Service

The "api-education-service" is responsible for the communication with the backend and provides methods for creating, updating, deleting, and listing education records. This service is injected into the "educationService". An example of his usage is the "add" method of the "educationService", this adds a record to the list in "educationService" and calls the "create" method of the "api-education-service".

Is this design proposal of an Angular based application future-proof, or do you see any side effects, problems or improvement that could be added ?

I will be happy to discuss it with you guys. Thanks for sharing your thoughts!!!

MVC - How to display POST data back into an edit view if errored?

I would like to know the best way in MVC to correctly organise the code when a user tries to update a record from an edit view, but it's errored and we want to display the POST data in the form so they can correct and re-submit.

Example:

  1. User clicks on a 'book' record (/book/123) which calls BookController->edit($id). This fetches the record and sends it's data to the view which displays a form for the user to update the details.
  2. User makes changes to the form details and hits submit. This calls BookController->update(). which validates the POST data. In this case, the user has created a validation error.
  3. User should then be re-presented with the edit form, on the same edit URL (/book/123) with the errors displayed as well as the POST data populating the form fields instead of the record's saved details.

In the past, I've used BookController->edit($id) to be responsible for both displaying edit form as well as handling the update POST. I'd usually do this by checking if POST data had been passed and if so, trigger the validation and updating.

But, I wonder if this is the best way or if there is a more correct/accepted way which ensures the user stays on the edit page with the POST data when they save. With an error/success message as required.

Thanks!

Editing or moving site-packages in django

In django ive installed the django-two-factor-auth package through my virtual environment, and it is installed in /env/Lib/site-packages/. What is best practice of editing such a package? If for example i want to edit the urls (or the views)? Do i move or copy the packages from the env/ into my django project as an app? My existing project setup is:

  • /env/
  • /project/
    -/app1/
    -/app2/

As im quite new to django, im looking for best practices before i start making my own judgements.

As my /env/ is not tracked by git, i cant imagine i should be editing the package directly within. I tried copying the entire django-two-factor-auth package into my project, but im not sure how to register it correct in settings.py (im also wary of having a copy of the same library in both /env/ and /project/).

lundi 11 septembre 2023

How do I refactor this code with if/else for Update/Delete event and the class is injected using Guice

I'm trying to refactor one of the classes we have which is very long. The class is a listener which has only two events Update and Delete. We started with just this

public class DocumentListener implements Listener
{
    @Inject
    public DocumentListener(// a bunch of injected parameters) {

    }

    public void receive(Event event)
    {
        Phase phaseWhenReceived = phase_;
        if (event instanceof UpdateEvent) {
            // do update
        } else if (event instanceof EntityDeleteEvent) {
            // do delete
        } else if (event instanceof PhaseEvent) {
            // do nothing for now.
        } else {
            LOGGER.warn("Received unknown event type : " + event.getClass().getName());
        }
    }
}

The class grew to be over 2000 lines long which naturally we want to have two classes; Update and Delete. However, the class is binded with Guice like this.

bind(DocumentListener.class).in(SINGLETON);

I started changing the class to be abstract class and then created Update and Delete classes to extract the behaviors.

But if I do this

public abstract DocumentListener implements Listener
{
    public DocumentListener(// a bunch of injected parameters) {

    }

    public abstract void receive(Event event);

}

Then I created Update

public class DocumentUpdate extends DocumentListener
{
    // injected constructor

    @Override
    public void receive(Event event)
    {
    }
}

And

public class DocumentDelete extends DocumentListener
{
    // injected constructor

    @Override
    public void receive(Event event)
    {
    }
}

Then Guice will complain with 1) [Guice/MissingImplementation]: because now the DocumentListener is an abstract class which it doesn't know how to bind.

I could do something like this

bind(DocumentListener.class).to(DocumentUpdate.class).in(SINGLETON);

But then I can only bind one class at a time. I can't bind two implementations as Guice will complain that the class is already binded and I can't bind twice.

Not sure if there's a pattern to solve this kind of problem with Guice and Listener pattern?

What pattern should I use for a CLI application consisting of multiple components?

I am building an CLI application which is composed of separate components that are not directly connected to each other, but the proceeding component uses the output of the previous one. The components need to run in order. What would be a suitable structure for this application or a design pattern that would help on this regard? Thank you!

C# - Global factory class to create and return instances

Is it a good design to have a global factory class in my C# application which is able to create every relevant class instance? So when the application is running and someone asks for class A it will be created on first call and just returned on all following calls. Then I have easy access to everything, everywhere the factory is accessible. On the other hand you often have access to instances you dont need which may be bad.

dimanche 10 septembre 2023

Can I call Swift URL Session from Kotlin Multiplatform?

I am working on an architecture where View is in Swift, VM in swift, however want to get the repository in Kotlin multiplatform. Similiar to this

I understand immediate question would be why you want to separate network layer as KMM can handle this?. I don't want to loose the nativeness of network operations. Is it possible?

How to create a Java Program which is like a client server

I am currently trying to connect my application to a front-end web application, our lecturer didn't explain how we should do it but it's due tonight. We had to use various Design Patterns in order to code namely the Domain, Factory, Repository, Services and Controller.

The first project has the backend, and everything functions correctly and is completed, the second must have the Domain and Factory along with the connectivity and the Views which we're deploying through a web-based application, I have not started with this just yet.

The issue that I have not done this before and don't know how to have the two projects communicate with one another along with how to implement a framework.

Does anybody know how we can make this connectivity between the two projects? And also ideas on what may be the better framework to use?

Currently I have not tried much as I have been struggling with where to get started.

What is a good pattern for implementing attacks for a tile based game?

I write a FF Tactics Advance like game. For those unfamiliar it's a tilebased game. I'm at the point where I need to implement the attack, which I would like to do as generic as possible, but I can't think of a good pattern/way. Some problems are:

Reachable tiles:

Normal attacks can reach one in every direction and bows can reach ~5 tiles (which could be generalised), but polearms can reach two in a stright line. Also Bows also only need line of sight to the target, but for normal attacks the target can not have too much of a hight differens and for the polearm the tile between the attacker and the target can be alot lower but not higher (even if there is line of sight). (Also there might be completly different areas for enemies)

Valid Targets:

Normal attacks would need living characters as targets, necromancy would need dead characters and AOE attacks should also be aimeable at empty tiles.

What is a good pattern for implementing attacks for a tile based game?

Zeromq 1 to 1 async req-rep unreliable pattern

I have a 1 client to 1 server model, let's say the client will emit 100 req/s, but the server can only handle 50 req/s.
The client side is very tolerant. It says okay, I don't care about you dropping some of my requests, just process the latest one. What pattern should be applied in this situation?

Timeline ('<' denotes the server is processing the latest requests):
client: 1 -- 2 -- 3 -- 4 -- 5 -- 6 -- 7 -- 8 -- 9 -- 10
server:  <<<<<<<<<< 1 <<<<<<< 3 <<<<<<<<<<<< 5 <<<<<<< (processing 8)    

samedi 9 septembre 2023

Triangle Digit ouput [closed]

I am currently trying to make a method that displays a triangle or pyramid. This special triangle counts the frequency of each number in the previous row. the method takes two inputs but has no parameters since I am creating a "pyramid" object. I have attached an example of the correct output. My current method has the correct digit combination but I am not able to space each digit and make it into a pyramid shape. enter image description here. I apologize for any formatting mistakes or any other issues. This is my first post on stack overflow. The desired output is enter image description here

here is my code so far and I have attached an image of my output: an image of my code:

  public void printpyramid() 
  {

   String ndig= String.valueOf(digit);
   String cdig="";
   int runl=1;

   int cumuldigits=0;
   while(runl<=numrows){
      cumuldigits=0;
   
      System.out.println(ndig + "");

    for(int index =0; index<10;index++)
     {
         if(ndig.charAt(i)==(char)(index+'0'))
         {   
         digcounter[index]=digcounter[index]+1;
          }
     }
  }
    for(int index =0; index<10;index++)
     {
       if(digcounter[index]>0)
        {
        cdig = cdig + String.valueOf(digcounter[index]) + 
        String.valueOf(index);
        cumuldigits++;
        }
      }
  if(cumuldigits>=10)
  {
    break;
   }
  if(cdig.equals(ndig))
  {
   System.out.println(ndig);
  break;
  }
  runl++; 
  ndig=cdig;
  cdig="";
}
 }

vendredi 8 septembre 2023

Domain-Driven Design: How to Handle External Payment Gateway in Domain Layer?

I'm designing a payment system that uses different gateways. I'm facing an architectural challenge when trying to adhere strictly to Domain-Driven Design principles:

I need to create a payment intent on the external gateway first. Then, I want to create my internal PaymentIntent, which will contain the external gateway's payment intent as a child entity. Before creating an external gateway payment intent, I have specific domain rules that need to be checked.

My dilemma:

Injecting Services into Entities: If I were to check these rules inside the entity, I'd need to inject the gateway service into the domain entity, which violates the principle of model purity.

Always-Valid Domain Model: If I first create the PaymentIntent and then set the external gateway payment intent, I violate the always-valid domain model principle.

Domain Logic in Service: Currently, I'm checking these rules in a domain service. However, I'm concerned this approach leaks domain logic. Here's a simplified version of my code:

export class PaymentIntentService {
  async create({
    marketplaceId, gateway, customerId, amount, 
    paymentMethodType, paymentSplitsData,
  }: CreatePaymentIntentParams) {
    checkRules(
      new TotalPaymentSplitsEqualsIntentAmountRule(amount, paymentSplitsData),
      new PaymentSplitReceiversMustBeUniqueRule(paymentSplitsData),
    );

    const externalGatewayPaymentIntent = await this.gatewayService.createPaymentIntent({
      amount, paymentMethodType, gatewayCustomerId,
    });

    const paymentIntent = PaymentIntent.create({
      paymentSplitsData, marketplaceId, customerId, amount,
      paymentMethodType, gateway, businessEntityId: '', 
      gatewayPaymentIntent: externalGatewayPaymentIntent,
    });

    await this.paymentIntentRepository.create(paymentIntent);
    return paymentIntent;
  }
}

How should I structure this to best adhere to DDD principles while ensuring proper domain logic encapsulation and always-valid state?

Suggestion needed to remove duplicate class, without changing #define depends on that class static object

There is a duplicate class implementation in two projects, which are using C++. When i tried to merge the minor differences of both into a single class, i faced a blocker as the #define's in the class are having direct dependency on static object which is created out of this class on both projects as shown below.

From Project1

enum severity_type
{
    debug = 1,
    error,
    warning
};


template< typename T >
class logger
{
public:
    logger(const std::string& name);

};

#define LOGGING_LEVEL_1
static logger< file_log_policy > log_inst(GetAppDataPath()+ "\\Logs\\backup.log");
#ifdef LOGGING_LEVEL_1
#define LOG log_inst.print< severity_type::debug >
#define LOG_ERR log_inst.print< severity_type::error >
#define LOG_WARN log_inst.print< severity_type::warning >
#else
#define LOG(...) 
#define LOG_ERR(...)
#define LOG_WARN(...)
#endif

#ifdef LOGGING_LEVEL_2
#define ELOG log_inst.print< severity_type::debug >
#define ELOG_ERR log_inst.print< severity_type::error >
#define ELOG_WARN log_inst.print< severity_type::warning >
#else
#define ELOG(...) 
#define ELOG_ERR(...)
#define ELOG_WARN(...)
#endif

From Project 2

enum severity_type
{
    debug = 1,
    error,
    warning
};


template< typename T >
class logger
{
public:
    logger(const std::string& name);

};

#define LOGGING_LEVEL_1
static logger< file_log_policy > log_inst(GetAppDataPath()+ "\\Logs\\restore.log");
#ifdef LOGGING_LEVEL_1
#define LOG log_inst.print< severity_type::debug >
#define LOG_ERR log_inst.print< severity_type::error >
#define LOG_WARN log_inst.print< severity_type::warning >
#else
#define LOG(...) 
#define LOG_ERR(...)
#define LOG_WARN(...)
#endif

#ifdef LOGGING_LEVEL_2
#define ELOG log_inst.print< severity_type::debug >
#define ELOG_ERR log_inst.print< severity_type::error >
#define ELOG_WARN log_inst.print< severity_type::warning >
#else
#define ELOG(...) 
#define ELOG_ERR(...)
#define ELOG_WARN(...)
#endif

Here, you can observe as we have two static objects from two projects.

I want to have these static objects while the program is running. But the major bottle neck while i try to merge these files are the #define's from Project 1

#define LOGGING_LEVEL_1
static logger< file_log_policy > log_inst(GetAppDataPath()+ "\\Logs\\backup.log");
#ifdef LOGGING_LEVEL_1
#define LOG log_inst.print< severity_type::debug >
#define LOG_ERR log_inst.print< severity_type::error >
#define LOG_WARN log_inst.print< severity_type::warning >
#else
#define LOG(...) 
#define LOG_ERR(...)
#define LOG_WARN(...)
#endif

and project2

#define LOGGING_LEVEL_1
static logger< file_log_policy > log_inst(GetAppDataPath()+ "\\Logs\\restore.log");
#ifdef LOGGING_LEVEL_1
#define LOG log_inst.print< severity_type::debug >
#define LOG_ERR log_inst.print< severity_type::error >
#define LOG_WARN log_inst.print< severity_type::warning >
#else
#define LOG(...) 
#define LOG_ERR(...)
#define LOG_WARN(...)
#endif

these #define's like LOG, LOG_ERR are used in thousands of places in code. can you suggest a better approach here, without modifying the #define's where i can merge these classes and use a single class for both projects.

i want the #define's to be unchanged and the duplicate classes to be merged into one, and the static objects should also exist.

Can someone suggest a better approach where i can refactor this code without touching #define's

jeudi 7 septembre 2023

Query about using Benchmark test singleton design pattern

local variable increases performance by 25 percent - Joshua Bloch "Effective Java, Second Edition", p. 283-284

I'm new to benchmark test, and i want to do a test for DoubleCheckLockingSingleton. But the result seems like the performance of DoubleCheckLockingSingletonWithoutLocalVar is better?

I'm using https://github.com/openjdk/jmh

The benchmark result:

# JMH version: 1.33
# VM version: JDK 17.0.6, OpenJDK 64-Bit Server VM, 17.0.6+10-b829.9
# VM invoker: /home/repo/idea-IU-231.9011.34/jbr/bin/java
# VM options: -javaagent:/home/repo/idea-IU-231.9011.34/lib/idea_rt.jar=46469:/home/repo/idea-IU-231.9011.34/bin -Dfile.encoding=UTF-8
# Blackhole mode: full + dont-inline hint (default, use -Djmh.blackhole.autoDetect=true to auto-detect)
# Warmup: 5 iterations, 10 s each
# Measurement: 5 iterations, 10 s each
# Timeout: 10 min per iteration
# Threads: 10 threads, will synchronize iterations
# Benchmark mode: Throughput, ops/time
# Benchmark: org.example.MyBenchmarkTest.measureWithLocalVar

Benchmark                                Mode  Cnt           Score           Error  Units
MyBenchmarkTest.measureWithLocalVar     thrpt    5    14543289.188 ±   1754652.871  ops/s
MyBenchmarkTest.measureWithoutLocalVar  thrpt    5  2238795119.169 ± 942222432.066  ops/s

MyBenchmarkTest file

@State(Scope.Benchmark)
@BenchmarkMode(Mode.Throughput)
public class MyBenchmarkTest {
    @Benchmark
    @Threads(10)
    public DoubleCheckLockingSingleton measureWithLocalVar() {
        return  DoubleCheckLockingSingleton.getInstance();
    }

    @Benchmark
    @Threads(10)
    public DoubleCheckLockingSingletonWithoutLocalVar measureWithoutLocalVar() {
        return DoubleCheckLockingSingletonWithoutLocalVar.getInstance();
    }

    public static void main(String[] args) throws RunnerException {
        Options options = new OptionsBuilder()
                .include(MyBenchmarkTest.class.getSimpleName())
                .forks(1)
                .build();

        new Runner(options).run();
    }
 }

DoubleCheckLocking file

public class DoubleCheckLockingSingleton {
   
    private static volatile DoubleCheckLockingSingleton instance = null;

    public static DoubleCheckLockingSingleton getInstance(){
        DoubleCheckLockingSingleton result = instance;

        if(result ==null){
            synchronized (DoubleCheckLockingSingleton.class){
                result = instance;
                if(result==null){
                    result = new DoubleCheckLockingSingleton();
                }
            }
        }
        return result;
    }
}

public class DoubleCheckLockingSingletonWithoutLocalVar {

    private static volatile DoubleCheckLockingSingletonWithoutLocalVar instance = null;

    public static DoubleCheckLockingSingletonWithoutLocalVar getInstance(){
        if(instance ==null){
            synchronized (DoubleCheckLockingSingletonWithoutLocalVar.class){
                if(instance==null){
                    instance = new DoubleCheckLockingSingletonWithoutLocalVar();
                }
            }
        }
        return instance;
    }
}

Can somebody give me a hand? thanks!

mercredi 6 septembre 2023

React: ternary operator or if statement. What is the best approach

Good day. I am sicking wisdom here. I have a tiny example in react code that can be written in two ways:

FetchComponent = ({ url }) => {
  const { loading, data } = useFetch(url);
  if (loading) {
    return <div>Loading...</div>;
  }
  return <div>{JSON.stringify(data)}</div>;
};

or in this way:

const FetchComponent = ({ url }) => {
  const { loading, data } = useFetch(url);
  return (
    <>{loading ? <div>Loading...</div> : <div>{JSON.stringify(data)}</div>}</>
  );
};

As you can see one is using if statement and the other one is using a ternary operator.

So, reaching this point, because we can achieve the same both ways, I wonder what is the better approach, or the react approach or the way of a senior placing the logic in this component example?

Enum and type table design

Let's say you have a type table with types red 1, blue 2, and green 3.

In my application when I populate a pulldown with those options I cache that type table as a hashmap.

If I need to take some action when the selection is 1(red) or 2(blue) I would normally create an enum and reference that enum for specific values. Which has the downside of needing to make sure that the enum stays in synch with the type table but it's a simple and clean solution.

I saw someone try to get around this by adding columns to the type table to allow filtering of types. So it's like there are types of types. For this example the type table would have an additional column that marks which types are primary colors. This legacy code pulls these subsets of the type table and then compares the selected values against the subset.

It's also kind of weird because in the legacy code they call out to the database to build that filtered group from the enum and save it as a string to the struts 1 form (yes, it's old) and then they parse that string in javascript to use it on the front end.

I'm inclined to rip out the old code and do it how I've always done it but I don't want to discount the previous efforts if they were on to something and I'm just not getting it.

So any opinions out there on if there's a best practice to follow in a situation like this? Is there something I'm missing?

Edit: For a little context I should specify that these are not frequently changed types. We might add a type once every 5-10 years.

Architecture of the game when i have 2 different game modes

I have a game(bullet hell kind of game) already built where each attack has some out of many variables i.e speed, count, location, movementType. Now I want to add another mode a multiplayer mode.

In this mode there will be a UI scene where a player can cutomize his/her attack queue and send it to the opponent and the opponent will play against that _attackqueue.

The way I envisage the things is that the player will have many attacks to chose from and sliders to modify the value of the variables speed, count etc to increase or decrease the difficulty of the attacks.

Currently i have a scriptable object for each of the attribute speed, count etc. The attack script reads the value and then GameManager plays the level. Now I will have to modify the values in the Multiplayer Scene and when i go back to the game scene it should be set back to default as the moidifiable attacks are only available for multiplayer.

Moreover, I might even need to save the created queue with all the attacks and their modified values as it will be a pain for the player to create the customized queue again and again.

I need some advice as to how i can approach this problem. Sample Scriptable object code Sample Prefab

public class SpeedData : ScriptableObject
{
    public float defaultSpeed = 10f;
    public float multiplayerSpeed = 15f; 

    // Method to get the current speed based on the game mode
    public float GetCurrentSpeed(GameMode gameMode)
    {
        switch (gameMode)
        {
            case GameMode.Multiplayer:
                return multiplayerSpeed;
            default:
                return defaultSpeed;
        }
    }
}

I was thinking something on lines of this. _gameMode could be a static variable or a scriptableObject. I don't know, a bit confused. Need some advice. Thank you.

mardi 5 septembre 2023

How to design a dynamic gamification microservice in django

I want to implement a gamification microservice with Django that works alongside other microservices.

In this microservice, I want to have points, ranks, coins, badges and credit cards for each user.

Points: A number that is earned based on the user’s activity and this activity is not limited to purchase operations and can be earned by performing any kind of activity. Uses of points include increasing rank, buying discount codes and increasing lottery chances.

Rank: For example, you can have 5 ranks for users and rank them based on the total points they have earned so far. The ranks can be named from “Newcomer” to “Professional” level. Special benefits are provided for each rank, which may include discounts, various notifications, coefficient in getting rewards, etc.

Coins: Only earned for financial transactions. The higher the transaction amount, the more coins the user earns. You can get benefits other than discount codes through coins.

Badge: They are awarded to a person for repeating a specific activity. Having badges gives the user special advantages.

Credit card: A type of credit for in-app and out-of-app purchases. For example, you can buy a credit card for a specific product with a credit of $100 for $80. In this way, the user gets a 20% discount.

I want everything in this microservice to be dynamic. The benefits that the user gets, the rules that increase the points or the rank or the badge, or the way of converting one feature to another, should be dynamic and if these things need to change, less code should change.

I want you to guide me in designing this microservice. How should I implement the models so that the development of this microservice is easier in the future, the code readability is higher, and the SOLID principles are followed in it? Or if these explanations are ambiguous, guide me in finding these ambiguities.

Pattern Recognition And Application

Dimensionality reduction aims at: I. Project feature vector to a lower dimension II. Features in the projected space are orthogonal or uncorrelated a) Only I b) Only II c) Neither I nor II d) Both I and II

Could you please provide me with the correct answer?

What's the difference between Anti-Corruption Layer and Adapters?

Even thought there was a good answer here: https://softwareengineering.stackexchange.com/questions/184464/what-is-an-anti-corruption-layer-and-how-is-it-used, the explanaition is still a bit confusing me. I do not see any huge differences between Anti-Corruption layer and Adapters and the only difference that I see is the difference in the definitions that Anti Corruption Layer is a kind of wrapper that allows you to isolate your domain from the corruption of someone else's domain. But in another article, the Anti Corruption Layer is generally acting as Adapter: https://medium.com/solutions-architecture-patterns/anti-corruption-layer-pattern-bd75e1f2be7f

Let's take an example. I have a library that allows me to query MongoDB from code, developed by the official MongoDB developers for my programming language. I also have a user domain model (let's name it User). The User has a unique UserID, which must match the ID in MongoDB. The library for MongoDB uses the primitive.ObjectID type for identifiers. Because I don't want to refer to the types for the database from the domain model, I create a separate type Identifier, which, in fact, is a regular string. Thus, in the domain model, UserID will be of type Identifier, and primitive.ObjectID itself will be converted to Identifier during mapping by conversion to a string. Question: in this case, is Identifier an anti-corruption layer? Do you have any examples that can most accurately show me the difference between the anti-corruption layer and the adapter pattern?

I have read the following articles: https://learn.microsoft.com/en-us/azure/architecture/patterns/anti-corruption-layer https://medium.com/solutions-architecture-patterns/anti-corruption-layer-pattern-bd75e1f2be7f https://softwareengineering.stackexchange.com/questions/184464/what-is-an-anti-corruption-layer-and-how-is-it-used but none of them I find useful.

lundi 4 septembre 2023

Use IF or Polymorphism?

I have a question about Java. I've been working with Java for less than a year, and I'm starting to have interesting doubts about design patterns:

For example, I want to improve my code with Object-Oriented (OO) principles to make it cleaner, but it raised a question: won't I increase the processing time?

In the code below:

import java.util.ArrayList;
import java.util.List;


public class EscritorioContabilidade {
    
    //metodo para recuperar a informacao salarial utilizando os IF´s da pior maneira....rsrsr
    public double getSalarioFuncionario(String tipoFuncionario){
        double salario = -1;
        if("gerente".equals(tipoFuncionario)){
            salario = 1000;
        }
        else if("balconista".equals(tipoFuncionario)){
            salario = 900;
        }
        else if("faixineiro".equals(tipoFuncionario)){
            salario = 550;
        }
        return salario;
    }
    
    //metodo para recuperar a informacao salarial utilizando os IF´s. Nao melhoramos muito
    public double getSalarioFuncionario(Object funcionario){
        double salario = -1;
        if(funcionario instanceof Gerente){
            salario = 1000;
        }
        else if(funcionario instanceof Balconista){
            salario = 900;
        }
        else if(funcionario instanceof Faixineiro){
            salario = 550;
        }
        return salario;
    }
    
    //metodo para recuperar a informacao salarial utilizando polimorfismo. Agora sim!
    public double getSalarioFuncionario(Funcionario funcionario){
        return funcionario.informarSalario();
    }
    
    public static void main(String [] asdf){
        EscritorioContabilidade escritorioContabilidade = new EscritorioContabilidade();
        double folhaPagamento = 0;
        
        List<Funcionario> listaFuncionario = new ArrayList<Funcionario>();
        
        //adicionando os funcionarios 
        listaFuncionar
io.add(new Gerente());
        listaFuncionario.add(new Balconista());
        listaFuncionario.add(new Faixineiro());
        
        //usando o polimorfismo para determinar a folha de pagamento
        for (Funcionario funcionario : listaFuncionario) {
            folhaPagamento += escritorioContabilidade.getSalarioFuncionario(funcionario);
        }
        System.out.println("folha de pagamento: "+folhaPagamento);
        
        //agora vamos usar um dos metodos que utilizam os IFs e voces podem ver a clareza em ambos os trechos de codigo
        folhaPagamento = 0;
        folhaPagamento +=  escritorioContabilidade.getSalarioFuncionario("gerente");
        folhaPagamento +=  escritorioContabilidade.getSalarioFuncionario("balconista");
        folhaPagamento +=  escritorioContabilidade.getSalarioFuncionario("faixineiro");
        
        System.out.println("folha de pagamento: "+folhaPagamento);
    }
}


public abstract class Funcionario {
    public abstract double informarSalario();
}


public class Gerente extends Funcionario {

    @Override
    public double informarSalario() {
        return 1000;
    }

}

class Balconista extends Funcionario{

    @Override
    public double informarSalario() {
        return 900;
    }
    
}

class Faixineiro extends Funcionario{

    @Override
    public double informarSalario() {
        return 550;
    }
    
}

In this code, if I use polymorphism, my code certainly becomes more elegant. However, if I use if statements, wouldn't it have better performance because it doesn't create memory pointers and such?

I hope to clarify a question about Java and design patterns.