vendredi 30 juin 2017

PHP MVC Data mapper pattern abstract class

I have a web MVC application with domain objects and data mappers. The class methods of the data mappers contain all database querying logic. I'm trying to avoid mirroring any database structure and, therefore, to achieve the maximum flexibility in constructing the sql statements. So, in principle, I'm trying to not make use of any ORM or ActiveRecord structure/pattern AT ALL.

Let me give you an example: Normally, I could have an abstract class AbstractDataMapper inherited by all specific data mapper classes - like the UserDataMapper class. And then I could define a findById() method in AbstractDataMapper, to fetch a record of a specific table - like users - by a given id value, e.g. user id. But this would imply that I'd always fetch a record from a single table, without the possibility to use any left joins to also fetch some other details from some other tables corresponding to the given id - user id.

So, my question is: Under these conditions - to which I myself obliged to, should I implement an abstract data mapper class, or each data mapper class should contain its own completely "proprietary" implementation of the data-access layer?

I hope I could express my idea clear. Please tell me, if I was somehow unclear or you have any questions.

Thank you very much for your time and patience.

Building Networking layer in iOS for multiple API's

I'm creating a social network app. I will be using various web services like Facebook for login, Instagram to get a users photos, and maybe others like Spotify.

I need to create a flexible Networking layer that can consume multiple REST API's, while minimizing duplicate code, coupling, and respects Single Responsibility Principle.

What I've managed to do is Abstract the process of sending a request into multiple parts.

  • First: its necessary to make enums that conform to the Request protocol. The enum will provide a group of related requests that can be executed. For instance, I'll have a UserRequest enum that contains a list of requests that involve the User Object Model. Same pattern for Messages, Posts, etc... By providing the associated values with a given enum case, the components of a URLRequest are assigned in an extension.

  • Second: create a Dispatcher Protocol, to create "client" objects that execute the actual requests. I only plan on needing one object that conforms, named NetworkDispatcher. This is where all the code that handles URL's, URLRequests, URLSessions, and handling response of that request.

  • Third: Create a service layer, that will interact directly with the view controllers. Service layer pretty much exposes an interface of all the requests that can be made that pertain to the type of service. For each method in the service layer, there is a corresponding enum case for the Request. Example: UserRequest has the method addUser('arguments'), which constructs a urlRequest. so UserService has the method addUser('arguments'), which calls on its instance of NetworkDispatcher to execute a request.

Is this a good flexible & maintainable approach? Im trying to pickup design patterns and follow good coding practices.

One thing Im also unsure about is if its okay for Services to be dependent on one another. For instance, what if I my ChatService class needs to make a request that the UserService exposes. Can I make the services singletons?

Any tip or guidance on how this can be improved upon or where I may have taken some wrong turns is greatly appreciated!

 /// - Request: Protocol that defines the components of a URLRequest.


protocol Request {

    var path: String { get }
    var method: Method { get }
    var body: [String: AnyObject]? { get }
    var queryItems: [URLQueryItem]? { get }
    var headers: [String: String]? { get }
}



enum UserRequest {
    case getUser(id: String, authToken: String)
    case addUser(data: [String: AnyObject], authToken: String)
}


extension UserRequest: Request {

    var path: String {
        switch self {
        case .getUser(let id, _): return "users/\(id)/" + ".json"
        case .addUser: return "users/" + ".json"
        }

    }

    var method: Method {
        switch self {
        case .getUser: return .get
        case .addUser: return .post
        }
    }


    var body: [String: AnyObject]? {
        switch self {
        case .addUser(let data, _): return data
        default: return nil
        }

    }


    var queryItems: [URLQueryItem]? {
        switch self {

        case .getUser(_, let authToken):
            let item = URLQueryItem(name: "auth", value: authToken)
            return [item]

        case .addUser(_, let authToken):
            let item = URLQueryItem(name: "auth", value: authToken)
            return [item]
        }
    }


    var headers: [String: String]? {
        switch self {
        default: return nil
        }
    }



}




 /// - Dispatcher: Responsible for making actual API requests.


protocol Dispatcher {

    init(host: String)

    func fireRequest(request: Request, _ completion: @escaping (_ success: [String: AnyObject]?, _ failure: NetworkError?) -> Void ) -> Void
}



 ///- Network Dispatcher: Conforms to Dispatcher, processes & fires off requests


class NetworkDispatcher: Dispatcher {

    private var host: String

    private var session: URLSession


    required init(host: String) {

        self.host = host

        self.session = URLSession(configuration: .default)
    }



    /// - Fires URLRequest via URLSession, leverages private helper methods to construct URLRequest and handle response.

    func fireRequest(request: Request, _ completion: @escaping ([String : AnyObject]?, NetworkError?) -> Void) {

        do {

            let urlRequest = try processRequest(request: request)

            session.dataTask(with: urlRequest, completionHandler: { (data, response, error) in
                let response = Response(data: data, response: response, error: error)
                switch response {
                case .json(let json): completion(json, nil)
                case .error(let error): completion(nil, error)
                }
            }).resume()

        } catch {
            completion(nil, error as? NetworkError)
            return
        }


    }




    /// MARK: - Helper Methods
    ///
    /// - Processes components from Request
    /// - Either returns URLRequest or throws an error


    private func processRequest(request: Request) throws  -> URLRequest {

        guard let url = processUrl(request: request) else {
            throw NetworkError.invalidUrl
        }

        var urlRequest = URLRequest(url: url)
        urlRequest.allHTTPHeaderFields = request.headers
        urlRequest.httpMethod = request.method.rawValue


        if let body = request.body {
            do {
                let _ = try JSONSerialization.data(withJSONObject: body, options: .init(rawValue: 0))
            } catch {
                throw NetworkError.invalidHTTPBody
            }
        }

        return urlRequest
    }



    private func processUrl(request: Request) -> URL? {

        var urlComponents: URLComponents {
            var components = URLComponents()
            components.path = host + request.path
            components.queryItems = request.queryItems
            return components
        }

        return urlComponents.url
    }


}





  /// - Response: handles response as json or error


typealias JSON = [String: AnyObject]

enum Response {

    case json(_: JSON)
    case error(_: NetworkError?)


    init(data: Data?, response: URLResponse?, error: Error?) {

        guard let httpResponse = response as? HTTPURLResponse else {
            self = .error(NetworkError.requestFailed)
            return
        }

        guard httpResponse.statusCode == 200 else {
            self = .error(NetworkError.responseUnsuccessful)
            return
        }

        guard let data = data else {
            self = .error(NetworkError.invalidData)
            return
        }

        do {

            let jsonData = try JSONSerialization.jsonObject(with: data, options: [])

            guard let json = jsonData as? [String: AnyObject] else {
                self = .error(NetworkError.jsonConversionFailure)
                return
            }

            self = .json(json)

        } catch {
            self = .error(NetworkError.jsonSerializationFailure)
        }
    }

}




/// SERVICE LAYER: Service objects that handle business logic for each Model.
///
/// - I'd have more services like ChatService, FeedService, and so forth.
/// - Interacts with View Controllers

class UserService {

    var dispatcher = NetworkDispatcher(host: "https://firebase.com/")


    func add(user: User, authToken: String, completion: @escaping (_ success: User?,_ failure: NetworkError?) -> Void ) {

        let request = UserRequest.addUser(data: user.toAnyObject(), authToken: authToken)

        dispatcher.fireRequest(request: request) { (data, error) in

            // TODO: Handle callback.

        }


    }

How to upcast Java 8 Optional objects?

Is there an efficient way to perform upcasting while using an Optional object. Here is a sample code:

class A{}
class B extends A{}

B func(){
    //do something
    return new B();
}

Optional<B> func2(){
    //do something
    return Optional.of(new B());
}

main() {
    A a = func(); // Upcasting works fine
    B b = func(); // Upcasting works fine
    Optional<B> b = func2(); // 1. Upcasting works fine
    Optional<A> a = func2(); // 2. Upcasting would not work
}

(2.) gives an error. I can solve it by creating another function.

But is there an efficient way, so that func2() can be used for both (1.) and (2.) ?

Add "uniqueness" constraint to Decorator Pattern in Java

I am trying to make some pizza with the Decorator Pattern (bear with me):

Suppose I have the following:

interface Pizza {
  public String makePizza();
}
class PlainPizza implements Pizza {
  @Override
  public String makePizza() {
    return "Base Pizza";
  }
}

And then I have a general decorator:

abstract class PizzaDecorator implements Pizza {

  protected Pizza specialPizza;

  public PizzaDecorator(Pizza specialPizza) {
    this.specialPizza = specialPizza;
  }

  public String makePizza() {
    return specialPizza.makePizza();
  }
}

And two implementations of the decorator:

class SausageDecorator extends PizzaDecorator {

  public SausageDecorator(Pizza specialPizza) {
    super(specialPizza);
  }

  public String makePizza() {
    return specialPizza.makePizza() + addSausage();
  }

  private String addSausage() {
    return " + sausage";
  }
}
class OliveDecorator extends PizzaDecorator {

  public OliveDecorator(Pizza specialPizza) {
    super(specialPizza);
  }

  public String makePizza() {
    return specialPizza.makePizza() + addOlives();
  }

  private String addOlives() {
    return " + olives";
  }
}

The problem is that I am able to have duplicate decorators. How can I change the structure of this code to add a "uniqueness" constraint - that is, each Decorator can appear as most once?

class PizzaMaker
    {
        public static void main (String[] args)
        {
            Pizza pizza = new SausageDecorator(new SausageDecorator(new OliveDecorator(new PlainPizza())));
            System.out.println(pizza.makePizza());
        }
    }

Output: Base Pizza + olives + sausage + sausage

downcast - grid - design pattern

I have a applications, that filters some files. There is a BaseRule, SpecificRule1 and SpecificRule2. Also these rules contains a List which do something with the file. Each of the actions classes (inherits from BaseAction) have a different constructor, due the algorithm needs different input (send file as email, move file to folder, delete file)

When I want to display the actions and rules on two grids with their parameters I use a List of BaseActions. If I want to modify the actions/rules parameters that are not shared I have to downcast them. Is it possible to avoid the downcast?

Flux design pattern and good practices

This is going to be lengthy post, containing my questions, backed with examples from the first Flux project, I recently created. I will split it into two sections and try to numerate my questions, for easier responses. If you know a good place where I can read about the topic - please share. I've done my reading, but I find it a bit hard to locate information regarding to general best practices. Here we go.

Section 1: General questions

1) Multiple stores per view component

