mercredi 30 novembre 2016

Spring State Machine Builder/Configuration Design Pattern with Large Number of Transitions

For example the Spring State Machine is configured like so: source

.source("S1")
.target("S2")
.event("E1")
.action(timerAction());

This will lead to hundreds of lines of configuration. Leaving a messy configuration class for the state machine. I was thinking to make this cleaner to wrap each of these into a method/bean themselves as a transition, and add transitions to the state machine.

statemachinebuilder.addTransition(transitionBean);

I wanted to hear if others had any better suggestions? It could be externalized but then this would just be defining the same transition objects and reading them into construct the state machine. Thanks.

Extracting line between two pattern using Sed and the next pattern should come in new paragraph in mac

I want to extract all lines that comes between two citation. I want to include first sentence containing citation and should stop extraction when new citation comes. This process should continue till end of file. I am using Mac. The two pattens must be separated by blank lines or some dashed lines. This is my input data which i extracted using command

sed -n '/([1-2][0-9]{3})/,/^([1-2][0-9]{3})/p;/^(*[1-2][0-9]{3})/q'

But i want the output should come like this


Any personal bias by authors has to be hedged (Hyland, 1995).

Negative sentiment is politically particularly dangerous (Ziman, 1968), and some authors have documented the strategy of prefacing the intended criticism by slightly disingenuous praise (MacRoberts and MacRoberts, 1984). This makes the problem of identifying such opinions particularly challenging.

This nonlocal expression of sentiment has been observed in other genres as well (Wilson et al., 2009; Polanyi and Zaenen, 2006).

Pattern to avoid Cyclic calls

I have Policy class as below:

interface IPolicy
{
public:
virtual void func1() = 0;
}

class CPolicy : public IPolicy
{
public:
void func1() override { // do something }
}

And I have Utility Class as

class Util {
public:
void func1() {
if( policy != nullptr ) policy->func1(); // customized behavior

// default behavior
}

}

Now problem is, consider policy implementation have some condition and if that condition fails, policy calls default implementation ( this is one of the scenario, there can be multiple combinations )

class CPolicy : public IPolicy
{
public:
void func1() override { 
 if( condition ) 
 {
    // customized logic
 }
 pDefaultUtil->func1();
}
}

Now if you see this implementation it will endup in cyclic calls.

To solve such problem, I introduced another function in IPolicy contract.

interface IPolicy
{
public:
virtual void func1() = 0;
virtual bool ShouldUsePolicy() = 0;
}


class CPolicy : public IPolicy
{
public:
void func1() override { 
 if( condition ) 
 {
    // customized logic
 }
 usePolicy = false;
 pDefaultUtil->func1();
usePolicy = true;
// other logic continues.
}

bool ShouldUsePolicy() override { return usePolicy; }
private:
bool usePolicy { true };
}

and Util class is modified as :

class Util {
public:
void func1() {
if( policy != nullptr && policy->ShouldUsePolicy() ) policy->func1(); // customized behavior

// default behavior
}

}

With these changes, everything will work as expected, but I am not happy with this design. I don't want to depend on whether Policy is setting usePolicy variable properly or not. If any call comes from Policy to Default implementation then I should be able to ignore policy.

Is there any good pattern / solution for such problems?

How to tokenize Spanish text with NLTK or Pattern-es

Basically the issue I am having is with separating object and direct object pronouns from verbs.

Ie 'aprenderlo' should ideally be tokenized as two separate entities, 'dimelo' should be tokenized as three. I have tried a variety of taggers in both libraries, and so far nothing has produced the results I want. However, I am sure this must be a common problem - any ideas?

Dynamicly assign pub/subs of different event types to multiple aggregator

I have various Modules which can send and receive different Event<T> . for example

class A : ISub<Event<Picture>>
class B : ISub<Event<SomeObject>>
class C : IPub<Event<Picture>>
...

etc.

Is there a proper way (existing framework) to dynamicly assign instances of these classes to different instances of EventAggregator<T>? For example by registering the pub/subs to a non generic EventController which then handles the connections between the modules independenly and makes it somehow easy to manage from wpf?

Designing a simple web application

I'm working on a web application for school, currently being at the point of designing the system. My application will have users with different roles: Admin,Student,Teacher,Parent,Principal etc. They will all have most of the properties in common (each will have a login name, a password and so on), but they will have slightly different behaviour(teachers will be able to assign marks, students to see their timetable, the principal will be able to generate some charts and so on). I want to design the entities as elegant as possible( I looked on some design patterns, but maybe I'm missing something). Using an interface User and some classes implementing the interface doesn't seem like a good option from my point of view. Some guidance would be really helpful.

require-uncached thread safety, creating new instances in javascript

I have a system that could be serving a high throughput of HTTP requests, and I am trying to load a custom module with a new instance for each request. The reason I want to create a new instance is because within the module is an object that is shared across promises in multiple promise chains. I would like the object to be isolated for each instance of this module. I realize this may be considered an anti-pattern in some shops, but I like having a single dynamic object that can be used across many complex promise chains, as it allows my promises to be reusable in many different wans. I like how the promise chains organize my code, and the pattern itself fits my needs well, but would like to hear about alternatives if any. Here is an example:

var reusableObject;

module.exports = function() {
    return {
        myFunction: function() {
            return somePromise()
            .then(anotherPromise)
            .then(yetAnotherPromise)
            .then(function() { return reusableObject; })
        }
}

I was unsuccessful in creating new instances with the new operator with the statement var service = new (require('myModule'))(). My best guess was that underneath, requirejs is fetching the module from cache.

I came across a module called require-uncached, and voila, I was successfully able to create new instances of my module. However, when glancing at the code, I can't tell if this module is going to be thread-safe. I realized it's time to get some expert analysis. Any help is appreicated. tia

time complexity of regular expression in java

I wrote the following script by using regular expression to find a repeated string in the string s,now i try to find the complexity of it, if any one know what is the complexity of it, please let me know.

String s = "ABCABCAAAABBBBCCAAABCGABCABC";
           Pattern pattern = Pattern.compile("(?:([ABC])(?!\\1)([ABC])\\1\\2)+");
           Matcher matcher = pattern.matcher(s);
           while (matcher.find()) {
            System.out.print("FOUND");

            }

Access to the leafs of Composite pattern Java

I implement the Composite pattern for represent a tree of elements like in the picture: enter image description here

But how I can access to the leafs of this tree, like a List of Leaf. Should I implement Visitor?

Composition/Inheritance/Factory - Best Pattern For This Case

Good [your_time_of_day],

Today I have been learning about composition and factory functions in javascript (es6). I understand that composition should be preferred over inheritance and have come to agree with that (at least in javascript). Then, I realised that I have a situation where I should be using composition...

Question first:

Is there a way I can change my complex, inherited structure so classes are composed of functions without having ridiculous numbers of decorators? Have I missed something about composition in general (I feel like I have)?

Situation

I have a base class AudioPlayer:

class BaseAudioPlayer {
    public track;
    protected seekBar;

    public togglePlay() {
        //
    }

    public seek(time) {
       //some seek methods using this.seekBar
    }
}

And a few player classes would extend from this like so:

class MainAudioPlayer extends BasePlayerComponent {
    public loadTrack(track) {
        //This is horrible
        this.track = track;
    }

    public setSeekBar(seekBar) {
        //This is horrible
        this.seekBar = seekBar
    }
}

Please bare in mind I actually have a lot more methods in parent and child classes and there are many methods in some children that are not in others. Of course, there is no multiple inheritance involved but I see at some point that might become a possibility with multiple alike child players (bad!).

I could use many decorators like @playable() @seekable() etc. but then I see that, eventually, the number of mixins would become huge. I guess I could also use factory functions in a similar manner but see the same problem.

Full disclosure: I am using Angular2 and have cut back the code a lot to keep any discussion about which design pattern to use and not about an implementation in a specific framework.

How to handle ThreadPool hitting the server connection limit

I could be asking a design pattern question here.

On Android, I am using a thread pool to open 8 threads to download some files.

    try {
        ExecutorService pool = Executors.newFixedThreadPool(8);
        for (int i = 0; i < someList.size(); i++) {
            pool.submit(new DownloadJsonTask(someList.get(i), context));
        }
        pool.shutdown();
        pool.awaitTermination(Long.MAX_VALUE, TimeUnit.MILLISECONDS);
    } catch (Exception e) {
    }

I noticed if I use one thread to download one-by-one, then I hardly get download fails but if I use 8 threads, then I sometimes get download fails. I am not a server/network person so I don't know in detail but I am guessing the server is putting a limit of one device (or one IP address) trying to connect multiple connections.

If this is the reason, then how do I design the code to overcome this issue? I have already implemented to try downloading 3 times before failing. It does seem to fixed it "for now". However, I know my code is not robust and it can fail at one point.

I figured, I wouldn't be the first one facing this issue. I would like to know a robust solution around this issue.

Solutions I could think of:
- Try to download at least 3 times before failing
- Once failed, then try to sleep for a random amount of time. So that failed threads don't wake up at the same time and fail again. - If the server throws come kind of unique message back such as Server busy, then re-try unlimited(?)(large amount of) times.

I have not yet implemented above possible solutions. I want to know the common/best solution first and spend time implementing it.

Any ideas?

js : canvas hex board game

I'm developing a hex-based board game for 3 or 2 players.

Following this excellent tutorial :

http://ift.tt/1xSfUuM

I'm now able to draw hex tiles with in-board ones and wall/holes (tiles outside the map, no display, no interactions)

For the moment and for debugging purposes, the default behavior is to display map tiles, with cube hex references on them, and setting up the background according to tile owned data.

Very basic for.in loop :

var layout = ...;
var ctx = ...;
var tile;

for(var ref in this.tiles) {
  tile = this.tiles[i];
  // something like tile { hex : {q:q,r:r,s:-q-r}, data : { ...} }
  this.render(ctx, layout, tile);
}

Where this.render is a board's method wich calls in turn this.drawBackGround, this.drawOutline, this.drawCoords... and so forth.

But I wish to keep things generic and carry drawing methods outside hex library perimeter...

How does achieve this ?

Tiles should hold : - sprites : who owns the tile, with what type of pawn ? - background gradient colored differently depending on player - animations when dropping or capturing players pawns... - behavior : selectable or not

I guess I have to inject some dependencies, a kind of theme manager for the whole board and draw tiles via a set of main rendering callbacks and various helper sub-callbacks...

Is it the right way ?

Is the `Builder` design pattern obsolete in Python?

I was reading through this article on design patterns in Scala, and they presented the argument that the Builder pattern is relevant in Java, as it allows for code such as:

CarBuilder carBuilder = new CarBuilder()
carBuilder.setSeats(2)
carBuilder.setSportsCar(true)
carBuilder.setTripComputer(true)
carBuilder.setGPS(false)
Car car = carBuilder.build()

versus the more confusion-prone form:

Car car = new Car(2, true, true, false)

They later stated that:

In a language like Scala which lets you name arguments while passing them in, the builder pattern is mostly obsolete...

Is this a similar situation for Python, as you're able to name keyword arguments in any call, or is there some reasonable application for this design pattern?

React states and mobx - antipattern?

Question: Is it an anti pattern to both have mobx and react, then utilise both reacts component states, and the @observer @observable from mobx?

Since from what i can understand, mobx tries to replace the react states, or at least does something that is very similar.

Design pattern java resource

Please I want to a good materials in Design pattern in Java and J2EE and I want to know the most used in real life Thanks and best regards

Correct approach to not instantiating a class because of X variable?

I do not know a lot of Patters but I heard that using Factory Pattern will help me with this, but I am not sure if this is the case or I have better solutions.

So, I have a class that, when calling ToString() it will return a string representation of an HTML control. When I use the constructor, it will recibe some parameters and it will use those to see if they are in a table like a row, if they exist this object will return an empty HTML string representation, so, to not instantiate the object (because it will be like empty) should I use a Factory Pattern and there return the object if it is valid or null if it is not ?

I don't have the code because I will start with it now, but I need to have this part clear so I will not "recode" some parts.

Thanks you in advance !

Compare string patterns and exclude characters that are not common C#

I have two string A = ABCDEFG, string B = ABCDHJKL and string C = ABC. I want to compare the strings and get only the maximum matching part of and non-matchng part as separate strings. For example, in the above example the result should be ABCD is matching and non-matching is EFGHJKL.

Is there a way we can do this using string manipulation or using Tries is the only way out?

How to load external pages in master page dynamically

I have two web applications :

  • Main Template Application --->MainTemplate
  • Consuming Application.--->DemoApp

With the following structure :

enter image description here enter image description here


How to load The pages which reside in DemoApp in the master page of MainTemplate dynamically ?

Design a rescue game

I would like to design a rescue game

Game has follwing elements

1) Zombie river , it contains zombies and some survivers
2) Safe river
3) One Ship which can acomodate 2 passengers other than sailor.

