mardi 28 février 2023

How to filter a Laravel parent model and all its nested child models in one place based on user info?

Imagine I have these Models : User, Country, State, City, Library, and we know that they have nested relationships together. Country Model has many nested child Models that belong to it. I need to filter all the data from all the child Models of Country based on User's country of origin.

For example I have a User from US and I want to limit his access to only view and edit the information related to the US. Like in LibraryController I need to get all the libraries that belong to US.

I can implement the logic in every Model by filtering the data using whereHas ( and filter the result based on country relationship ) but I want to know is there a way to do this only in the Parent ( Country ) Model? This way a lot of redundant code will be avoided.

How to properly design register class in C++ accessing register bits by reference

I need to design a class which manages the CPU internal registers like CR0, CR2, the MSRs etc. in object oriented manner. The requirements are:

  • particular bits are declared as bitfields representing the register values. For instance:

     struct cr0 : public cpu_register<...> {
         using raw_type = uint32_t;
    
         uint8_t pe      : 1     { 0 };      /* bit0 - Protected Mode Enable */
         uint8_t mp      : 1     { 0 };      /* bit1 - Monitor co-processor */
         uint8_t em      : 1     { 0 };      /* bit2 - Emulation */
         uint8_t ts      : 1     { 0 };      /* bit3 - Task Switched */
         uint8_t et      : 1     { 0 };      /* bit4 - Extension Type */
         uint8_t ne      : 1     { 0 };      /* bit5 - Numeric Error */
         uint16_t        : 10;               /* Reserved */
         uint8_t wp      : 1     { 0 };      /* bit16 - Write Protect */
         uint8_t         : 1;                /* Reserved */
         uint8_t am      : 1     { 0 };      /* bit18 - Alignment Mask */
         uint16_t        : 10;               /* Reserved */
         uint8_t nw      : 1     { 0 };      /* bit29 - Not-write Through */
         uint8_t cd      : 1     { 0 };      /* bit30 - Cache Disable */
         uint8_t pg      : 1     { 0 };      /* bit30 - Paging */
    
         inline raw_type load( void ) noexcept {
             raw_type raw;
             asm volatile ( "movl %%cr0, %0\n" : "=r" ( raw ) );
             return raw;
         }
    
         inline void store( raw_type raw ) noexcept {
             asm volatile ( "movl %[v], %%cr0\n" :: [v] "r" ( raw ) );
         }
    
     } __attribute__((packed));
    

For each and every register there are specific write/store and read/load functions.

The goal is to implement a base class cpu_register<> from which each and every register class analogical to cr0 shall derive, eg.

class cr2 : public cpu_register<...> { ... };
class cr3 : public cpu_register<...> { ... };

to share the common functionalities like writing to the register and reading from it. The problem is, it is not possible to return by reference to particular bit representations (the bitfield) in order to uniformly read and write the bit values in within the register using the defined load() and store() functions.

I was thinking about to implement the proxy class somehow to perform the load and stores of particular bits but I was not successfull to do so. The goal is to have simple and uniform interface to read and write the registers:

cr0.pe = 1;                 // writes 1 into PE bit using the store() function
int value = cr0.pg;         // reads the value of PG bit using the load() function
if( cr0.pg == 0 ) { ... };  // same as above

I am focused on clean OOP design. Any kind of advice, help, design pattern recommendation, code snippet would be warmly welcomed... thanks in advance.

lundi 27 février 2023

Should I Call Repository Functions In Controller or Service? [closed]

My team started a new Golang microservices project. Previously, we used monolith Laravel. We're on a discuss to determine the best design pattern we can implement and decided to use Repository Service pattern.

But there are 2 approaches that my team faces. Here's how the patterns look like:

First approach: Route -> Controller -> Service -> Controller -> Repository -> Controller -> Response

Second approach: Route -> Controller -> service -> Repository -> Service -> Controller -> Response

What I want to ask is which pattern I should follow, considering the maintainability, performance, etc.

Thanks in advance! Feel free to add some comments if my question needs to be adjusted.

When to use sealed interface wrappers vs just an interface?

When refactoring code like:


interface Offer {
    val sharedProperty: Property
}

class Product(...): Offer {
    override...
}

class Category(...): Offer {
    override...
}

fun Offer.doSomething(...) {
    when(this) {
        is Product -> ...
        is Category -> ...
        else -> <handle not supported implementation>
    }
}

I've recently been using this pattern quite a bit:

class Product(...)

class Category(...)

sealed interface Offer {

    val sharedProperty: Property

    class ProductOffer(
        val product: Offer
        override...
    ): Offer

    class CategoryOffer(
        val category: Category
        override...
    ): Offer
}

fun Offer.doSomething(...) {
    when(this) {
        is ProductOffer -> ...
        is CategoryOffer -> ...
    }
}

Now I realize the semantics and particularities this implies when containing an item vs being an item. I also realize consumers of my code won't be able to extend external classes with my sealed interface but I was wondering if there are other potential pitfalls from using this wrapping pattern?

ER Diagram of University [closed]

https://i.stack.imgur.com/Pawoo.png

This is ER Diagram of a University Model. How to implement this on a database system?

C# upcasting object - best practice or pattern

I am stumbling over a simple problem for years now and I'm not sure if I missed a good feature of C# or a pattern which could help out.

Imaging a simple class Person which only has 2 properties - string FirstName and string LastName. This could either be your own class in own libs or a third party lib. Now you want to use a grid and display the Person's, so that a user can select multiple persons via checkboxes in the grid. So we are creating a PersonsSelectable class, which inherits from Person and gets a new property "bool Selected". Are there any way's or patterns which would allow me to use the already created Person objects to create PersonsSelectable objects?

Please note, that I broke down the problem to a very simple class and a very specific example. Normaly the classes are way more complex and the problem is not limited to select objects in a grid.

There could be multiple way's to solve this, but I think all of the way's I know are messy (but simple). They either produce large amound's of boilerplate code or they are prone to error.

  1. Way - just copy the properties
    internal static class Program
    {
        [STAThread]
        static void Main()
        {
            Person person = new Person() { FirstName = "Testi", LastName = "McTestincton" };
            PersonSelectable selectable = new PersonSelectable();
            selectable.ReadData(person);
        }
    }

    public class Person
    {
        public string FirstName { get; set; }
        public string LastName { get; set; }

        // Could also be an extension method
        public void ReadData(Person person)
        {
            FirstName = person.FirstName;
            LastName = person.LastName;
        }
    }

    public class PersonSelectable : Person
    {
        public bool Selected { get; set; }
    }

This way is prone to error, because if you get an update of the lib, the class Person may get new properties, which will not be copied (which could be fatal in db applications).

  1. proxy/decorator etc.
    internal static class Program
    {
        [STAThread]
        static void Main()
        {
            Person person = new Person() { FirstName = "Testi", LastName = "McTestincton" };
            PersonSelectable selectable = new PersonSelectable(person);
        }
    }

    public interface IPerson
    {
        string FirstName { get; set; }
        string LastName { get; set; }
    }

    public class Person : IPerson
    {
        public string FirstName { get; set; }
        public string LastName { get; set; }
    }

    public class PersonSelectable : IPerson
    {
        protected IPerson Person { get; set; }
        public bool Selected { get; set; }
        public string FirstName { get => Person.FirstName; set => Person.FirstName = value; }
        public string LastName { get => Person.LastName; set => Person.LastName = value; }

        public PersonSelectable(IPerson person)
        { Person = person; }
    }

Produces way to much boilerplate code in complex classes. It would be really nice if you could define the "over" implementation more implicit like "public class PersonSelectable : IPerson over Person", but I don't think, that C# has such a feature.

  1. Way - imho the best and cleanest way - use reflection

I often use a method, which just copies all field's to an inheriting target object.

I'm sure there are way more pattern's to implement this, but most of them will just copy all of the data, which is slow and messy. Are'nt there any better way's?

How to remove repetitive parameters in class methods?

I've got a class implementing an interface, with some 15 methods. The methods all need a string SectorId that is passed onward to another service, which make the class looks like this:

public class A: IA {
 public string A1(string sectorId, ....) => _otherService.B1(sectorId, ....);
 public string A2(string sectorId, ....) => _otherService.B2(sectorId, ....);
 public string A3(string sectorId, ....) => _otherService.B2(sectorId, ....);
 public string A4(string sectorId, ....) => _otherService.B2(sectorId, ....);
 ...
}

Is it possible to get rid of the repetitive string sectorId while still achieving the same objective? This class handles webAPI calls and is dependency injected to the controller which calls it.

I thought of having the sectorId as a constructor initialized parameter, but that would mean either not using the class as a DI singleton and, instead, scoping it to the request or not using DI altogether and just initializing it on every request. Is there a better way to handle this?

vendredi 24 février 2023

When are times when it is preferable to copy-and-paste code, slightly changing it, instead of using something like composition?

I have heard design patterns and reducing duplicated code can be very helpful for maintainability, I would like to know when it is preferable to simply copy-and-paste code from one part of a codebase to another and change it slightly instead of using something like composition or some design pattern that avoids this situation?

I also would love to learn about how common this strategy of copying-and-pasting code and changing it slightly is across the industry? Is this common to see at many developer jobs? Also, when does it become preferable to use a different approach?

Java Design/Spring Boot question, how to break down responsibilities inside a Service

Lets say you have a business flow that evolves around creating multiple queries on a songs database, and you have some steps in all

The example is in Spring Boot but the logic can be applied anywhere

  1. Have a factory that decides the query
  2. Parse: Receive some data, break them down, create the query
  3. Query: Perform query on repository, the query returns a List<SongItem>
  4. PrepareAnswer: Create a return DTO

Steps 2, 4, have different implementations, thus the different classes

you can create an interface or abstract class Query

private interface Query(){
    public ?? parse();
    public QueryBuilder createQuery();
    public ?? PrepareAnser();
}

and implement multiple Query types like RockQuery PopQuery FolkQuery

public class RockQuery implements Query

How should the service be organized and the data List<SongItem> carried around the several steps?

I have several thoughs, its mostly wether to include the SongList in the class or keep it in the Service

1)

@Service
public class SongService()