Is it a good practice for a single container (or higher order component) to depend on multiple stores. That may cause a lot of unused properties in the component's state. Is that a problem? If it is I could get state like this:

//constructor
this.state = { 
    field1: // from Store1
    field2: // from Store2
}

//componentDidMount
Store1.listen(this.updateFromStore1)
Store2.listen(this.updateFromStore2)

//updateFromStore1
this.setState({
    field1: state.field1
});

I think such an approach would separate the data across stores very well - UserStore will only hold info about the user, {data}Store will only hold information about it's type of data. And every component can take whatever it needs from all the stores. Or should it be more like - every container has its own store, which would lead to data-repetition, but cleaner project.

2) Use single store for multiple components

For example - a FormStore, which is responsible for holding information about every form in our application. all fields of our forms are held there, and only those of the currently mounted component(for example UserRegister) are initialized and used. This may result in a lot of unused fields, with null value in the state, but again we could prevent that, if we select only the fields we are using, as I described above.

3) What should be responsible for loading the initial data?

I designed my app in a way that when a component mounts, it fires action method, which calls server for data, and then fires a Success of Fail action, which updates the store. But i read somewhere that stores can get the initial data internally, and then actions will be used only to change that data. If stores are to be responsible for this, when and how should that work?

4) The concept for actions:

Are actions supposed to drive everything, or are they only necessary when we update data. For example I have tried redirecting within actions and I get simultaneous actions error, because the component I redirected to, fires action inside componentDidMount to get more data. Maybe this would not be a problem if a store handles initial data internally.

Section 2: Specific questions

1) User authorization

URL based restriction is easy. I used another HOC on top of my container, which listened to UserStore and redirected to Login page, if there is no logged in user. But how would I hide a button, down in my component chain? I used the same approach (but instead of redirecting, I just didn't render the button). But that's sort of violation of Flux's rule, that all actions and stores should be operated by the container components only. Is there a better approach.

2) Self-contained statefull components

Flux docs say that best case would be if all view components are stateless. But what If I have an expandable view component? For example I have a box, with Book summary and a Read more button. When the button is pressed the box expands and additional information is shown. My solution would be to keep a state self-contained inside the component, which holds component-specific information. Logically I don't think there is any point for stores, which don't hold actual data. Any thoughts?

3) Forms located lower in the component chain

This may be similar to 2), but I think forms are a bit different. For Example, I have list of movies, on every movie you can click the "Comments" button, which will show the comments and also a form, to add new comment. How to handle that form? Self-contained logic and state? What I did was to add comment field to my FormStore, and reuse it and FormActions (The same actions and stores I use for every from there is in my app).

Javascript Module design pattern in polymer 2.0

A question coming from someone who has no background in polymer 1.0/2.0. There is this huge project currently being held and I've gotten used to using module design pattern for managing code. However in polymer 2.0, we have class based style. Sorry to sound dumb, but is it possible to implement module design pattern in polymer 2.0, or even OOP design pattern? if you have any resources, please direct me there.

Typical skeleton in polymer 2.0

class MyApp extends Polymer.Element {
  static get is() {
    return 'my-app';
  }
  ready() {
    super.ready();
  }
}

How can we make the above in to module design pattern style?

Thanks

The number game algorithm

Can anyone help me about this question. I found those numbers that elif wins between 0 and 100: 11, 22, 33, 44, 55, 66, 77, 88, 99, 101, 110, 123, 132, 145, 154, 167, 176, 189, 198. However, I couldn't figure out the general pattern among them.

The Number Game

KEO and Elif love card games. They decided to play one turn as part of their ritual, however they are bored playing the ordinary games, so they invented their own. Their game is played by the following rules:

• Before starting the game, a number N is determined.

• KEO goes first in every game and they take turns consecutively.

• Assume that both players play the game optimally.

• In their turns, players replace a non-zero digit of the number N with a smaller digit. (i.e. 5024 -> 1024, the player chose 5 and replaced it with 1.)

• The purpose of the game is to obtain 0 from the chosen number N in their turns.

You are asked to find how many times KEO and Elif will win the game in the range [L, R] (including L&R).

Input Format The first line contains the number of test cases (T). The next T lines contain numbers L and R consecutively.

Output Format Print wins of KEO and Elif consecutively for every test case in the given range.

Sample Input 2 1 11 100 200

Sample Output 10 1 91 10

Explanation For the first test case, for numbers {1,2,3,4,5,6,7,8,9,10} KEO may replace any of them with 0 in the first turn and wins the game. For the number {11}, KEO is obliged to replace it with {10} or {01}. Next, Elif may replace 10 or 1 with 0 and wins the game. Eventually, in the given range, KEO wins for 10 numbers, Elif wins for 1 number.

Boost: locale::date_time, locale generator, and wrapper class - Initializing Locale Generator cleanly

I'm writing a wrapper to use around the Boost library's locale::date_time class, to make it friendlier and easier for me to use. One thing I've figured out is that a date_time object cannot be declared (or be a member of a wrapper class that is declared) unless a locale generator has been created first.

So I need to ensure that a locale generator has been created BEFORE I create an instance of my wrapper object (which necessarily has a date_time member object). What is the best pattern/implementation to do this?

#include <boost\locale\date_time.hpp>
#include <boost\locale.hpp>

class DateTimeWrapper
{
    public:
        boost::locale::date_time m_date_time_object;
};

void Initialize_Locale()
{
    // Create locale generator
    boost::locale::generator gen;
    std::locale::global(gen(""));
}

int main()
{
    Initialize_Locale();

    // The following declaration will cause a failure if the above function is not first called
    DateTimeWrapper example_wrapper;

    return(0);
}

The problem with the above code is that I can't just blindly plug in my DateTimeWrapper class into any source file I want, unless I'm confident that main() or another function has called Initialize_Locale() first. I don't want to always have to watch out for that loose end in future projects if I want to reuse my DateTimeWrapper code - I'd rather just drop in the source file and have it work, without also having to ensure that main() or other function calls the Initialize_Locale() function.

I don't like that dependency - and making Initialize_Locale() a function of DateTimeWrapper that's called in the constructor also does not work, because the member m_date_time_object will still cause a failure when initialized before any DateTimeWrapper constructor code is run.

The only solution I can think of is to make m_date_time_object a pointer and dynamically allocate m_date_time_object in the constructor, AFTER the constructor calls Initialize_Locale(). But dynamically allocating m_date_time_object (and deleting it on destruction) will introduce a lot more complexity (related to how I'm implementing the DateTimeWrapper's other functionality), so I would like to avoid that solution if possible.

Is there an alternative pattern or approach I can use to address this problem?

Thanks.

jeudi 29 juin 2017

Creating static behavior that can be overridden in derived classes in C#

Here's the specific situation: I have a base abstract class Effect that contains some behavior that is shared amongst all types of effects. Then I have several derived class that inherit from Effect.

I want to have something like

public static virtual Effect CreateEffect(GameObject obj)
{
    if (!IsCreateable()) {
        return;
    }

    //Otherwise create the effect
}

public static virtual bool IsCreateable()
{
    //Some generic logic common amongst all Effects
}

And then in derived classes some of them require some extra custom logic

public static override bool IsCreateable()
{
     if (custom logic) {
         return false;
     }

     return base.IsCreateable()
}

Obviously this isn't possible because c# doesn't support static virtual function. I would like a way to share this static code amongst the classes without having to rewrite code. I can't have it as an instance method because in this case the code is being used to decide whether to create an instance in the first place.