Ship will take survivers from zombie river to safe river .As soon as ship reaches zombie river, survivers go form hidden state to running state. Whoever comes first takes ship.

As per design I can think of following Objects

Vehichle

LivingBeing
1) Zombie 
2) Surviver

LivingBeings can be in two states hidden or running.

Vehicle can also be in stop, running , boarding , unboarding states.

Ship can be derived from Vehicle.

We also need some random number generator so that we can generate which surviver will board ship. How can I use good design principles like SOLID to solve this problem

what are the design patterns used in codeIgniter 3 or PHP 7?

I just want to understand the design patterns, it would be better if I know the design patterns used in codeigniter 3 or PHP 7.

I found that java libraries are mostly build with the help of design patterns.

Builder pattern - configuration file reading

all

I'm facing a design problem. I want to separate building objects with a builder pattern, but the problem is that objects have to be built from configuration file.

So far i have decided that all objects, created from configuration, will be stored in DataContext class (container for all objects), because these objects states will be updated from a transmission (so it's easier to have them in one place).

I'm using external library for reading from XML file - and my question is how to hide it - is it better to inject it to concreteBuilder class? I have to notice that builder class will have to create lots of objects, and at the end - connect them between each other.

Base class could look like that: /* * IDataContextBuilder * base class for building data context object * and sub obejcts / class IDataContextBuilder { public: / * GetResult() * returns result of building process */ virtual DataContext * GetResult () = 0; /* * Virtual destructor */ virtual ~IDataContextBuilder() { } };

class ConcreteDataContextBuilder { public: ConcreteDataContextBuilder(pugi::xml_node & rootNode); DataContext * GetResult (); }

How to implement it correctly? What could be better pattern to build classes from configuration files?

Is the class a singleton?

Is the class listed below a singleton? Since the constructor is declared as public, can I infer that the class is a singleton with wrong implementation?

public class CreateDevice extends Functionality{

  private static Simulator simulator;
  ConnectionDB connect = ConnectionDB.getInstance();


  public CreateDevice(Simulator simulator){
    this.simulator = simulator;
  }

  private static CreateDevice instance;
  synchronized public static CreateDevice getInstance() {
    if(instance == null){
      instance = new CreateDevice(simulator);
    }       
      return instance;
  }
}

mardi 29 novembre 2016

HTML - Pattern to validate nomenclature

I'm trying to use the "pattern" attribute for HTML5 but I do not have much experience in the regex.

The nomenclature that I wish to validate is the following:

0100455_LM_Izaguirre

Where "0100455" will generally have 7 to 10 characters, "LM" may vary "LM, LI, AQ" and everything that comes after (eg "Izaguirre") is a text with at least 1 character. What is important is that scripts are maintained and needed.

All this is necessary to validate a value that will then be modified in PHP and will later be pasted into a Word with PHPWord.

//0100455_LM_Izaguirre
$sitebase = "0100455_LM_Izaguirre";
$string = explode("_", $sitebase);
$idcontrol = $string[1].'_'.$string[0];

Is this an IIFE?

I'm trying to understand how this JavaScript code works. It's a library to help make multi-step modals. It relies on Bootstrap and jQuery. (Full code on github)

This is a very stripped down version that shows the basic outline:

function multistep($) {
    'use strict';

    var modals = $('.modal.multi-step');
    modals.each(function (idx, modal) {
        //variables set
        //many other functions

        function initialize() {            
            //code...
        }
        initialize();
    })
} (jQuery);

This is how it's called on the HTML page:

<script type="text/javascript">

    $(function () {
        multistep(jQuery);
    })

</script>

I would have thought that the (jQuery) following the function multistep($) declaration means that multistep is an IIFE, but:

  1. There are no parentheses around the entire function
  2. The function has to be called in the document.ready, and doesn't execute automatically

What pattern does this code follow? What am I missing?

What are B2B Patterns?

I am planning to make a B2B application using ASP.NET MVC. Before getting started i am willing to learn if there are B2B patterns and what are these, how to used?

We have built different B2B softwares for different companies from different sectors. But every sector has different needs and we have to start from beginning. We would like to solve this problem.

Singleton Pattern Recommended Method

Case 1:

public class Singleton {

  public static final Singleton INSTANCE = new Singleton();

  private Singleton() {
    ...
  }
}

Case 2:

public class Singleton {

  private static final Singleton INSTANCE = new Singleton();

  private Singleton() {
    ...
  }

  public static Singleton getInstance() {
    return INSTANCE;
  }
}

Is the second method the recommended way to implement the Singleton design pattern, because I have never seen the first one in any example for Singleton pattern.

iOS MVVM architecture

I would like to ask you guys about MVVM architecture on iOS using Swift. Basically I got to know what is Model, ViewModel and ViewController. Now to the point:

The goal is to make TableViewController with viewModel's data. If I say that I want to make a list of cars then my viewModel should represent the data for one car or for all cars? Referring to this example he puts the data into AppDelegate - but I'm not convinced if it is a good place. When I would like to supply my TableViewController with the data from Database - how it should be made from architectural point of view?

Do you know some good and advanced example to have a look?

I also had a look on VIPER, cleanSWIFT, but I want to check them all and see the differences.

I'm so tired of using MVC pattern where I haven't implemented neither unit test.

Is Data Binding bad for long term?

While i am looking for Android patterns i came across with following comment about data binding in following question:

However, there is one prediction I can make with a high degree of confidence: usage of Data Binding library will not become an industry standard. I'm confident to say that because Data Binding library (in its current implementation) provides short term productivity gains and some kind of architectural guideline, but will make the code non-maintainable in the long run. Once long term effects of this library will surface - it will be abandoned.

Which design patterns are used on Android?

What is your opinion about it? If you agree with it can you explain why?

lundi 28 novembre 2016

Data transfer object class can contain other objects?

I just wanted to know DTO class contain another objects or not. Please tell me the below code is valid DTO class or not?

class Address implements Serializable{

private String city;
private String location

}

class EmployeeDTO implements Serializable{
private String name;
private int age;
private Address address;
//setters and getters
}

Market Interface on DTOs

I have something like this

//A marker Interface
public interface User {
}

//2 DTO Classes
public Administrator implements User{
//getters and setters
}

public OperativeUser implements User{
//getters and setters
}

//A generic interface
public interface UserService<T extends User>{
    public void createUser(T user);    
}
//Two concrete clases
public class AdministratorService implements UserService<Administrator>{
    public void createUser(T user){
       //specific stuff for an administrator
    }    
}
public class OperativeUserService implements UserService<Administrator>{
    public void createUser(T user){
       //specific stuff for an operative user
    }    
}

All this because if I write a simple UserDTO then in order to differenciate them I will end with an spagetti code like if is administrator do this and if is operative user do that, so a need to classify the users of my system as a common interface but no common behavior

