vendredi 7 avril 2023

Multiple calling @property that reduce list

I'm training my skills of design patterns. With a Factory schema i tried to get and pop example numbers from a imited list.

With initialization of seccond account i recieved an IndexError. In debug mote i noticed that between initialisation of acc01 and acc02 I have a 4 uses of AccountManager.number() func. Same with AccountManager.account_id().

from abc import ABC
from random import choice, randint


class AccountsManager:
    def __init__(self) -> None:
        self._last_id_number = 0
        self._allowed_numbers = [randint(10_000, 99_999) for _ in range(5)]

    @property
    def number(self) -> int:
        if not self._allowed_numbers:
            raise IndexError
        number = choice(self._allowed_numbers)
        self._allowed_numbers.pop(self._allowed_numbers.index(number))
        return number

    @property
    def account_id(self) -> int:
        account_id = self._last_id_number
        self._last_id_number += 1
        return account_id


class TemplateBankAccount(ABC):
    def __init__(self, manager, owner: str, account_type: str = '') -> None:
        self.manager = manager
        self.id_number = manager.account_id
        self.account_number = manager.number

        self.owner = owner
        self.account_type = account_type
        self._amount = 0

    def __str__(self) -> None:
        raise NotImplementedError

    @property
    def amount(self) -> int:
        return self._amount

    @amount.setter
    def amount(self, direction: str, value: int) -> None:
        if direction == '+':
            self._amount += value
        elif direction == '-':
            self._amount -= value
        else:
            raise ValueError


class PersonalBankAccount(TemplateBankAccount):
    def __init__(self, manager, owner) -> None:
        super().__init__(manager, owner, account_type='Personal Account')

    def __str__(self) -> str:
        return f'{self.account_type}: {self.owner}'


class CompanyBankAccount(TemplateBankAccount):
    def __init__(self, manager, owner) -> None:
        super().__init__(manager, owner, account_type='Company Account')

    def __str__(self) -> str:
        return f'{self.account_type}: owner name restricted.'


class SavingsBankAccount(TemplateBankAccount):
    def __init__(self, manager, owner) -> None:
        super().__init__(manager, owner, account_type='Savings Account')

    def __str__(self) -> str:
        return f'{self.account_type}: {self.owner}'


class AccountCreator:
    def __init__(self) -> None:
        self.manager_group = AccountsManager()

    def create_account(self, owner_name, account_type):
        allowed_types = {'Personal': PersonalBankAccount(self.manager_group, owner_name),
                         'Company': CompanyBankAccount(self.manager_group, owner_name),
                         'Savings': SavingsBankAccount(self.manager_group, owner_name)}

        return allowed_types.get(account_type, 'Non offered account type')


def main() -> None:
    creator = AccountCreator()
    create_account = creator.create_account
    acc_01 = create_account('Andrew Wiggins', 'Personal')
    acc_02 = create_account('NASA Inc.', 'Company')
    acc_03 = create_account('John Paul Wieczorek', 'Savings')

    list_of_accounts = [str(account) for account in (acc_01, acc_02, acc_03)]
    print('\n'.join(list_of_accounts))


if __name__ == '__main__':
    main()

I do not know how to change code to get values from self._last_id_number and self._allowed_numbers only once per create_account call.

jeudi 6 avril 2023

Execute a method right before execution of various methods in different classes using Java

I am facing a code design challenge and not very sure how to resolve it. Tried researching a bit on the net but that made me even more confused.

InterfaceI1 -> Parent level interface (Single method)

Class C1 -> C1 implements I1 (C1 overrides method from I1 has no method of its own)

Class CC1, CC2, CC3, CC4, CC5 -> All these extend C1 (Overrides method in C1 and has methods of its own as well)

The problem is : I need to execute a piece of code on execution of certain methods in classes CC1, CC2, CC3, CC4, CC5. These methods have nothing in common and certainly its not the overridden method.

Is there a way to write this common piece of code in a central place and make it execute on execution of concerned methods?

Also the execution of this common piece of code would also depend on another environmental condition. For eg :

If the method in CC1 is executed && its a weekend { Execute the common code }

Since i dont want to clutter all the methods with the same boilerplate code i did some research and came across AOP. It looked like a fit for the requirement though not sure if conditional execution could be managed with AOP. As i was reading about it i learned about Action At Distance anti-pattern and how its not good for the code manta inability.

Any leads or suggestions would be helpful.

Edit : CC1, CC2, CC3, CC4 is not a spring bean

AWS Step Function - Wait until a group of other Step Functions have finished then fire a different Step Function

I have a scenario where I need to post process results that have been produced by a group of discrete Step Functions. How can I orchestrate this arrangement such that, if I have Step Function A, B and C. Once A, B and C have completed successfully then trigger Step Function D.

Step Function D will take as a payload outputs from Step Functions A, B and C. A, B and C are triggered from an external Java Microservice. I have a Dynamo DB table containing details of A, B and C, so I know which execution IDs belong together.

This seems to be quite a common pattern so I was hoping that there was already some sort of robust design to address it.

I have thought about using SNS to trigger an event when Step Functions A, B and C complete but I need to capture these events together in a group. So if I had a Lambda which captured the event, I would need to somehow know which event this is and whether or not all prior events have been received. I could use a Dynamo DB table to track each Step Functions completion status, at the end of the Step Function update the row. Then the lambda when it receives the completion event can check if each of the rows pertaining to the group of executions is marked as completed? Would this introduce a race condition? is this a trustworthy method?

mercredi 5 avril 2023

How can I FIX/CHANGE the almost invisible Menu Items in my Website's Mobile Version?

As you develop your application, you can use Swift syntax to write code that interacts with the user interface, accesses device hardware and sensors, communicates with servers, and more. There are many resources available online to help you learn Swift, including official documentation, tutorials, and communities.

What Design Patterns can be applied to my application?

I have a student project, a simple standalone Python application to track common expenses (Split Wiswe analog).

The code is complete and working. The goal of the project is to apply several Design Patterns and I need help with this.

Can anyone tell me which Design Pattern can be implemented here?

Which design pattern to implement in order to split the responsibilities?

I have a part of my application that I would like to refactor. The classes involved have too many responsibilities as well as too many dependencies. Different parts of the code that needs refactoring make use of the same app modules. These modules are used in the same way - to check whether another operation can occur.

Example:

  1. The user wants to perform an update - check if the user is signed in.
  2. The user tries to use a paid app feature - check if the user is signed in and has the right to use that feature.

I am seeking for a design pattern that will centralize the logic that is used in too many places in the same way.

Do architecture patterns force a specific folder structures?

By following an architecture patterns, am I forced to follow a specific file structure? For example if I'm following MVC, am forced to have a folder structure similar to what asp.net core mvc has?

Doesn't architecture patterns just tell us how different components should communicate?