In general, how do you have functions that is type-level (doesn't require an instance) with default behavior that can be overridden or modified in C#?

Assume this behavior is something separate from the constructor (for example in Unity3D you can't use a constructor to instantiate Monobehaviors).

Java regex not working in extracted text

I'm trying to use regex to match a part of the text. First I extract the text using Tika (it's a somewhat large pdf, 3mb of text) then I try to use the matcher on this text but it doesnt work

My text follow this pattern

Word: Match match match match

My regex is written this way

private final Pattern pattern = Pattern.compile("(word:\\s)(.*$)", Pattern.CASE_INSENSITIVE);

When I run this on a small sample, like the example above it'll work as expected. I'll have group(2) with "Match match match match"

But with the big text it doesnt work. I saved the file in .txt after and tried the ctrl+f with the regex expression and it works but not in my code.

What could it be ?

Many to many relationship with extra information

I'm having this Reddit like relationship shown as below. Basic idea is, each user can join many communities, and write many blogs in each community.

And there's community specific information about this user, like reputation etc. My question is, is it a good practice to put the extra information on the associative table (i.e. UserCommunities)? Why any why not?

Thanks!

enter image description here

How to make grid pattern design ?

I was wondering about how to make that "grid pattern" design as seen here : http://ift.tt/2maTneh Or here : https://klimov.agency

I already tried many times but it doesn't work The thin lines in the background... Thanks

How to implement a recursive Builder Pattern in Java?

I'm trying to grow a tree via Builder Pattern in Java. This tree has LongBranches, BlueBranches and RedBranches. Each kind of branch can be parent to any other type of branch. In addition, I have a Trunk and Leaf's. As you can see, this is quite complicated.

The tree builder is meant to be used like this:

Sapling.grow()
    .long()
         .red()
              .leaf()
         .end()
    .end()
    .blue()
    .end()
    .red()
         .long()
              .leaf()
              .leaf()
         .end()
    .end()
.end()

I tried to implement this via mutually recursive Builders and generics but only managed to generate (non-working) noodle code.

Please show me a minimal example of how this can be accomplished.

PHP Design Pattern for modifying Objects

I'm still a beginner when it comes to best practice OOP Patterns in PHP. What im trying to do is modifying the attributes of an object but um not quite sure how to implement it.

To be more specific: I have an 'order' object and the payment for that order is split into two payments, the pre payment and the final Payment. The calculation for each payment is a bit complex so i put the calculation in a seperate class, the 'costumerPaymentCalculator' which needs information from the order object to calculate the payments.

Should i just pass the Order Object to the calculator, modify the attributes within the calculater class and return the Order object?

Clean architecture/MVP: Using different repositories for different models. Is it okay?

The scenario: In my application, I have different types of models from different data sources that my presenter needs, eg UserState and Tasks. I have created two seperate repositories for both of these models namely, UserStateRepository and TaskRepository.

Both of these are injected into the TaskPresenter to show tasks and user specific info based on data from both the repositories.

In fact this is just one scenario. My app has many such models, eg Dictionary, Resources, etc. Almost every presenter for a view needs two repositories injected: UserStateRepository and the "MetaInformation"Repository. Hence I end up with at least 7 different repositories.

PS: I use Dagger2 to inject these repositories, but only the user state repository is an application level singelton whereas other repositories generally have activity level scope. This is because I need to refresh the cache of other activity scoped repositories everytime a new instance of an activity is created but the userstate must persist.

The question: Does this architecture actually make sense or is there a better solution? Also how about handling different lifecycles of these repositories

this regx @"^(?:\s*)((?:[a-zA-Z]+[\s-]?)+[a-zA-Z]+)(?:\s*)$ is taking long time

This regx @"^(?:\s*)((?:[a-zA-Z]+[\s-]?)+[a-zA-Z]+)(?:\s*)$ is taking so long time. In some complex cases, it is horrible. can you please how can optimize this regx. Using for c# development in Web Application.

Connect observers to observable automatically using dependency injection container

I have several services that implement an observer interface and one service that implements the corresponding observable interface.

I'm currently using unity together with Prism so I would prefer to keep this combination. My current solution is to inject the observable service in the observer services and let the observers subscribe themselves. I'm not sure this is a good design since the observer doesn't really depend on the observable.

Is there a way to automatically couple these using a dependency injection container? Is there another way?

mercredi 28 juin 2017

describe "this._sender" in Javascript Observer pattern?

Hi there great developers

I don't get it the role of this._sender in below Code.

var Event = function (sender) {
this._sender = sender;
this._listeners = [];
}

Event.prototype = {

    attach: function (listener) {
        this._listeners.push(listener);
    },

    notify: function (args) {
        for (var i = 0; i < this._listeners.length; i += 1) {
            this._listeners[i](this._sender, args);
         }
    }

};

Will someone please describe it?

Thanks in advance

javascript about AOP

review my code make it print expected result thax


    var Obj = (function () {
            var b = 'b',
                    _f = function () {
                        // print arguments
                        Array.prototype.push.call(arguments,b);
                        console.log(arguments,b);
                    }

            return {
                f:_f
            };
        })();


        //rewrite Obj.f
        Obj.f = function () {
            // add parameters dynamically
            Array.prototype.push.call(arguments,333);

            // it dose not work
            Obj.f.apply(Obj.f,arguments);
        }


        //when I rewrite Obj.f how to make it print result below

        // expected result print 111 333 'b'
        Obj.f(111);
        // expected result print 666 333 'b'
        Obj.f(666);
        // expected result print 444 333 'b'
        Obj.f(444);

What do Model and Controller exactly do

I have a object: User {id; name; value; password;}. I want to construct a MVC model for user management. But I don't know exactly what function i need to implement between model and controller layer. Make it easy to understand, i have some situation: 1. I implement change_password function. Should I implement in model or do it in controller and call update function in model? 2. I want to get total value of all users. Should I implement SUM query in model a directly or get all user (call get_all function) from model then i calculate total by "for array" in controller?

Self-Executing Anonymous Function

Was reading a blog post from appendTo and came across this pattern:

(function( skillet, $, undefined ) { 
  //Private Property 
  var isHot = true;

  //Public Property
  skillet.ingredient = 'Bacon Strips';

  //Public Method
  skillet.fry = function() {
    var oliveOil;

    addItem( 'tn Butter nt' );
    addItem( oliveOil );
    console.log( 'Frying ' + skillet.ingredient );
  };

  //Private Method
  function addItem( item ) {
    if ( item !== undefined ) {
        console.log( 'Adding ' + $.trim(item) );
    }
  }

}( window.skillet = window.skillet || {}, jQuery ));

This is intuitive for me, but as soon as this pops up:

//Adding a Public Property 
skillet.quantity = "12";

//Adding New Functionality to the Skillet
(function( skillet, $, undefined ) { 
  //Private Property 
  var amountOfGrease = "1 Cup";

  //Public Method
  skillet.toString = function() {
    console.log( skillet.quantity + ' ' +
                 skillet.ingredient + ' &amp; ' +
                 amountOfGrease + ' of Grease' );
    console.log( isHot ? 'Hot' : 'Cold' );
  };
}( window.skillet = window.skillet || {}, jQuery ));

skilet.ingredient skillet.quantity amountofGrease is accessed into the toString but I'm not entirely sure how isHot is accessed. Can anyone explain how when adding new functionalities later, this design still has access to original variables in the IIFE?

(Language Agnostic) Design Pattern for Unreliable Data Partner

What is the (generic, any OO) design pattern for the use case where you have a client that puts/gets data from the server, but the server isn't always available?

Python façade class: proper way to redirect methods

A façade. SmallManager objects are composed of a Manager object:

---------
Manager
---------
method1(a1, a2, a3)
method2()
method3()

---------
SmallManager           <--- façade of LargeManager
---------
__manager: Manager
method1(a1, a2, a3)    <--- Manager.method1()

I don't want to modify the arguments a1, a2, and a2 in SmallManager.method1 every time they are changed in Manager.method1. I could lazily implement SmallManager like this:

Implementation_1:

class SmallManager:
    def __init__(self, large_manager: Manager):
        self.__manager = large_manager
        self.self.__manager.method1

Implementation_2:

class SmallManager:
    def __init__(self, large_manager: Manager):
        self.__manager = large_manager

    def method1(self, *args, **kwargs):
        return self.__manager.method1(*args, **kwargs)

Problem:

Implementation_1:

when calling small_manager_instance.method1, the IDE can tell the user that this method is Manager.method1. Also, I might be possible for the user of SmallManager to get Manager attributes. This contradicts the façade pattern?

Implementation_2:

the IDE cannot sugggest the required arguments (pycharm suggests *args and **kwargs). Also I think I would need to rewrite the type hints in SmallManager if they are changed in Manager.method1.

What is the best option? Any other suggestions?

Thanks

OOP design: force calling virtual members from constructor

I have a problem in a library I am developing. The problem is that, for what I designed, I need to call a pure virtual function from the constructor. But I need to avoid undefined behavior.

This is the design I have a class shape that needs to be used as a sort of interface:

class shape
{
public:

    shape(std::shared_ptr<configuration> conf)
    { generate(); }

    std::shared_ptr<generated> mesh;

protected:

    virtual void generate() = 0;
};

The user, as far as I have designed, will write a class that will actually create the mesh. My idea, right now not working, is to force calling the generate method without the user's intervention.

In other words, the construction of the derived class must create the mesh. If I leave it to the user, the explicit call to generate could be forgotten and will result in some weird and destructive behavior that won't be noticed until really later (this should never happen for this library). I was thinking also of using CRTP or something from TMP but I cannot devise anything that is similar in simplicity to the above code.

How can I design the base class and eliminate the possibility of forgetting one call?

Any suggestions are more than welcome!

Property file based conditional patterns in java

I have a property file (a.txt) which has the values (Example values given below) like below

test1=10  
test2=20  
test33=34  
test34=35  

By reading this file, I need to produce an output like below

value = 35_20_34_10

which means => I have a pattern like test34_test2_test33_test1

Note, If the 'test33' has any value other than 34 then I need to produce the value like below

value = 35_20_10

which means => I have a pattern like test34_test2_test1

Now my problem is, every time when the customer is making the change in the logic, I am making the change in the code. So what I expect is, I want to keep the logic (pattern) in another property file so I will be sending the two inputs to the util (one input is the property file (A.txt) another input will be the 'pattern.txt'),

My util has to be compare the A.txt and the business logic 'pattern.txt' and produce the output like

value = 35_20_34_10 (or) 
value = 35_20_10

If there an example for such pattern based logic as I expect? Any predefined util / java class does this?

Any help would be Great.

thanks, Harry

Using singletons in Python (Django)

I was suggested to define a singleton in Python in the following way:

class Controller:
    pass
    # ...

controller = Controller() However, this way, controller cannot be replaced with a derived class.

What are other sensible ways to define singletons in Python Django?

Maybe, when defining a reusable app, I should not define the singleton instance right in the app, but define it in the program which uses it? What are advantages and disadvantages of doing this?

Avoiding ifs using patterns

I know that you can remove if blocks by using polymorphism with Strategy or Command patterns. However, let's say my code looks something like this:

ArgumentObject arg = getArg();

if (arg.getId() == "id2" || arg.getId() == "id3" || arg.getId() == "id4") {
    //do something
}
if (arg.getId() == "id2") {
    //do something
}
if (arg.getId() = "id2" || arg.getId() = "id3") {
    //do something
}
if (arg.getId().startsWith("id1") || arg.getId().startsWith("id4")) {
    //do something
}

I am not sure how can I use Strategy pattern here? If I create one Strategy to handle first if statement, then how can I proceed handling the second statement? The problem is that the ifs aren't mutually exclusive. Should I just move the relevant ifs to Strategy classes? Any pattern that would help me refactor this so its easier to test?

Proper way to create a static virtual factory method in C#

I'm implementing classes for Effects (something with a duration that applies a behavior in the FixedUpdate loop while it is active) in Unity3D.

I have a base abstract Effect class which has the behavior for keeping track of the duration, removing itself when the duration is up, and calling a protected abstract _doEffect function while its duration is up. In my derived classes, I override _doEffect to create Effects with different behaviors.

public abstract class Effect : MonoBehaviour
{
    public virtual float kDuration { get { return 1.0f; }}
    public static bool IsStackable { get { return false; }}
    private float _elapsed = 0.0f;

    protected virtual void Start()
    {
        _elapsed = kDuration;
    }

    protected virtual void FixedUpdate()
    {
        _elapsed -= Time.fixedDeltaTime;
        if(_elapsed <= 0) {
            Destroy(this);
        }

        _doEffect();
    }

    protected abstract void _doEffect();
}

Now, because you can't use constructors with Unity3D, I need a way to do the following for each derived Effect class when I'm applying a new Effect of that type to a game object:

1) If this type of effect is not stackable, then remove all other instances of this monobehaviour from the game object. 2) Create a new component of the effect type to the game object. 3) Do some initialization specific to that effect type.