So my questions are

1.-There is a better way to achieve this kind of hierarchy with composition (implements) and no with inheritance(extends) if yes could you give me some guidence?

2.- Is a good use of markers interfaces the way I did or I misunderstood?

This is base on the following questions and answers

Nice way of factory method pattern with inheritance

Interfaces for DTOs

Thank you very much!

3 Methods in a repository or merge into 1 method?

I have created a TokenRepository class with 3 methods.

Those methods create an entry to same a table but each method have different fields. Is this good pattern or should I use an interface and 3 implementations or merge 3 methods into 1 method?

For example:

class TokenRepository
{

  public function createTokenDigitalOcean(User $user, $name, $accessToken, $refreshToken = null)
    {
        return $user->tokens()->create([
            'name'          => $name,
            'provider'      => 'digital_ocean',
            'access_token'  => $accessToken,
            'refresh_token' => $refreshToken,
        ]);
    }

    public function createTokenLinode(User $user, $name, $key)
    {
        return $user->tokens()->create([
            'name'       => $name,
            'provider'   => 'linode',
            'linode_key' => $key,
        ]);
    }

    public function createTokenAws(User $user, $name, $key, $secret)
    {
        return $user->tokens()->create([
            'name'       => $name,
            'provider'   => 'aws',
            'aws_key'    => $key,
            'aws_secret' => $secret,
        ]);
    }
}

Game engine structure OOP

I am currently working on a small engine in C++. I reached a stalemate in the OOP structure of my project and I am not sure if this schema I would like to use is right or not. I would like to know if this approach is good in terms of a clean OOP design or what is a mistake in my case. The reason I am asking is that I found some sources of potential include conflicts and circular dependencies.

This is how it looks like:

Scene - Finds out what objects to load, stores them, on update calls physics etc to update the object positions

AssetManager - Does the loading of textures, models,...

Renderer - Displays the data, OpenGL in this case but I want to keep it alone like this since I would love to make for example a Vulkan version later

Object - stores basic data about objects

Schema (assume that the arrows are dependencies):

Scene ---creates the objects and stores them---> Object
Scene ---tells what to load---> AssetManager 
Object ---keeps what assets are assigned to it---> AssetManager
Scene ---tells which assets to prepare to render---> Renderer
Renderer ---needs to ask for the asset data---> AssetManager

What bothers me is the need of communication like: AssetManager<-Scene->Renderer->AssetManager<-Renderer

Simplified code:

class Scene
{
  objects
  loadScene(assetManagerPointer, rendererPointer)
}
class Object
{
  someInfo
  assetPointer
  drawObject //needs the call from renderer
}
class Renderer
{
  preparedModels //needs the asset to know which data to use 
}

Thanks.

Observer pattern: notify with state

The examples I've seen on the internet only give notifyObservers() method to the Observable object. What if I want to also pass some data to the observers, so that they know if they should react to it or not? Does the observer pattern allow passing the data like maybe:

notifyObservers(Event e).

Or maybe the observers themselves should pull the change? Like maybe: notifyObservers() -> call observer.update()

and then each observer decides if the new data is relevant for them, observable.getData(). However with this approach, it is unclear to me, how to get only the data that has changes, if it's at all needed.

java singleton class vs final class

can anybody explain me clearly on java singleton design pattern class vs java final class. can we use final class instead of using singleton class, for final class we can create the instance of the class and use the methods in that but not overriding properties, if that methods are static in final class we can just call the methods like ClassName.getMethod, why we go for singleton instead of final class.

Open Closed Principle: Different ways / scenarios it can be applied

One of the most common ways of applying the OCP, is through abstractions and inheritance like below. Where the design is closed, but behavior can still be extended by adding new types of Shape abstraction without modifying existing behavior.

class GraphicEditor 
{
    public void drawShape(Shape s) 
    {
        s.draw();
    }
 }

 class Shape 
 {
    abstract void draw();
 }

 class Rectangle : Shape  
 {
    public void draw() 
    {
        ...
    }
 } 

What are the other different ways / scenarios that you are aware of (or have come across), of implementing the open close principle?

Want to enforce specific order of methods execution of a class, when this class is used. Does exist a design pattern for this?

I have a class that represents a process

internal class IntegrationWithSalesforce
{
    public IntegrationWithSalesforce()
    { // Initialize internal variables }

    public bool GetListOfCustomersToImport() { ... }
    public bool CreateSalesforceJob() { ... }
    public bool CreateJobBatches() { ... }
    public bool CloseSalesforceJob() { ... }    
    public void UpdateBatchesProcessingInfo() { ... }
    public bool AbortJob() { ... }
}

methods should be execute in specific order until you invoke CloseSalesforceJob.

I want to enforce this order of execution: 1- class initialization 2- call GetListOfCustomersToImport if true 3- call CreateSalesforceJob if true 4- call CreateJobBatches if true 5- call CloseSalesforceJob 6- then keeps calling UpdateBatchesProcessingInfo until all batches states have value Completed ,Failed

My first idea is have boolean variables that represent state(or execution ) and set the one related with method to true when method is called, or throw custom Exception ProcessOrderExecutionException if method is not the next in order.

For example:

// add this variable to my class
bool processInitialized = false;
bool customerSumaryListRetrieved = false;
bool salesforceJobSuccessfullyCreated = false;
bool salesforceBatchesSuccessfullyCreated = false;

a) method GetListOfCustomersToImport implementation

public bool GetListOfCustomersToImport()
{
    .....
    //at the end
    customerSumaryListRetrieved = true;

}

b) method CreateSalesforceJob

public bool CreateSalesforceJob()
{
    if(!customerSumaryListRetrieved)
        throw new ProcessOrderExecutionException();

    //at the end
    // method implementation
    salesforceJobSuccessfullyCreated = true;    
}

Is there a better way to do this? A design pattern, or a known implementation?

Rails - Strong Params on a Module?

My controllers need to create more than one model. I could use nested attributes to whitelist the params. However I would have strong params for the same models all over the place and whenever I changed one of the models I would have to change all the strong params.

To solve this, I found this idea of creating a module with the strong params and call them in the controllers. I am new to rails, so I would like to know if this is a good or bad pattern/idea??

Find words with pattern on java code

I have the following code, trying to extract two words(The ball) based on a regex(regex()), but matcher does not find these words. Can you help me?

import java.util.regex.Matcher;
import java.util.regex.Pattern;
public class change1 {
private static String[] sentence_to_array;
public static void main(String[] args) {
    String sentence = "The ball is round";
    sentence_to_array = sentence.split(" ");        
    Pattern p = null;
    Matcher m = null;
    String to_remove = findings(p, m, sentence_to_array, regex());
}//method
private static String findings(Pattern p, Matcher m, String[] pieces, String fr) {
    String word = "";
    pieces = sentence_to_array;
    p = Pattern.compile(fr);
    for (String piece : pieces) {
        m = p.matcher(piece);
        if (m.find()) {
            word = word.concat(piece + " ");
        }//if
    }//for
    return word;
}//method
public static String first_regex() {
    return "(The|or|what)";
}//Method
public static String second_regex() {
    return "(Peter|Luke|Hans|ball)";
}//method
public static String regex() {//επιστρέφει το υποκείμενο ως regex
    return "(" + first_regex() + " " + second_regex() + ")";
}//method
}//class

Name patterns to use in query methods

I would like to receive suggestions from the community about this question:

What's a good pattern to use to name query methods in PHP?

Examples below:

// I want to get the users count from Users Table. Should I use this name?  
public function getCountUsers()  
{  
  //code here
}  

// I want to get all users from Users Table. Should I use this name?  
public function getAllUsers()  
{  
  //code here
}

If you guys have a great idea or good experiences naming query methods, I would appreciate to receive some tips about it!

Thanks

dimanche 27 novembre 2016

Which design pattern should I use for this task?

“The ABC car company is designing a new dashboard subsystem for its cars. The dashboard subsystem will need to interact with the drivetrain, engine, and breaking subsystems. What design pattern could be used to allow the dashboard to remain?”

What technology for handling complex stateful workflows

Let's say I have a platform with a number of users, and each goes through a heavy process that involves actions/steps to perform on the platform (forms to fill, information to validate, files to upload, etc.) over a couple of days/months.

We basically need to keep track of the "state" in the process for all of theses users as they go through it, report errors in case a given step fails, send reminders when a user is stuck in a particular step to offer help, ...

One can easily imagine giving all theses steps a name and write the current state for each user in the database, but the problem is more complex when you count in all the metadata that comes with a state (error/warning messages, uploaded files, validated information, etc).

Is there a technology to handle this kind of stuff?

Factory Method pattern discussion

I have some ideas in my mind, would like to know your opinions. Happens that one of the big deals about Factory Method pattern is to keep Client class without knowing the Product Interface subclasses.

Usually you get two different implementations:

  1. As described above, the Client class doesn't know which Product Interface instantiate, it just delegates this task through the factory method and usually receive a String type parameter to request correct concrete product.

  2. Client class contains references to both concrete products and factory class. In this case, Client class passes a concrete product object to the factory method and form there concrete product is created.

Don't you think approach 1 is best suited with the correct description of this design patterns and also, keeps one of the main principles, keeeping Client class without knowing of concrete products?

Thoughts?

Share microservices between diffrent projects

I want to make a microservice project including some microservices like : page , order , products and etc I have two questions about that :
1 . I want to know if it is a good idea to reuse the same microservice in different projects and store multiple websites data in one microservie and retrive corresponding data by the project token ?
For example we have website A and website B and share their data in the same microservice database and products microservice holds website A and website B products.
2 . If reusing microservice is a good idea the problem may occur is maybe there is some slight changes in website A and website B products. Should I rewrite another microservice for website B or write product microservice generic so it can handle diffrent types of products

Are service object, transaction script and strategy design patterns the same?

I couldn't find any definition of the Service Object design pattern.

