samedi 5 mars 2022

Design pattern for isolating parsing code?

I have C++ class Foo:

class Foo
{
public:
    [constructor, methods]

private:
    [methods, data members]
};

I want to add to class Foo the possibility for it to be constructed by reading data from a text file. The code for reading such data is complicated enough that it requires, in addition to a new constructor, several new private methods and data members:

class Foo
{
public:
    [constructor, methods]

    Foo(const std::string& filePath); // new constructor - constructs a Foo from a text file

private:
    [methods, data members]

    [several methods used for text file parsing] // new methods
    [several data members used for text file parsing] // new data members
};

This works, but I feel it would be better to isolate the new parsing code and data members into their own entity.

What would be an adequate design pattern in order to achieve this goal?

Form Input with Pattern

I need help, first character in the input must be "M" or "S"

<input type="text" name="trackid" id="trackid" value="<?= set_value('trackid'); ?>" class="form-control form-control-user text-center" placeholder="TrackID" required>

Higher-level SQL constructs?

I'm writing what is effectively SQL++. It's going well and is outputting code which I've used to write a small app in so it's not vapourware though it is early days.

It currently supports automatic joins via foreign keys, temporary views with scalar and relational (table/view) parameters, dynamic pivoting (non-relational, I know), 'matches' which can be used to implement semi- and antisemi-joins, stronger type checking, including some static analysis of nullability errors. I'm planning to add relational division.

What kind of high-level SQL features would you, as professional SQL devs, like to see? These features could probably be used to it implement features which if done by hand would require procedural code or/and triggers (this language could write those triggers, but if it's declarative this will be hidden from the user which is what I want). Basically, what do you want this language to do for you that you have to do manually now? What error checking would you like that is currently not done? Please note that any suggestions must be driven by actual business needs, (everything I've implemented has been driven by requirements for my SQL dev work). Cool ideas without a business reason aren't good. I'm not interested in syntactic changes, but underlying support of functionality (that can include stuff like further error checking, but checking for what?)