For these requirements, I was imagining doing something like

public class DerivedEffect : Effect
{
    public override float kDuration { get {return 1.0f; }}
    public static bool IsStackable { get { return true; }}

    private int _derivedData;

    public static void Create(GameObject obj, int data)
    {
        DerivedEffect effect = DerivedEffect.CreateEffect(obj);
        effect._data = data;
    }

    protected override void _doEffect()
    {
        //Do some stuff
    }
}

and then in the base class putting

public static virtual Effect CreateEffect(GameObject obj)
{
    //T is somehow magically the type of the class you called this function on
    if(!T.IsStackable()) {
        //delete all components of type T on obj
    }
    T effect = obj.AddComponent<T>();
    return effect;
}

Obviously this isn't possible unless I do some weird stuff with generics and reflection that seems a bit extreme and probably not that right way to do things.

The crux is that I want a static function that does 1), 2), 3), and I want to share the code that does 1) and 2), and 1) depends on a bool which is different for every derived class.

What is a proper, working design for these desiderata?

MVVM : interactively adding new model instance

I have a program designed using MVVM approach: there is some data, stored in DB with Model classes encapsulating this data and all the business logic, there is a set of Views (UI controls) and there are ViewModels, that serve as in-between, getting data from models and passing it UI for presenting and working with.

All is working fine. Now I have a new requirement: to create a new instance of data interactively. So I should have a kind of dialog with its fields following strictly my model's inner structure. The user fills in the fields, presses Apply and new instance of a model is created.

The problem is: in doing so I am interfering with the main MVVM principle: now my views are intimately acquainted with my models. Obviously, I can use my ViewModel, to pass all the fields to it one by one, and make it responsible for a new model instance creation. However there are tens of fields and it hardly looks a better solution, it is still a very tight coupling.

I work with C++, not C#

Any advice?

Printing a * pattern

So I have to print the following pattern by accepting a value of n Input : 7 Output has to be this :

    *
    **
    ***
    ****
    *****
    ******
    *******
    ******
    *****
    ****
    ***
    **
    *
code:

public static void printPattern(int n)

{

for(int i=1;i<=n;i++)

    {
        for(int j=1;j<=i;j++)

           {
            System.out.println("*");

            }
            System.out.println("\n");

      } 

for (int a = n-1; a >= 1; a--)

    {
        for (int b = 1; b <= a; b++)
             {
              System.out.print("*");
             }
               System.out.println("\n");
    }
}

But for some reason it prints this pattern(say n=8):

*

* * * * *

* * * * * *

* * * * * * *

* * * * * * * *






**

* What is the mistake here? Thanks in advance!

hashow to persist query result between objects in php

in my case , i have query result came from database :

the result is a array,

i want to pass result in multiple object and get result .

i try to use mediator pattern but it wont work in my case , because i need to get result from first object and pass theme to second and so on .

code:

$mediator->add('test',[$obj1,'methodobj1']);
$mediator->add('test',[$obj2,'methodobj2']);
$mediator->run('test','resultCameFromDataBase(array)');

is there any advice ? should i use mediator ?

i know out there has many tools like doctrine2 , but in my case i cant use theme .

mardi 27 juin 2017

Polymorphed UI elements

I am building the following app using Javascript and Electron.js. There's video playing at the top, and corresponding data are displayed at the bottom. When the video plays, a marker move along in the charts.

When the use press the Add data button, new data could be imported. Depending on the type of data, different UI chart will be shown.

Which design pattern/architecture should be used to implement this feature? I know that the question is quite vague, but I'm at the designing and planning phase and any advices are appreciated.

enter image description here

Which design pattern/approach would be appropriate for implementing oEmbed api?

I would like to add oEmbed tags to my site (I'm the oEmbed api provider). My api should respond the results based on the file type.

oEmbed Types has

  • Photo
  • Video
  • Link
  • Rich

My response to photo contains the following field

{
    "author_name": "rajasuba.s",
    "author_url": <author_image_url>,
    "thumbnail_width": 130,
    "provider_url": <provider_url>,
    "thumbnail_url": "<thumbnail_image_url>",
    "title": "Picture.png",
    "provider_name": "XYZ",
    "type": "photo",
    "version": "1.0",
    "url": "<given_url>",
    "thumbnail_height": 120
}

My response to video contains the following field

{
    "author_name": "rajasuba.s ",
    "author_url": "<image_url_of_author>",
    "thumbnail_width": 130,
    "html": "<iframe src="<source_url>" width=\"480\" height=\"270\" frameborder=\"0\">",
    "provider_url": "<service_url>",
    "thumbnail_url": "<thumbnail_image_url>",
    "title": "video_small_resource.mp4",
    "provider_name": "XYZ",
    "type": "video",
    "version": "1.0",
    "thumbnail_height": 120
}

And similarly for link and rich types.

  1. Which design pattern would be appropriate for the following case?
  2. What is the mandatory fields while providing oEmbed? oEmbed documentation says type and version as mandatory param?
  3. What are the params that can be added in response for each type?

Any suggestions are welcome :-)

centralized server for event tracking instead of using segment.io directly?

I'm facing a design problem:

We are trying to implement events so that users' behavior can be analyzed. Here are the two ways we might take, and I'd like to ask what problems each method might cause

1) we use segment.io on clients directly. thus when user clicks a button, the data sends to segment's server 2) we implement an endpoint for our clients to send data to our server first, then server sends the data to segment.io

for 2, I can see the advantages are

  1. the clients doesnt need to worry about integrating any sdk
  2. server can send data to segment.io too (i.e. how long each request takes etc. server side actions)
  3. we can store the events data on our server as well without asking client to make two calls (when clients send data to our server, we store it in our db first, then send it to segment.io)

2 seems reasonable, but 1 seems to be what everyone else is doing

any suggestion?

QA servers and Development server Weblogic in same machine

If I have the next scenario: A server with two instances of weblogic configurated with the same specification of resources. The "customer" wants to designate one instance for QA and other instance for Development.

In my opinion this will be not correct because the separation must be clear between environments, even if the instances operates separately, the resources of the machine are equal and any problem of application in the server will impact in the process of QA, specially configuration at general level, I will prefeer have a separate machine. But more than this I don't find another strong argument to strength my vision.

I will glad to read your interested opinions, thanks in advance.

Is there a [JEE] Design Pattern for class [Application Controller] doing a set of similar activities?

In a Web application, there is a Front Controller, which based on a request, obtains an "action" string and an application controller instance. it then calls the application controller's method:

process(httpRequest, httpResponse, action)

This method, based on the action passed to it, calls one of several
do<action>(httpRequest, httpResponse) methods.

Each such doAction method:
performs an action on some BO/s then create an object with the view data (viewObj),
then based on the results picks a view (JSP),
sets the viewObj as the value of an attribute in the request,
finally calls requestDispatcher.include

Suppose There is a need to sometimes customize any of the do methods for some customer... in that case the customer contributes a new controller which extends the given controller, and overrides any of the do methods that need to be customized. (Suppose which controller to load is controlled by some configuration)

On the other hand, each doAction method may be written in a class by itself in a Command Pattern, where all these commands extend from a base Command class which implements a Template pattern. The process method of the controller would hold maintain a map of action-to-command and invoke the command. This can also be customized by providing a new Command class, and some configuration change.

So I was wondering, since this is a very common problem in the presentation layer of web applications, there must be a well accepted design pattern that should be followed in this case. In fact the design pattern is not necessarily a JEE only pattern...

So what is the accepted/preferred design pattern in this situation?

Dao design pattern for only data retrieval

Is it recommended to use DAO design pattern for jdbc connection if you only want to read data and not all CRUD operations

When are classes to similar

I would like to make report from sales data in a POS system.

So, I have a ReportGenerator that has a List <Ticket> The Ticket class represents a registration in the cash register. This can be a SalesTicket (DirectSalesTicket, InvoiceSalesTicket,...) or CashRegisterMovementTicket for a registration of money leaving or entering the cash register without a sale (e.g. taking money to the bank).

InvoiceSalesTicket has a invoiceNumber which a DirectSalesTicketdoesn't have. So I'm OK with having 2 different classes.

For CashRegisterMovementTicket I could make 2 classes (CashInRegisterMovementTicket and CashOutRegisterMovementTicket) that inherent from CashRegisterMovementTicket(which is a Ticket) that represent money that was added to the cash register or money that was taken out of the register. That would make 3 classes, that do not really differ from one another internally.

When I want to generate a report with al the money that has been taken out of the cash register I can just take the List <Ticket> and only use the ones that are of the CashOutRegisterMovementTicket type.

Another example:

SalesTicket has List <SalesLine>

Some reports are based on SalesTicket that have a gift certificate So I have NormalSalesLine and GiftCertificateSalesLine, both inherent from SalesLine but internally they are the same.

It feels like I have a lot of classes that are sometimes very similar. What am I missing?

checking regular expressions, Java patterns [duplicate]

This question already has an answer here:

I am trying to check different expression through java.util.regex.Pattern but It doesn't work well.

The next code return "no" but in my opinion must be return "yes". What is the problem?

if (Pattern.compile("historic").matcher("ahistoricbuilding").matches()) {
    System.out.println("yes");
} else {
    System.out.println("no");
}

Thanks.

lundi 26 juin 2017

How should i decouple branches in Scala(FP)?

Currently i'm scrapping a url, based on url value i will need to scrap page A or B(maybe i will need C,D,E and more), to compose my object, it's like:

case class X( val1 : ..., val2: ..., a: Optional[A] = None , b: Optional[B] = None)
case class A(...)
case class B(...)

So i have this functions:

def scrapBody() : Future[TagNode] // referent to HtmlCleaner
def scrapA(): A = { ws.url(...).post(...).map(scrapBody).map(produceA) }
def scrapX : X = { 
 ...
 //Scrap val1, val2 ...
 val condition = ...
 condition match{
 case a if ... => scrapA() // Optional
 case b if ... => scrapB() // Optional
 case _ => None   
 }
 return X// 
}