The Transaction Script design pattern

Organizes business logic by procedures where each procedure handles a single request from the presentation.

The Strategy design pattern

Define a family of algorithms, encapsulate each one, and make them interchangeable. Strategy lets the algorithm vary independently from clients that use it.

Are they similar/equal?

PHP Observer pattern for sending email?

I have a contact form on my website where the client can send messages to me.

When my server receives the message, I want to send a notification to the client and another one to myself (server).

So I thought the observer pattern is suitable to this task where the client and the server are both observers.

Below is my attempt:

Interface:

interface Observer
{
    function onChanged(Observable $Observable, array $params);
}

interface Observable
{
    function addObserver(Observer $Observer);
    function removeObserver(Observer $Observer);
    function notifyObserver(array $params);
}

The concrete observable:

class MessageObservable implements Observable
{
    private $Observers = [];

    public function recieved($message)
    {
        return $this->notifyObserver($message);
    }

    public function addObserver(Observer $Observer)
    {
        $this->Observers[] = $Observer;
    }

    public function notifyObserver(array $params)
    {
        foreach($this->Observers as $Observer) {
            return $Observer->onChanged($this, $params);
        }
    }

    public function removeObserver(Observer $Observer)
    {
        foreach($this->Observers as $observerKey => $observerValue) {
            if ($observerValue === $Observer) {
                unset($this->Observers[ $observerKey ]);
            }
        }
    }
}

The concrete observers:

class ClientObserver implements Observer
{
    public function onChanged(Observable $Observable, array $params)
    {
        // Client e-mail.
        $emailTo = $params['email'];

        // Server e-mail.
        $emailFrom = 'server@example.com';

        // Headers.
        $emailHeaders = "From: " . $params['name'] . " <$emailFrom>";

        // Server subject.
        $emailSubject = 'Message Sent - ' . $params['subject'];

        // Server content.
        $emailContent = "Dear " . $params['name'] . ",

You have sent a message at example.com website using this e-mail.

Your Name : " . $params['name'] . "
Email : " . $params['email'] . "
Subject : " . $params['subject'] . "
Message : " . $params['content'] . "

With thanks,
example.com
";

        // Send email.
        // $sentMail = mail($emailTo, $emailSubject, $emailContent, $emailHeaders);

        // Assume sent OK.
        $sentMail = true;

        // If sent ok.
        if($sentMail) {
            return [
                "status" => "success",
                "message" => "Your message has been sent successfully. Thanks for contacting us."
            ];
        } else {
            return [
                "status" => "fail",
                "message" => "Your message is not sent. Please try again."
            ];
        }

    }
}

class ServerObserver implements Observer
{
    public function onChanged(Observable $Observable, array $params)
    {
        // Server e-mail
        $emailTo = 'server@example.com';

        // Client e-mail
        $emailFrom = $params['email'];

        // Client Headers
        $emailHeaders = "From: " . $params['name'] . " <$emailFrom>";

        // Client subject
        $emailSubject = $params['subject'];

        // Client Message.
        $emailContent = $params['content'];

        // Send email.
        // $sentMail = mail($emailTo, $emailSubject, $emailContent, $emailHeaders);

        // Assume sent OK.
        $sentMail = true;

        return false;
    }
}

On a controller:

$MessageObservable = new MessageObservable();
$ClientObserver = new ClientObserver();
$ServerObserver = new ServerObserver();
$MessageObservable->addObserver($ClientObserver);
$MessageObservable->addObserver($ServerObserver);

$message = [
    'name' => 'Client Name',
    'email' => 'Client Email',
    'subject' => 'Client Subject',
    'content' => 'Client content',
];

$res = $MessageObservable->recieved($message);
print_r($res);

Result:

Array
(
    [status] => success
    [message] => Your message has been sent successfully. Thanks for contacting us.
)

It works fine but I have repeated:

  1. $sentMail = mail($emailTo, $emailSubject, $emailContent, $emailHeaders);

  2. $emailTo, $emailFrom, etc.

Is there anyway to make to better? Or it is not the observer pattern that I should be using?

samedi 26 novembre 2016

pattern search in a text by using three methods

I want to write a program for pattern searching in a given text which reads in a text and then one or more patterns and gives for each pattern: if it is found(prints out the position of the first appearance in the text) if not the number of comparison for of the methods: Brute-force, Boyer-Moore Heuristics, and KMP.
But I don't know how to write my main class to get output:

import java.util.HashMap; import java.util.Map;

public class PatternSearch {

/** Returns the lowest index at which substring pattern begins in text (or else -1).*/
 public static int findBrute(char[] text, char[] pattern) { 
 int n = text.length;
 int m = pattern.length;
 for (int i=0; i <= n - m; i++) { // try every starting index within text
 int k = 0; // k is index into pattern
 while (k < m && text[i+k] == pattern[k]) // kth character of pattern matches
 k++;
 if (k == m) // if we reach the end of the pattern,
 return i; // substring text[i..i+m-1] is a match
 } 
    return -1; // search failed
 }

 /** Returns the lowest index at which substring pattern begins in text (or else -1).*/
 public static int findBoyerMoore(char[] text, char[] pattern) {
     int n = text.length;
 int m = pattern.length;
 if (m == 0) return 0; // trivial search for empty string
 Map<Character,Integer> last = new HashMap<>( ); // the 'last' map
 for (int i=0; i < n; i++)
 last.put(text[i], -1); // set -1 as default for all text characters
 for (int k=0; k < m; k++)
 last.put(pattern[k], k); // rightmost occurrence in pattern is last
 // start with the end of the pattern aligned at index m-1 of the text
 int i = m-1; // an index into the text
 int k = m-1; // an index into the pattern
 while (i < n) { 
      if (text[i] == pattern[k]) { // a matching character
 if (k == 0) return i; // entire pattern has been found
 i--; // otherwise, examine previous
 k--; // characters of text/pattern
 } else { 
      i += m - Math.min(k, 1 + last.get(text[i])); // case analysis for jump step
 k = m - 1; // restart at end of pattern
 } 
  } 
 return -1; // pattern was never found
 }


 /** Returns the lowest index at which substring pattern begins in text (or else -1).*/
 public static int findKMP(char[] text, char[] pattern) { 
 int n = text.length;
 int m = pattern.length;
 if (m == 0) return 0; // trivial search for empty string
 int[] fail = computeFailKMP(pattern); // computed by private utility
 int j = 0; // index into text
 int k = 0; // index into pattern
 while (j < n) { 
 if (text[j] == pattern[k]) { // pattern[0..k] matched thus far
 if (k == m - 1) return j - m + 1; // match is complete
 j++; // otherwise, try to extend match
 k++;
 } else if (k > 0)
 k = fail[k-1]; // reuse suffix of P[0..k-1]
 else
 j++;
 } 
 return -1; // reached end without match
 }


 private static int[] computeFailKMP(char[] pattern) { 
 int m = pattern.length;
 int[ ] fail = new int[m]; // by default, all overlaps are zero
 int j = 1;
 int k = 0;
 while (j < m) { // compute fail[j] during this pass, if nonzero
 if (pattern[j] == pattern[k]) { // k + 1 characters match thus far
 fail[j] = k + 1;
 j++;
 k++;
  } else if (k > 0) // k follows a matching prefix
  k = fail[k-1];
  else // no match found starting at j
  j++;
  } 
  return fail;
  }

public static void main(String[] args) {



}

}

When would Presenter update model in MVP

I was reading about MVP, and in case of supervisor controller, Presenter can update the model and View can listen to those changes.

I am not able to understand when would presenter update a model. Ideally presenter acts on request from view. And if view is requesting to something, why can't presenter return the result to view. Instead of going through different route where presenter updates the model and view listen to that and act accordingly.

And even if one view is updating and other view is interested in this event, then also view can raise event which other view can listen to.

Thanks in Advance

RegExp incorrectly invalidate user unput

Already spent 2 days on this very basic regex .I want it to validate inputs exactly of 4 characters.And only upper & lower case Letters.No digits or special symbols.But it is invalidating everything including the correct ones. Can't catch the issue. Please help.Code below:---

thanks

pkj

<!DOCTYPE html>

<HTML><HEAD>
<TITLE>
 RegEx Test
</TITLE>
</HEAD>
<BODY>
     <P>
        <FORM action="cgi-bin/page2.py"
           Type something:<input  Id="usrInput" TYPE="text" VALUE="" onblur="chkInput()">
                  <input Id="ts" TYPE="number" NAME="ts" value=0> 
                  <input id="submit" type="submit" value="Go" >
        </FORM>
    </P>
     <script>
        function chkInput(){
         var myRgx=new RegExp(/^[a-zA-Z]{4}$/);   
         var input=document.getElementById("usrInput").innerHTML;  
          var rslt=myRgx.test(input);
          alert(rslt)
        }

     </script>
</BODY>

Testability - MVP or breaking Controller into ViewController and Model Controller in iOS

I am from web background and have majorly worked on MVC, so please excuse me if my question sound trivial.

To get rid of Massive View Controller in iOS, I could see two possibilities (from many others) like MVP or breaking 'Massive Controller' into two controller-

  1. Breaking controller into two

    • View Controller (regular iOS controller) - This will be close to view and handle all the presentation logic.

    • Model Controller - This controller will handle all the interaction with Application/Data provider class. View Controller would have its reference and will call ModelController's method in case of any event. ModelController would not have any reference to ViewController.

  2. And if I introduce MVP in iOS, my controller and presenter would talk to each other through interface (protocol in swift). In this case, communication from view controller to Presenter would be through event handling. And from Presenter to ViewController, would be done by calling ViewController API's.

Looking at both the approach, approach 1 seems to be less complicated (since there is one way communication from viewController to modelController, and that through API), where as MVP seems bit overcomplicated.

What extra benefits one would get by using 2nd approach over 1st? Please let me know my there are gaps in my understanding.

