samedi 11 juin 2022

How to design User class

Suppose I have a requirement where I have to deal with users accessing my website. There can be two kinds of users an Admin and Normal user.

  1. Single user class that will be inherited by two child classes Admin and Normal. If so how to do this properly with JPA.
@Getter
@Setter
@Entity
@Inheritance
public class User{
    private String name;
    private String userId;
}
@Data
@Entity
public class Admin extends User{
    private String adminId;
}
@Data
@Entity
public class Normal extends User{

}
  1. One and only one User class and which will have an attribute stating the role of that user.

Which will be the best design strategy and if we are looking towards inheritance should we persist those in a single table or multiple tables with a super table or should the parent not have a table and details should be persisted along with the sub tables using mapped super class.

Also if we shouldn't use inheritance then where should we probably use that and what should be the usecase and vice versa.

Is the UML/Design Pattern for my portfolio correct or how could it be improved (should?)?

First of all, I'm trying to create my web portfolio with Django and React to start as a Full Stack developer. I thought it would be a good idea to show already on my portfolio some of the things I can do (my portfolio would be ALREADY a fullstack project). So this is what I want to do: A web portfolio that is managed by me, with kind of a blog/comment functionality.

  1. I can add a project whenever I have sth new to display
  2. Those projects can be reviewd by users (who may or may not register to my site)
  3. Those projects can be liked only by registered users (I figured that might be simpler)
  4. Reviews can be answered by anyone

It doesn't need to be complicated, so if you think that might work, just say so BUT, if you notice ANY problem I might run into with this design, please let me know. I don't know much about UML, but I noticed it makes your life so much simpler to actually create the backend once you designed your tables.

The Tables shown on the graphic below will be represented by the Models on Django.

This is the UML that I came up with:

UML / Design/Pattern for my portfolio website

vendredi 10 juin 2022

How to print this pattern in C (for loop)

78910 456 23 1

How to print this program in C. in this pattern I can not insert numbers like this please help me.

Is there a common pattern to instantiate a library class as a singleton and have the library able to access that instance internally?

Say I have a library project which provides a class MyService.

I'd like clients to be able to instantiate MyService as a singleton and at the same time, I'd like the library to be able to access that singleton internally.

Now I can do the standard MyService.getInstance() sort of thing, but that doesn't lead to a very testable code if my library has MyService.getInstance() calls all over the place.

Perhaps any classes in the library that need an instance of MyService can take in MyService as a constructor parameter:

class MyTestableClass(val myService: MyService) {
    // Now this class can be unit tested with a mock/fake MyService
}

But at some higher level in the library I'm still going to have to pass MyService.getInstance() to this class.

Is there a standard pattern to accomplish this? Basically I want the client to be able to instantiate MyService as a singleton and also have the library able to access that instance internally, while having the ability to swap out the singleton instance with a mock/fake for unit testing.

How to structure laravel projects properly?

Recently started working with laravel and have a hard time structuring my project related to the current feature I'm working on.

Basically there exists a Subscription model that contains info about a subscription and most notably contains an expiry date. The feature I'm working on is to automize subscription expiry reminders to "customers" and also auto renew if the customer has not unsubscribed.

The problem is that I'm not sure how to structure the logic for this properly. Currently I have created a class called SubscriptionManager that has 2 functions. notifyExpiring($subscription) and renewExpired($subscription).

These functions require logic based on the subscription. For example: a customer should only be notified by email if the sub is 2 months from expiring. Where should this function be?

Currently I have it as a static function in class SubscriptionHelper called isExpiring($subscription).

As i've understood, logic in a Model class is a no go and I 'm not sure if a Service class is something for this.

Thanks in advance

mercredi 8 juin 2022

Is it okay to pass an endpoint string to a repository?

I have a question regarding the repository design pattern. Let's say I have a datatype Foo. In several places in my application, I must fetch a list of Foo from a remote database. For example, let's say I need to fetch a list of trending Foos and somewhere else a list of the most recent Foos. In my mind I have two options:

  • I could define two repository classes, one called TrendingFoosRepository which fetches from /foos/trending and another called RecentFoosRepository which fetches from /foos/recent.
  • However, since TrendingFoosRepository and RecentFoosRepository do exactly the same thing just at different endpoints, I could define one repository class called FoosRepository which takes in an endpoint argument, and instantiate FoosRepository('/foos/trending') and FoosRepository('/foos/recents').