// The main body
for {
  x <- ws.url(...).post(...).map(scrapBody).map(getAorB)
} yield x

I can't figure out, how i unwrap A and B from Future, if i use a onComplete i cannot return Some or None, and i didn't see a way using Neither, the value of these traits it's just in the end of a chain of computations . So how should i handle conditional branches in a functional way? Also wanna know if i'm using composition in a right way.

Thanks.

Javascript 'Workflow Control'?

As I learn JS and design my self-study projects (SPAs mostly), I attempt to make sure I maintain separation of concerns and ensure each snippet of code that I write controls/does one thing.

Take the following example:

  1. I have a quiz application that presents questions, one at a time, to a user.
  2. The quiz has a 'Next' button, which calls a next() function.
  3. The next() function handles increasing the question index and retrieving the next question from the data source.
  4. Before I execute next(), I want to make sure the user gave a valid respnose - so I want to call a validate() function first; responsible for making sure the user input is valid.

In the above example, is it best practice to call validate() within my next() function, before it in sequence, or do I wrap both statements in a separate function and label it as a 'workflow'? This is greatly simplified, of course.

More broadly, is there a name for this topic? Perhaps something I can Google? 'Flow control' comes to mind, but when I Google that, the only thing that comes up are If statements, While loops, and basic control structures of the language itself. I'm looking for something more meta. Ironically, 'Design-patterns' seems to be too broad. Is there something in between?

Thank you in advance.

-Novice JS self-learner

Factory pattern with shared functions

I am trying to create some sort of factory pattern. However the thing I am stuck on, is that I need to call on some methods in each of the objects created by the factory. I wanna try to prevent this because it removes the single point of responsibility thingie.

My code looks like this:

class ActivityFactory : IActivityFactory
{
    public IActivityType CreateActivity(ActivityType type)
    {
        IActivityType activityType;
        switch (type)
        {
            case ActivityType.Customer:
                activityType = new CustomerActivity();
                break;
            case ActivityType.Lead:
                activityType = new LeadActivity();
                break;
            case ActivityType.Opportunity:
                activityType = new OpportunityActivity();
                break;
            case ActivityType.Appointment:
                activityType = new AppointmentActivity();
                break;
            default:
                throw new ArgumentException("Unsupported activity type.");
        }

        return activityType;
    }
}

            public ProcessingStatus SendActivity()
    {
        GetContactPersons();
        GetCustomers();
        EditContactPerson();
        SaveCustomer();
        SaveContactPerson();
        SaveCustomerContactPersonCombination();

        return ProcessingStatus.Succeed;
    }

    private void SaveCustomerContactPersonCombination()
    {

    }

    private void SaveContactPerson()
    {

    }

    private void SaveCustomer()
    {

    }

    private void EditContactPerson()
    {

    }

    private void GetCustomers()
    {

    }

    private void GetContactPersons()
    {

    }

Where the part starting at GetContactPersons() till SaveCustomerCombination is basically always the same, besides that they are talking with a different part of a webapplication.

Which is also the reason that I can't just put those methods before the factory even creates the objects.

For example: if I choose to create a Lead the getcontactpersons method will talk to url example/contactperson1 and when I choose customer it will talke to url example/contactperson2. The reason why I can't put those methods together is because of the different methods and objects they use provided by a third party.

Any ideas for a nice and pretty solution? Also thought about using a different design pattern. Just couldn't find a nice one for this problem.

Puppet Roles/Profiles with Overlapping Profiles

I am attempting to implement Puppet with the roles & profiles pattern. I have identified two distinct profiles at this point:

-security: provides a wide range of security-related configurations to hosts.
-ad_client: provides configurations to enable AD authentication to Linux clients.

I think these both make sense as independent profiles because either one may apply to a given host not necessarily both. Therefore, I think I have to make each one complete (i.e. fully instantiate classes in each) so that it can stand on its own.

However, for hosts that may require both of these profiles there exists fairly substantial overlap (e.g. both configure pam, sshd and sssd).

How can one create modular profiles but avoid such overlap?

Rule engine to filter multiple input objects based on multiple criteria

I wanna design a rule engine to filter incoming objects as follow:

At the beginning, I have three different classes: A, B, C. The list of classes is dynamic, i.e: I wanna extend this to work with class D, E, etc if D and E will be added later.

public class A {
   int a1;
   String a2;
   boolean a3;
   Date a4;
   List<String> a5;
   ...
}

public class B {
   String b1;
   boolean b2;
   Date b3;
   long b4;
   ...
}

public class C {
   String c1;
   boolean c2;
   Date c3;
   long c4;
   ...
}

There will be different objects of class A, B, or C that are gonna be filtered by my rule engine.

The users can define different rules based on a set of predefined operations that each member variable of a class can possibly have.

An example of some operations:

  • a1 can have operations like: >=, <=, or between some range, etc.
  • a2 can have operations like: is not, or is, etc.
  • a3 can only be true or false.
  • a4 can be: before certain date, after certain date, or between, etc.
  • a5 can be: exists or not exists in the list, etc.

Some example rules for an object of class A would be:

  • a1 is between 0 and 100, and a2 is not "ABC", and a3 is false, and a4 is before today, and a5 contains "cdf", etc.
  • a2 is "abc", and a3 is true, and a4 is between some date range.
  • etc.

One bullet is one rule. In a rule, there can be one criterion or more criteria (multiple criterion's that AND's together).

Each criterion is defined by a member variable with an operation that I can apply on that variable.

The rule engine must be able to process rules defined by users for each object of class A, B, or C. For every rule (A Rule, B Rule, or C Rule) coming in, the return will be a list of objects that matched the specified rule.

I can create Criterion, Criteria, ARule, BRule, CRule, Operation objects, etc; and I can go with the Brute Force way of doing things; but that's gonna be a lot of if...else... statements.

I appreciate all ideas of any design patterns/design method that I can use to make this clean and extendable.

Thank you very much for your time.

Can ARToolKit load a pattern file dinamically from outside?

Can ARToolKit load a pattern file (source) dinamically from outside after when i builded from the studio and not added exactly source?

Is there any example for this?

Strategy within Spring boot

Hi I have a strategy pattern in a spring boot application. All my strategies have autowired constructors. I am new to spring boot. I do not have a simplest of idea how am I going to write my factory for strategy classes as autowired constructors have injected dependencies. I appreciate any help I get with this.

NOTE: I am leaving out out Intefaces and base classes to not to clutter sample.

public class StrategyA implement Strategy {
private DependencyA depA;
private DependencyB depB;
   @Autowired
   public StragegyA(DependencyA depA, DependencyB depB) {
       this.depA = depA;
       this.depB = depB;
   }
}

public class StrategyB implements Strategy {
private DependencyA depA;
private DependencyB depB;
   @Autowired
   public StragegyB(DependencyA depA, DependencyB depB) {
       this.depA = depA;
       this.depB = depB;
   }
}

public class StrategyFactory {
    public Strategy getStrategy(String strategyName) {
      if (name.equals("StrategyA")) {
         <b>return StrategyA; //My problem is here
      } else {
         return StrategyB; // And Here
      }
    }
}

Is there any named pattern for composing a pojo according to parameter passed?

I need a factory like method that popoulate the same object according to parameter passed. Something like this:

Car output = CarFactory.getCar(EnumCarType.FAST_CAR)

CarFactory

public static Car getCar(EnumCarType type) {

    Car car= new Car();

    switch (type) {
        case FAST_CAR:
            car.setSpeed(200);
            car.setGears(7);
            ...
            break;
        case SLOW_CAR:
            car.setSpeed(120);
            car.setGears(5);
            ...
            break;
    }

    return car;
}

As you can see is not a properly factory because I need to return only one type of object so I don't need any kind of abstraction.

Can you help me identifying the right pattern case?

How to represent sensors and actuators, that both can be digital and analog?

I'm working on project, connected to hardware, especially sensors and actuators. Both sensors and actuators can be digital and analog. Example of all four types:

  • digital sensor: returns one of several possible states (i.e. "presence"/"absence"/"can't find out")
  • analog sensor: returns any value from range, but results are round according to scale interval (i.e. temperature sensor returns any value from 0 to 60 Celsius, with one digit precision, for example 18.5 C)
  • digital actuator: can get one of several possible states (i.e. motor, that opens window, can set window "open"/"half-open"/"closed")
  • analog actuator: can gat any value from range, and value is also rounded according to scale interval (i.e. fan rotations per second can be from 0 to 10, for example 9.5)

The question is, how I can represent these classes, without violating OOP principles, at least make design clear and logical.

One of my solutions is on the picture: uml_diagram_solution_1 But I think this solution is "ugly"

Next solution is here: uml_diagram_solution_2 This solution is also bad, because of redundant attributes and not uniform methods' names.

What do you suggest? Maybe there exists design pattern that solves my problem? Thanks for help!

Java MVC architecture

I'm developing an email client/server java application with RMI. I designed client based on MVC architecture. In particular, I've registered the Controller as a View event listener so that, for example, if I press the "inbox" button of the View, the Controller can download incoming emails from the server through a stub of the server itself.

The consequence of all this is that the controller is full of conditional code blocks on the name of the button pressed, which is very bad. Can anyone recommend me a way for replace conditional blocks? I thought about using some design patterns but I'd not know which is the best in this case.

Thanks!!

Design pattern for accessing static data

I have a scenario where I have a set of credentials for each environment e.g. for dev env username1/pwd1, for qa env username2/pwd2, for staging username3/pwd3 and so on. Now I want to create a class which will return me a set of credentials based on the env I feed to it. All the data has to go within code (as per my brilliant boss, no xml files and all), what design pattern I could use so that the code will be elegant and data can be made extensible in future?

dimanche 25 juin 2017

How to implement Design Patterns for my Wordpress Plugin

I'm creating a WooCommerce Product Database for Gadgets together with ACF Custom Fields. Now what I would like to do is to simplify these codes. I'm thinking of Factory method? or other design patterns? Because these codes will be so big and cluttered in the long run as I add more Custom Product, and its Custom Fields. I have also resolved in the method of adding hidden fields as suggested from my previous question