Thanks In Advance

Best pattern to handle null pointer exception

I am looking for best pattern to handle NPE(Null Pointer Exception). I am using retrofit for web api calls, but some times there may chance that some fields might be null, or that might be chance of null array too. What i am looking for, is there any way to handle all in just once?.

E.g.

Model Class

public class ModelClass{
     String name;
     String email;
     List<Items> items;
}

JSON File

{
  name:null,
  email:"NPE@jvm.com",
Items:[]
}

So after deserializing json file, when i try to get name it will through NPE

I have very large collection of model class, and practically it is wrong to put each field in try{}catch() while using it. Is there a better way to handle this kind of scenario?.

Best practise to separate concerns when accessing database

I've been trying to improve the separation of concerns when it comes to applications that access a database (via Hibernate).

On one of the applications I've been using the following approach:

  • Create services with business logic that have no connection/awareness of the database. They only communicate with GeneralDAO (and with other services);
  • A GeneralDAO responsible for CRUD/find operations, and with methods that involve more complex database queries.

The problems I see with this approach are:

  • GeneralDAO slowly becomes a God Object, when your application grows and require lots of specific database queries.
  • Sometimes the more specific Services become only proxies to the GeneralDAO, since the method is simple and only requires a database query. See example 1.

Example 1: Service is just a proxy

BookService manages things related to books in the Library application. Let's consider 2 methods:

  • archiveBook(Book)
  • findByIsbn(String isbn)

In archiveBook(Book) there might be considerable business logic involved - we might imagine this involves calls to:

 distributionService.unbox(Book);
 archivalBook.archive(Book);
 librarianService.informNewBook(Book);

But findByIsbn(String isbn) is a lot more simple: it just needs to execute an SQL call to the database. So in this case I see two options:

  1. Redirect the call to an object that can speak to the database to execute the query. For example generalDAO.findByIsbn(String isbn), that uses a db communication layer (in Hibernate it would use a sessionFactory or EntityManager) to execute the query.
  2. Make that database layer available to the BookService, so that it executes the query itself

Questions/opinions (first number identifies the option above):

1.1. Isn't it strange to have 2 methods with the exact same signature, even if this is done to keep the BookService independent of the database layer (and ORM)?

1.2. How do you suggest avoiding The God anti-pattern? Would you suggest breaking the GeneralDAO into several DAOs depending on what the methods do? In this case, won't we risk needing to inject lots of DAOs into some Services, leading to a Service having too many objects injected into it?

2.1 What do you think of this alternative? Doesn't it break the "separation of concerns" by having the BookService be aware of objects at two different levels of abstraction (the DAO and the sessionFactory/EntityManager)?

3.1. Would you suggest any other approach/pattern/best practise?

Thanks!

C++ optimisation vector

I'm working on an Entity Component System, but I have some trouble with how I'll stock every components. Right now I have a manager created when a new component derived is created. And this manager manage a pool of component (by default std::vector) and another pool with the same size which contains an int32_t to manage how I access to the component, and the component ptr.

I was thinking that will be better because I can't now the size of a component, so a ptr to quick access will be better (in a small vector). But I'm young so I'm afraid that I'll made a huge mistake.

So I can't decide which one will be more interesting in a generic way:

  • 2 pools, one small for access and one big for contain raw data.
  • merge these 2 pool and have only one with my int32_t and the raw data.
  • something else.

Any advice is welcome :)

Have a great day.

vendredi 25 novembre 2016

What is the best pattern to sync data between two recycler view with two activities?

i have two activities where they have almost same data,i am using same Adapter, But the problem is how to sync data...

E.g. Activity A has recyclerview where it has like buttons in each row with unique id. Activity B also have same recyclerview but with some filter mechanism so it is not going to show all row, my question is how to handle like button state in Activity A and Activity B, such that if i click on activity B's like button than activity A's like button will automatically gets checked and vise versa.

Thanks in adv. for your help... happy coding :)

Class that does things to another class

I have a class that is essentially a wrapper for a large data object on a database. Looks like this:

public class ServerWrapper {
    private DataObject object;

    public ServerWrapper(DataObject object) {
        this.object = object;
    }

    public void doAThing1() {
        getSomeStuff();
        // do stuff that modifies this object
    }

    public void doAThing2() {
       getSomeStuff();
       // do other stuff that modifies this object
    }

    private List<> getSomeStuff();
}

This is the problem: there are many, many "doAThing" methods. And some of them are quite large. Also, a lot of them use other private methods also in ServerWrapper. Ideally, I'd like to break off these public methods into their own classes, like ThingDoer1, ThingDoer2, but I don't know the best way to do this.

Something like this:

public class ThingDoer1() {
    public void doAThing1(ServerWrapper wrapper) {
        wrapper.getSomeStuff();
        // do the thing to wrapper
    }

seems very smelly; it's tightly coupled to ServerWrapper (ServerWrapper calls it and it calls ServerWrapper), plus it needs to either do stuff with the object it's given (which is bad), or make a copy, do the stuff, then return the copy.

Really, I think what I'm looking for is a set of partial classes, just to make this monster of a class more manageable; but I'm using Java, which doesn't support that.

Is there some standard practice for breaking down a large class like this? Thanks in advance!

Pattern or texture fill in ggplot or base plot in r

Does latest version of ggplot2 support pattern or texture fill in stacked bar chart or is there any way to get such plot in other packages?

Best Object Oriented approach to solve this simple scenario

I'm not so sure about what's the best approach to model this problem in the object oriented world.

Suppose I have to represent a graph and it's nodes in Java and suppose I to visit the graph using a depth first search (DFS).

What the best approach in Software engineering among these two:

  • Create a class Node, a class Graph and a class GraphsFunctions where the GraphsFunctions class contains the DFS method which takes the Graph and a Node as parameters. Something like this: public void DFS(Graph g, Node n) and the call new GraphsFunctions().DFS(new Graph(), new Node())

  • Create a class Node, a class Graph where the Graph class contains the DFS method which takes only the Node as parameter. Something like this: public void DFS(Node n) and the call new Graph().DFS(new Node())

I would rather use the first of the two options but I can't say why it's the best for me. Can you tell me what makes the best choice, actually the best?

Specializing method arguments in subclasses in Java

Consider the following situation:

public abstract class AnimalFeed{
}
public class FishFeed extends AnimalFeed{
}
public class BirdFeed extends AnimalFeed{
}

public abstract class Animal{

public void eat(AnimalFeed somethingToEat)

}

Now I would like to define a class "Bird" extending "Animal" being sure that when the bird eats, it eats only BirdFeed.

One solution would be to specify a sort of contract, in which the caller of "eat" must pass an instance of the appropriate feed

public class Bird extends Animal{

@Override 
public void eat(AnimalFeed somethingToEat){

    BirdFeed somethingGoodForABird

    if(somethingToEat.instanceOf(BirdFeed)){
    somethingGoodForABird = (BirdFeed) somethingGoodForABird
    }else{
    //throws error, complaining the caller didn't feed the bird properly
    }
}
}

Is it acceptable to delegate the responsibility of the parameter to the caller? How to force the caller to pass a specialization of the parameter? Are there alternative design solutions?

Is "Domain Driven Design" by Eric Evans still valid

I was highly recomended Domain-Driven Design: Tackling Complexity in the Heart of Software. The book was published in 2003, so i would like to know if the concepts are still valid and this is still a state of the art book?

C++ Calling the right free function from a base pointer/reference

Let a class hierarchy :

class Base { virtual ~Base() throw(); };

class DerivedA : public Base { };

class DerivedB : public Base { };

I would like to have some code specific to each of these derived classes. However that code also being specific to the application that makes use of this class hierarchy, I do not want to embbed this derived-class-specific code into these derived classes. To avoid doing so, I thought about writing free functions :

void DerivedASpecificWork( DerivedA da );

void DerivedBSpecificWork( DerivedA da );

However, when given an instance of a derived class through a reference/pointer to a Base, I do not have access to the actual type of the instance, and thus cannot call the proper Derived*SpecificWork() function.

I would like to know if there is nome kind of design pattern that would allow me to call a derived-class-specific function without knowing the actual type of the instance, i.e having the same mechanism as virtual functions provide, but without having these virtual functions that would require me to embbed application-specific code into that class hierarchy.

Actually, why I want to do that is to provide informations about an exception that occured within a natively implemented function called by a Lua script. Each exception carrying its own set of information, the way I want to represent the error within the script depends on the type of the exception. I could create a pure virtual method in the base class that would be implemented by derived classes, but this would require me to embbed Lua-related code into my exception hierarchy, which I do not want to do since the Lua is specific to one of the application using that exception hierarchy.

Also I cannot use C++11.

Thank you.

what is name of the List

As we know that the List for C# is possible to put the function behind but do the function to filter the list.

For example, Assume that the many count inside the students List.

var students=new List<student>();

Then to get the list of student we can add some function behind like

students.find(id).sortbydesending(k=>k.x).skip(10).take(5).toList();

the sequence of putting the skip() and take() will effect the result.

I was doing the coding on an method to retrieve the list of student accordingly.

First, I want to do something similar with the list function. For example i need order the list Of Student According student name.

instead of doing

student.sortbydescending(k=>k.name).toList();

I want code is like

student.sortbyNamedesc().toList();

and it will return the same result as above.

Second is the design pattern name and (If possible) implementation guide

This is because I plan to do something like this.

getStudent().searchName(searchQuery).sortby(id);

Then i can get student name similar with search query and sort it by the student id instead of

getstudent(searchQuery,id,skip,take);

public IList<Student> getStudent(searchQuery,id,skip,take){
   var students=new List<student>();
   if(searchquery!="")
        student.where(x=>x.x==searchquery);

   if(skip!=null&&skip!=0)
        students.skip(skip);

   if(take!=null&&take!=0)
     students.take(take);

    return students;

  }

jeudi 24 novembre 2016

suitable design pattern for below scenario in java

Please suggest suitable design pattern for below scenario in java

Class InfoParser{
public Map<String,String> parseData(List<String>);
}
Class QuestionParser{
public Map<String,String> parseData(List<String>,Map<String,String>);
}

Even you can add interface to the above code,but which design patterns suits here.

How to properly design interface

I have two classes. Let's call them PostClass and CommentClass. Both classes implement the Reportable interface:

public interface Reportable {