This language can only implement what the underlying database provides; it can't do magic (nor can I, I'm no genius and my time is limited). Also it must be able to implement what you want efficiently and in a conceptually obvious way (if you can't do it manually neither can this language). The output is TSQL for MS SQL Server but eventually should be others, but I can't take that on now.

I realise this is a very broad call but it's a start. Suggestions welcome. Links to existing/proposed descriptions of relevance also very welcome but I've found little except image relations in Date/Darwen's work and a few things in Tutorial D. There are some wishlists like Erland Sommarskog's, Brent Ozar's and a few others I'm aware of which are useful, but others?

Things like distributed foreign keys are interesting but I've found no need for them but others might have different experiences, please chip in.

vendredi 4 mars 2022

Design pattern recommendations for oop game

Hi, I'm making a simple oop game in python using pygame.

Currently, my game object classes have methods like move, draw and check collision. I would like to create a new class with the intention of handling these interactions in a way that my game object classes don't have to know about other game objects anymore

Here are the abstract classes for the game objects

import pygame
from abc import ABC, abstractmethod
import copy


class ABCObject(ABC):
def __init__(self, initial_x: int, initial_y: int, size: int, color: tuple):
    self._size = size
    self._rect = pygame.Rect(
        initial_x, initial_y, self._size, self._size)
    self._color = color

@property
def size(self):
    return self._size

@property
def rect(self):
    return self._rect

@property
def color(self):
    return self._color

@size.setter
def size(self, new_size: int):
    if isinstance(new_size, int):
        self._size = new_size

@color.setter
def color(self, new_color: tuple):
    if isinstance(new_color, tuple):
        if len(new_color) == 3 and isinstance(new_color[1], int) and isinstance(new_color[0], int) and isinstance(new_color[2], int):
            self._color = new_color

def draw(self, win, offset):
    fake_rect = copy.deepcopy(self._rect)
    fake_rect.topleft -= offset
    pygame.draw.rect(win, self._color, fake_rect)
from abc_object import ABCObject


class Kinetic_object(ABCObject, ABC):
    def __init__(self, initial_x: int, initial_y: int, size: int, color: tuple, speed: int):
        super().__init__(initial_x, initial_y, size, color)
        self._speed = speed
        self._velX = 0
        self._velY = 0

    @property
    def speed(self):
        return self._speed

    @property
    def velX(self):
        return self._velX

    @property
    def velY(self):
        return self._velY

    @velX.setter
    def velX(self, new_velX):
        if isinstance(new_velX, (int, float)):
            self._velX = new_velX

    @velY.setter
    def velY(self, new_velY):
        if isinstance(new_velY, (int, float)):
            self._velY = new_velY

    @speed.setter
    def speed(self, new_speed):
        if isinstance(new_speed, int):
            self._speed = new_speed

    @abstractmethod
    def move(self):
        pass

And here is my player class:

import math
import copy
from abc_command import Command
from abc_kinetic_object import Kinetic_object


class Player(Kinetic_object, Command):
    def __init__(self, initial_x: int, initial_y: int, size: int, speed: int, obstacles: list):
        Kinetic_object.__init__(
            self, initial_x, initial_y, size, (250, 160, 60),  speed)
        Command.__init__(
            self, {'up': False, 'down': False, 'right': False, 'left': False})
        # usar depois para mudar sprite
        self._facing_direction = 'down'
        self._obstacles = obstacles

    # usar para normalizar os vetores de velocidade, caso contrario, anda mais rápido nas diagonais
    def normalize(self):
        if self._velX != 0 and self._velY != 0:
            self._velX *= 1/math.sqrt(2)
            self._velY *= 1/math.sqrt(2)


    # Colisoes, funciona se nao colidir com objetos em movimento
    def move(self):
        self.normalize()
        self._rect.x += self._velX
        self.check_collisions('horizontal')
        self._rect.y += self._velY
        self.check_collisions('vertical')

    def check_collisions(self, direction):
        if direction == 'horizontal':
            for obstacle in self._obstacles:
                if obstacle.rect.colliderect(self._rect):
                    if self._velX > 0:  # direita
                        self._rect.right = obstacle.rect.left
                    elif self._velX < 0:  # esquerda
                        self._rect.left = obstacle.rect.right

        if direction == 'vertical':
            for obstacle in self._obstacles:
                if obstacle.rect.colliderect(self._rect):
                    if self._velY > 0:  # baixo
                        self._rect.bottom = obstacle.rect.top
                    elif self._velY < 0:  # cima
                        self._rect.top = obstacle.rect.bottom

    def change_facing_direction(self):
        # so apertando para direita
        if self._commands['right'] and not (self._commands['down'] or self._commands['up'] or self._commands['left']):
            self._facing_direction = 'right'
        # so apertando para esquerda
        elif self._commands['left'] and not (self._commands['down'] or self._commands['up'] or self._commands['right']):
            self._facing_direction = 'left'
        # so apertando para cima
        elif self._commands['up'] and not (self._commands['down'] or self._commands['right'] or self._commands['left']):
            self._facing_direction = 'up'
        # so apertando para baixo
        elif self._commands['down'] and not (self._commands['up'] or self._commands['left'] or self._commands['right']):
            self._facing_direction = 'down'

    def execute_commands(self):
        self.change_facing_direction()
        self._velX = 0
        self._velY = 0
        if self._commands['left'] and not self._commands['right']:
            self._velX = -self._speed
        if self._commands['right'] and not self._commands['left']:
            self._velX = self._speed
        if self._commands['up'] and not self._commands['down']:
            self._velY = -self._speed
        if self._commands['down'] and not self._commands['up']:
            self._velY = self._speed

I would like to know which design pattern would be appropriate in order to remove methods like "move" from game objects and implement them in other controller classes, I have different objects that all move in a different way.

C# Should I make readonly properties all public [closed]

I started in a new project and a colleague is insisting of making all readonly properties public I argued (because I was learned to) that the encapsulation should be always as high as possible, so for me does not make any sense use public accessor in a property that could be protected or private, just because it is read only. What is the benefit of doing so?

Java implement schema and row interface

I am implementing an in-memory table library. I have a ITableSchema interface that defines the columns, table name etc. I also have a IRow interface with methods like get(Column), set(Column). What would be a good practice way to ensure that. If I have Say Two table schemas TableA, TableB and a row implementation for each schema- what would be a good way to ensure RowAs are not used with TableBs etc. can I use templates for this somehow?

jeudi 3 mars 2022

Postgres architecture for one machine with several apps

I have one machine on which several applications are hosted. Applications work on separated data and don't interact - each application only needs access to its own data. I want to use PostgreSQL as RDBMS. Which one of the following is best and why?

  1. One global Postgres sever, one global database, one schema per application.
  2. One global Postgres server, one database per application.
  3. One Postgres server per application.

Feel free to suggest additional architectures if you think they would be better than the ones above.