Will appreciate if you can give me examples from these codes I have so far. Let me describe part by part so you can think of how I can do like templating these. and for reference I attached the screenshot of the final output of this when implemented.

IN THE FUTURE or Coming Soon: I'll create also the comparing of products in the page.

Also, feel free to suggest if there are parts here that can be simplified? maybe. I'll check. Thank you so much.

Create Custom WooCommerce Product Type

 <?php
    /**
     * Plugin Name:     WooCommerce Custom Product Type
     * Plugin URI:      http://ift.tt/2sctq08
     * Description:     A simple plugin to add a custom product type.
     * Version:         1.0
     * Author:          RJ Ramirez
     */


    /**
     * Register the custom product type after init
     */
    function register_simple_mobile_product_type() {

        /**
         * This should be in its own separate file.
         */
        class WC_Product_Simple_Mobile extends WC_Product {

            public function __construct( $product ) {

                $this->product_type = 'simple_mobile';

                parent::__construct( $product );

            }

        }

    }
    add_action( 'plugins_loaded', 'register_simple_mobile_product_type' );

Add the Product Type in the Dropdown

/**
 * Add to product type drop down.
 */
function add_simple_mobile_product( $types ){

    // Key should be exactly the same as in the class
    $types[ 'simple_mobile' ] = __( 'Simple Mobile' );

    return $types;

}
add_filter( 'product_type_selector', 'add_simple_mobile_product' );

Some custom settings for the WooCommerce Product Created

/**
 * Show pricing fields for simple_mobile product.
 */
function simple_mobile_custom_js() {
    if ( 'product' != get_post_type() ) :
        return;
    endif;
    ?><script type='text/javascript'>
        jQuery( document ).ready( function() {
            jQuery( '.options_group.pricing' ).addClass( 'show_if_simple_mobile' ).show();
        });
    </script><?php
}
add_action( 'admin_footer', 'simple_mobile_custom_js' );

/**
 * Remove Product tabs from the page
 */
function woo_remove_product_tabs( $tabs = array() ) {

    unset( $tabs['shipping'] );         // Remove the description tab
    unset( $tabs['linked_product'] );           // Remove the reviews tab
    unset( $tabs['advanced'] );     // Remove the additional information tab

    return $tabs;

}
add_filter( 'woocommerce_product_data_tabs', 'woo_remove_product_tabs', 10 );


/**
 * Hide Attributes data panel.
 */
function hide_attributes_data_panel( $tabs) {

    $tabs['attribute']['class'][] = 'hide_if_simple_mobile hide_if_variable_mobile';

    return $tabs;

}
add_filter( 'woocommerce_product_data_tabs', 'hide_attributes_data_panel' );

//Remove Tabs at the Page
add_filter( 'woocommerce_product_tabs', 'woo_remove_product_page_tabs', 98 );
function woo_remove_product_page_tabs( $tabs ) {

    unset( $tabs['description'] );          // Remove the description tab
    unset( $tabs['reviews'] );          // Remove the reviews tab
    unset( $tabs['additional_information'] );   // Remove the additional information tab

    return $tabs;

}

Start adding Custom Product Tab in the WooCommerce Product Created

/**
 * Add a custom product tab.
 */
function custom_product_tabs( $tabs) {
    $tabs['General'] = array(
        'label'     => __( 'General', 'woocommerce' ),
        'target'    => 'general_contents',
        'class'     => array( 'show_if_simple_mobile', 'show_if_variable_mobile'  ),
    );

    $tabs['Launch'] = array(
        'label'     => __( 'Launch', 'woocommerce' ),
        'target'    => 'launch_contents',
        'class'     => array( 'show_if_simple_mobile', 'show_if_variable_mobile'  ),
    );

    $tabs['Network'] = array(
        'label'     => __( 'Network', 'woocommerce' ),
        'target'    => 'network_contents',
        'class'     => array( 'show_if_simple_mobile', 'show_if_variable_mobile'  ),
    );

    $tabs['Platform'] = array(
        'label'     => __( 'Platform', 'woocommerce' ),
        'target'    => 'platform_contents',
        'class'     => array( 'show_if_simple_mobile', 'show_if_variable_mobile'  ),
    );

    $tabs['Body'] = array(
        'label'     => __( 'Body', 'woocommerce' ),
        'target'    => 'body_contents',
        'class'     => array( 'show_if_simple_mobile', 'show_if_variable_mobile'  ),
    );

    $tabs['Display'] = array(
        'label'     => __( 'Display', 'woocommerce' ),
        'target'    => 'display_contents',
        'class'     => array( 'show_if_simple_mobile', 'show_if_variable_mobile'  ),
    );

    $tabs['Memory'] = array(
        'label'     => __( 'Memory', 'woocommerce' ),
        'target'    => 'memory_contents',
        'class'     => array( 'show_if_simple_mobile', 'show_if_variable_mobile'  ),
    );

    $tabs['Camera'] = array(
        'label'     => __( 'Camera', 'woocommerce' ),
        'target'    => 'camera_contents',
        'class'     => array( 'show_if_simple_mobile', 'show_if_variable_mobile'  ),
    );

    $tabs['Sound'] = array(
        'label'     => __( 'Sound', 'woocommerce' ),
        'target'    => 'sound_contents',
        'class'     => array( 'show_if_simple_mobile', 'show_if_variable_mobile'  ),
    );

    return $tabs;

}
add_filter( 'woocommerce_product_data_tabs', 'custom_product_tabs' );

Start Adding Custom Fields in the created Custom Tabs

/**
 * Contents of the mobile options product tab.
 */
function general_product_tab_content() {

    global $woocommerce, $post;

    //General
    $label_text_model_number = __( 'Model Number', 'woocommerce');

    ?><div id='general_contents' class='panel woocommerce_options_panel'><?php

        ?><div class='options_group'><?php


            woocommerce_wp_text_input( array(
                'id'            => '_text_model_number',
                'label'         => $label_text_model_number,
                'desc_tip'      => 'true',
                'description'   => __( 'The model number of the product', 'woocommerce' ),
                'type'          => 'text',
            ) );

            //Add hidden inputs for label
            echo '<input type="hidden" id="text_model_number_label" name="text_model_number_label" value="'.$label_text_model_number.'" />';

        ?></div>

    </div><?php
}
add_action( 'woocommerce_product_data_panels', 'general_product_tab_content' );

/**
 * Contents of the mobile options product tab.
 */
function launch_product_tab_content() {

    global $woocommerce, $post;

    // Setting here your labels
    $label_text_announced = __( 'Announced(Global)', 'woocommerce' );
    $label_text_announced_ph = __( 'Announced(Philippines)', 'woocommerce' );
    $label_text_availability_ph = __( 'Availability(Philippines)', 'woocommerce');

    ?><div id='launch_contents' class='panel woocommerce_options_panel'><?php

        ?><div class='options_group'><?php

            woocommerce_wp_text_input( array(
                'id'            => '_text_announced',
                'label'         => $label_text_announced,
                'desc_tip'      => 'true',
                'description'   => __( 'Year and Month it was announced global', 'woocommerce' ),
                'type'          => 'text',
            ) );

            woocommerce_wp_text_input( array(
                'id'            => '_text_announced_ph',
                'label'         => $label_text_announced_ph,
                'desc_tip'      => 'true',  
                'description'   => __( 'Year and Month it was announced global', 'woocommerce' ),
                'type'          => 'text',
            ) );

            woocommerce_wp_text_input( array(
                'id'            => '_text_availability_ph',
                'label'         => $label_text_availability_ph,
                'desc_tip'      => 'true',
                'description'   => __( 'Schedule date of availability in the Philippines', 'woocommerce' ),
                'type'          => 'text',
            ) );

            //Add hidden inputs for label
            echo '<input type="hidden" id="text_announced_label" name="text_announced_label" value="'.$label_text_announced.'" />';
            echo '<input type="hidden" id="text_announced_ph_label" name="text_announced_ph_label" value="'.$label_text_announced_ph.'" />';
            echo '<input type="hidden" id="text_availability_ph_label" name="text_availability_ph_label" value="'.$label_text_availability_ph.'" />';

        ?></div>

    </div><?php
}
add_action( 'woocommerce_product_data_panels', 'launch_product_tab_content' );

function network_product_tab_content() {

    global $woocommerce, $post;

    // Setting here your labels
    $label_text_network_technology = __( 'Technology', 'woocommerce');
    $label_text_network_speed = __( 'Speed', 'woocommerce');


    ?><div id='network_contents' class='panel woocommerce_options_panel'><?php

        ?><div class='options_group'><?php

            woocommerce_wp_text_input( array(
                'id'            => '_text_network_technology',
                'label'         => $label_text_network_technology,
                'desc_tip'      => 'true',
                'description'   => __( 'Schedule date of availability in the Philippines', 'woocommerce' ),
                'type'          => 'text',
            ) );

            woocommerce_wp_text_input( array(
                'id'            => '_text_network_speed',
                'label'         => $label_text_network_speed,
                'desc_tip'      => 'true',
                'description'   => __( 'Speed per technology category', 'woocommerce' ),
                'type'          => 'text',
            ) );


            //Add hidden inputs for label
            echo '<input type="hidden" id="text_network_technology_label" name="text_network_technology_label" value="'.$label_text_network_technology.'" />';
            echo '<input type="hidden" id="text_network_speed_label" name="text_network_speed_label" value="'.$label_text_network_speed.'" />';

        ?></div>

    </div><?php
}
add_action( 'woocommerce_product_data_panels', 'network_product_tab_content' );

Start adding the Save functionality of Custom fields added

/**
 * Save the custom fields.
 */
function general_product_tab_save( $post_id ) {

    if ( isset( $_POST['_text_model_number'] ) ) :
        update_post_meta( $post_id, '_text_model_number', sanitize_text_field( $_POST['_text_model_number'] ) );
    endif;


}
add_action( 'woocommerce_process_product_meta', 'general_product_tab_save' );