    void report();

    boolean isReported();

    . . .

Now I need to add two additional methods to each one of the classes. These methods logically fit into the same interface but needs to have different names. For example:

PostClass will have methods -> remove(), restore()

CommentClass will have methods -> hide(), show()

Question: What would be the preferred way to design this change? The options are as I see it:

  1. Create an additional interface which will extend the Reportable interface. Problem: Too many interfaces
  2. Add all four new methods into the Reportable interface and then just leave the irrelevant two methods unimplemented in each class. Problem: Untidy/ugly

EJB Design Pattern: Multiple hosts on ApplicationServer

I have a design pattern question. If someone has a better heading, please let me know (difficult to find a good one for this).

My Situation:
There is a running application server. There are two different types of clients, a host client and a guest client. Host clients should be able to create, let's say a party with an identifier. Then the guest clients should be able to join any of those parties, depending on that identifiers.

My Idea:
Using different types of EJBs. As PartyController i wanna use a Singleton Session Bean:

@Singleton
public class PartyController {

    private Map<String, Party> parties;

    @Lock(LockType.WRITE)
    public void createParty(String identifier, Party party) { ... }

    @Lock(LockType.READ)
    public Party findParty(String identifier) { ... }
}

And for every client a Stateful Session Bean:

@Stateful
public class GuestController {

    @EJB
    PartyController partyController;

    private Party party;

    public void joinParty(String identifier) {
        party = partyController.get(identifier);
    }
}

And then the typical other stuff, like servlets and bla, but doesn't matter here. Just to say: the Party class has members, that are instance-dependent (initialized by the host-client). All clients at a party need to use the same party instance as read-only. So there shouldn't be problems with concurrent accesses.

My Question:
Is this a good way to solve this problem? Are there better ways to do this? I know that the singleton blocks while being accessed, but only when a party is created. Is this a stable solution for, let's say 10 Parties and 100 guests, or 100 parties and 1000 guests, and so on?

I'm at the beginning of developing my solution, so i need to have a good and stable base for further programming.

Thank you very much!

How to use the memento design pattern?

I'm very confused about how the memento is supposed to be implemented.

I understand the Memento has a State. And the Memento Pattern is used to store different (previous) states so that one can restore an object to previous states,

Well lets say I have multiple objects, each of this comes with 10 attributes, 5 of which stay the same throughout the life of each individual object, but 5 of which change. So i need, for each object to save it's previous states and go back to them.

The question:

How do I apply the Memento Pattern with these objects?

My idea so far:

So Memento Pattern has 3 classes, Memento of which you create many, one for each state. Caretaker which stores all the previous states of an object AKA Mementos. And then the Originator that creates Mementos and also gets the states from a Memento.

This would mean that each object instance would require it's own Caretaker instance (a list of it's previous states), and this Caretaker would have Mementos with the previous states of this object's 5 attributes (and also the current state or only previous ones?), but all objects with a caretaker can use the same Originator instance because the Originator can be used to create new mementos into any Caretaker.

Is this how it would be implemented or am I misunderstanding it?

It would look something like this:

Originator and Memento class

public class Memento {
   private Object1Attributes state;

   public Memento(Object1Attributes state){
      this.state = state;
   }

   public Object1Attributes getState(){
      return state;
   }    
}


static class Originator {
   private Object1Attributes state;

   public Memento saveStateToMemento(){
      return new Memento(state);
   }

   public void getStateFromMemento(Memento Memento){
      state = Memento.getState();
   }

   public void setState(Object1Attributes state){
      this.state = state;
   }

   public Object1Attributes getState(){
      return state;
   }

}

Other object

public class Object1Attributes{
    string attribute1;
    int attribute2;
    someObject attribute3;
    someObject attribute4;
    someObject attribute5;
}

public class Object1 {

    CareTaker careTaker = new CareTaker();

    Object1Attributes;

    string attribute6;
    int attribute7;
    someObject attribute8;
    someObject attribute9;
    someObject attribute10;


    public void returnToPreviousState(){
        if(caretaker.Length()>0){
            Object1Attributes = originator.getStateFromMemento(careTaker.get(caretaker.Length()-1));
            caretaker.remove(caretaker.Length()-1);
        }
   }

    public void newState(ObjectAttributes OA){
        originator.setState(OA);
        this.ObjectAttributes = OA;
        this.caretaker.add(originator.saveStateToMemento());

    }

}

Another option

would be making the Memento class and the Originator class hold the 5 attributes, instead of encapsulating the 5 attributes inside another class. Like so:

public class Originator {
    string attribute1;
    int attribute2;
    someObject attribute3;
    someObject attribute4;
    someObject attribute5;

   public Memento saveStateToMemento(){
      return new Memento(attribute1, attribute2, attribute3, attribute4, attribute5);
   }

   public void setAttribute1(string state){
      this.attribute1 = state;
   }

   public void setAttribute2(int state){
      this.attribute2 = state;
   }

}

This way each Object1 instance would hold its own instance of Originator instead of Object1Attributes though, and this Originator would contain the current state of the attributes in the object1 instance; I don't know which way is the correct way of implementing the pattern.

All examples online use mementos to store a "state" which is just a string, none of them involve the creation of multiple objects that can have multiple states, so that's why I'm so unsure.

Use special 'propose' object's instead of arrays

its gonna be a fully theoretical thread.

Let's talk about change arrays to specially object's, to compare and work on it.

For example we have a EntityClass, EntityInterface, SomeRepository, SomeManager, SomeCommand.

Entities is a clear object, example:

class EntityClass implements EntityInterface {
    public $name;

    public funtion getName() {
        return $this->name;
    }

    public function assign($data) {
        $this->name = $data['name'];
    }
...
}

Repository ofc. have method's to save object in source and get it from source.

Manager have all of 'busines logic', it can modify a entities using command pattern, one command for one properties, so a busines logic for all properties its store in separate's command's, and manager fire it's.

Now, in manager start all logic and fun. Little shorthand:

  1. Repository create new entity by getOne().
  2. We create a new instance of manager and pass by constructor some dependencies like array of data from controller and Entity.
  3. Array of data have information about changes, example: ['data' => 'New name']; mapper resolve what command should have been fired by manager for given array.
  4. Manager execute all commands for this request and passing raw array to each command.

Now, why we passing a array ? when we are in OOP, why don't use special variation of EntityClass ??

Now let's add a new interface EntityProposeInterface, and change a raw array to class implements this interface, and pass them.

for example we can add to SomeManager speciall method to morph entity like this (PHP7+):

class SomeManager {
   public function morph($entity) {
       $buff = new class extends EntityClass implements EntityProphoseInterface{};
       $buff->assign($entity->toArray());
       return $buff; 
  }

And now we have a EntityProphose lets make some changes on it, now manager change a EntityProphose from raw data array, and all commands and other method's in our code work's on object kinde EntityProphose instead of array.

But ofc. our repository cant save object's instance of EntityProphoseInterface.

And that's all... Is there some design pattern name ? or something like this ?

Or this idea is very bad ?

I hope it's clear for all of you, if not please ask. Any ideas ? advice ?

Developing a Football Manager with Java; What to consider for: Design pattern, JavaFX skinning (/w ps), MP functionality, Android version, etc

I am developing a Football Manager Game with a group of friends, what should we consider for:

  • Design pattern: We don't really know which one we should use. One that took my attention during previous lectures is MVC, but isn't that kinda overkill in this situation? And what other design patterns are great for our situation, and why?

  • GUI: We decided to work with JavaFX, but no one really has experience with it yet. How should we use JavaFX to work together with Photoshop (for skinning the GUI). Are there handy tools and/or plugins for this?

  • Game saves: We plan on using Json files for game saves and want to use gson to make this easier. What should we keep in mind while doing this?

  • Multiplayer: Is there an easy way to implement online multiplayer functionality to the game?

Least priority:

-Android version. What should we keep in mind if we want to potentially create an Android version of the game, and are there easy ways to do this?

Any kind of help is really appreciated!

How to Design a shedManager

I try to design a shed car with design patterns.

My shed contain abstract class car:

public abstract class Vehicle {
      public string Name { get; set; }
      public Color Color { get; set; }

      public void ChangeColor(Color color)
    {
        Color = color;
    }
    public void ChangeName(string name)
      {
        Name= name;
      }
 }

I create a ShedManager based on singlethon pattern.

ShedManager contain List of Vehicle The ShedManager Use Factory pattern to create appropiate instance of Vehicle.

The operation i want to support:

Draw Vehicle blue;

Darw Vehicle green;

Chnage Name;

so, i create a menu item at Console.Main and by Switch case i call relevant function at Vehicle object.

So, there is two cases for change color so each them sent with relevant color.

I try to think how can i implement this so if in the future i will add another option (like change color to black) i can to do without code change.

I iterate over design pattern and no one visible to be appropriate..

So, you think its possible or the current design is good enough?

How to divide logic of returned object's creating between base and derived class in C#?

How to divide logic of object's creating between base and derived class without redundant methods, copying objects, passing by reference and other dirty hacks? This is example. I need write more details. I need write more details. More details.

public abstract class Base
{
    protected int Property1;
    protected int Property2;

    public View GetView()
    {
        View view = new View();
        view.Property1 = Property1.ToString();
        view.Property2 = Property2.ToString();
        return view;
    }
}

public class Derived1 : Base
{
    int Property3;