public SongListDTO makeAList(Data data){
    
    @Autowired
    SongRepository repository;
    
    Query query = factory(data).getQuery(Type.ROCK); // or something similar
    List<SongItem> songs = repository.query(query.createQuery());
    return query.prepareAnswer(songs);
    
}

    instead of creating a different querytype, actually perform the query inside the QueryClass, not the Service. Of course inject the repository there.

    Keep the List<SongItem> as class member. Dont expose it to the Service

    public SongListDTO makeAList(Data data){
        Query query = factory(data).getQuery(Type.ROCK); // or something similar
        query.performQuery()
        return query.prepareAnswer(songs);
    }
    
    1. Something similar, multiple variations may apply

    interface/inherited class in paylaod + serialize/deserialize multiple model in one property

    Let me introduce the problem, we have an API that accepts multiple values in one field, let's assume we can have a request model and inside there is a field named animal like:

    {
      // other properties
      "animal":
      {
        "type":"dog",
        // other specific dog properties
      }
    }
    
    or
    
    {
      // other properties
      "animal":
      {
        "type":"cat",
        // other specific catproperties
      }
    }
    

    Now, we have layers, where we receive view model -> we transform it into dto for application layer -> and finally to db model, and vice versa for reads: db model -> dto model -> view model. We have created extension methods to map those to different layer model, eg.

    internal static AnimalResponse ToDto(this AnimalReadModel dbModel)
    {
      // mapping other properties
      Animal = MapAnimal(dbModel)
    }
    
    private static IAnimal MapAnimal(IAnimalDb dbAnimal)
    {
      return dbAnimal switch
      {
        DogDb dog => new DogDto {//mapping dog specific props},
        CatDb cat => new CatDto {//mapping cat specific props}
      }
    }
    

    and we do that for all layers, so they look extremelly similar, but we have to multiply Cat/Dog/Other in all layers, when we want to add new animal we also need to change all those places. This seems like major solid issue we would like to solve.

    And as a bonus, we have asynchronous communication between services where we send byte array, and in this solution we have used json converter (system.text.json) for another different model (but also very similar) like:

    public class AnimalQueueModelConverter : JsonConverter<IAnimalQueueModel>
    {
      public override IAnimalQueueModel Read(ref Utf8JsonReader reader, Type typeToConvert, JsonSerializerOptions options)
      {
        var jsonObject = JsonElement.ParseValue(ref reader);
        var animal = jsonObject.GetProperty("type").ToString() switch
        {
          AnimalQueueType.Dog => jsonObject.Deserialize<DogQueueModel>(),
          AnimalQueueType.Cat => jsonObject.Deserialize<CatQueueModel>()
          // if more will come we need extend this as well
        }
      }
    
      public override void Write(Utf8JsonWriter writer, IAnimalQueueModel value, JsonSerializerOptions options)
      {
        switch (value)
        {
          case DogQueueModel:
            // here write this model using writer
          case CatQueueModel:
            // here write this model using writer
        }
      }
    }
    

    And even tho, in the "reader" class after someone deserialize the byte[] they still need to create this stupid if cat(), if dog(), if hippo()..

    So we have so many places to edit when we need to add another animal to our system. Can someone give me a pattern, lib, example what we could use to make this code better to maintain? I was thinking about disctiminators, but not sure how to propagate them. I think someone already had similar problem and there is a better solution to this.

    Thanks

    jeudi 23 février 2023

    How to modify routing pattern before {controller} to handle multiple languages in ASP.NET Core

    In ASP.NET core, I created a simple Controller and Action with the default routing

    app.MapControllerRoute(
        name: "default",
        pattern: "{controller=Home}/{action=Index}/{id?}" });
    
    
    public class Test1Controller:Controller
    {
        public string HelloAct()
        {
            return "Hello World.";
        }
    }
    

    https://localhost:port/Test1/HelloAct It is OK, shows "Hello World."

    I want to handle multiple languages with URL like Microsoft web site.

    https://learn.microsoft.com/en-us/aspnet/core/fundamentals/routing?view=aspnetcore-7.0 https://learn.microsoft.com/ja-jp/aspnet/core/fundamentals/routing?view=aspnetcore-7.0 https://learn.microsoft.com/ko-kr/aspnet/core/fundamentals/routing?view=aspnetcore-7.0

    Add language name after domain, if the parameter is omitted, I wish it will go to "en-us".

    I tried below, modified routing pattern:

    app.MapControllerRoute(
        name: "default",
        pattern: "{lang=en-us}/{controller=Home}/{action=Index}/{id?}" });
    
    app.MapControllerRoute(
        name: "default",
        pattern: "{lang?}/{controller=Home}/{action=Index}/{id?}" });
    

    Input: https://localhost:port/Test1/HelloAct but neither is right. Returns 404 not found.

    How to modify the routing pattern?

    Proper design of classes that call methods of stored objects

    Say you have a node class and a graph class. nodes have a method, split() that uses its inner properties and returns new nodes. nodes are added to graphs which have a method splitWhen() which splits all nodes that fit certain criteria and stores the new nodes.

    class Node {
      split() { }
    }
    
    class Graph {
      this.nodes = [];
      addNode(node) { }
      splitWhen(callback) { 
        // Call this.node[x].split() and store the returned nodes
      }
    }
    

    Testing splitWhen isn't straightforward since mocking node.split() to return new nodes, feels like too much mock implementation. At the same time, having graph call a node's method feels like there's room for improvement.

    Is there a technique or pattern that does this type of stored inner object method calls in a more testable and maintainable way or is that not necessary?

    A simple but indirect analogue would be calling built in prototype methods. Say instead of nodes, it's just an internal array property, and that graph.splitWhen() just uses Array.prototype.filter(). We wouldn't need to mock filter and we just test that splitWhen() is implemented correctly by asserting on the results.

    Can we extend the same logic to node.split() since it's tested in the node class and not have to mock it?

    What is the right design for a single ORM used between multiple repositories?

    I have two Python repositories (Data pipeline and API) which access the same database. They use sqlalchemy as an ORM to read/write the tables with models in this format:

    from sqlalchemy import Column, Integer
    from sqlalchemy.orm import declarative_base
    
    Base = declarative_base()
    
    class MyData(Base):
        id: int = Column(Integer, primary_key=True)
        ...
    

    And then read/write in the usual way:

    from sqlalchemy import create_engine
    from sqlalchemy.orm import Session
    
    engine = create_engine(connection_string)
    Base.metadata.create_all(engine)
    with Session(engine) as session:
        session.query(MyData).filter(MyData.id == 0).one_or_none()
        session.add(MyData(id=1))
        ...
    

    I don't want to combine the two repos into a monolith to avoid this problem, so I see four options, none of which are good:

    1. Duplicate the ORM code across both repos - this is obviously a bad code smell, maintenance becomes labour-intensive.
    2. Avoid using ORM in one of the repos, e.g. use pandas read_sql/to_sql in the pipeline repo - this is a poor compromise, sacrificing functionality plus a serious hit to write speed.
    3. Create a separate ORM repo and add it as a git submodule to both repositories - this seems better but it strikes me as a bad code smell to have an __init__.py at the top level of this repo.
    4. Bundle an ORM repo as a pip package and add it as a dependency to the two repositories. This is what I have currently:
    db_orm
      __init__.py
      models.py
    setup.py
    

    setup.py:

    from setuptools import setup
    
    setup(
        name="db_orm",
        version="0.0.1",
        packages=["db_orm"],
        package_dir={"db_orm": "db_orm"},
        install_requires=["SQLAlchemy==1.4.44"],
        classifiers=[
            "Programming Language :: Python :: 3",
        ],
    )
    

    This approach again is not great as I need to maintain credentials for both repositories to be able to install the ORM package via pip, I also need to ensure their versions are kept up to date.

    Is there a better way to solve this problem?

    What happens when incorrectly use static class, singleton class? [closed]

    I know there are many advantages of a singleton class over a static class. And I know utility class should be static because it doesn't have any variables and it does not maintain state. My question:

    1/ Can I replace static utility class with Singleton? Does it cause performance or memory leaks?

    2/ Can I use singleton or static vavariables to store single current informations sush as user information, session information,... and reset it when login again instead of storing it in database (sqlite, shared preference, ...)? Why not?

    Translate workflow into state machine with respect to SOLID and OOP

    Lets say you start with a method that accepts two complex objects. This method is some sort handler and it needs to process workflow (see workflow flowchart)

    public Task Handler(Object A, List<object> lisftOfObjectsB)
    {
        //execute workflow steps here 
    }
    

    You can do this by using statements like 'if', 'if-else', 'switch' etc. But if you program it that way you will end up with messy code and you will probably violate at least one of SOLID principles (open-close principle for example). How can you program a workflow with respect to SOLID principles and using OOP instead of using many different if, if-else, switch ect statements ? enter image description here

    public Task Handler(Object A, List<object> lisftOfObjectsB)
    {
        bool inDb = IsAInDatabase();
        if(inDb == false)
        {
             //Add to DB
        }
        else
        {
             bool hasLastState = CheckForLastState(A);
             if(hasLastState == false)
             {
                 //Add laststate
             }
        }
        ....
     }
    

    If you do it this way you will end up with many different if/else/for/for-each statements and imagine if workflow will have much more steps and YES/NO decisions.

    Design pattern for building SQL string in Python

    I'm looking for good design pattern for building SQL queries in Python. Queries will be just SELECT statements only and also underlying database might never change during the lifetime of the project that I'm working on. I found Design Pattern for Creating Sql Queries. Wondering if there are any other alternative and better approaches.

    Tried Design Pattern for Creating Sql Queries

    mercredi 22 février 2023

    2D RPG using the mvc design pattern

    I want to use the mvc for my 2d rpg game. I know there are newer and better design patterns than mvc, hoping just using this

    But I dont know how arccurately I've understanded it.

    So I wonder- this mvc:

    Model: the trait of palyer and weapon(data) and the skill of them(method)

    Control: Control collects the datas(trait) and methods(skill) from both player and weapon, resulting a overall trait data and skill method, applying the skill method to ones enemy. Also, send a imfortant infomation to View.

    View: View makes the moniter sawn.

    • is correct.

    mvcmvcmbcmvcmvcmvcmvc

    IOS - Swift : Fetch the property name of an object using KeyPath

    Issue :

    Update the property of a specific object in Firebase. To do so I want to update one value only within an object without having to interact with the current object. The required part from firebase, other than the collection and the document are the key and the new value

    I have figured an implementation which works - And I'd like some improvement ideas. Especially there, static func createEmpty() -> Self, this bothers me. Initializing a model to find a key seems really not efficient to me. I'd like if a nice swifty soul could show me the way.

    Here how it looks:

    This protocol will be the key property reader :

    protocol KeyPathValueReadable {
        static func createEmpty() -> Self
    }
    
    extension KeyPathValueReadable {
       fileprivate subscript<T:Any>(at path : KeyPath<Self,T> ) -> String{
           print(self[keyPath: path])
           return "\(self[keyPath: path])"
       }
       func readValue<T : Any & Hashable>(at keyPath : KeyPath<Self,T>) -> String{
           let mirror = Mirror(reflecting: self)
           var dict : [T: String] = [:]
           for case let (label, value) in mirror.children {
               if let label = label {
                   dict[value as! T] = label
               }
           }
           return dict[self[keyPath: keyPath]] ?? "no key at path"
       }
    }
    

    Here's an example of the model to update :

    struct UserModel : Codable, KeyPathValueReadable {
        
        var name : String
        
         static func createEmpty() -> Self {
             return Self.init(name: "")
        }
    }
    
    

    And here is the client implementation and use :

    protocol UpdateDataClientDelegate {
        associatedtype D : Codable & KeyPathValueReadable
    }
    
    extension UpdateDataClientDelegate {
        func update<T : Hashable>(in collection : String, for document : String, at path : KeyPath<D,T>, newValue : Any) {
            let key =  D.createEmpty().readValue(at: path)
            print(key)
            //update key with newValue
        }
    }
    
    struct UpdateUserClient : UpdateDataClientDelegate {
        typealias D = UserModel
    }
    
    let client = UpdateUserClient()
    
    client.update(in: "pouf", for: "plaf", at: \.name, newValue: "chocolate")
    
    

    mardi 21 février 2023

    I have productListArray and I would like to add product into it but each product has unique ID and unique name and I am getting some errors

    before I added the product to the non-empty list, I tried to validate if the product id and name of the product already existed in the list by going through the list and if there is no such id and name in the list then added the product to the list, but, I got this error #ConcurrentModificationException

    -thanks for advance

    import java.util.ArrayList;
    import java.util.Iterator;
    
    public class ProductList implements Iterator<Product> {
    
        private ArrayList<Product> productListArray = new ArrayList<>();
    
        /* Singleton Design begin */
        private static ProductList productListSingleton;
    
        private ProductList() {
    
        }// end of private constructor
    
        public static ProductList instance() {
            if (productListSingleton == null) {
                productListSingleton = new ProductList();
            }
            return productListSingleton;
        }
    
        /* Singleton Design Phase end */
        /*
         * method add product into list
         * 
         * @param Product Type
         */
        public void addProduct(Product product) {
    // if the list is  empty just add the product into the list
            if (productListArray.isEmpty()) {
                productListArray.add(product);
            }
            /*
             * add product only if the id and name not existed in the productList
             */
            else {
                for (Product product1 : productListArray) {
                    if (product1.getProductId() == product.getProductId()) {
                        System.out.println(" the product is already in the list");
                    }
                    else if (product1.getProductName().equals(product.getProductName())) {
                        System.out.println("choose another name for product");
                    }
                    else {
                        productListArray.add(product);
                    }
                }
            }
        } // end of addProductMethod
    
        /*
         * remove the product from the ProductList Parameter product id
         */
        public void remove(int productId) {
            Iterator<Product> iteratorList = productListArray.iterator();
            while (iteratorList.hasNext()) {
                Product product = iteratorList.next();
                if (product.getProductId() == productId)
                    iteratorList.remove();
            } // end of while
        } // end of remove method
    
        /* retrieve the productlist */
        public void retrieve() {
            Iterator<Product> iteratorList = productListArray.iterator();
            while (iteratorList.hasNext()) {
                System.out.println(iteratorList.next());
            }
        }
    
        @Override
        public boolean hasNext() {
            // TODO Auto-generated method stub
            if (next() == null) {
                return false;
            }
            else {
                return true;
            }
        }
    
        @Override
        public Product next() {
            // TODO Auto-generated method stub
            return next();
        }
    }
    

    PHP Shift Pattern

    Im looking to create a shift pattern that is ongoing from a start point, in excel this is easy enough to do with networkdays.intl but unable to find something in php,

    I need to know what staff are working on what day for a custom built system, can anyone point me in the right direction?

    Thanks

    Different number of parameters in Strategy Pattern

    I am adopting strategy pattern in coding some filtering logics:

    1. filterByEventName(event, request), where filter is done by matching event.name and request.name;

    2. filerByEventDate(event, request), where filter is done by matching event.date and request.date;

    3. filterByEventDist(event, request, k), where filter is done by calculating the distance between event.longitude and event.latitude and request.longitude and request.latitude, and return the top k closest ones

    I have the strategy pattern designed like below:

    class Strategy(ABC):
        @abstractmethod
        def filter(self, *args):
            pass
    
    class StrategyByEventName(Strategy):
        def filter(self, events, request):
            ...
    
    class StrategyByEventDate(Strategy):
        def filter(self, events, request):
            ...
    
    
    class StrategyByEventDist(Strategy):
        def filter(self, events, request, k):
            ...
    
    
    class Context:
        def __init__(self, strategy, events, request):
            self.strategy = strategy
            self.events = events
            self.request = request
    
        def filterByType(self):
            events = self.strategy.filter(self.events, self.request)  
    
    
    strategy: Strategy = StrategyByEventDate()
    context: Context = Context(strategy, events, request)
    context.filterByType()
    
    strategy: Strategy = StrategyByEventDist()
    context: Context = Context(strategy, events, request)
    context.filterByType() # for StrategyByEventDist, where should I pass the parameter k? 
    

    since the last strategy has different number of parameters as the first two, how should I design the call func filterByType to handle the additional parameter in StrategyByEventDist? Or I should not use strategy pattern here?

    lundi 20 février 2023

    pythonic way to decorate an iterator at run-time?

    I have the following code:

    def assertfilter(iterator, predicate):
        # TODO support send()
        for result in iterator:
            if not predicate(result):
                raise AssertionError("predicate failed in assertfilter()")
            yield result
    

    Any attempt I could come up with to refactor it to support send() seems to look horrifically convoluted, unreadable, and non-obvious:

    def assertfilter(iterator, predicate):
        result = None
        while True:
            try:
                sent = yield result
                if sent is not None:
                    result = iterator.send(sent)
                else:
                    result = next(iterator)
                if not predicate(result):
                    raise AssertionError("predicate failed in assertfilter()")
            except StopIteration:
                return
    

    Is there a recognized, common, readable way to inject/wrap logic onto an existing iterator? Or is the above the best-practice currently?

    How can I design an abstract model for different implementations in Java

    Currently, I'm using Json to send different data to different vendors, but I'm curious about if there is a better alternative to do it.

    Let's see this way.

    I have one library, to make some operations for different vendors.

    Provider Library

    class Google {
      String id;
      Integer amount;
    
      // getters and setters
    }
    
    class Oracle {
      String id;
      Integer amount;
      Instant request;
    
      // getters and setters
    }
    
    class AbstractRequest {
      String id;
      Integer amount;
      Instant request;
    
      // getters and setters
    }
    
    class ConverterGoogle<Google, AbstractRequest> {
      // convert between models
    }
    
    class ConverterOracle<Oracle, AbstractRequest> {
      // convert between models
    }
    
    interface Provider {
      void execute(AbstractRequest request);
      String key();
    }
    
    class GoogleProvider extends AbstractProvider {
      void execute(AbstractRequest request) {
        Google model = ConverterGoogle.convert(request);
        // operations with model
      }
      String key() { return "google"; }
    }
    
    class OracleProvider extends AbstractProvider {
      void execute(AbstractRequest request) {
        Oracle model = ConverterOracle.convert(request);
        // operations with model
      }
      String key() { return "oracle"; }
    }
    

    There is another Service project that uses the before library. Depending on specific runtime data, will determine which provider will be used.

    Service Project

    class OperationsService {
      void process(String data) { // data could be something like "google_ujk345678iju78fh4"
        Provider provider = providerService.getProvider(data);
        
        AbstractRequest request = requestCreatorService.create(provider.getKey(), data);
    
        provider.execute(request);
      }
    }
    
    class RequestCreatorService {
      AbstractRequest create(String providerKey, String data) {
        // retrieve information from database to create the proper AbstractRequest for each provider
      }
    }
    

    And well, what's the issue? If a new provider comes in, with a different model, the AbstractRequest only has 3 fields, then it should change to hold the new ones.

    At this moment, I solved it by sending a JSON request and the provider library and each implementation is responsible to retrieve its necessary data. So, we do not depend on a generic/common abstract model, with specific fields.

    interface Provider {
      void execute(String jsonRequest);
      String key();
    }
    
    class GoogleProvider extends AbstractProvider {
      void execute(String jsonRequest) {
        Google model = GoogleDataExtractor.convert(jsonRequest);
        // operations with model
      }
      String key() { return "google"; }
    }
    
    class OracleProvider extends AbstractProvider {
      void execute(String jsonRequest) {
        Oracle model = OracleDataExtractor.convert(jsonRequest);
        // operations with model
      }
      String key() { return "oracle"; }
    }
    

    Of course, I had to create a v2 of the library to not break current implementation and the service. It's in testing phase.

    I would like to know if there is another way to do it, using other specific model data class, specific pattern, etc.

    How do ESPN and other spots sites continuously keep their scores and stats up to date without the user needing to refresh for new content?

    This is more of a high-level question about the relationship between client and server described above. I would have to assume this is typically accomplished by the server pushing out updates to the client, but I'm trying to wrap my head around how this happens for a massive user-base that needs to receive updates every few seconds. Any direction for technologies and design patterns I can start researching would be helpful.

    I've tried a few different web searches with simlarly worded questions, but have yet to find anything useful.

    What is .dtt file Extension and what is its use?

    Recently I came across the file extension '.dtt', which I was wondering that what type of the file extension is that, eventually I surfed on stack overflow, I couldn't get the exact answer, so I just thought to share about the '.dtt' from what I understood!

    .dtt Extension

    Thanks in Advance!

    System Design - API Response Translator

    Let say I have a service called as User which has getUser() and createUser() APIs.

    We have different channel through with these apis can be access like B2B (Partner 1(P1), Partner 2(P2) ...), B2C (Mobile, Web).

    Now the use case is the API response can vary based on the channel/partners.

    Example: getUser has in total 10 fields. If the api is accessed through B2C web channel, we need to return all 10 fields. If the api is accessed through B2C mobile channel, we need to return 8 the fields. If the api is accessed through B2B channel by partner P1, we need to return 6 the fields. If the api is accessed through B2B channel by partner P2, we need to return 8 the fields.

    My question is what would be the best way to achieve this?

    Here are few of the approaches which I can think :

    1. In user service, we can have one translator which will convert the service DTO object to API response. We can have conditional statement to determine if that field needs to be added in the API response based on channel/partner
    • Pros: - Could think any
    • Cons:
      • Code manageability would be difficult
      • Dynamic changes in the response(addition/removal of any field) for any channel/partners required service deployment
    1. In user service, we can have different translators which will convert the service DTO object to API response.
    • Pros:
      • Since translator are maintained at channel/partner level so changes done in one translator won't impact other
      • Follows Single responsibility principle
    • Cons:
      • Dynamic changes in the response for any channel/partners required service deployment
    1. We can maintain template of response based on different channel/partners in some config service. When the request comes in we will call the config service (can be cached to improve performance) and get the response template and fill the required field info.
    • Pros:

      • Dynamic changes in the response for any channel/partners does not required service deployment
      • Onboarding of new partner with custom response would be easier. Does not required any user service level changes
    • Cons:

      • Need to manage separate config service
    1. The core service (user) will always return all the fields irrespective of channel/partner. We can have an orchestrator layer in between caller and user service which will be responsible for setting the response field.
    • Pros
      • Orchestrator layer can be further extended to enable of disable any feature based on channel/partner.
      • User service will have core logic. We don’t need to deploy user service until there is any change in core logic
    • Cons
      • Orchestrator layer needs to be maintained separately
      • Need deployment of config service when there is any changes in response for any channel/partner

    dimanche 19 février 2023

    Improving wrapper function when handling different embedded if-else scenarios

    I wish to refactor this fugly function - running on an object collection robot - handling all possible sounds in response to stimuli of different data types.

    How can I Pythonically improve the following?

    '''
    Produce different sounds based on various parameters comprising robot's
    proximity to different objects & time taken for collecting said objects.
    
    `obj` := nearest object captured within front-camera's field of view
    `timeSinceAnyObjLastCollected` := global timer
    
    `objPassThruInfraRedEntryGates` := returns bool
    `cameraSensorWithinTwoFeetOfObj` := returns bool
    '''
    def soundManager(obj, timeSinceAnyObjLastCollected):
        ## Order of these if-statements determine sound-output precedence
        if timeSinceAnyObjLastCollected > 60:
            timeSinceAnyObjLastCollected = 0    ## Reset timer
            playSound("A")
    
        elif objPassThruInfraRedEntryGates(obj):
            timeSinceAnyObjLastCollected = 0    ## Reset timer
            if obj.color == "RED":
                playSound("B")
            elif obj.color == "GREEN":
                playSound("C")
    
        elif cameraSensorWithinTwoFeetOfObj(obj)
            if obj.color == "RED":
                playSound("D")
            elif obj.color == "GREEN":
                playSound("E")
    
        else:
            playSound("F")
    

    Moreover, is implementing this "catch-all" soundManager() any more scalably elegant than separately calling playSound(), where those situations indented within these if-statements are actually encountered within the script?

    Is using Abstract classes to map common JSON fields a bad practice?

    I'm implementing some input data validators in my app and I ended up with an Abstract class containing common props that are mapped to JSON. I also created abstract and virtual methods to force derived classes to always keep the same validation algorithm pattern. I have not followed any Design Pattern and because of it I would like to know your opinion about my code.

    My abstract class is something like that:

    public abstract class DataValidation
    {
      [JsonProperty("cleaned")]
      public string CleanedInput => _cleanedInput;
    
      [JsonProperty("isValid")]
      public bool IsValid => _isValid;
    
      protected string _cleanedInput;
      private bool _isValid;
    
      public DataValidation(string input)
      {
        _cleanedInput = CleanInput(input);
        _isValid = ValidateInput(_cleanedInput);
      }
    
      protected abstract bool ValidateData(string cleanedInput);  
      protected virtual string CleanInput(string input) => input.Trim();
    }
    

    And some derived classes where I perform validations like birth date or documents format:

    public sealed class ClassA : DataValidation
    {
        public ClassA(string input) : base(input)
        {
        }
        
        protected override bool ValidateData(string input)
        {
          // ... Logic to validate input. 
          // Returns true as an example.
    
          return true;
        }
    }
    

    And another class that overrides CleanInput method and returns invalid validation:

    public sealed class ClassB : DataValidation
    {
        public ClassB(string input) : base(input)
        {
        }
    
        protected override string CleanInput(string input) =>
          return input.Trim().Replace(".", "").Replace("-", "");
        
        protected override bool ValidateData(string input)
        {
          // ... Logic to validate input. 
          // Returns false as an example.
    
          return false;
        }
    }
    

    Finally, I serialize these objects and have a json like that:

    // ClassA
    {
      "cleaned": "inputA_cleaned",
      "isValid": true
    }
    
    // ClassB
    {
      "cleaned": "inputB_cleaned",
      "isValid": false
    }
    

    What I did is considered to be a good or bad practice?

    Best Practice Open Close Principle

    Please take a look at my class. In it WoW avatars are created. In the constructor method instances of different classes are created. If the program is extended by a new class (e.g. Tauren), the constructor method must be changed stupidly. One would have to add another object instantiation into the method. This contradicts the Open Close principle, according to which a software should be open for extensions but closed for changes. How can I solve this problem.

    public class UpdateAvatarFactory{
    
        public UpdateAvatarFactory(Client client){
            ICreateMethod createHuman = new CreateHuman();
            createHuman.name="Human";
            ICreateMethod createElf = new CreateElf();
            createElf.name="Elf";
            ICreateMethod createGnome = new CreateGnome();
            createGnome.name="Gnome";
            ICreateMethod createOrc = new CreateOrc();
            createOrc.name="Orc";
    
            client.avatarFactory.addCreateMethod(createHuman);
            client.avatarFactory.addCreateMethod(createElf);
            client.avatarFactory.addCreateMethod(createGnome);
            client.avatarFactory.addCreateMethod(createOrc); 
        }
    
    }
    

    vendredi 17 février 2023

    What is the design pattern to use for extending a base class with additional properties?

    I have "business entities" and their counterpart for saving them to Azure Storage Table, which requires a few additional properties.

    // MyData is the business entity with a few properties
    public record MyData_AzureTable : MyData, ITableEntity
    {
        // Required properties for storing data to Azure Storage Table
        public string PartitionKey { get; set; } = "";
        public string RowKey { get; set; } = "";
        public DateTimeOffset? Timestamp { get; set; }
        public ETag ETag { get; set; } = new ETag();
    }
    

    I am getting tired of having to duplicate each business entity with its AzureTable counterpart but I can't find the correct pattern to use. Something like that, except it's illegal to inherit from a type parameter.

    public record AzureTable<T> : T, ITableEntity
    {
        public string PartitionKey { get; set; } = "";
        public string RowKey { get; set; } = "";
        public DateTimeOffset? Timestamp { get; set; }
        public ETag ETag { get; set; } = new ETag();
    }
    

    What pattern should be used for adding properties to a base class?

    The object saved to Azure Table Storage needs to be "flat" (tabular data as property values, no hierarchical data)

    Abstract method's parameters aren't all used in the child classes

    class parent:
      @abstractmethod
      def process(self, x, y, z):
        pass
    
      def post_process(self):
        self.process(x, y, z)
    
    class child1(parent):
      def process(self, x, y, z):
        # do stuff with x and y, and ignore z
    
    class child1(parent):
      def process(self, x, y, z):
        # do stuff with x, y, z
    

    This is an existing design in the codebase I am working in. I don't like it for readability because the variable z isn't used for all child classes, and I suspect it was designed this way so that post_process doesn't need to check which child class is calling.

    I am thinking of changing it to:

    class parent:
      def post_process(self):
        if isinstance(self, child1):
          self.process(x, y)
        elif isinstance(self, child2):
          self.process(x, y, z)
    
    class child1(parent):
      def process(self, x, y):
        # do stuff with x and y
    
    class child1(parent):
      def process(self, x, y, z):
        # do stuff with x, y, z
    

    This does the case work of checking which child class is calling post_process, but I feel it is better for readability and avoids having to pass in unnecessary arguments. Are there other ways besides this to resolve this issue?

    Loading files - pattern

    I am currently dealing with the fact that I have to import about 15 csv files into db tables. Each csv file already has its own db table. The code for filling the table works for me, see below.

    public class Loader {
            public void load(Connection conn, String file, String[] columns, String tableName) {
                String sqlLoadData = "LOAD DATA LOCAL INFILE " +
                        file +
                        " INTO TABLE " +
                        tableName +
                        " FIELDS TERMINATED BY " +
                        "';' " +
                        "LINES TERMINATED BY " +
                        "'\n' " +
                        "IGNORE 2 ROWS " +
                        Stream.of(columns).collect(Collectors.joining(", ", "(", ")"));
        
                try (PreparedStatement ps = conn.prepareStatement(sqlLoadData)) {
                    ps.setInt(1, packageInfo.getIdPackage());
                    ps.execute();
                }
            }
        }
    

    Loading files

    Loader loader = new Loader();
    loader.load(conn, "user.csv", new String[] { "firstName", "lastName"});
    loader.load(conn, "permissions.csv", new String[] { some columns });
    loader.load(conn, "roles.csv", new String[] { some columns });
    // calling for next files
    

    I don't like this solution. I'm still thinking about a suitable way to do some encapsulation in trid instead of calling the Loader.load method. I went through the design patterns, but I couldn't match any of them to my problem. Can you give me some advice?

    What's the point of using composition when the composed class is only used at a single place?

    I see some code design like this

    class my_class:
      def __init__(self, arg1, arg2, arg3)
        self.data = data(arg1, arg2, arg2)
        # initialize some other attributes
    
    # the only place data class is used is in my_class
    class data:
      def __init__(self, arg1, arg2, arg3)
        self.arg1 = arg1
        self.arg2 = arg2
        self.arg3 = arg3
    

    I don't see the point of doing that, when you can just do

    class my_class:
      def __init__(self, arg1, arg2, arg3)
        self.arg1 = arg1
        self.arg2 = arg2
        self.arg3 = arg3
        # initialize some other attributes
    

    which gets rid of the seemingly unnecessary layer.

    Is there some advantage of design standard that motivates the former design?

    Separating UI and data in gaming, what design pattern should I use?

    So I come from a background of web development, and working with primarily react. In this style of development people tend to use design patterns that separate the data layer from the UI layer.

    The normal design goes: prepare data and state -> render the UI deterministically and declaratively from the data and state. The state can trigger an update to the data, which will then trigger a rerender of the UI.

    This is nice because your data code only has to deal with the data, and so code about data fetching or transformations like filtering doesn't have any references to the UI at all.

    I'm currently building something in Pixi.JS, which is a JS library for building graphics and games. The "take the data and then pass it to code that renders it" strategy is not an option. Pixi.JS is more imperative in design.

    Let me demonstrate with an example.

    Imagine you're showing on screen a list of bullet points (the UI) which is generated from a list of strings (the data).

    In React you just have a component that returns a list of bullet points in JSX from the list of strings. If a bullet point is removed from the list of strings, the component rerenders with the bullet point taken out. Simple.

    In Pixi.JS, the bullet points are all their own sprite objects that you create. When a bullet point is removed you have to explicitly and imperatively tell Pixi.JS to remove the sprite from the scene. Data transformations therefore usually involve performing some manual imperative changes to the UI.

    This then ends up meaning that you start smooshing your data and UI code together. You make a method removeBulletPoint() that changes the data and the UI at the same time. This leads to more closely coupled code, and makes it harder to follow the single responsibility principle. It makes it harder to test because you can't test the data code isolated from the UI code.

    I've read a lot that your data code shouldn't know about your UI code, but with this library that seems impossible. What design patterns should I apply to manage all this complexity?

    Highly Available requirement in Distributed Environment

    Need to design a distributed HA (High Availability) solution in cloud. The backend resources should be distributed across multiple availability domains and fault domains (FD are sub-part of AD)in a way that we avoid skewness of resources. Is there a design/architecture pattern that can be followed to achieve this. Ex : Suppose we have 3 AD and each AD has 3 FD , and say we have 10 resources to distribute with the condition that if can't allocate in 1 FD move to other FD (fail-safe condition).

    I tried allocating ADs directly to resources in a loop to uniformly distribute it. Ex : 8 Resource

    AD1 (3)-> FD1 1 , FD2 1,FD3 1 AD2 (3)-> FD1 1 , FD2 1 , FD3 1 AD3 (2)-> FD1 1 , FD2 1 , FD3 1

    But want some better solution to allocate with fail-safe method.

    Definig page component only by HOC in NextJS

    I have nextjs (react) website I use (on every "page") same template - there is Detail and List component.

    I have definition of every page as XML (not nextjs thing but my implementation). Root element here is Forms and childrens are individual form defined like this:

    <Form FID="Event">
        <DetailFrame createNewEntryText="Add event">
            <Component attributeKey="img_url" componentName="chose file" componentType="FileChooser" path="img/albums/other/event-photos/@[img_url]"/>
            <Component attributeKey="title" componentName="Title" componentType="TextField" transformation="@[title]"/>
            <Component attributeKey="date" componentName="Date" componentType="DateField" transformation="@[date]"/>
            <Component attributeKey="description" componentName="Description" componentType="RichTextField" transformation="@[description]"/>
        </DetailFrame>
        <ListFrame orderBy="date" descending="true">
            <Component attributeKey="id_event" componentName="ID" componentType="TextField" transformation="@[id_event]"/>
            <Component attributeKey="img_url" componentName="Image preview" componentType="ImagePreview" transformation="img/albums/other/event-photos/@[img_url]" />
            <Component attributeKey="title" componentName="Title" componentType="TextField" transformation="@[title]"/>
            <Component attributeKey="date" componentName="Date" componentType="DateField" transformation="@[date]"/>
            <Component attributeKey="description" componentName="Description" componentType="RichTextField" transformation="@[description]"/>
        </ListFrame>
    </Form>
    

    Only thing what I need specify on every nextjs page is FID and individual component will then compose by their own by XML definition of form. All the stuff like menu and other components (except FormFrameContainer which is wrapper for Detail and List components) are defined in _document.tsx (= html wrapper for nextjs pages offered by nextjs) and _app.tsx (= components wrapper for nextjs pages offered by nextjs; wrapped by _document.tsx). To be clear - FormFrameContainer is wrapped by that stuffs in _app.tsx and _document.tsx.

    So every administration page look almost same, like this:

    const EventsPage: NextPage = (props: any) =>{
        const dispatch = useAppDispatch();
        
        useEffect(() => {
            dispatch({ type: SagaActions.SET_FORM_DEFINITIONS_AND_SET_FORM_BY_ID, FID: "Event" });
        }, [dispatch])
    
        return (
            <div>
                <FormFrameContainer />
            </div>
        )
    
    }
    

    Because of repetition I decided to move useeffect logic into hoc named withAdminPage:

    export default (Page: NextPage, formID: string) => {    
    
        return (props) => {  
            const dispatch = useAppDispatch();
        
            useEffect(() => {
                dispatch({ type: SagaActions.SET_FORM_DEFINITIONS_AND_SET_FORM_BY_ID, FID: formID });
            }, [dispatch])
    
            return <Page {...props} />;
        }
    
    }
    

    So literaly the only thing what remains in particular pages is returning:

            <div>
                <FormFrameContainer />
            </div>
    

    What comes to my mind is also move it to hoc, because it is also same in all pages => duplication. But it would mean, that I will not actually define components (my hoc will generate them) and in every page file will be only this one line:

    export default withAdminPage(EventsPage, "Event");
    

    For me it seems logic but also as some anitpattern to hoc (because hoc is defined as function, that take component and return new (enhanced) component). So? What would be best practise here? Would it be violation of some code standards?

    jeudi 16 février 2023

    Should utility functions used within a class method be part of the class or outside of the class in its own file or same file as the class? [closed]

    Suppose you have a class in test.py

    class test:
      def method1(self, arg1, arg2):
        # do some stuff and call utils_func(arg1, arg2)
    

    utils_func is only used within method1. I am wondering which one of the following is more appropriate:

    1. Define utils_func as a method for test. I'm not sure if this makes much sense since it doesn't directly operate on any attribute of method1.

    2. Don't do #1, but define utils_func within test.py so that you don't have to import it.

    #3) Do #2, but define utils_func in a separate file, e.g., utils.py and then import it in test.py.

    I think this question is partly opinion-based, but I'm wondering if there's any standard way to do this for Python development, and what things I should consider when making a decision?

    Builder Pattern to build object with static classes

    I am having a question of building the object in a scenario like ,

       @Builder
       public class Al {
        
        public Logic logic;
    
        @Value
        @Builder
        public static class Logic{
            public Eq eq;
            public Neq neq;
        }
        
        @Value
        @Builder
        public static class Eq{
            public Arg1 arg1;
            public Arg2 arg2;
        }
        
        @Value
        @Builder
        public static class Neq{
            public Arg1 arg1;
            public Arg2 arg2;
        }
        
        @Value
        @Builder
        public static class Arg1{
            public String myvar;
        }
        
        @Value
        @Builder
        public static class Arg2{
            public String val;
        }
     }
    

    I need to build an object and transform to json similar to

    {
      "logic": {
        "neq": {
          "arg1": {
            "var": "pos"
          },
          "arg2": {
            "val": "0"
          }
        }
      }
    }
    

    Here , neq under logic is decided by one of the condition. Based on the condition , "neq" may be replaced with "eq" and the logic block look as follows

    {
      "logic": {
        "eq": {
          "arg1": {
            "var": "pos"
          },
          "arg2": {
            "val": "0"
          }
        }
      }
    }
    

    While forming the object using builder pattern i use something like
    Code block

    I am interested to know to reduce the duplicate block and making it as single build object.

    Dapper ContextClass DI scope and repository class scopes best practices

    What is the best practices to register DapperContext.cs and repository classes. What scope should be used for Context class and what scope should used repository classes ?

    This is my current code. DbContext Class

        private readonly ICoreLogger<AntiguaCacheContext> _logger;
        private readonly DatabaseOptions _options;
        private readonly string _connectionString;
    
        public IDbConnection CreateConnection() => new SqlConnection(_connectionString);
    
        public DbCacheContext(IOptions<DatabaseOptions> options, ICoreLogger<DbContext> logger)
        {
            _logger = logger;
            _options = options.Value;
            _connectionString = GetConnectionString(ConnectionStrings.DbContext_Connection_String_Key);
        }
    
        private string GetConnectionString(string key)
        {
           //get string
        }
    

    And i adding depdendencies like this

            public static void ConfigureDataAccessLayer(this IServiceCollection services)
            {
                services.AddSingleton<DbContext>();
    
                services.AddTransient<IRepository, Repository>();
            }
    

    Hos should be relation betwwen context and repo injections?Context always sjhould be singleton ? Reposr transient or Scoped ? and so onn...what is the best practices.

    how to check logic from all existing and future implementation of "ICheck" to get the right content type

    I have a interface where I am returning result for a check and this interface has currently 2 implantations but in future it will keeps added.

    public interface ICheck
    {
        Task<CheckReturn> GetCheckReturn(string fileName);
    }
    
    public class ATypeCheck : ICheck
    {
        public async Task<CheckReturn> GetCheckReturn(string fileName)
        {
            //logic to check A Type
            //return CheckReturn with right content type
            return await Task.FromResult<CheckReturn>(new CheckReturn { ContentType = "Type A" });
        }
    }
    
    public class BTypeCheck : ICheck
    {
        public async Task<CheckReturn> GetCheckReturn(string fileName)
        {
            //logic to check A Type
            //return CheckReturn with right content type
            return await Task.FromResult<CheckReturn>(new CheckReturn { ContentType = "Type B" });
        }
    }
    
    // Future CTypeCheck
    // Future DTypeCheck
    

    With below code I am able to do only one check validation, but I need to check all the implementation of ICheck?

    static async Task Main(string[] args)
        {
            ATypeCheck check = new ATypeCheck();
    
            var result = await check.GetCheckReturn("XYZ");
        }
    

    Which design pattern help here & how?

    mercredi 15 février 2023

    Design Pattern for multiple similar APIs in one application

    Let's say I'm working with multiple different music stream APIs. User passes me the link from one of the supported streaming services. Similar API responses should be mapped on the same application's object for further processing, but every API has unique algorithm of doing that. What's the correct way of doing that?

    I came up with next solution. I'm creating an interface MusicApi, which contains methods getAppObject and isLinkMatches

    public interface MusicApi {
        public static AppObject getAppObject(String link);
        public static boolean isLinkMatches(String link);
    }
    

    For example we're working with these APIs. Let's say they're implementing method correctly.

    public class NapsterApi implements MusicApi {}
    public class SpotifyApi implements MusicApi {}
    public class YoutubeApi implements MusicApi {} // As example of completely different audio extraction algorithm
    

    Now I have to choose when to use which API. I've decided to create MusicApiSelector class (Kept implementation listing simple without using Java Reflection API or Spring @Component)

    public class MusicApiSelector {
        private static final MusicApi[] registeredApis = new MusicApi[]{NapsterApi, SpotifyApi, YoutubeApi};
    
        public static MusicApi getApi(String link) {
            for (MusicApi api : registeredApis) {
                if (api.isLinkMatches()) {
                    return api;
                }
            }
            throw new Exception("This link is not supported")
        }
    }
    

    Using this should look something like this

    public class Main {
        public static void main(String[] args) {
            String link = https://www.youtube.com/watch?v=djV11Xbc914;
            MusicApi api = MusicApiSelector.getApi(link);
            AppObject appObject = api.getAppObject(link);
        }
    }
    

    Can you tell me if that's valid approach how this pattern is called (i guess it's Strategy Pattern). And what I can do better (maybe some completely different patterns)

    Trying to Create Sequential Color Pattern with CSS

    I'm trying to create a color pattern that looks something like this https://snipboard.io/po6jrn.jpg that isn't just simply:

    li:nth-of-type(1) {
       background: blue;
    }
    
    li:nth-of-type(2) {
       background: dark-blue;
    }
    
    li:nth-of-type(3) {
       background: red;
    }
    
    [...]
    
    

    Ideally, I'd like to be able to structure the CSS in a way that manages the color pattern automatically for an unknown amount of dynamic elements.

    I've been getting close in my tests, but I can't seem to get the color pattern exactly the way I want it. See my Fiddle: http://jsfiddle.net/MaxxSkywalker/v0xpub7e/4/

    How to create a classes that inherit any class at runtime

    I am guessing this isn't possible since c# doesn't support prototyping but worth an ask.

    I have a big set of unrelated classes, all inheritable, let's take two of them: Bar and Baz.

    I want to extend all these classes in the same way: adding two public int properties: X and Y, and potentially some other private variables and methods down the road. Let's call this class (before inheriting) Foo, and Foo is meant to inherit Baz, Bar and so on.

    I don't want to have to explicitly create different classes for Bar, Baz, ....

    class FooBaz : Baz
    
    class FooBar : Bar
    
    ...
    

    Instead, Is there a way I can create a kind of factory that takes the classes, e.g bar, baz and then returns an object of the that is foo : bar, or foo : baz etc?

    Var FooedBaz = New Foo(Baz);
    
    WriteLine(FooedBaz.X);
    

    Why do I want this?

    Because I am using WPF and extending various UIElements like Image to add x and y coordinates onto them. This way I can directly use the classes within the WPF system without have to access members etc.

    mardi 14 février 2023

    Is it bad design to have an abstract method with a parameter that isn't used by all inherited classes?

    There is an inheritance structure at my work's codebase, where there are 2 inherited classes that define an method get_df, however one of the parameters, var2, is unused in the second inherited class. I believe it was designed this way so that when get_df is called in process, it can use polymorphism rather than if/else checks.

    Here's the skeleton code of what I'm referring to:

    class base_class:
      @abstractmethod
      def get_df(self, var1, var2):
        pass
    
      def process(self):
        # obtain var1, var2
        self.get_df(var1, var2)
    
    class inherited_class1:
      def get_df(self, var1, var2):
        # define get_df
    
    class inherited_class2:
      def get_df(self, var1, var2):
        # define get_df, but var2 is not used here
      
    

    In general, is this kind of design frowned upon since you're passing in an argument that's unused?

    An alternative design would be to get rid of the abstract method and do if/else checks:

    class base_class:
      def process(self):
        if self is inherited_class1
          # obtain var1, var2
          self.get_df(var1, var2)
        else # self is inherited_class2
          # obtain var1
          self.get_df(var1)
    
    class inherited_class1:
      def get_df(self, var1, var2):
        # define get_df
    
    class inherited_class2:
      def get_df(self, var1):
        # define get_df
      
    

    Are there other approaches that I should consider?

    Many producers single consumer fair job scheduling in Golang

    I have multiple producers that stage objects (jobs) for processing, and a single consumer that takes objects one-by-one. I need to design a sort of a scheduler in golang.

    1. Scheduling is asynchroneous, i.e. each producer works in a separate gorourine.
    2. Scheduler interface is "good" in terms of golang-way (I'm new in Go).
    3. A producer can remove or replace its staged object (if not yet consumed) with zero or minimal lost in the position in a queue. If a producer misses its slot because it canceled and then restaged an object, it still keeps a privilege to stage as soon as possible early till the end of the particular round.
    4. "Fair" scheduling between producers.
    5. Customizable multi-level weighting/prioritization

    I'd like some hints and examples on right design of such a scheduler.

    I feel I need every producer to wait for a token in a channel, then write (or don't write) an object to a shared consumer channel, then dispose the token, so it is routed to a next producer. Still, I'm not shure this is the best approach. Besides, it takes 3 sequential syncrhoneous operations per producer, so I'm afraid I'll have performance pitfalls because of the token traveling too slowly between producers. Also, 3 steps for one operation is probably not a good golang-way.

    lundi 13 février 2023

    Refactoring a class method to be under an abstract base class and splitting the logic without changing the base class method signature?

    I'm currently working on redesigning a class to be under an abstract base class. The current class has a method func that does some logic for two things, say A and B.

    class current_class:
      def func(self):
        # does stuff for A 
        # does stuff for B
    

    During logic A, it loads a large dataset into a dictionary, say, dataset and later dataset.keys() is used for logic B, but other than that, A and B are independent of each other.

    I will create an alternate class, say, another_class that is similar to current_class, but this class doesn't need B and only needs A. So something like

    class another_class:
      def func(self):
        # does stuff for A
    

    And then both will be under an abstract base class base. Since both inherited classes involves A, I plan on just creating a method in base class that does A, say, func_A. But I'm having trouble with figuring out the best way to approach this so that the function signatures conform and without having to reload dataset for B.

    If another_class also needed the logic for B, I think we can just return dataset.keys() from func_A and use it in func_B, but another_class doesn't.

    So I don't know if there's a good way to conform this without having different signatures for the methods.

    So in code, I have the following two ideas:

    1)

    class base:
      @abstractmethod
      def func(self):
        pass
      def func_A(self):
        # does stuff for A and gets the dataset
        return dataset.keys()
    
    class current_class:
      def func_B(self, keys):
        # does stuff for B
      def func(self):
        keys = self.func_A
        self.func_B()
    
    class current_class:
      def func(self):
        _ = self.func_A() # the return is unused...
    
      class base:
        @abstractmethod
        def func(self):
          pass
      
      
      class current_class:
        def func_A(self):
          # does stuff for A and gets the dataset
          return dataset.keys()
        def func_B(self, keys):
          # does stuff for B
        def func(self):
          keys = self.func_A()
          self.func_B()
      
      class current_class:
        def func_A(self):
          # does same stuff as func_A for current_class, and doesn't return anything
        def func(self):
          self.func_A()
      

      I don't like the first design because func_A only needs to return something for one of the subclasses and not for all of them. I also don't like the second design because we have to separately implement func_A in each inherited class even though they're identical methods, except one needs to return something and the other doesn't.

      Why do we inherit from the component class in decorator pattern?

      In the decorator pattern, the decorator class inherits from the component class and has an aggregation relationship with it. Well, the aggregation relationship is logical, but why should we inherit from the component? This pattern is supposed to decorate the component, so why does it need to inherit from it? If we have a component object in the decorator, we can add new functionalities to our class at runtime as we want, but I don't understand the inheritance.

      uml photo

      Reusing symbol in SVG pattern

      I found that symbol reused in pattern looks blurry.

      <svg version="1.1" xmlns="http://www.w3.org/2000/svg" width="70mm" height="84mm">
      
      <defs>
      <symbol id="Pole" viewBox="0 0 30 30">
          <path fill="#666" fill-rule="evenodd" d="m 9 9 l 3 6 l -3 6 l 6 -3 l 6 3 l -3 -6 l 3 -6 l -6 3 z m -6 4 v 4 h 10 v 8 h 4 v -8 h 10 v -4 h -10 v -8 h -4 v 8 z m 12 -13 a 1 1 0 0 0 0 30 a 1 1 0 0 0 0 -30"/> 
      </symbol>
      
      <pattern id="Poles_StepDependedWidth" x="0" y="0" width=".25" height="1" patternUnits="objectBoundingBox">
          <rect height="100%" width="100%" fill="red" opacity="0.25" />
          <use href="#Pole" width="7mm" height="7mm" />
      </pattern>
      </defs>
      
      <rect x="7mm" y="4.5mm" height="7mm" width="70mm" fill="url(#Poles_StepDependedWidth)"/>
      <use href="#Pole" x="0" y="4.5mm" width="7mm" height="7mm" />
      
      </svg>

      Playng with combination of patternUnits, viewBox (for pattern and symbol) didn't fix the blurring symbol in pattern (with red background).

      Pipeline design chain of responsibility pattern

      I'm designing a pipeline, in its simplest form: a customer applies for a loan, the request goes to the credit score service, after the credit score is calculated, it goes to the credit service with the credit score and the approval or rejection of the loan is calculated there. In this system, would the Chain of Responsibility design pattern be appropriate?The working logic of the system

      I'm confused little bit

      dimanche 12 février 2023

      What is the smartest way of creating complex custom themed components with Chakra UI?

      We want to implement a scalable way of using Chakra UI to create complex custom components with our custom theme styles. But we are finding it difficult to crack which approach would be most scalable.

      For instance, let’s say we want to create a ExerciseButton that has a text, an image, and a progress bar that displays how much of the exercise the user has completed

      We have thought about different approaches.

      1. Create variant styles for each of the sub Chakra Ui components.
      2. Create a new component, Exercise Button and style its parts

      Abstract_factory UML diagram in Wikipedia incorrect?

      Referring to the UML diagram depicted in https://en.wikipedia.org/wiki/Abstract_factory_pattern#/media/File:Abstract_factory_UML.svg, one could conclude that ConcreteFactory1 and ConcreteFactory2 are derived from AbstractFactory.

      But AbstractFactory is an interface, therefore it must be 'implemented', not 'extended'.

      What am I missing?

      samedi 11 février 2023

      How to implement Observer Design Pattern in Java? [duplicate]

      I am trying to implement observer in my project. I have created a test package and started very small and simple, without any interfaces and additional classes to see how it might work out. This is the code:

      ConcreteSubject:

      package observer;
      
      import java.awt.Color;
      import java.awt.Component;
      import java.util.ArrayList;
      import java.util.List;
      import javax.swing.JLabel;
      import javax.swing.JTextField;
      
      public class ConcreteSubject {
      
          private List<Component> component;
      
          public ConcreteSubject() {
              this.component = new ArrayList<>();
          }
      
          public void register(Component c) {
              component.add(c);
          }
      
          public void unregister(Component c) {
              component.remove(c);
          }
      
          public void unregisterAll() {
              component.removeAll(component);
          }
      
          public void newLogin() {
              loginPerformed();
          }
      
          private void loginPerformed() {
              JLabel errorLabel = (JLabel) component.get(0);
              JTextField usernameField = (JTextField) component.get(1);
              JTextField passwordField = (JTextField) component.get(2);
              if (usernameField.getText().equals("") || passwordField.getText().equals("")) {
                  errorLabel.setForeground(Color.RED);
                  errorLabel.setText("EMPTY FIELDS!");
                  return;
              }
              errorLabel.setForeground(Color.GREEN);
              errorLabel.setText("YOU HAVE SUCCESSFULLY LOGGED IN!");
              usernameField.setText("");
              passwordField.setText("");
          }
      }
      

      Form:

      package observer;
      
      public class Form extends javax.swing.JFrame {
      
          ConcreteSubject subject;
      
          /**
           * Creates new form Form
           */
          public Form() {
              initComponents();
              subject = new ConcreteSubject();
              subject.register(error_Label_);
              subject.register(username_Field_);
              subject.register(password_Field_);
          }
      
          /**
           * This method is called from within the constructor to initialize the form.
           * WARNING: Do NOT modify this code. The content of this method is always
           * regenerated by the Form Editor.
           */
          @SuppressWarnings("unchecked")                       
      
          private void login_Button_MouseClicked(java.awt.event.MouseEvent evt) {                                           
      
              subject.newLogin();
          }                                          
      
          /**
           * @param args the command line arguments
           */
          public static void main(String args[]) {
              /* Set the Nimbus look and feel */
      
              /* Create and display the form */
              java.awt.EventQueue.invokeLater(new Runnable() {
                  public void run() {
                      new Form().setVisible(true);
                  }
              });
          }
      
          // Variables declaration - do not modify                     
          private javax.swing.JLabel error_Label_;
          private javax.swing.JButton login_Button_;
          private javax.swing.JTextField password_Field_;
          private javax.swing.JLabel password_Label_;
          private javax.swing.JTextField username_Field_;
          private javax.swing.JLabel username_Label_;
          // End of variables declaration                   
      }
      

      Basically what i want to do in my real project is to be able to dynamically change components of jframe whenever a button is clicked or some object has changed.

      And when i want to click on another button i want to change other set of components.

      I don't know what might be the best way of implementing observer in this case.

      Plus i am generally confused on how am i supposed to work around with netbeans gui builder.

      Any help will be appreciated!

      Best way to peeping a reference to context in State / Strategy patterns

      I often implement finite state machines following the State/Strategy OOP patterns with two classes - StateMachine and State

      Option 1

      class State(ABC):
          context: StateMachine
          def __init__(self, context: StateMachine):
              self.context = context
      
          @abstractmethod
          def execute(self):
              ...
      
      class StateMachine:
          state: State
      
          def __init__(self, initial_state: State):
              self.state = initial_state
          
          def enter(self, state: State):
              self.state = state
              
          def run(self):
              self.state.execute()
      

      However, requiring context as a constructor argument for every State quickly feels redundant

      class StateFoo(State):
          def execute(self):
              ...
              self.context.enter(StateBar(self.context)) # <-- feels redundant
      

      It feels implicit that the StateMachine context being passed to StateBar will always be the same one that StateBar is being given to through .enter(). Yet I'm having to reference it twice.

      I've considered moving the responsibility of giving a State it's context inside of StateMachine.enter()

      Option 2

      class State(ABC):
          context: StateMachine | None
          # removed constructor
      
          @abstractmethod
          def execute(self):
              ...
      
      class StateMachine:
          state: State
      
          def __init__(self, initial_state: State):
              self.state = initial_state
          
          def enter(self, state: State):
              self.state = state
              state.context = self # <-- inject dependency here
              
          def run(self):
              self.state.execute()
      
      class StateFoo(State):
          def execute(self) -> None:
              print("foo")
              self.context.enter(StateBar()) # <-- No need to pass context now
      

      The ergonomics are better, but it possibly introduces a safety impurity: the type of State.context is now potentially None. It's possible (although unlikely and probably unreasonable) for a developer to create a State and call .execute() without passing it to a StateMachine.enter() first, making any internal logic that relies on a .context fail.

      A solution I've considered is to have StateMachine call an inherited State.safe_execute() method which will pre-confirm that .context is set before delegating to the real .execute() that every State implements.

      class State(ABC):
          context: StateMachine | None
      
          @abstractmethod
          def execute(self):
              ...
      
          def safe_execute(self):
              if self.context is None:
                  raise Exception("self.context is not set!")
              self.execute()
      
      class StateMachine:
          state: State
      
          def __init__(self, initial_state: State):
              self.state = initial_state
          
          def enter(self, state: State):
              self.state = state
              state.context = self
              
          def run(self):
              self.state.safe_execute() # <-- replaced self.state.execute()
      

      This gets rid of the runtime safety concern, but I feel that it might be overcautious.

      A third option is to remove the reference to .context on State and instead parameterize .execute() to take it as an argument.

      Option 3

      class State(ABC):
          @abstractmethod
          def execute(self, context: StateMachine): # <-- context is passed in
              ...
      
      class StateMachine:
          state: State
      
          def __init__(self, initial_state: State):
              self.state = initial_state
          
          def enter(self, state: State):
              self.state = state
              
          def run(self):
              self.state.execute(self) # <-- pass self for context parameter
      

      This isn't particularly appealing. Some State descendants will not need a reference to the context for their .execute() details, resulting in an unused parameter, potentially tunneled down through multiple State.execute() calls before ever being used. It also - like Option 1 - allows for the possibility of passing a different StateMachine context to a state on different .execute() calls, which may or may not be a bad thing.

      In summary

      Option 1

      • Results in long redundant lines `self.context.enter(StateFoo(self.context))
      • Allows for a StateMachine to enter/execute a State who has a reference to a different StateMachine

      Option 2

      • Better code ergonomics/readability self.context.enter(StateFoo())
      • It makes sense to hide away construction details to the StateMachine, as it might be philosophically implied that a State can only exist within the context of a StateMachine. May be better separation of concerns and ontological clarity.
      • Introduces a runtime safety flaw; a State may be constructed and executed before passing it to self.context.enter() to receive .context
      • Prevents a State from having a reference to a StateMachine other than the one executing it, but does allow for another `StateMachine' to hijack it.

      Option 3

      • All .execute() implementations now require a context parameter which may be unused

      This naturally poses a few questions:

      1. Is it ever advantageous to have State instances able to swap out their .context?

      2. Is it ever advantaegeous to have StateMachine able to call .execute() on a .state whose .context is set to a different StateMachine?

      3. Which of the options are best in which scenarios?

      4. Are there any other alternatives?

      vendredi 10 février 2023

      java composition to reduce code complexity

      Let us say there is a class LargeClass with 4k lines of code. I would like to reduce the file size to manage it better by extracting the code into some other classes.

      class LargeClass extends SomeLibraryClass {
      
        void featureOneLargeMethod1() {
        }
      
        void featureOneLargeMethod2() {
        }
      
        void featureOneLargeMethod3() {
        }
      
        void featureTwoLargeMethod1() {
        }
      
        void featureTwoLargeMethod2() {
        }
      
        void featureTwoLargeMethod3() {
        }
      
      }
      

      I could create two classes FeatureOne and FeatureTwo and move the corresponding methods into these new classes but the featureOneLargeMethod1() calls protected SomeLibraryClass.someLibraryMethod() which makes it impossible to move these methods. I was thinking of creating a wrapper interface that LargeClass implements and thereby FeatureOne and FeatureTwo class can access them. Any better approach in java or kotlin instead of creating the wrapper interface?

      jeudi 9 février 2023

      Angular 14: Implement Factory pattern

      I want to implement Factory pattern in Angular.

      The point is, I need to create several forms but every form has its owns properties so I thought the best approach was to create a Factory of forms and depends of the type the factory will render one form or another.

      app.component.html

      <app-form-builder [type]="'phoneForm'"></app-form-builder>
      

      form-builder.component.ts

      interface FormMapping {
        [key: string]: ComponentRef<FormNameComponent | FormPhoneComponent>;
      }
      
      @Input() type: string = '';
      
      constructor(public viewContainerRef: ViewContainerRef) {}
      
      getFormTypes(type: string) {
        const formMapping: FormMapping = {
          nameForm: this.viewContainerRef.createComponent(FormNameComponent),
          phoneForm: this.viewContainerRef.createComponent(FormPhoneComponent),
        };
      
        formMapping[type];
      }
      
      ngOnInit(): void {
        this.getFormTypes(this.type);
      }
      

      The form components are not relevant since the phoneForm displays a form with a input type number and the nameForm displays a form with a input type text.

      The approach works if I use multiple If's but I don't know why don't if I use the object because it renders the two forms at the same time.

      getFormType(type: string) {
        if (type === 'nameForm') {
          this.viewContainerRef.createComponent(FormNameComponent);
        }
      
        if (type === 'phoneForm') {
          this.viewContainerRef.createComponent(FormPhoneComponent);
        }
      }
      

      Demo @ StackBlitz

      I have followed this StackOverflow question but this example shows how to instantiate a Service but in my case I want to instantiate a component.

      Trying to understand the difference in what matches and the resulting output for findall vs finditer

      1. Using findall:
      import re
      
      target_string = "please sir, that's obviously a clip-on."
      
      result = re.findall(r"[a-z]+('[a-z])?[a-z]*", target_string)
      
      print(result)
      
      # result: ['', '', "'s", '', '', '', '']
      
      1. Using finditer:
      import re
      
      target_string ="please sir, that's obviously a clip-on."
      
      result = re.finditer(r"[a-z]+('[a-z])?[a-z]*", target_string)
      matched = []
          
      for match_obj in result:
          matched.append(match_obj.group())
      
      print(matched)
          
      # result: ['please', 'sir', "that's", 'obviously', 'a', 'clip', 'on']
      

      How does these two methods match patterns and why is there a difference in resulting output. Please explain.

      Tried to read the docs but still confused on the workings of findall vs finditer

      Map Based Web Application Architecture

      I was recently hired by a startup that performs data analysis on agriculture groves and is looking to present it on a new web app. My role is to build a more scalable, modern system for the team. I have done a boatload of research and diagraming to reach a feasible starting point for fulfilling my task, but want some direct feedback on my chose of the tech stack/architecture.

      Frontend:

      • ReactJS with Typescript / Redux
      • MapBox

      Backend:

      • NodeJS with Express as the server framework
      • GraphQL API using AWS AppSync, chosen for its efficient data retrieval and ease of use compared to a RESTful API

      Database:

      • AWS Aurora for storing relational data
      • AWS DynamoDB for storing unstructured JSON data
      • AWS S3 for image data

      Hosting

      • Vite (fastest dev builds & bundling)
      • AWS EC2 (deployment and running the machine learning models on the images)

      I am looking to get some open-source feedback, as well as any pointers or alternatives that would fit better for our use case. Thank you in advance.

      Why do we need design patterns? [closed]

      Why do we need design patterns? Tell me what to do to appreciate the importance of a design pattern, not tell me it's important.

      I've learned basic computer knowledge and written code. I often see factory patterns or singleton patterns in projects. I don't realize the benefits of writing like this? What kind of project I can write to get these things?

      How to implement Mediator Design Pattern in Netbeans?

      I am trying to implement something similar to this example on refactoring guru: Mediator in Java in my project.

      I have created additional package with simple login form frame and some of the classes to test how it might work. Here is some code for more context...

      Component interface:

      package mediator;
      
      public interface Component {
      
          void setMediator(Mediator mediator);
      
          String getName();
      }
      

      Mediator interface:

      package mediator;
      
      public interface Mediator {
      
          void login();
      
          void registerComponent(Component component);
      }
      

      Login button:

      package mediator;
      
      import java.awt.event.ActionEvent;
      import javax.swing.JButton;
      
      public class LoginButton extends JButton implements Component {
      
          private Mediator mediator;
      
          public LoginButton() {
              super("Log in");
          }
      
          @Override
          protected void fireActionPerformed(ActionEvent actionEvent) {
              mediator.login();
          }
      
          @Override
          public void setMediator(Mediator mediator) {
              this.mediator = mediator;
          }
      
          @Override
          public String getName() {
              return "LoginButton";
          }
      }
      

      Username field:

      package mediator;
      
      import java.awt.event.KeyEvent;
      import javax.swing.JTextField;
      
      public class UsernameField extends JTextField implements Component {
      
          private Mediator mediator;
      
          @Override
          public void setMediator(Mediator mediator) {
              this.mediator = mediator;
          }
      
          @Override
          protected void processComponentKeyEvent(KeyEvent keyEvent) {
              mediator.login();
          }
      
          @Override
          public String getName() {
              return "UsernameField";
          }
      }
      

      Passoword field:

      package mediator;
      
      import java.awt.event.KeyEvent;
      import javax.swing.JTextField;
      
      public class PasswordField extends JTextField implements Component {
      
          private Mediator mediator;
      
          @Override
          public void setMediator(Mediator mediator) {
              this.mediator = mediator;
          }
      
          @Override
          protected void processComponentKeyEvent(KeyEvent keyEvent) {
              mediator.login();
          }
      
          @Override
          public String getName() {
              return "PasswordField";
          }
      }
      

      Mediator:

      package mediator;
      
      public class Dialog implements Mediator {
      
          private UsernameField username;
          private PasswordField password;
          private LoginButton login;
      
          @Override
          public void login() {
              if (username.getText().trim().isEmpty()) {
                  System.out.println("Username is empty!");
                  return;
              }
              if (password.getText().trim().isEmpty()) {
                  System.out.println("Password is empty!");
                  return;
              }
              System.out.println("All good!");
          }
      
          @Override
          public void registerComponent(Component component) {
              component.setMediator(this);
              switch (component.getName()) {
                  case "LoginButton":
                      login = (LoginButton) component;
                      break;
                  case "UsernameField":
                      username = (UsernameField) component;
                      break;
                  case "PasswordField":
                      password = (PasswordField) component;
                      break;
              }
          }
      }
      

      Frame:

      package mediator;
      
      public class LoginFrame extends javax.swing.JFrame {
      
          Mediator mediator;
      
          /**
           * Creates new form LoginFrame
           */
          public LoginFrame() {
              initComponents();
              mediator = new Dialog();
              mediator.registerComponent(new LoginButton());
              mediator.registerComponent(new UsernameField());
              mediator.registerComponent(new PasswordField());
          }
      
          /**
           * This method is called from within the constructor to initialize the form.
           * WARNING: Do NOT modify this code. The content of this method is always
           * regenerated by the Form Editor.
           */
          @SuppressWarnings("unchecked")
      
          private void login_Button_MouseClicked(java.awt.event.MouseEvent evt) {
      
              mediator.login();
          }
      
          /**
           * @param args the command line arguments
           */
          public static void main(String args[]) {
              /* Set the Nimbus look and feel */
              /* Create and display the form */
              java.awt.EventQueue.invokeLater(new Runnable() {
                  public void run() {
                      new LoginFrame().setVisible(true);
                  }
              });
          }
          // Variables declaration - do not modify
          private javax.swing.JButton login_Button_;
          private javax.swing.JTextField password_Field_;
          private javax.swing.JLabel password_Label_;
          private javax.swing.JTextField username_Field_;
          private javax.swing.JLabel username_Label_;
          // End of variables declaration
      }
      

      I want to be able to validate and dynamically change components on jframe when action is called from mediator.

      The problem is i dont know how to do it because of netbeans built in gui builder and action listeners. I have similar jframes in my project where i used gui builder and i would like to keep it that way.

      Do i send for example the whole jbutton i created in jframe as a parameter and then cast it to a class? What is the general best practice to follow when doing something similar? I am generally confused :).

      Does enyone know what is the best way to do this?

      When i run the code above and click login button a couple of times with the text displayed i get this output: Output picture! I have also tried to pass login_Button_ variable to a LoginButton class to type cast it but i was not able to do it.

      I know i missed something crucial but i just don't know what.

      Any help will be appreciated!

      Ada: polymorphic callbacks

      I'm trying to implement an Observer pattern using OOP and dynamic dispatching, but I'm not able to create an access-to-subprogram constant because the argument types of the named access and the procedure of the type extension don't match.

      I provide a minimal reproducibable example, ommiting subscription:

      package Alarms is
      
        type time_t is mod 2**32;
      
        type AlarmObserver_t is interface;
        type Callback_t is access procedure (this : in out AlarmObserver_t);
      
        type AlarmPublisher_t (<>) is tagged limited private;
        function fConstructor (capacity : in Positive) return AlarmPublisher_t;
      
      private
      
        type AlarObserverAcc_t is access AlarmObserver_t'Class;
      
        type dummy_t is new AlarmObserver_t with null record;
        procedure pEventDummy (this : in out dummy_t) is Null;
      
        dummy : constant AlarObserverAcc_t := new dummy_t;
        dummyCallback : constant Callback_t := pEventDummy'Access; --Fails
      
        type Node_t is limited
          record
            Observer : AlarObserverAcc_t := dummy;
            Callback : Callback_t := dummyCallback;
            time : time_t := time_t'Last;
          end record;
      
        defaultNode : constant Node_t := Node_t' (Observer => dummy,
                                                  Callback => dummyCallback,
                                                  time     => time_t'Last);
      
        type ObserverArray_t is array (Positive range <>) of Node_t;
      
        type AlarmPublisher_t (capacity : Positive) is tagged limited 
          record
            --Member "observers" has default initialisation because Node_t is initialised
            observers : ObserverArray_t (Positive'First .. capacity);
          end record;
      
      end Alarms;
      

      And the implementation to let you reproduce it:

      package body Alarms is
        
        function fConstructor (capacity : in Positive) return AlarmPublisher_t is
        begin
          return Obj : AlarmPublisher_t (capacity => capacity) do
            Null;
          end return;
        end fConstructor;
      
      end Alarms;
      

      I was inspiring in Matthew Heaney callbacks Observer pattern

      He use a class-wide argument for the access-to-subprogram procedure, but I would like to use OOP notation and let the concrete observers to have those procedures as primitives.

      Why procedure pEventDummy is not compatible if dummy_t implements AlarmObserver_t interface? Can I do what I want?