function launch_product_tab_save( $post_id ) {

    if ( isset( $_POST['_text_announced'] ) ) :
        update_post_meta( $post_id, '_text_announced', sanitize_text_field( $_POST['_text_announced'] ) );
    endif;

    if ( isset( $_POST['_text_announced_ph'] ) ) :
        update_post_meta( $post_id, '_text_announced_ph', sanitize_text_field( $_POST['_text_announced_ph'] ) );
    endif;

    if ( isset( $_POST['_text_availability_ph'] ) ) :
        update_post_meta( $post_id, '_text_availability_ph', sanitize_text_field( $_POST['_text_availability_ph'] ) );
    endif;


}
add_action( 'woocommerce_process_product_meta', 'launch_product_tab_save' );


function network_product_tab_save( $post_id ) {

    if ( isset( $_POST['_text_network_technology'] ) ) :
        update_post_meta( $post_id, '_text_network_technology', sanitize_text_field( $_POST['_text_network_technology'] ) );
    endif;

    if ( isset( $_POST['_text_network_speed'] ) ) :
        update_post_meta( $post_id, '_text_network_speed', sanitize_text_field( $_POST['_text_network_speed'] ) );
    endif;

}
add_action( 'woocommerce_process_product_meta', 'network_product_tab_save' );


add_filter( 'woocommerce_product_tabs', 'woo_new_product_tab' );
function woo_new_product_tab( $tabs ) {

    // Adds the new tab
    $tabs['specifications_tab'] = array(
        'title'     => __( 'Specifications', 'woocommerce' ),
        'priority'  => 5,
        'callback'  => 'woo_new_product_tab_content'
    );

    return $tabs;

}

Start generating the Display of Custom Product in Page when embedded

function woo_new_product_tab_content() {

    //GENERAL
    $field_object_text_model_number = get_field_object('_text_model_number', $post->ID);

    // LAUNCH
    $field_object_text_announced = get_field_object('_text_announced', $post->ID);
    $field_object_text_announced_ph = get_field_object('_text_announced_ph', $post->ID);
    $field_object_text_availability_ph = get_field_object('_text_availability_ph', $post->ID);

    /*
    *  get all custom fields, loop through them and create a label => value markup
    */
    echo '<h2>' . get_the_title( get_the_ID() ) . '</h2>'; ?>
        <div id="mobile_specs_wrapper" class="table-responsive">
            <table id="table_mobile_specs" class="flat-table flat-table-3">
                <thead>

                </thead>
                <tbody>
                    <tr>
                        <td>GENERAL or <?php echo esc_html( $field_object_text_model_number['label'] ); ?></td>
                        <td>1<?php echo esc_html( $field_object_text_model_number['value'] ); ?></td>
                        <td>2<?php echo get_post_meta(get_the_ID(),"_text_model_number_label",true); ?></td>
                    </tr>
                    <tr>
                        <td>LAUNCH</td>
                        <td>3<?php echo get_post_meta(get_the_ID(),"_text_announced_label",true); ?></td>
                        <td>4<?php echo esc_html( $field_object_text_announced['value'] ); ?></td>
                    </tr>
                </tbody>
                <tfoot>
                    <tr>
                        <td colspan="3"><b>Disclaimer.</b> Information inscribed here are with utmost accuracy but not 100% guaranteed.</td>
                    </tr>
                </tfoot>
            </table>
        </div>



<?php   
}


Custom WooCommerce Product Embedded in the Page

Generic Factory pattern Implementation

I am trying to implement a template factory pattern.

template <typename T1, typename T2>
class SpawnManager
{
public:
        static bool registerit(const T1& type, std::unique_ptr<T2>(*f)(const sf::Vector2f & pos));
        static std::unique_ptr<T2> create(const T1& type, const sf::Vector2f& pos);

private:
        static std::map<T1, std::unique_ptr<T2>(*)(const sf::Vector2f& pos)> m_map;
};
//the problem is here!
template <typename T1, typename T2>
std::map<T1, std::unique_ptr<T2>(*)(const sf::Vector2f& pos)> SpawnManager<T1, T2>::m_map = std::map<T1, std::unique_ptr<T2>(*)(const sf::Vector2f& pos)>{};

This code complies fine, but it fails at running time..

Exception thrown: read access violation. std::_Tree > (__cdecl*)(sf::Vector2 const &),std::less,std::allocator > (__cdecl*)(sf::Vector2 const &)> >,0> >::_Root(...) returned 0x4.

How to properly setup naming convention for classes and namespaces?

In every C# project I always end up with a same issue. For example, I have the following namespace

ProjectName.Application.Invoicing

and classes

class InvoiceResponse
{
   ....
   public InvoiceType invoice_type {get;set}
   ....
}
class InvoiceUpdateRequest
{
   ....
   public InvoiceType invoice_type {get;set}
   ....
}
class InvoiceType
{
   public int type_id {get;set;
   ....
}

Now I believe i have two options

1. namespace ProjectName.Application.Invoicing 
class InvoiceResponse {} 
class InvoiceUpdateRequest {} 
class InvoiceType {}

in case InvoiceType class is differently declared for InvoiceResponse and InvoiceUpdateRequest, i would need to have something like InvoiceResponseInvoiceType {} InvoiceUpdateRequestInvoiceType {} that can help me differentiate classes Problem here in case main class changes, all related classes/classnames should be updates in order to keep class name consistency

2. Split into different namespaces
namespace ProjectName.Application.Invoicing.InvoiceResponse
class InvoiceResponse {} in this case I would have to use same namespace/classname convention which is not recommended
class InvoiceType{} 
namespace ProjectName.Application.Invoicing.InvoiceUpdateRequest
class InvoiceUpdateRequest {} in this case I would have to use same namespace/classname convention which is not recommended
class InvoiceType{}

Regular Expression VBA : find particular set of data

I've encountered an issue with my macro. I'm trying to find in a string, elements beginning with FP 608 or TM 608.

The string I try to extract always begins with FP or TM. The elements after are numbers, 3 or 4 numbers (100 or 1000). they can also have 2 decimals (100.10 or 1000.10).

For instance it should extract :

  • ABCDF FP 573,83 ABDFEG HIJ KLM 0124" : Extract : 573,83
  • ABCFED ERD 536,98 [...] = no extraction
  • TM 123,12 ABCDD EFGHIJ KLM : Extract TM 123,12
  • FP 100 : Extract : FP 100

This seems to work but it's inefficient :

Function GetRealCost(MyRange As Variant)

Application.ScreenUpdating = False
Application.EnableEvents = False
Application.DisplayStatusBar = False

    Dim regEx As Object
    Set regEx = CreateObject("vbscript.regexp")
    Dim strPattern As String
    Dim strInput As String
    Dim strOutput As Object

    strPattern = "\b(TM )([0-9]{3,4})(,[0-9]{1,2}\b)"

    With regEx
        .Global = True
        .MultiLine = True
        .IgnoreCase = False
        .Pattern = strPattern
    End With

        strInput = MyRange

        If regEx.test(strInput) Then
            regEx.Pattern = "(\b[0-9]{3,4})(,[0-9]{1,2}\b)"
            Set strOutput = regEx.Execute(MyRange)
            GetRealCost = regEx.Execute(strInput)(0)
        Else
            strPattern = "\b(TM )([0-9]{3,4}\b)"
            regEx.Pattern = strPattern
                If regEx.test(strInput) Then
                    regEx.Pattern = "(\b[0-9]{3,4}\b)"
                    Set strOutput = regEx.Execute(MyRange)
                    GetRealCost = regEx.Execute(strInput)(0)
                        Else
                            strPattern = "\b(FP )([0-9]{3,4})(,[0-9]{1,2}\b)"
                            regEx.Pattern = strPattern
                                If regEx.test(strInput) Then
                                regEx.Pattern = "(\b[0-9]{3,4})(,[0-9]{1,2}\b)"
                                Set strOutput = regEx.Execute(MyRange)
                                GetRealCost = regEx.Execute(strInput)(0)
                                        Else
                                strPattern = "\b(FP )([0-9]{3,4}\b)"
                                regEx.Pattern = strPattern
                                    If regEx.test(strInput) Then
                                        regEx.Pattern = "(\b[0-9]{3,4}\b)"
                                        Set strOutput = regEx.Execute(MyRange)
                                        GetRealCost = regEx.Execute(strInput)(0)
                                            Else
                                        GetRealCost = ""
                                    End If
                    End If
                End If
        End If

Application.ScreenUpdating = True

End Function

Thank you !

Design patterns: many objects of same type with multiple objects of other type

Which would be a good approach if I were to make an application where I had to store all countries in Europe and as well as their respective cities?

I considered using an enum to store the information but since that'd require me to hard-code lots of data I quickly scrapped that idea.

Afterwards I considered something like:

class Country {

    public Country(String name, City... cities) {
        //Stuff
    }
}

That way I'd be able to read cities from a .txt and create objects accordingly thus eliminating the need for manual labor. However, that brings a new issue, where do I store my list of countries? I considered the following:

class Country {

    public Country(String name, City... cities) {
        //Stuff
    }

    public static List<Country> getAllCountries() {
        return countries;
    }
}

but I feel like such code pollutes the structure and cleanliness of the project.

I thought about going with a combination of an enum (Country) and a class (City) but that doesn't feel right either.

Ideally I'd like to be able to access countries like an enum Country.FRANCE or Country.getByName("France") but neither seems like a solution here. So, I'm back to my initial question. What is a good way to go about doing this?

memory got lost during chain of responsibility example c++

I am running sequence of image processing operations using chain of responsibility in opencv C++. The return result seems got lost as soon as the recursive function processRequest(OpRequest request) returns. Could someone point of the error I made here. Thanks in advance. The following are the code:

#include <opencv2/highgui/highgui.hpp>
#include <opencv2/imgproc/imgproc.hpp>
#include <opencv2/core/core.hpp> 
using namespace cv;


#define ABS_DIFF_OP 1<<0
#define THRESHOLD_ADAPTIVE_OP 1<<1

class OpRequest
{
int
    opType;
vector<Mat> imgs;

public:

OpRequest(int opType, const vector<Mat> imgs)
{
    this->opType = opType;
    this->imgs = imgs;
    return;

}//End method

int getOpType()
{
    return opType;
}//End method

void setOpType(int opType)
{
    this->opType = opType;
    return;
}//End method

void setImages(const vector<Mat> imgs)
{
    this->imgs = imgs;
    return;
}//End method

vector<Mat> getImages()
{
    return imgs;
}//End method

};//End class

// Base class
class Op  
{
private:
Op* successor;
int op;
Mat result;
public:
Op()
{
    successor = NULL;
    op = -1;
}

Op(Op* successor, int op)
{
    this->successor = successor;
    this->op = op;
    return;
}//End method


virtual Mat apply(const vector<Mat> imgs) = 0;
void setSuccessor(Op* successor)
{
    this->successor = successor;
    return;
}//End method

void setOpType(int opType)
{
    op = opType;
    return;
}//End method

int getOpType()
{
    return op;
}//End method

Mat getResult()
{
    return result;
}//End method

void processRequest(OpRequest request)
{

    if( op == request.getOpType() )
    {
        vector<Mat>
            imgs = request.getImages();
        Mat m = apply(imgs);

        if( this->successor == NULL )
        {
            m.copyTo(result);

        }
        else
        {
            vector<Mat>
                nextImgs;
            nextImgs.push_back(m);
            OpRequest nextRequest(successor->getOpType(), nextImgs);
            successor->processRequest(nextRequest);
            cout<<"move to next"<<endl;
        }
    }//End if( op == request.getOpType() )

    //imshow("result", result);
    //waitKey(0);

    return;
}//End method

};  //End class


class DIFF_Op : public Op
{
 public:

    DIFF_Op()
    : Op()    
    {

    }//End constructor

     DIFF_Op(Op* successor, int op)
    : Op(successor,op)    
    {

    }//End constructor

    Mat apply(const vector<Mat> imgs)
    {
        Mat
            f1 = imgs[0],
            f2 = imgs[1];
        Mat
            diff;
        cv::absdiff(f1,f2,diff);
        return diff;

    }//End method

};//End class


class THRESHOLD_ADAPTIVE_Op : public Op
{
 public:

    THRESHOLD_ADAPTIVE_Op()
    : Op()    
    {

    }//End constructor

     THRESHOLD_ADAPTIVE_Op(Op* successor, int op)
    : Op(successor,op)    
    {

    }//End constructor

    Mat apply(const vector<Mat> imgs)
    {
        Mat
            diff = imgs[0];

         Mat
            th;
        adaptiveThreshold(diff,th,255,ADAPTIVE_THRESH_MEAN_C, 
THRESH_BINARY,7,4);
        //imshow("th",th);
        return th;

    }//End method

};//End class
//The testing function is here:

void testChainOfRes()
{
int opType = ABS_DIFF_OP;
vector<Mat> imgs;

imgs.push_back(imread("test/0c.bmp", CV_LOAD_IMAGE_GRAYSCALE ));
imgs.push_back(imread("test/1c.bmp", CV_LOAD_IMAGE_GRAYSCALE ));

OpRequest
    request(opType, imgs); 


THRESHOLD_ADAPTIVE_Op*
    thAdOp = new THRESHOLD_ADAPTIVE_Op(NULL,THRESHOLD_ADAPTIVE_OP);
DIFF_Op*
    diffOp = new DIFF_Op(thAdOp,ABS_DIFF_OP);


diffOp->processRequest(request);

Mat 
    result = diffOp->getResult(); 

loadImage(result);




delete diffOp;

return ;
}//End method

The result Mat becomes empty as soon as the last processRequest function call returns.

Which design pattern should I use and why?

Pharmacy sells medicine from different producers. Each medicine has a name, type (antibiotics, anti-inflammatory, stomach), price etc. However, imported medicine must have a certificate from a lab in the current country. Moreover, if customer purchases an imported medicine, the pharmacy worker has got to query the medicine database and see the data about the counterpart medicine from domestic producers (which are usually cheaper).

How do we develop a class structure to handle medicine data in this pharmacy?

How can i implement the following typescript code better?

I have following typescript code which implements a request-response flow.

There can be two types of DataRequest - FooDataRequest & BarDataRequest .

There are multiple resolvers for these request types . FooResolver does Foo specific things and sends back FooDataResponse and BarResolver which does Bar specific things and send back BarDataResponse

abstract class DataRequest{
    public type: typeof DataRequest;
    public payload: string;
}
abstract class DataResponse { 
    public data: any;
}

class FooDataRequest extends DataRequest { 
    constructor() { 
        super();
        this.type = FooDataRequest;
        this.payload = "foo request";
    }
}

class BarDataRequest extends DataRequest { 
     constructor() { 
        super();
        this.type = FooDataRequest;
        this.payload = "foo request";
    }
}

class FooDataResponse extends DataResponse { 
    constructor() { 
        super();
        this.data = "foo response";
    }
}
class BarDataResponse extends DataResponse { 
    constructor() { 
        super();
        this.data = "bar response";
    }
}

abstract class DataResolver { 
    abstract resolve(request:DataRequest): DataResponse 
}

class FooViewResolver extends DataResolver { 
    public resolve(reportRequest:FooDataRequest): FooDataResponse { 
        return new FooDataResponse();
    }
}

class BarViewResolver extends DataResolver { 
    public resolve(dashboardRequest:BarDataRequest): BarDataResponse { 
        return new BarDataResponse();
    }
}

class ResolverFactory { 
    public static getResolver(request: DataRequest): DataResolver { 
        //If there is 100 request , then so many if else statement
        //That is not effective
        if (request.type === FooDataRequest) {
            return new FooViewResolver();
       }
        else if (request.type = BarDataRequest) { 
            return new BarViewResolver();
        }
    }
}



const request :DataRequest = new FooDataRequest();
const resolver: DataResolver = ResolverFactory.getResolver(request);
console.log(resolver);
const response: DataResponse = resolver.resolve(request);
console.log(response);

What is the best method to implement a resolver factory? If i have 100 request types then if will have multiple if else statements to identify appropriate resolver. Or is there a better way to design this problem?

samedi 24 juin 2017

MVC pattrern. Which class is the entry point?

MVC pattern separates data model, GUI view and event handling by controller. One can make Model the entry point

public class MyModel {

    private Integer value;
    MyView view = new MyView(this); 
    MyController controller= new MyController (this);
    //MyController controller= new MyController (this, view);
    }

Or, one can start with Controller and create model and view from controller.

Which class should be be called first and create other two classes?

vendredi 23 juin 2017

How to identify 2d patterns?

In a stream of (x,y) points, how do I go about identifying patterns in consecutive points in the stream? For example I want to set a flag if I see points coming in a zigzagging pattern, or in a "roughly" a circle pattern. Appreciate any pointers to algorithms or better yet to Java libraries that already do that.

JavaFx - What is the design patterns for the Pure Java coding ? (No CSS or FXML)

Good evening, everyone!
I'm having trouble to get the knowledge of the design patterns for a JavaFx project made entirely of Java (Pure Java Coding, no CSS or FXML).
Can someone explain to me and give me a simple example of it ?

EXTRA : Also , what is the difference of the the Property objects properties (ex. StringProperty) to the normal ones (ex. String)?
Sorry for the newbie questions and thank you in advance!

Better programing practice?

What would be better programing practice ?

In this example I have class Person and PersonDisplay.

    class Person{
        private String name;
        private String surname;
        private String adress;
        private String nickname;
        private String sex;
        private Int age;
        private String email;
        ... and other attributes that i need for something else

        public Person(String name, String surname, String adress, String nickname, String sex, String age, String email){
          this.name =name;
          this.surname = surname;
          ...
        } 
    }

Should I implement PersonDisplay like this:

    class PersonDisplay{
        private TextField nameText;
        private TextField surnameText;
        private TextField adressText;
        private TextField nicknameText;
        private TextField sex;
        private TextField age;

        public PersonDisplay(String name, String surname, String adress, String nickname,String sex,int age){
          nameText.setText(name);
          surnameText.setText(surname);
          ...
        }
    }

Or like this

    class PersonDisplay{

        private Person person;

        private TextField nameText;
        private TextField surnameText;
        private TextField adressText;
        private TextField nicknameText;
        private TextField sex;
        private TextField age;

        public PersonDisplay(Person person){
          this.person=person;
          nameText.setText(person.getname());
          surnameText.setText(person.getsurname());
          ...
        }
    }

1.What is better constructor implementation?

2.Would using something else like build pattern here be recomended?

Delete everything from an custom Object MyString except a single part plus unknow numbers

my Problem is (maybe because I am a little bit tired), that I have a custom Object called myString. It contains a line of a Json-file. Now I want to delete everything except one part of it, that contains the info that I need.

Class MyString:

import com.google.gson.Gson;

import java.io.BufferedReader;
import java.io.IOException;

public class MyString {
    public String myString;

    public MyString(String myString) {
        this.myString = myString;
    }

    public Object toJson(Gson gson){
        return gson.fromJson(myString, Object.class);
    }

    public boolean nextLine(BufferedReader bufferedReader) throws IOException {
        return ((myString = bufferedReader.readLine()) != null);
    }
}

myString has some kind of this value:

[{date={year=2012.0, month=1.0, day=1.0}, time={hour=12.0, minute=0.0, second=0.0, nano=0.0}}, {date={year=2012.0, month=1.0, day=1.0}, time={hour=13.0, minute=0.0, second=0.0, nano=0.0}}, {titel=idk}, {text=pls}, {woerter=wtf}, {seconds=3600.0, nanos=0.0}]

form which I just want

{seconds=3600.0, nanos=0.0}

to

3600

Now if I use this, it does not even find "seconds=", not even speaking about those numbers:

MyString dateiInhalt = new MyString("");

//dateiInhalt gets the Line from the Json-file

Pattern regex = Pattern.compile("seconds=");
Matcher regexMatcher = regex.matcher(dateiInhalt.toString());
MyString justSeconds = new MyString(regexMatcher.group(0));

Sry for this probably really retarded question, but I am tired af and need to get this done :(

Thanks a lot!

How to fire actions simultaneously from multiple components with Alt (Flux)

I am using Alt library for Flux architecture implementation. I have a component, which displays information about movie. Now I am stuck in a situation where I need to render array of such components under my home page. The problem is that each of these components calls ajax request inside componentDidMount. So when I have more then one - I get:

Uncaught Error: Invariant Violation: Dispatch.dispatch(...): Cannot dispatch in the middle of a dispatch.

I wrote a longer post here. I'm sorry for the urgency, but I need this done in couple of days, and I simply cannot understand the nature of the problem.