    public override View GetView()
    {
        View1 view = new View1();
        view.Property3 = Property3.ToString();
        //return view;
        //return base.GetView();
        //return view UNION base.GetView(); ???
    }
}

public class Derived2 : Base
{
    int Property4;

    public override View GetView()
    {
        View2 view = new View2();
        view.Property4 = Property4.ToString();
        //return ???
    }
}

public abstract class View
{
    public string Property1;
    public string Property2;
}

public class View1 : View
{
    public string Property3;
}

public class View2 : View
{
    public string Property4;
}

Thanks.

Parse error: syntax error... When I try get one static instance another php class

I'm trying to get a static instance of a class in another php class (singleton pattern), but it throws a syntax error "Parse error: syntax error, unexpected '(', waiting ',' or ';'".Can someone explain me why I can not do that in Php?. I am using php 5.5.38.

Example code:

<?php

    Class A{

        private static $instance=null;

        private function __Constrcut(){
          #Some initialization of parameters

       }
       public static function getInstance(){
          if(self::$instance==null){
             self::$instance=new A();
          }
          return self::$instance;
       }
   }
?>

Another class file

<?php

    include ('path/to/A class/A.php');

    Class B{

       #Line error
       private static $a_instance = A::getInstance();

       public funtion __Construct(){
          #Some parameters....           

       }

      #Some other functions....

  }

?>

Thank you for helpme :) .

Opinions for my project

I want to make a project which I have divided into 2 parts.

First is ASP.net website and second part is Windows form application, both applications are connected to same database, user can go, and view data/information on website and some of the users who want just specific part of the whole application can use the Windows form application.

Users who use Windows form application can make offline changes which will be sync to online database later when connected to Internet and their data will be available on ASP.net website.

I want to make architecture in a way that I don't need to write separate code for both applications like if I am going to make login on both apps than the class which contain the method to validate user login can be used for both apps. How and what scenario should I follow for implementation?

And one more thing, Windows forms application may have multiple instances for single login (user).

Is there already an architecture design available that I can follow?

Modular Pattern JavaScript

Attached code can catch situation when new images are created and it is checking that image request is related to particular domain. I want to write a similar JavaScript function which can catch Google's DFA(anything similar) would also do.Please guys help ASAP.Check the document.create function something similar approach to catch google's DFA or anything else will do.Please suggest

var test = (function(pixelHost) {
var _pixelHost = pixelHost || "google-analytics.com";
var lastClickedElement = null;
    (function(proxied) {
        document.createElement = function() {
            var x = proxied.apply(this, arguments);
            if ( typeof arguments !== "undefined" && typeof arguments[0] === "string" && arguments[0].toLowerCase() === "img") {
                onload = function() {
                    if (url_domain(x.src).indexOf(_pixelHost) >-1) {
                    console.log('image src:', x.src);
                    logItem(x.src);
                    }
                };
                // hell is freezing:
                setTimeout(onload, 10);
            }
            return x;
        };
    })(document.createElement);

    function url_domain(data) {
    if (typeof data ==="undefined" || data ==="" || data === null) {
        return null;
    }
    var a = document.createElement('a');
         a.href = data;
    return a.hostname;
}

    function getLogObject() {
        var logObject = sessionStorage.getItem('superTLogItems');
        if (logObject === null || logObject ==="null" ) {
            logObject = [];
        } else {
            try {
                logObject = JSON.parse(logObject);
            } catch (e) {
                console.log(e);
                logObject = [];
            }
        }
        return logObject;
    }

    function logItem(src) {
        var logItem = createLogItem(src);
        var logObject = getLogObject();
        logObject.push(logItem);
        var logString = JSON.stringify(logObject);
        sessionStorage.setItem('superTLogItems', logString);
    }

    function clearStorage() {
        sessionStorage.setItem('superTLogItems', null);
    }

    function createLogItem(src) {
        var delimeter = ";";
        var dlh = document.location.href;
        var dlc = document.cookie;
        return dlh + delimeter + dlc + delimeter + lastClickedElement + delimeter + src;
    }

    function exportToCsv() {
            var logObject = getLogObject();
            var myCSV = "";
            logObject.forEach(function (k,i) {
               myCSV += k + "\r\n";
            });
            window.open('data:text/csv;charset=utf-8,' + escape(myCSV));
        }

    function init() {
        function lastClickObject(event) {
            var obj = event.target.tagName + ":#" + event.target.getAttribute("id") + ":" + event.target.getAttribute("class");
            console.log('u clicked:', obj);
            lastClickedElement = obj;
        }


        document.addEventListener('click', lastClickObject);


    }

    init();

    return { clearStorage: clearStorage, exportToCsv:exportToCsv};

})();

What is the best way to get the ImplStructure variable and ImplStructureHandler in the Bayes class?

1) Should I pass both [ImplStructure and ImplStructureHandler] to the Bayes class in its constructor?

2) Should I create the another variable in ImplStructureHandler to store the value of b and then only pass ImplStructureHandler to the Bayes Class.

Or If there is any another way Please share?

My Code:

public class ImplStructure {

    private int a;
    private int b;


    public void build(int a, int b) {

        this.a = a;
        this.b = b;
    }


    public int getA() {
        return a;
    }


    public int getB() {
        return b;
    }
}


public class ImplStructureHandler{

    ImplStructure structure 

    public ImplStructureHandler(ImplStructure structure) {
        this.structure = structure;
    }


    public int compTotal(int c) {
        return c + structure.getA() + structure.getB();
    }
}


public class Bayes {

    public int doAddition(int d){

        //here need value of b from Structure and c from Structure Handler to do: d = b + c

        return d;

    }
}

Best practices for web apps security

I have a web app that, upon login, sends the credentials to the server for validation - and returns back, among other things, a dictionary of permissions for different UI components throghout the app - which is used to enable/disable or show/hide these components in the front-end.

This is, of course, not secure at all - anyone opening a browser's developer tools console can change these settings on the fly.

I posed this as a problem to my team, and was asked to propose a solution. I am hence trying to sum up what I could think of, and would be glad if anyone could add alternatives I am not aware of (specially if this is a best-practice or common standard):

  1. Have the server return the full html the user is entitled to see.
  2. Use encryption to protect server-client exchanges. The UI would decrypt server responses, and display the data accordingly.

What other alternatives are there for this ?

My stack is server side in C# (implemented as a WCF server) and devextreme for the UI (html + js (with some js libraries such as knockout)).

(this issue happens throughout all the app, in almost all server served data, not only with login authorizations)

Is it a good idea to make service calls during deserialization?

In the Newtonsoft docs for CustomCreationConverter, it says:

"A more complicated scenario could involve an object factory or service locator that resolves the object at runtime."

I'm dealing with such a scenario where I have to hydrate a persistent object with an incoming DTO (which is in JSON). To hydrate the persistent object, I have to first load it using a service call. I can make this call during deserialization using CustomCreationConverter. Or I can consume the JSON as an ExpandoObject and transitively assign all members. Complexity is not much as the object graph is small.

Something about making service calls during deserialization does not seem right. It makes testing more complicated as I would have to first load that object into memory to be able to deserialize it. This also screams tight coupling.

So my question is: Is it a good idea to make service calls during deserialization?

mercredi 23 novembre 2016

Single-use Class Idiom?

There are times where you want to execute logic on some data once and only once per instance of that data. To my knowledge there is no such pattern (let alone idiom) for accomplishing this.

There is the std::call_once() but that only ensures something is executed once per process instance. Even if the std::once_flag could be used as a class data member it would simply ensure the function is only called once at runtime rather than trying to enforce it at compile time.

Enter the Single-use class:

class single_use_key {
public:
  single_use_key() : _self(new model_t()) {}
private:
  struct model_t {

  };

  std::unique_ptr<const model_t> _self;
};

class consumer_object {
public:
  consumer_object(single_use_key key) : _self(std::make_shared<const model_t>(std::move(key))) {}
private:
  struct model_t {
    model_t(single_use_key key) : _key(std::move(key)) {}
    single_use_key _key;
  };

  std::shared_ptr<const model_t> _self;
};

single_use_key key;
consumer_object consumer(key); // Error
consumer_object consumer(std::move(key)); // OK

This idiom ensures that the class instance is used only once since it can only be moved and not copied.

If you wanted to try and use the object more than once you would have to reference it after you promised you would not (since std::move() was called). Even if you did this, the consumer class/function could be setup to ignore it just like how std::call_once() does because std::unique_ptr<> is guaranteed to be nulled after std::move().

Do you see any problems with this idiom? Is there already something like this that I simply have not found yet? (Or perhaps I am stating something so obvious no one has ever bothered to document it...)

which pattern should i use when i have json to parse to objects

i have large json which im parsing , this json holds objects and objects properties and object actions . something like this :

