Can Object pool design pattern cause memory shortage?

When I am using the Object pool design pattern, and allowing the pool to grow, by creating new objects when they are required but not available in the pool, and placing them in the pool after they have been used, can it eventually cause memory shortage, or some kind of an out of memory exception/error?

It looks very reasonable that after some time it will happen, because the pool grows, and the object within it don’t get deleted.

Go to Source
Author: Daniel

What are the pros and cons of using a reference/pointer vs an ID

I’m writing in C++, but this problem applies to any language without GC and even to languages with a GC as well.

I have a structure in memory in which I create/add objects. The structure takes ownership of those objects. I should never need to use an object after it’s removed from the structure.

When I first implemented this data structure, it seemed natural to use an ID/key/name/handle for the objects stored in it. I’m using it like this:

id1 = structure.addObj(new Square());
id2 = structure.addObj(new Square());
id3 = structure.addObj(new Circle());

obj3 = structure.getObj(id3);
obj3.addFriend( id1 );
obj3.addFriend( id2 );

idMax = structure.findObjWithMostFriends();
objMax = structure.getObj(idMax);
print(objMax.name);

After using it for a while, I’m thinking that it would be better to forget about the IDs and always use references to the objects instead. This way I wouldn’t need to pass a reference to the structure around every time.

I’m thinking about refactoring everything to only use references but I’m afraid of regretting it. I’d like to know more about what are the pros and cons of using IDs to decide whether I should proceed.

Memory details:

The objects are allocated on the heap and their address never changes.

The structure deallocates those objects when they’re removed (they could be released to the caller instead, but I don’t need this at the moment).

I’m not supposed to ever use objects that don’t belong to the structure. If my program is correct, I should never end up with a dangling ID or pointer. But it could happen if the program has bugs.

What are your experiences switching from IDs to references for similar problems? Which solution should I use?

Go to Source
Author: Helloer

Pattern name for “Platform independant class with Hooks + sub class implementing platform specific”?

I am developing an android app to process jpg exif meta data in a workflow.

The Workflow class is implemented platform independant (i.e. code runs on android and on j2se).

The Workflow contains and calls protected virtual methods that do nothing for android specific .functions (i.e save changes to android media database)

package de.k3b.media;

// platform independant
public class Workflow {
    public void processPhoto(...) {
        ...
        saveChangesToMediaDatabase(....);
        ...
    }
    
    protected void saveChangesToMediaDatabase(...) {    
        // to nothing in platform independant version
    }
}

I also have a android platform specific sub class that implements the platform specific code

package de.k3b.android.media;

// android platform dependant
public class AndroidWorkflow extends Workflow {
    @Override
    protected void saveChangesToMediaDatabase(...) {    
        ... do something with android media database
    }
}

I can use Workflow.processPhoto(...) in non-android j2se apps and in automated unit or integration tests
and i can use AndroidWorkflow.processPhoto(...) in my android app

My question: Is this an established pattern and is there a name for this pattern?
My current pattern name “Platform independant class with Hooks” and “Platform specific Hook implementation”.

I hope to find a better (??established??) name for this pattern.


Remarks:

One established pattern to have platformindependat code is by using a Facade pattern.

Example: I use a FileFacade with a j2se implementation based on java.io.File and AndroidFileFacade which is based on android specific DocumentFile.

Although the goal of platform independance is the same the way how this is achieved is different.

Go to Source
Author: k3b

Pattern design for a trading application

Do you know how trading sites/applications manage data and then display it?
e.g. prorealtime, tradingview, metatrader etc.
From our side, we receive raw data or already processed data that are just displayed?

I don’t understand why you down vote my post.
What is the difference with this kind of question?
Why does Java use :: for method references instead of .?

Is maintenance, feedback, or support an integral phase of SDLC?

They just ask questions

Go to Source
Author: antho

Trying to figure out running multiple queries with single endpoint based on the input parameters

I am trying to create a system, which has multiple queries for different kinds of reports. My plan is to queries in the database tag them report A, report B. Obvisouly SQL query will have some placeholders to pass paramterers.

I am trying reduce my coding work. So that i’ll keep adding queries in the database without touching the code.

i have explored diffrent django tool, but i haven’y found any suitable tool.

Any guidence will be apperictaed.

Go to Source
Author: wizard

Decoupling and Command Pattern

I am working on some project to learn how to make bigger and better software (multiplayer game) and I found a problem about having in my code a design pattern Command Pattern and anti-pattern God Object. Often I do end up win the latter one and I know that Fascades are okay, but my understanding of something being right and wrong in OOP is very blurry.

I’ve implemented the Command Pattern. Shortly, my command:

public interface IGameCommand : ICommand
{
    bool Execute(Game game);
}

And an executor

public interface IExecutor<TState, TCommand>
{
    void Execute(TCommand command);
}

Let’s say that I have a command that does a lot: modifies some data, plays sound etc.

So, in my case, this should look like this:

public class MagicSpell: IGameCommand
{
    int x; int y; int damage; string soundClipName; string effectName;
    bool Execute(Game game)
    {
         game.gameState.map[x][y].unit.TakeDamage(damage);
         ...
         game.soundPlayer.PlaySound(soundClipName);
         ...
         game.specialEffectPlayer.PlayEffect(effectName);
         ...
    }
}

As you can see, this forces my Game class to become a God object… or doesn’t it? Since my Game class contains specialized classes that do their thing I am fulfilling the Single responsibility principle. I have some bad experience with ending up with a God Object, but is my solution viable and acceptable with OOP?

Or maybe is something wrong with my Command Pattern implementation and Execute(Game game)?