To me, the second option is more concise and reusable and is therefore preferable. However, something feels odd to me about passing in endpoints into a repository. Is this antipattern? If so, why and what is the alternative?

Rust: How to implement Command pattern with Dependent Components

Business Requirements

I need to deploy a handful of services to an server environment. The services have dependent relationships (directed acyclic graph). For example, ServiceB relies on ServiceA to be deployed first and then ServiceB needs to configure ServiceA (e.g. MyWebService is dependent on Nginx to be deployed beforehand for its reverse proxy needs)

Problem

Attempt #1

I tried to implement this with Command pattern, using Vec, trait objects similar to what Rust book described:

trait Service {
    fn deploy(&self){}
}

struct ServiceA {}
impl Service for ServiceA {}

struct ServiceB<'a> {
    dep: &'a ServiceA,
}
impl<'a> Service for ServiceB<'a> {}

struct Environment {
    services: Vec<Box<dyn Service>>
}
impl Environment {
    fn deploy(&self) {
        for service in &self.services {
            service.deploy();
        }
    }
}

fn main() {
    let service_a = Box::new(ServiceA {});
    let service_b = Box::new(ServiceB { dep: &service_a });
    let environment = Environment {
        services: vec!(service_a, service_b)
    };
    environment.deploy();
}

This results in compile errors:

error[E0597]: `service_a` does not live long enough
  --> src/main.rs:26:45
   |
26 |     let service_b = Box::new(ServiceB { dep: &service_a });
   |                                             ^^^^^^^^^ borrowed value does not live long enough
27 |     let environment = Environment {
28 |         services: vec!(service_a, service_b)
   |                                   -------- cast requires that `service_a` is borrowed for `'static`
...
31 | }
   | - `service_a` dropped here while still borrowed

error[E0505]: cannot move out of `service_a` because it is borrowed
  --> src/main.rs:28:24
   |
26 |     let service_b = Box::new(ServiceB { dep: &service_a });
   |                                              --------- borrow of `service_a` occurs here
27 |     let environment = Environment {
28 |         services: vec!(service_a, service_b)
   |                        ^^^^^^^^  -------- cast requires that `service_a` is borrowed for `'static`
   |                        |
   |                        move out of `service_a` occurs here

Attempt #2

I added Rc for shared ownership:

use std::rc::Rc;

trait Service {
    fn deploy(&self){}
}

struct ServiceA {}
impl Service for ServiceA {}

struct ServiceB<'a> {
    dep: &'a ServiceA,
}
impl<'a> Service for ServiceB<'a> {}

struct Environment {
    services: Vec<Rc<Box<dyn Service>>>
}
impl Environment {
    fn deploy(&self) {
        for service in &self.services {
            service.deploy();
        }
    }
}

fn main() {
    let service_a = Rc::new(Box::new(ServiceA {}));
    let service_b = Rc::new(Box::new(ServiceB { dep: &service_a }));
    let environment = Environment {
        services: vec!(Rc::clone(&service_a), Rc::clone(&service_b))
    };
    environment.deploy();
}

Now the errors become:

error[E0308]: mismatched types
  --> src/main.rs:30:34
   |
30 |         services: vec!(Rc::clone(&service_a), Rc::clone(&service_b))
   |                                  ^^^^^^^^^^ expected trait object `dyn Service`, found struct `ServiceA`
   |
   = note: expected reference `&Rc<Box<dyn Service>>`
              found reference `&Rc<Box<ServiceA>>`

error[E0308]: mismatched types
  --> src/main.rs:30:57
   |
30 |         services: vec!(Rc::clone(&service_a), Rc::clone(&service_b))
   |                                                         ^^^^^^^^^^ expected trait object `dyn Service`, found struct `ServiceB`
   |
   = note: expected reference `&Rc<Box<dyn Service>>`
              found reference `&Rc<Box<ServiceB<'_>>>`

Can you help shed some light on the errors? Thanks!