[{

  "Obj1_type" : "o1",
  "Obj1_name" : "o1_name",
  "pos": {
       x:20,
       y:20
   }
}
,
{

  "Obj2_type" : "o2",
  "Obj2_name" : "o2_name",
  "pos": {
       x:40,
       y:40
   },
   "method": {
         "name": "move" ,
          "arg1: 1,
          "arg2: 2
}
,
{

  "Obj2_type" : "o2",
  "Obj2_name" : "o2_name",
  "pos": {
       x:40,
       y:40
   },
   "method_1": {
         "name": "move" ,
          "arg1: 1,
          "arg2: 2
    },
    "method_2": {
         "name": "jump" ,
          "arg1: 1 
    }
}
]

i have different objects each object contains different properties what will be the best pattern for this ?

C code generation from XML template

I have heard of a design paradigm where we use XML language to define a generic MODEL for the data structures and then use a code generator to create the code in the respective programming languages (I am interested in C). This helps in writing generic interfaces to the program and provide interfaces to the logic written in various languages.

This sounds more like CORBA where IDL file is used.

Since I don't want to use heavy weight like CORBA is there a simple example or ope source application which achieves the same behavior and generates code in C ?

Thanks in advance for your comments and suggestions.

Data Mapper, Repository and Unit of Work patterns

I'm learning about the following patterns

  • Data Mapper
  • Repository
  • Unit of Work

I think I understand each of them but I can't answer these questions

  • are they always used to together?
  • which pattern uses the others?
  • which pattern is known by the Domain Model?
  • what CRUD operations are handled by each of them?
  • who owns the database code (i.e. SQL)?

Thanks.

How to invoke a Data Mapper? Is persistence layer a dependency of Data Mapper?

Data Mapper is a layer of separation between domain and persistence layers. The following are facts (unless I misunderstand):

  • domain layer is ignorant of persistence layer
  • persistence layer is ignorant of domain layer
  • both domain and persistence layers are ignorant of Data Mapper.

All that said, please find my questions below.

  • How to invoke a Data Mapper if the domain layer has to be ignorant of it?
  • Is persistence layer a dependency of Data Mapper?

Thanks

How Laravel's container binding mechanisms differ?

I'm looking at Laravel's service container docs, specifically the binding section.

What are the differences and when should I use each type of binding? The documentation mentions:

  • Simple Binding
  • Singleton Binding
  • Instance Binding
  • Primitive binding
  • Interface binding

vanilla JS : module bundled or not

Given a set of module-patterned files (a main one, and various subs),

is there a way to detect if modules are bundled together into one single file OR not ? In the last case, I will load manually modules with head script src="" tag added via JS.

Non-bundled files are for development, bundled one is for production use.

Code is ES 5 / 2015.

I don't consider using Browserify, Require or so on...

I assemble my code with (very basic) gulpfiles (using concat, wrap)

someone have an idea ?

How to design codes to parse urlencoded data to array?

I have made some codes to parse url encoded data to array.

What I did is something like below.

var_dump(getArrayFromUrlEncoded());

public function getArrayFromUrlEncoded(){

    $urlEncoded = "timestamp=2016-10-10%20&id=123%20";

    $urlDecoded = $this->decodeUrlEncoded($urlEncoded);

    $array = $this->makeUrlToArray($urlDecodded);

}

public function decodeUrlEncoded($urlEncoded){
    //some codes here
    return $urldecoded;
}

public function makeUrlToArray($urlDecoded){
    //some codes here
    return $arrays;
}

But When I made these codes, I feel like I'm stuck and ask myself that is there any other way to be more nice than I made before? or well structured? or well designed?

Please advice me.

Thank you

Use Table Module pattern with Data Mapper pattern

I have a task where I must use Table Module (business logic) pattern with Data Mapper (database logic) pattern. As I know it's unusual situation, because DM returns only one row, but TM uses collection of rows. Therefore Table Gateway is recommended to use in this situation.

But I must to use TM with DM. Explain me please, how to get collection of rows using DM with example please, because I'm newbie in patterns.

How can I reduce boilerplate with the visitor pattern in Swift?

I am implementing the visitor pattern in Swift 2.2 for a project at work.

So that I don't have to boil down my source code and to save me some time I will use an example of visitor pattern in swift by Oktawian Chojnacki.

protocol PlanetVisitor {
    func visit(planet: PlanetAlderaan)
    func visit(planet: PlanetCoruscant)
    func visit(planet: PlanetTatooine)
}

protocol Planet {
    func accept(visitor: PlanetVisitor)
}

class PlanetAlderaan: Planet {
    func accept(visitor: PlanetVisitor) { visitor.visit(self) }
}
class PlanetCoruscant: Planet {
    func accept(visitor: PlanetVisitor) { visitor.visit(self) }
}
class PlanetTatooine: Planet {
    func accept(visitor: PlanetVisitor) { visitor.visit(self) }
}

class NameVisitor: PlanetVisitor {
    var name = ""

    func visit(planet: PlanetAlderaan)  { name = "Alderaan" }
    func visit(planet: PlanetCoruscant) { name = "Coruscant" }
    func visit(planet: PlanetTatooine)  { name = "Tatooine" }
}

The problem I have been trying to solve is to reduce the boilerplate on each class that derives from Planet. As you can see they all have same function duplicated func accept(visitor: PlanetVisitor) { visitor.visit(self) }.

I have tried putting a default implementation on the Planet protocol and implementing it on a base class and Swift does not seem to allow it due to compile time overload resolution.

Examples:

Default Implementation on Protocol:

extension Planet {
    func accept(visitor: PlanetVisitor) { visitor.visit(self) }
}

Base Class:

class PlanetBase: Planet {
    func accept(visitor: PlanetVisitor) { visitor.visit(self) }
}

class PlanetAlderaan: PlanetBase {}
class PlanetCoruscant: PlanetBase {}
class PlanetTatooine: PlanetBase {}

Does anyone know of a way that the accept function could be made generic and applied automatically to each concrete class that derives from Planet? It is not a critical issue but it is a great puzzle!

mardi 22 novembre 2016

Using pub/ sub to generate adobe tracking code across a site

I'm looking to use pub/sub messaging to implement adobe tracking across a site that uses a range of technologies. I'm suggesting to use pub/sub because different webpages across the website are written in different technologies, ranging from webforms, mvc and angular. The pub/sub approach seems very lean and keeps the amount of code to a minimum without polluting the existing code.

The tracking code needs to include a variable digitaldata that encapsulates the page statistics, i.e. locale, environment etc..

Are there any concerns/ known problems with using pub/sub, particularly to generate the tracking object?

Many thanks,

Tracking code example

var digitalData = {
    locale: "en",
    environment: "production"
};

Thanks,

Pattern like Bridge but can add primitive method?

Suppose two abstract class:

  Log:
   property:timestamp;
   property:message;

  LogFormatter:
   (String *)formatlog:(Log)log;

This look like a bridge, Log behave like Abstraction and LogFormatter like Implementor. In my opinion, bridge can't add primitive method to Implementor. But I want to dynamic add property to log in the future, and use a subclass of LogFormatter to format it. This will break Liskov Substitution principle.

Anyone has any suggestion?

Mobile App - Best approach to display 20000 data items

I made an application to scan malware and dangerous files on Android devices. In worse case, there may be over 1000 infected items (even more) to show. I don't ask about correctness of scanning engine, I want to find some ideas how should I display scanning result to users. I mean, assume I find 1000 or 20.000 infected items, which is the good approach to display them to users. A flat list of 20k items is not readable, I think. This question may not have 100% exactly answer, but I hope we can find some good ideas/experience to solve it.

Thanks.

C++ minimal progressive disclosure implementation for API

Following another post I am trying to implement a minimal, working, C++ application to understand how to implement the progressive disclosure pattern. Here is what I have written so far:

#include <iostream>

using std::cout;
using std::endl;

struct IExtBase;

struct IBase
    {
    virtual void basicMethod()   = 0;
    virtual IExtBase& ext()      = 0;
    };

struct IExtBase
    {
    virtual void advancedMethod() = 0;
    };

struct BaseImpl : public IBase, IExtBase
    {
    static IBase& initialize(int p_attr)
        {
        return reinterpret_cast<IBase&>(BaseImpl(p_attr));
        }

    void basicMethod()
        {
        m_attr++;
        cout << "basic...\tattr: " << m_attr << endl;
        }

    IExtBase& ext()
        {
        return reinterpret_cast<IExtBase&>(*this);
        }

    void advancedMethod()
        {
        m_attr++;
        cout << "advanced...\tattr: " << m_attr << endl;
        }

    private:
        BaseImpl(int p_attr) : m_attr {p_attr} {}

        int m_attr;
    };

int main()
    {
    IBase& myBase = BaseImpl::initialize(0);

    myBase.basicMethod();           // Only IBase part of the BaseImpl object
    myBase.ext().advancedMethod();  // Fails...

    return 0;
    }

When I try to run this, I get an error:

Unhandled exception at 0x00EFF798 in ProgressiveDisclosure.exe:
0xC0000005: Access violation executing location 0x00EFF798.

I'm guessing it has to do with the casting I'm doing. Furthermore, I find that code rather complex and ugly for such a small example. I fell like there should be another way, by I fail to see it.

Could you please tell me what's wrong here and/or how this could be implemented in a better way?

Thanks.

java : observer pattern theoretical issue

In java observer pattern , Subject has a List of observers which is populated once observer register's on Subject.

Suppose 1000 observers have register on Subject. Subject is having a List in Subject Class.

Now after few days, observer is no longer interested in notification from subject but observer forget to ( or he is lazy ) do unregister.

Now here Subject contains unnecessary observer's object in the List which is wasting memory unnecessary.

What is the solution if memory is really important and don't want to waste memory.

Is the solution lie's in weak references ?

Or while doing register, we do register for lets say 10 days and after that observer has to re-register.

Progressive Disclosure in C++ API

Following my reading of the article Programmers Are People Too by Ken Arnold, I have been trying to implement the idea of progressive disclosure in a minimal C++ API, to understand how it could be done at a larger scale.

Do you know of any example I could take a look at?

I have found only one example on the web of such an implementation: the db4o library (in Java), but I do not really understand their strategy. For example, if we take a look at ObjectServer, it is declared as an interface, just like its extended class ExtObjectServer. Then an implementing ObjectServerImpl class, inheriting from both these interfaces is defined and all methods from both interfaces are implemented there.

This supposedly allows code such as:

public void test() throws IOException {
    final String user = "hohohi";
    final String password = "hohoho";
    ObjectServer server = clientServerFixture().server();
    server.grantAccess(user, password);

    ObjectContainer con = openClient(user, password);
    Assert.isNotNull(con);
    con.close();

    server.ext().revokeAccess(user); // How does this limit the scope to 
                                     // expert level methods only since it
                                     // inherits from ObjectServer?

    // ...
});

My knowledge of Java is not that good, but it seems my misunderstanding of how this work is at an higher level.

Thanks for your help!