Maybe making some specialized commands would help?

Go to Source
Author: Clockworker

Repository pattern – using information from other repositories

I am trying to understand what is the proper approach when the objects generated from a Repository have a reference to objects which are responsible for another Repository.

Let’s say I have terminals which can have a list of possible quantities assigned and each quantity has a type. In this case I have 3 repositories TerminalsRepository, QuantitiesRepository, and QuantityTypeRepositories.

How should I populate the quantities information for the terminals and the type information for the quantities? Should the repositories use internally the other repositories or is there a better way to achieve that (for example a service method is retrieving the terminals and then populating the needed data)?

Go to Source
Author: djvuk

Can a GoF Builder implementation be considered valid without an explicit getProduct()?

For studying purpose, I’ve tried to create a simple PHP implementation of Builder GoF (not the Joshua Bloch’s one) inspired on this slide.

The main goal of this example is to encapsulate the construction of data files from diferents inputs (Directors) and outputs (Builders)

Lots of Builder example (including the wikipedia’s one) define an explicit “getProduct/getResult” on the Builder Class.

In my case, I thought the creation of output file would be considered the literal product, so I have opted to not use a method to get the file.

So, I would like to know if the absence of this method would invalidate it as Builder GoF implementation.

<?php
namespace BuilderGoFEnglish;
abstract class Builder {
    protected SplFileObject $output;
    public function __construct(string $outputFileName) {
        $this->output = new SplFileObject($outputFileName, 'w');
    }
    abstract function addHeader(array $header);
    abstract function addLine(array $linha);
    abstract function finish();
}
abstract class Director {
    protected Builder $builder;
    public function __construct(Builder $builder) {
        $this->builder = $builder;
    }
    public abstract function build(string $inputFileName);
}
class XmlDirector extends Director {
    public function build(string $inputFileName) {
        $document = new DOMDocument();
        $document->preserveWhiteSpace = false;
        $document->load($inputFileName);
        $root = $document->firstChild;
        $item1 = iterator_to_array($root->firstChild->childNodes);
        $this->builder->addHeader(array_column($item1, 'tagName'));
        foreach($root->childNodes as $child){
            $item = iterator_to_array($child->childNodes);
            $this->builder->addLine(array_column($item1, 'nodeValue'));
        }
        $this->builder->finish();
    }
}
class JsonDirector extends Director {
    public function build(string $inputFileName) {
        $jsonArray = json_decode(file_get_contents($inputFileName));
        $this->builder->addHeader(array_keys((array) $jsonArray[0]));
        foreach ($jsonArray as $jsonObject) {
            $this->builder->addLine((array) $jsonObject);
        }
        $this->builder->finish();
    }
}
class HtmlBuilder extends Builder {
    private DOMDocument $document;
    private DOMElement $table;
    public function __construct(string $output) {
        parent::__construct($output);
        $this->document = new DOMDocument('1.0', 'utf-8');
        $this->document->appendChild($this->document->createElement('html'));
        $this->table = $this->document->createElement('table');
        $this->table->setAttribute('border', 1);
        $this->document->firstChild->appendChild($this->table);
    }
    private function createTableRow(array $linha, $tipo = 'td'){
        $tr = $this->document->createElement('tr');
        array_map(fn($v) =>
                $tr->appendChild($this->document->createElement($tipo, $v)),
                $linha);
        $this->table->appendChild($tr);
    }
    public function addHeader(array $header) {
        $this->createTableRow($header, 'th');
    }
    public function addLine(array $linha) {
        $this->createTableRow($linha);
    }
    public function finish() {
        $this->output->fwrite($this->document->saveHTML());
    }
}
class CsvBuilder extends Builder {
    private array $csvArray = [];
    public function addHeader(array $header) {
        $this->csvArray[] = $header;
    }
    public function addLine(array $linha) {
        $this->csvArray[] = $linha;
    }
    public function finish() {
        foreach ($this->csvArray as $linha) {
            $this->output->fputcsv($linha);
        }
    }
}

Go to Source
Author: celsowm

Class Design question concerning adding a new “DRAFT” state to an object

Class Design question concerning adding a new “DRAFT” state to an object

We have some entities in our code:

-“View” and View has some attributes and also contains one or many “SubViews”

-And each “SubView” has some attributes and contains one or more “Tweet” entities.

So far so good. User edits Views/SubViews/Tweet (adding/removing tweets from subviews, adding/removing subviews fro views etc) in our UI and as everything is linked it updates fine. At the moment the user after editing, can decide to make her changes “Live” Or just discard them, there is no option to save and come later.

So now we want to introduce a “Draft” system. So user can edit a View/SubView/Tweet in a draft state (This is to be persisted) and eventually decide to make it “Live”. On making it “Live” the draft doesn’t die. User can continue to work on the draft and make it live again. So they both live side-by-side and have to be linked.

I’m not sure how to go about introducing this is code as the “Live” is just implicit in code/db atm. Some options I could think:

  1. Add a flag to each class with Live/Draft state indication. This will mean that I need to keep them in synch between the entities that are linked together
  2. Add another “Manager” like class that holds the objects related to Draft/Live versions of the views and manages the relationship between them. Using only the current types. The Manager is the only one that knows what is draft and what is live object
  3. Add a completely new type “DraftView”->”DraftSubView”->”DraftTweet” and manage the relationship between Draft and Live entities

At the DB level I’m thinking of just adding another column to the table to say Live/Draft.

More likely, there is a better way to do this and there are patterns to help with this, so i’m hoping I can get some opinions on my suggestions or better ways to do this. Hopefully I could make the question clear.

Thanks,

Go to Source
Author: user642770