lundi 31 juillet 2017

Share Common Variables in Multi-Instance moved from Singleton in Java

I am refactoring my code by moving from signleton to multi-instance due to some requirement. There are certain part of my objects they all share the same common properties. After the object creation, each object also has its own instance variables.

For example, my singleton way

MyLibrary.getinstance().init(a,b,c,d);

my multi-instance way

MyLibrary library1 = new MyLibrary(a,b,c,d);
MyLibrary library2 = new MyLibrary(a,b,c,d);

My question is that some of the parameter passed in to the constructor is repetitive, for example, a,b. In the old singleton way they are used to init the library, and do not get used afterward. In other words, all MyLibrary objects share a,b and only need one time init.

Can you please share some insights of how to define the common variables across all objects of MyLibrary?

How to use list serializer in django to serialize according to inherited serializer?

Lets assume there are three models Animal, Cat, Dog where Cat and Dog are inheriting from parent class Animal.

class Animal:
   name
class Cat:
   sleep_hours
class Dog:
   breed

Considering that sleep_hours and breed are mutually exclusive property of cat and dog respectively. Now we have serializers :- enter codAnimalSerializer: name CatSerializer(AnimalSerializer): sleep_hours DogSerializer(AnimalSerializer): breede here

Now we want to develop an API where we return all the information about animal so it should return something like this 
[
{'tommy', 'pug'},
{'kitty', '10'},
]
So consider animal class is linked to user i.e. user.animals returns a list of animals (parent class) we want to use modelSerialiser on user.
class UserAnimalSerializer(serializers.ModelSerializer):
    animals = AnimalSerializer(read_only=True)

 class Meta:
        model = User
        fields = ('animals')

Now we want to use different serializer(child serializer) based on the instance type. Is there any good way to handle these type of scenarios. Please comment if there is some confusion about the question.

Does Canvas class in android follow any Design Pattern? Or its violating OCP?

I am studying about design pattern and gone through the code of Canvas.java in android sdk. First of all it contains thousand of lines of code, is it right of having this much of line in a class? And my second point is it has some methods like drawCircle(), drawRectangle() etc in same class. So is this pattern is right to do so.

As I am beginner to designing code and architecture, it will very helpful if someone put some light on this.

Hope my question is relevant on this portal.

Generic way to call Network Requests for API Client

I have provided the code for my firebase API client.

Is it smart to use generics, to initialize any entity straight from json this way?

To download lists, I needed an indicator to let me know that I'm requesting a list of entities, so I added a GETALL to my HTTPMethod enum, is this bad, and something that would be confusing to others?

I also feel like this isn't flexible because I can't get entities on a node that may be a different nested levels. Hopefully that makes sense. So this probably doesn't follow open/closed principle since I have nest my entities in firebase differently ill have to change implementation inside FirebaseAPI.

From open source code i've seen, I haven't quite seen a api client designed like this and not sure if I'm using an anti pattern or something. Any help or guidance to make this maintainable.

class FirebaseAPI {

    private let session: URLSession

    init() {

        self.session = URLSession.shared
    }

    /// Responsible for Making actual API requests & Handling response
    /// Returns an observable object that conforms to JSONable protocol.
    /// Entities that confrom to JSONable just means they can be initialized with json.
    func rx_fireRequest<Entity: JSONable>(_ endpoint: Endpoint) -> Observable<[Entity]> {

        return Observable.create { [weak self] observer in

            self?.session.dataTask(with: endpoint.request, completionHandler: { (data, response, error) in

                /// Parse response from request.
                let parsedResponse = Parser.init(data: data, response: response, error: error)

                    .parse()


                switch parsedResponse {


                case .error(let error):

                    observer.onError(error)

                    return




                case .success(let data):

                    var entities = [Entity]()

                    /// Consider edge case where a list of entities are retrieved, rather than a single entity.
                    /// Iterate through each entity and initialize.
                    /// Denoted by 'GETALL' method.
                    switch endpoint.method {

                    case .GETALL:


                        /// Key (underscored) is unique identifier for each entity, which is not needed here.
                        /// value is k/v pairs of entity attributes.
                        for (_, value) in data {

                            if let value = value as? [String: AnyObject], let entity = Entity(json: value) {

                                entities.append(entity)

                            } else {

                                observer.onError(NetworkError.initializationFailure)

                                return
                            }

                            observer.onNext(entities)

                            observer.onCompleted()

                            return
                        }



                    default:

                        if let entity = Entity(json: data) {

                        observer.onNext([entity])

                        observer.onCompleted()

                    } else {

                        observer.onError(NetworkError.initializationFailure)

                        }

                    }
                }
            })

            return Disposables.create()
        }


    }
}

Makefile, pattern rule with sub directory only work with the first dependence

here is my problem

SOURCES_FUNCTIONS=cJSON.c parallelisationUtilities.c
$(BUILD_DIR)/%.o : $(SOURCE_DIR)/%.c    
    $(CC) $(CFLAGS) -c $< -o $@ $(IFLAGS)

make: *** Aucune règle pour fabriquer la cible « parallelisationUtilities.o », nécessaire pour « build/mainFunction ». Arrêt

By placing parallelisationUtilities.c before cJSON.c in SOURCES_FUNCTIONS, i get the same error with cJSON.o. Fore sure, there are no missing files..

++ Michael

Use repository pattern in a mid-size Laravel app?

I have a mid-size project in Laravel which will act as an API service. I was inspired by an article 2 years ago to use the repository pattern with Eloquent. Specifically, move all queries to dedicated repositories, wrap model attributes with getters/setters, defined model constants, no use of magic query scopes, etc. Then I found criticism of this approach, saying that it's unnecessary with Active Record and even an overkill for most projects. J. Way himself warns about the visual debt.

I do understand that a large project would benefit from a Data Mapper like Doctrine, and a small one using plain Eloquent would be just fine. But what about a medium size project? Few things off the top of my head:

  • TDD with focus on feature tests; unit tests for some classes
  • Simple (->where(...)->get()) and complex queries (like multiple joins)
  • Models are more than just POPOs (fillable, casts, getRouteKeyName, etc.)
  • Pretty certain the app won't move to a different DB engine like Mongo

Considering these, should my controllers do

$products = $this->repository->paginate(100); // vs..

$products = Product::paginate(100); // worthwhile?

And if I use both depending on the complexity of the query, would I suffer from inconsistencies down the road? I don't see a point in rewriting find or get with findBy and getWith. I'm also skeptical about the getter/setter boilerplate in each model, as well the purpose of repository interfaces if I will only ever use Eloquent. At the same time, I am very aware how fat controllers can get as the codebase grows, and how ugly models can become with methods like getProductNamesByKeys.

Can't seem to find a golden mean between the two worlds.

Code Best Practices tutorials

is there is any online training course to learn Design patterns(using PHP),code best practices,Database Design,SQL optimization, and other related topics ?

Reset Component react-history pattern

I'm trying to use to the react-history and especially the <Push /> Component to push a new entry in the history when I click on one of my menu items.

But maybe I want to do it too much in the declarative react way. When I see this in react-history docs, I don't really get it:

render() {
   const { to, ...props } = this.props;

   // If the <Link> was clicked, update the URL!
   if (this.state.wasClicked)
     return <Push path={to} />

   return (
     <Item {...props} onClick={() => this.setState({ wasClicked: true })} />
   )
}

They say in their docs that's not a good way, I understand that. The Push component gets rendered and the previous menu item disappears.

This may be ridiculous, but I'm guessing what is the proper pattern to use a Component like this, dependent on a user action? Splitting the behaviour in another component?

dimanche 30 juillet 2017

Bidirectional association, what's better?

Not really a problem, but I wondered many times about how to implement double association in code...

Let's have an example. A man car wear a single hat and a hat can be on a single man. But if the man wears the hat, the hat's owner have to be that man.

Here is how I used to do it (Java) :

In Character :

public void setHat (Hat hat) {
    Hat former = this.hat;
    this.hat = hat;
    if (former != null && former.getOwner() == this)
        former.setOwner(null);
    if (hat != null && hat.getOwner() != this)
        hat.setOwner (this);
}

And in Hat :

public void setOwner (Character c) {
    Character former = this.owner;
    this.owner = c;
    if (former != null && former.getHat() == this)
        former.setHat(null);
    if (c != null && c.getHat() != this)
        c.setHat (this);
}

This way, the man's hat and the hat's owner are always coordinated.

But... that sounds a bit clumsy to me. What's the better way to implement this kind of conditional setter, please ? It's very useful to me.

(if I made mistakes, that's just because baguette ok? ^^)

Is this a correct implementation of the Strategy pattern?

Below is the implementation in PHP. I aim to have a different coupon code and a different discount returned, based on the type of book (vintage or new).

<?php

interface BookOffer {
    function generateCoupon();
    function generateDiscount();
}


class VintageBookOffer implements BookOffer {
    function generateCoupon() {
        return "VINTAGECOUPONCODE";
    }

    function generateDiscount() {
        return 10.0;
    }
}


class NewBookOffer implements BookOffer {
    function generateCoupon() {
        return "NEWBOOKCOUPONCODE";
    }

    function generateDiscount() {
        return 5.0;
    }
}


class OfferGenerator {

    function generateOffer($bookType) {

        if($bookType == "vintage") {
            $bookObject = new VintageBookOffer();
        }
        else if($bookType == "newbook") {
            $bookObject = new NewBookOffer();
        }

        return $bookObject;
    }
}


$bookType1 = "vintage";
$bookType2 = "newbook";


$offerGenerator = new OfferGenerator();
$bookOffer1 = $offerGenerator->generateOffer($bookType1);
$bookOffer2 = $offerGenerator->generateOffer($bookType2);


echo "You chose book type " . $bookType1 . ". Your coupon code is " . $bookOffer1->generateDiscount() . ", and your discount is " . $bookOffer1->generateCoupon();

echo "You chose book type " . $bookType2 . ". Your coupon code is " . $bookOffer2->generateDiscount() . ", and your discount is " . $bookOffer2->generateCoupon();

?>

Does this look correct? I believe it is. But any feedback from the community would be welcome. The only reason I think it might be incorrect is because it does not use type hinting, which is frequently seen in the Strategy Pattern.

Code design: objects depending on one another and short-lived composite objects

I am working on a piece of software and am trying to solve a particular problem in an elegant way. I was hoping to get a bit of input to improve my code.

I am trying to calculate a report. The report contains a number of fields. Some of the fields depend on other fields. E.g., one might be the sum of other fields.

Each field has its own algorithm and is defined by a class deriving from a base class ReportFieldBase. The fields are displayed in a hierarchy (composite pattern).

The problem is that some of the fields require the results of certain simulations. A field might require multiple simulations, and each simulation might be used by multiple fields. The simulations are so large that they cannot all be kept in memory simultaneously. Furthermore, each simulation should only be performed once for performance reasons. A simulation is defined by a set of parameters (SimulationParameters).

How can I solve this problem elegantly? The current state of my code looks similar to this:

MustInherit Class ReportFieldCachedBase
Inherits ReportFieldBase
Sub CalculateAndCacheValue()
...
End Class

Interface ISimulationField
Readonly Property SetsOfSimulationParameters() As IEnumerable(Of SimulationParameters)
ReadOnly Property DependsOnSimulationFields() As IEnumerable(Of ISimulationField)
Property SimulationHolder() As IEnumerable(Of Simulation)
Sub CalculateAndCacheValue()
End Interface

The fields that need simulations would now inherit from ReportFieldCachedBase and implement ISimulationField, and define the SetsOfSimulationParameters() for the simulations that they need at runtime. Before filling the report, all ISimulationFields will be calculated and cached:

Sub CacheSimulationFields()
' Algorithm to perform the simulations and cache the corresponding values iteratively. Due to the interdependence, in each iteration a number of
' simulations will be performed and all fields will be calculated that use any of these simulations.
...
' For each iteration:
' - Determine all fields and all simulations that are to be calculated in this iteration.
' - Fill the SimulationHolder() for each of the fields.
' - Call CalculateAndCacheValue() for each of the fields
End Sub

The design feels weird. E.g., any of the ISimulationFields can only be called after the SimulationHolder() has been filled from the outside. This is very error-prone. But I have no idea for a better design. Any suggestions?

Identifying the failed item from a list in bulk transactions

Am trying to batch a list of items into single transaction like below

Lists.partition(new ArrayList()<>(customer),100).parallelStream().forEach(customers->{
                    UserTransaction userTransaction = new UserTransactionImp();
                    try {
                        userTransaction.begin();
                        for(String cus : customers){
                            //code to write to db 
                        }
                        userTransaction.commit();
                    } catch (Exception exception) {

                        //collect the failed list and re partition them into smaller lists say 50
                    }

But i dont want to fail all the 100 just because few faulty accounts.I am thinking to collect the failed items into one more list and partition further into small list .I can do this normally by invoking parallel stream again.But i wanted to know if there is any design pattern to solve this

Dependency injection and model controllers knowing about each other

When using "Model" Controllers and passing them between VCs using dependency injection, how to handle the fact that some controllers need to know an information from another controller?

Here's a concrete example, with a fictive app having 3 model controllers:

  • ContentStore: loads and holds the content of the app, specific for the user logged in.
  • UserManager: contains a User object, and logs user in/out, updates info for the logged in user, etc.
  • NetworkController: the only controller to know about web service.

ContentStore and UserManager will hold a reference to the Network Controller, to call the web services without knowing their implementations (to respect the Separation of concerns and Single Responsibility principles). The AppDelegate creates the NetworkController and then passes its reference to ContentStore and UserManager:

AppDelegate - didFinishLaunchingWithOptions:

let networkController = NetworkController()
let contentStore = ContentStore(networkController: networkController)
let userManager = UserManager(networkController: networkController)

// Inject contentStore and userManager into the first VC

But let's say the ContentStore wants to load the app content tailored for a specific User logged in. It needs to know its User ID. And NetworkController will need to know the User Id as well, to pass in the web calls.

What would be a clean way to achieve this, sharing information between controllers? From the different ways I could come up with, the only one that doesn't seem too bad is:

All ContentStore and NetworkController methods have a userId parameters, and they never call these methods themselves, they are always called by a VC. That VC can then pass the user ID, since it knows about both UserManager and ContentStore.

Is there a cleanest way than this suggestion?

I need php pattern to preg_much

I need help a pattern to preg_much the value and keys and assign a value to its key in fast way i try some way but its lazy I want to get these values and keys code

line.one = {
    "l1": 732,"l2": 708,"l3": 780,"l4": 586,"l5": 451   };
line.two = {
    "l1": 2506.61,"l2": 2225.6916,"l3": 2974.5775,"l4": 3063.9443   };
line.three = {
    "l1": 530,"l2": 900,"l3": 258,"l4": 214 };


**example what i want**



array(  
        [1] => Array
        (
        [11]=>732,
        [12]=>708,
        [13]=>780,
        [14]=>586,
        [15]=>451
        )
            [2] => Array
        (
            [11] => 2506
            [12] => 2225
            [13] => 2974
            [14] => 3063

        )

    [3] => Array
        (
             [11] => 530
            [12] => 900
            [13] => 258
            [14] => 214
        )

samedi 29 juillet 2017

SOLID design principles on MEAN application

me and my team (good programmers but bad in architecting) have started working on a MEAN application with following ER diagram. http://ift.tt/2v7VM0U

We have written REST apis for following use-cases so far. We see our whole code violates all of the SOLID principles, we have written Mongoose models and router classes without any principles or patterns

1. user registration
2. user fills the initial info (used for screening the prospect, once screening is done this info is never used) via a link send in email. (user is not allowed to login yet)
3. user pays the registration fee via link from email(sent when planner changes the stage of the user), now user is allowed to login.
4. other use cases like forgot password etc.
5. Upon login user fills bunch of forms like Profile(Profile, Spouse, Dependents), assets(not modelled yet), liabilities (not modelled yet) etc
6. Similarly Chief Planner or Super admin have login use, Invite team member use case, change prospect to client use case.

We want to model this with a good principles, we followed Robert C Martin's - Clean Architecture and Design from https://www.youtube.com/watch?v=Nsjsiz2A9mg, we are still confused, can you help us model this with SOLID/Domain Driven.

Finding escape character in files (PowerShell)

I'm trying to find the carriage return (\r) and new line (\n) in files but the following two statements return nothing:

Get-ChildItem -recurse | Select-String -pattern "\r" | group path | select name
Get-ChildItem -recurse | Select-String -pattern "\n" | group path | select name

However, the tab (\t) escape character seems to work:

Get-ChildItem -recurse | Select-String -pattern "\t" | group path | select name

How to force inheriting class's method implementation to call base method before invoke own implantation?

I wrote some not sealed class that contain 3 virtual public method and one private method.

And i make this class public that all my develop group member could use this class ( include inherits and override the virtual public methods ) .

One of the private method name is 'PrivateMethod77()'.

Each time the public method 'PublicMethod77()' is call => the 'PrivateMethod77' is call in the first line of the method implementation ( after this line there are more implication logic ).

I want to keep this logic and 'force' the inherits and override of the method PublicMethod77 to call the PrivateMethod77 method as the first line of the PublicMethod77

Is there a way to do it ?

Should I use abstract class or Util class?

I had a scenario like below

interace A {

}

class B implements A {
}

Now during making changes, I realized that I have to extract out a repeating piece of code into a method.

say there is a method like below in class B:

private void domSomething() {
 //sequence of steps
}

Now, the issue is that in future we expect other implementations of interface A to use method doSomething().

So the dilemma here is should method doSomething() be moved to a util class or we should create an abstract class with a protected doSomething() method. Something like below.

abstract class C implements A {
 protected void doSomething();
}

class B extends C {

}

Or create a Utils class and let B to still implement A.

Generally, I like to refrain from using abstract and look for ways to avoid them. So that leads to some questions here:
1. Is that right way to think about abstract classes?
2. Which approach should be more preferred here and why?
3. Any other suggestion behind the thought process is always welcomed.

Thank for your time.

vendredi 28 juillet 2017

Substring query, count no. of length L occuring P times

You are given a string S and N queries. Each query is defined by two integers - Li and Pi. Count the number of strings of the length Li that occur exactly Pi times (as the consecutive substrings) in the string S.

Example 1

Input

abacaba

1

3 2

Output

aba

Explanation We need substrings of length 3 occurring twice in S. Clearly, aba is the only such substring

Example 2

Input

mynameispujanshahandmybrothersnameischintanshah

1

4 2

Output

name

amei

meis

ansh

nsha

shah

Explanation We need substrings of length 4 occurring twice.

Here is the code to count the number of the substrings, but what I want is to print out the substrings itself.

How do I print the substrings itself?

     int main(){

     string s;

     int q,l,p;

     cin>>s;

     cin>>q;

     while(q--){

     cin>>l>>p;

     int cnt =0;

     string ss,ss1;

     for(int i=0;i<=s.size()-l;i++){

     ss=s.substr(i,l);

     int tot = 0;

    for(int j=0;j<=s.size()-l;j++){

    ss1 = s.substr(j,l);

    if(ss==ss1){

    if(j<i)

    break;

    else

     tot++;
  }

}

if(tot==p)

    cnt++;

     }

       printf("%d\n",cnt);

         }

         return 0;

    }

ways to avoid creating N classes in Factory

I need to know how to avoid creating N classes in factory. For example, one way I know is to return the clone of the object without creating it. Thanks.

Best way to make the user select a time?

Hi I'm wondering what is the best way to make the user select a time, I already have the user select a date with a calendar but then needs the user to select a time to be able to create a date based notification. What is the easiest way for the user to select time? Should I show another VC when the user selects a date to show a clock or show a date picker with time showing? Are there any other ways?

Reducing if else branches and cleaning code using chain of functions, does it make sense

I am working on legacy code that has lots of if/else. I can use conditional decomposition and/or guard statements etc. to clean it. Another approach which can be used is to create functions out of branches and execute these functions as chain and exit with first response. I am wondering if using function chain is an overkill? Any views?

My chain looks something like below. This is a simplified example.

public class RequestStateHandler {
    private final List<Function<RequestStateInfo, Optional<Response>>> handlers = new ArrayList<>();

    public RequestStateHandler() {
        handlers.add(requestStateInfo -> xStateValidator(requestStateInfo));
        handlers.add(requestStateInfo -> yStateValidator(requestStateInfo));
        handlers.add(requestStateInfo -> zStateValidator(requestStateInfo));
    }

    public Response getResponse(RequestStateInfo requestStateInfo) {
        try {
            for (final Function<RequestStateInfo, Optional<Response>> handler : handlers) {
                final Optional<Response> response = handler.apply(requestStateInfo);

                if (response.isPresent()) {
                    return response.get();
                }
            }
        } catch (Exception e) {
            LOGGER.error("Some log", e);
        }

        return getDefaultResponse(requestStateInfo);
    }

    private Optional<Response> xStateValidator(RequestStateInfo requestStateInfo) {
        final A a = requestStateInfo.getA();
        if (a.isABC()) {
            return Optional.of(requestStateInfo.getX());
        }

        return Optional.empty();
    }

    private Optional<Response> yStateValidator(RequestStateInfo requestStateInfo) {
        if (requestStateInfo.isXYZ()) {
            final Response response = requestStateInfo.getX();
            final A a = response.getA();
            if (a.isSomeOtherTest()) {
                return Optional.of(response);
            }
        }

        return Optional.empty();
    }

    private Optional<Response> zStateValidator(RequestStateInfo requestStateInfo) {
        final Response response = requestStateInfo.getX();
        final A a = response.getA();
        if (a.isSomeAnotherTest()) {
            return Optional.of(response);
        }

        return Optional.of(getDefaultResponse(requestStateInfo));
    }

    private Response getDefaultResponse(RequestStateInfo requestStateInfo) {
        return new Response(A.create(requestStateInfo.getY()), null, null, null);
    }
}

I thought of creating a reusable executor so that we can have only business logic here. To me it looks much cleaner but it obviously add a dependency to execute the functions in order. Something like chain of responsibility, I would say. What are your thoughts?

A generic executor could be something like:

import org.apache.commons.lang3.Validate;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;

import java.util.ArrayList;
import java.util.List;
import java.util.Optional;
import java.util.function.Consumer;
import java.util.function.Function;
import java.util.function.Supplier;

public class ChainedExecutor<T, R> {
    private final static Logger LOGGER = LoggerFactory.getLogger(ChainedExecutor.class);
    public final List<Function<T,Optional<R>>> handlers;
    private R defaultResponse;

    private ChainedExecutor() {
        this.handlers = new ArrayList<>();
    }

    public R execute(T request) {
        return execute(request, Optional.empty(), Optional.empty());
    }

    public R execute(T request, Function<T, R> defaultSupplier) {
        return execute(request, Optional.of(defaultSupplier), Optional.empty());
    }

    public R execute(T request, Consumer<Exception> exceptionHandler) {
        return execute(request, Optional.empty() ,Optional.of(exceptionHandler));
    }

    public R execute(T request, Function<T, R> defaultHandler, Consumer<Exception> exceptionHandler) {
        return execute(request, Optional.of(defaultHandler), Optional.of(exceptionHandler));
    }

    public R execute(T request, Supplier<R> defaultSupplier) {
        final Function<T, R> defaultHandler = (input) -> defaultSupplier.get();
        return execute(request, Optional.of(defaultHandler), Optional.empty());
    }

    private R execute(T request, Optional<Function<T, R>> defaultHandler, Optional<Consumer<Exception>> exceptionHandler) {
        Optional<R> response;
        try {
            for (final Function<T,Optional<R>> handler: handlers) {
                response = handler.apply(request);

                if (response.isPresent()) {
                    return response.get();
                }
            }
        }
        catch (Exception exception) {
            handleOrLog(exceptionHandler, exception);
        }

        return getDefaultResponse(defaultHandler, request);
    }

    private void handleOrLog(Optional<Consumer<Exception>> exceptionHandler, Exception exception) {
        if (exceptionHandler.isPresent()) {
            exceptionHandler.get().accept(exception);
            return;
        }
        LOGGER.error("Unhandled exception occurred while executing handler chain. This most probably is a developer error.");
    }

    private R getDefaultResponse(Optional<Function<T, R>> defaultHandler, T request) {
        if (defaultHandler.isPresent()) {
            return defaultHandler.get().apply(request);
        }
        return getDefaultResponse();
    }

    public R getDefaultResponse() {
        return defaultResponse;
    }

    public static class Builder<T, R> {
        private final ChainedExecutor<T, R> chainedExecutor = new ChainedExecutor<>();

        public Builder(List<Function<T,Optional<R>>> handlers) {
            Validate.notNull(handlers);
            for (final Function<T, Optional<R>> handler: handlers) {
                Validate.notNull(handler);
                handlers.add(handler);
            }
        }

        public Builder() {}

        public ChainedExecutor.Builder<T, R> withHandler(Function<T, Optional<R>> handler) {
            Validate.notNull(handler);
            chainedExecutor.handlers.add(handler);
            return this;
        }

        public ChainedExecutor.Builder<T, R> withDefaultResponse(R defaultResponse) {
            Validate.notNull(defaultResponse);
            chainedExecutor.defaultResponse = defaultResponse;
            return this;
        }

        public ChainedExecutor<T, R> build() {
            Validate.isTrue(!chainedExecutor.handlers.isEmpty());
            return chainedExecutor;
        }
    }
}

Divide module into submodules in VIPER

Have read "Book of VIPER" by "Rambler&Co". There is a suggestion to use one module for one scene and that the modules can be custom and simple. For the custom (compound) modules they suggest divide them into sub-modules. For example, according to how many sections scene has. And they do also offer 5 approaches for the different cases:

  • Container
  • Scroll View Controller with a title, contact, attachment, body submodules etc.
  • Table with a section submodules
  • Table with a cell-submodules
  • View-submodules

Seems clear in theory but what's about realization? How does it should look like? Let's say if i do have a table(module) with 2 sections and would like to divide each section into submodule? How does it look in code? Should i use additional folders (don`t think so) for each submodule or is it just on the level of code? Would appreciate the examples.

State pattern for FSM

I want to create FSM, which have 4 states, like this: http://ift.tt/2w6jYNZ

I think to use State pattern, but I can't figure out how to set all this transferring. Maybe I should use another one? How I made it for now:

public class Driver {
public static void main(String[] args) {

    Context context = new Context();
    State AAAllocked = new StateAAAllLocked();
    State ADAllocked = new StateADAllLocked();
    State ADAllUnlocked = new StateADAllUnlocked();
    State ADDriverUnlocked = new StateADDriverUnlocked();

    context.setState(ADAllUnlocked);

    context.doAction();

}

I have these 4 states and can choose which action do. But how make it like on the picture?

std::streambuf and boost::asio::basic_streambuf

I am implementing an interface's method that receives a std::streambuf as argument using the boost::asio library and downcasting that std::streambuf to boost::asio::streambuf.

The objetive is implement a TCP/IP communication API abstrating the boost library, so enabling the possibility of changing it in the future, re-implementing the interface.

Below is the code:

class Interface {
  [...]
  virtual size_t readUntil(std::streambuf &streamBuffer,
            const std::string &until) = 0;
  [...]
}

class BoostImplementation : public Interface {
  virtual size_t readUntil(std::streambuf &streamBuffer,
            const std::string &until) {
    [...]
    size_t numBytes = boost::asio::read_until(
      *m_socket,
      dynamic_cast<boost::asio::streambuf&>(streamBuffer),
      until);
    [...]
  }
}

Is the above dynamic_cast<boost::asio::streambuf&>(streamBuffer) an anti-pattern? Is there any other way to do what I want?

Spring boot and rabbitmq integration, how to recover on component failure?

I have a spring rest app with rabbit as messaging middle ware. When the app accepts incoming rest request, it replies to the user meanwhile it does some extra processing asynchronously, generates a new message and puts it on rabbit. From there, some consumers read the message and deliver it to the external system. Now, there is a case that the rabbit server itself may be down. To handle that kind of failure, I have a blocking queue (of course with an adjustable size)

 @Bean
public TaskExecutor taskExecutor() {
    ThreadPoolTaskExecutor executor = new ThreadPoolTaskExecutor();
    executor.setCorePoolSize(5);
    executor.setMaxPoolSize(10);
    executor.setQueueCapacity(25);

    return executor;
}

The queue will be able to handle some messages until rabbit comes online. But if it takes too long and the requests exceeds the queue size, then it is going to fail. Now the question is, are there a ways that I can improve this and make it more efficient? What is the industry best practice? Are there any patterns for that scenario?

Best Practise for every each action on the business service depends on the type of given role

I have a lot of Business Services(BS)s that read data from the database or add data to the database.

 public class BranchBS : BaseBS<BranchDT, Branch>, IBranchBS 
    {
        public BranchBS(ICXFServerConnection iCXFServerConnection, UserDT userDt = null)
            : base(iCXFServerConnection)
        {
            Visitor = userDt;
        }

        private UserDT Visitor;

        //Getting Branches by LibraryId
        public IEnumerable<BranchDT> GetByLibraryIds(List<int> libraryIds)
        {
            IBranchLibraryBS iBranchLibraryBs = new BranchLibraryBS(ContextFactory);
            List<BranchLibraryDT> lstBranchLibraryDt = (List<BranchLibraryDT>)iBranchLibraryBs.GetByIds(libraryIds, "Library.Id");
            List<BranchDT> lstBranchDt = (List<BranchDT>)GetByIds(lstBranchLibraryDt.Select(x => x.Branch));
            return lstBranchDt;
        }

        //Getting Branches by company Id
        public IEnumerable<BranchDT> GetByCompanyid(int companyId)
        {
            var lstBranch = (from b in ContextFactory.Retrieve().Branches
                             join c in ContextFactory.Retrieve().Companies on b.Branch_CompanyId equals c.Id
                             where c.Id == companyId && c.CompanyStatus == true && b.BranchStatus == true
                             select b).ToList();
            var lstBranchDt = DataTransformation.DataTransformation.ConvertSourceObjToDestinationObj<Branch, BranchDT>(lstBranch);
            return lstBranchDt;
        }
}

Every action of the BusinessService depends on Visitor field. for example, I show it on GetAll() function.

public GetAll( )
{
if (Visitor.Type==IsCompanytype)
{
     return "select..."
} 
if (Visitor.Type==IsBranchtype)
{
     return "select..."
}     
if (Visitor.Type==IsSupertype)
{
   return "select..."
}           
}

And I have approximately 20 Business Service classes and every class has approximately 5 functions. And Visitor can be in different 3 type. What is the best practice structure for this purpose?

Thanks in advance.

How can I design User Preferences module in my Swing application?

I have dialog for storing user preferences of the application which is developed using Java Swing. There are 20+ preferences and I would like to notify other modules when the particular preference changes. I know that I can hold a list of listeners and notify them whenever the preferences change. However, I would like to know about two issues:

  • How can I bind my Swing components to a bean object,
  • How can I fire an event when the preferences change,

Dependending your experience, how would you resolve that architecture? What are the best practices to follow?

Thanks

Designing Python client for multiple different REST APIs

We are about to develop a Python wrapper for a REST API in our platform. Right now, the platform has 12 different APIs, which are unrelated in a function, they don't necessarily share the same base url, and have different authentication methods. However they are related in a sense, that they are part of the platform. At this moment we are developing the client for a single API (out of the list of twelve), but it's very likely that the remaining apis will have their Python wrapper in the future.

To avoid headeaches down the road, we've been discussing the structure of the package and can't 100% agree on the structure

One point of view is creating (ultimately) 12 different packages, one for each api. That is (names are non-pythonic for the sake of clarity)

$ pip install platform_apiclient_foo 
$ pip install platform_apiclient_bar
$ pip install platform_apiclient_spam
...

and in a code use it like:

from platform_apiclient_foo import ClientFoo
from platform_apiclient_bar import Bar

The argument for this is that the do not have a common function and thus should be separated.

The second point of view is creating one package encompassing all current and possible future apis, which would require to install single package

$ pip install platform_apiclient

For each API, there would be a separate module, leading to this usage

from platform_apiclient.spam import SpamClient
from platform_apiclient.foo import FooClient


I am definitely fan of the second approach as it seems to be easier to maintain (from the devs perspective), easier to use (from the user's perspective) and might benefit from at least some code reuse. An argument against the second approach might be how to take into account different versions of the REST APIs (altough this might be solvable by an argument when instantiating the client class).

Which of the two desgins seems more appropriate? Are there any other ways to solve this? Am I missing something some arguments pro/against any of the two?

jeudi 27 juillet 2017

c#: how to implement singleton pattern to return client that should be initialised just once in application life cycle?

Currently, we are initialising elastic search client. We want to initialise ElasticClient just once in our application and re-use it to avoid unnecessary initialisation every time we make elastic search call.

The code looks like:

public sealed class ElasticClientInstance
{
    private static readonly ElasticClientInstance _clientInstance = new ElasticClientInstance();

    private ElasticClient _client;

    static ElasticClientInstance () {

    }

    public static ElasticClient GetInstance() {
        return _clientInstance._client;
    }

    private ElasticClientInstance()
    {
        try
        {
             Uri[] nodes = ConfigurationManager.AppSettings["ElasticHostUrl"].Split(';')
                            .Select(s => new Uri("http://" + s)).ToArray();
            var connectionPool = new SniffingConnectionPool(nodes);
            var settings = new ConnectionSettings(...); //some code not mentioned here
            _client = new ElasticClient(settings);
        }
        catch (Exception ex) 
        {
            //do necessary handling
        }

    }
}

Anytime we need elastic client, we do ElasticClient.GetInstance(). Is it the correct way to make this client singleton?

I read that initialising "_clientInstance" as readonly makes it thread safe? Is this performance oriented and safe implementation of singleton pattern?

How to access request from ui to database

If DataBase only accept 20 requests at the same time, but in UI, We have 100 requests at the same time. How to resolve this in java?

java type inference in builder pattern

i want to create a parameterized (generic) class MyType<T> and its builder. builder will have some methods that ignore the type T and some methods that use the type. but it seems like using this pattern i have to repeat the T declaration:

                     how to omit this declaration?
                                   |
                                   V
MyType<String> myType = Builder.<String>of()
                               .method1(argument_can_be_of_any_type)
                               .method2(argument_must_be_of_type_T)
                               .build();

is it possible to use some java syntax tricks or other design patterns to omit the second type declaration and make the API more user friendly? like for example:

List<String> aList = Lists.emptyList();

or

List<String> aList = new LinkedList<>();   

i don't want to enforce any order of methods in the builder

What is the best way to implement the adaptor pattern in c++

I have seen that it is possible to use inheritance, such as:

class A {
};

class Legacy{
};

class B : public A, private Legacy {
};

But it is weird to me to inherit public and private from two different classes.

Dynamically instantiating classes using the Decorator pattern in PHP

Typically, when working with the decorator pattern, I usually instantiate the classes directly, one within the other:

abstract class Handler
{
    public function __construct(Handler $handler = null)
    {
        $this->handler = $handler;
    }

    abstract public function handle();
}

class FirstHandler extends Handler
{
    public function handle()
    {
        // Just calls the next guy in the chain. Obviously, this isn't doing anything, it's just for example sake.
        $this->handler->handle();
    }
}

// ... and so on with the SecondHandler, ThirdHandler, FourthHandler

$chain = new FirstHandler(
    new SecondHandler(
        new ThirdHandler(
            new FourthHandler()
        )
    )
);

$chain->handle();

However, with the possibility of the chain growing to say, perhaps, 20 handlers, you can see that the code would begin to indent far too much and makes it difficult to read, especially if different handlers in the chain don't have names as simple as "FirstHandler", "SecondHandler", but overall, it just doesn't look good.

I am wondering if there is a way to dynamically instantiate the classes by placing them in an array, and iterating down the array and passing the n+1 element in the array as the constructor argument to the nth element in the array.

I had something kind of like this in mind:

$chain = null;

$links = [
    FirstHandler::class,
    SecondHandler::class,
    ThirdHandler::class,
    FourthHandler::class
];

foreach ($links as $index => $link) {
    $chain = new $link(new $links[$index + 1]());
}

You might be able to tell that the first problem is that $chain gets overridden on each call. The second problem is that even with the loop, I still have to pass each handler into the chain manually, and all that is really doing is creating the chain the original way four times, which is actually worse. And the third problem is that eventually I will get an out of bounds exception.

Is there a way to instantiate this chain dynamically as demonstrated in my intention (perhaps a recursive call of sorts) or am I doomed to do it the way I was doing it before?

Why one of the cases is always unreachable?

Why the output of the following code is always suck. How to get happy as the output? Why the happy branch is unreachable?

public class HowToMakeStackoverflowBetter {

    private static final int HUMAN_PATIENCE = 10;
    private List<Member> members = new ArrayList<>();
    private int atmosphere = -10;
    private Random r = new Random();
    public HowToMakeStackoverflowBetter(int size) {
        for (int i = 0; i < size; i++) { members.add(new Member()); }
    }
    public Member pick() { return members.get(r.nextInt(members.size())); }

    public class Member {
        private int patience = HUMAN_PATIENCE;
        private Question question = null;
        public Member() { patience = r.nextInt(patience+1) + atmosphere; }
        public void vote(Question q) {
            if (patience >= 0) {
                voteUp(q);
            } else {
                voteDown(q);
            }
        }
        public void ask() {
            question = new Question();
            for (Member member : members) {
                member.vote(question);
            }
        }
        private void voteUp(Question q) { ++q.vote; }
        private void voteDown(Question q) { --q.vote; }
        public String toString() {
            return (question.vote >= 0)? "Happy!" : "Suck!";
        }
    }

    public class Question { private int vote; }

    public static void main(String[] args) {
        HowToMakeStackoverflowBetter stackoverflow = new HowToMakeStackoverflowBetter(100);
        Member me = stackoverflow.pick();
        me.ask();
        System.out.println(me);
    }
}

After a 1000 times loop, it gives us 1000 sucks. I remember 2 or 3 years ago, this was not the case. Something changed?

If you can only change one line in the above code, how to get happy :)?

Need tips about creating frameworks for coded ui for windows application

I've never created/designed a framework from scratch and I've been looking online for some guidance on creating coded ui framework for windows application. I've seen some frameworks for testing Web applications and have used one such as code first. I've been looking at some videos dealing with UML design and such and don't really know where to begin when doing design work such as creating my first framework/or designing a system.

I was wondering if anyone had any tips when it comes to designing a framework(do you start with a class UML diagram, or do you write what you want to accomplish first? etc...). I eventually want to get comfortable with with creating a framework and being able to repeat this with any project i'm given.

I know this topic can be mistaken to be broad, but my assumption is people that design frameworks/any other applications have a set of repeatable task that they perform when designing a great framework/system, whether that is for coded ui test or some new application that their working on. Any tips or guidance on where for me to start would be greatly appreciated. thanks

.

How to reuse GUI objects (Flyweight pattern)

In my Java app i'm having a complex GUI which has certain JPanel (custom control) repeated, lets say, 100 times (in reality it could be more, but i don't wanna make this example too complex). Each of those 100 JPanels contains 4 JTextBox controls that show certain values to the users.

JTextBoxes of one panel may be empty, while in another only one may have a value, in some other all boxes may show some numbers and you get the idea - i don't know upfront which textbox of which panel will contain which data.

Now, in order to reduce memory footprint i started learning about the Flyweight design pattern. It seems like exactly the thing i need but, if i keep one JPanel as a seed, and use it to represent other 99 panels (just changing the JTextBox values accordingly) it means all those panels will share the common reference.

In that case, changing JTextBox values in one of them would also change value in all others, right? How to overcome this problem and still keep the memory footprint of the application low?

Am i missing something?

Gathering/ melting multiple column sets, integer values for the variable column?

first of all, I am sorry, I know that my question overlaps with couple of other questions here, but I am really new to R and I could not find an answer that fills the task completely and that I could actually understand.

my data set is something like that:

ID … Exam_t_minus_3 Exam_t_minus_2 Exam_t_minus_1 Grade_2012 Grade_2013 Grade_2014
1       Math        Physics         Chemestry         98         70         76
2       English     French          Russian           77         85         59
3       English     Chemistry       Biology           65         77         69

and I want it to become something like that:

ID  …   i(as t_minus_i_)    Exam         Grade
1       3                   Math          98
1       2                   Physics       70
1       1                   Chemistry     76
2       3                   English       77
2       2                   French        85
2       1                   Russian       59

I have gone through swirl() course and thought I could do it with tidyr, but I could not figure out how could I gather more than one set of columns. I ended up with a result like:

ID  …   ................    Exam         Grade
1       .                   Math          98
1       .                   Math          70
1       .                   Math          76
1       .                   Physics       98
1       .                   Physics       70
1       .                   Physics       76

I looked into this: Gather multiple sets of columns and some others, but most of them lost me on half way.

I tried the answer for this question as well (I changed the earning columns to end with T_minus_* beforehand): Gather multiple columns with tidyr

i.e I tried

library(data.table)
res = melt(setDT(sample_df), 
measure.vars = patterns("^Exam", "^Grade"), 
variable.name = "i")
res[, i := factor(i, labels = c("3","2", "1"))]

It does the most of the thing I need, however, I need to the values in my i columns to be integers not categorical variables, because I need them for the future calculations.

I tried to do res$i <- as.numeric(res$i), but that changed the order, i.e "3" was evaluated to 1, "1" to 3. I tried to just leave it out, but that gives me 1,2,3 as well for the i column values.

As I changed the earnings columns to be Earnings_T_minus_* could I perhaps just get those * values in the i column somehow?

library(data.table)
res = melt(setDT(sample_df), 
measure.vars = patterns("^Exam_T_minus_*", "^Grade_T_minus_*"), 
variable.name = "i")

Sorry, the question became a bit long and perhaps confusing, but hope someone can lead me in right direction.

How properly arrange notifying mechanism between GUI and Model in MVVM?

I faced with a following problem in my MVVM project. I have ViewModel object which has event notify the model when he has property updating from GUI.

This was working properly, but after this it took me updating property in model programmaly and refresh GUI accordingly. Therefore i added event property in the model for VIewModel notifying, and got hanged application.. Since i got next loop: model -> viewmodel -> GUI -> ViewModel -> model .. etc.

I may use following ways for solution:

1) To create two different methods in the model: for updating property from GUI and for updating programmaly.

2) In the model perform verification (through reflection)- which object call the method and later to do notify or not.

My question in the subject.. thank you!

PHP object composition practice

I have a Parent Class Model Like this:

namespace vendor\appname\core;

class Model
{
    protected $db;
    protected $session;
    protected $cookie;
    protected $record;

    public function __construct()  
    {
        $this->db = new Db;
        $this->session = new Session;
        $this->cookie  = new Cookie;
        $this->record  = new Record;
    }
}

here I have my child models where i can extend the base model and use there objects

namespace vendor\appname\models;

use vendor\appname\core;  

class Login extends Model
{
      // here i can use simply like so 
      $this->db->prepare() // and so on 
      $this->session->set() // and so on so fourth
}

So if i have 100 class should i do the same thing "object composition " is this a good practice ??? what about the registry pattern or factory ? is it possible to implement it here ? or dependency injection

Factory Design Pattern VS Constructor

I have a Product class that contains methods and a complex data structure. I will have 8 types of products that differ only in the contents of the data structure, nothing else. In my application I will then need to create one instance of each of the 8 types of product, once, and the types of products that exist do not change at run-time.

What is the best approach and why?

A) Class Product has 8 sub-classes. Each of these sub-classes defines only the constructor. Inside each constructor the data structure is properly created for that type of product.

B) A Factory class has 8 sub-classes. Each of these sub-classes is a concrete factory for each of the 8 types of products. Class Product has no sub-classes. Each concrete factory creates the specific type of product by creating the appropriate data structure and passing it as an argument to the constructor of class Product.

I have been reviewing the advantages of the Factory design pattern and I can't see, for this specific case, any of those advantages in B over A. Am I missing something?

Python 3: best way to reuse the code in project, when need to expose both classic + asyncio interfaces to user

The project is Python 3 library (package), implementing custom stream binary protocol. Think of pair of stream processing classes:

MyEncodingWriter(dst_stream) - translates Python objects to raw byte stream MyDecodingReader(src_stream) - translates raw encoded bytes to messages or Python objects

I need to support both blocking sync streams and asyncio StreamReader + StreamWriter, (probably, with subclassing from them)

I understand I can't use coroutines as regular sync functions directly.

I think to mimic asyncio reader/writer API's (read(), readexactly(),...) in my classes MyEncodingWriter() and MyDecodingReader(), so the only differences will be extra async/await keywords in asyncio version.

It's strange for me I will have two copies or repos with very similar code which I can't reuse.

For now I have only this idea... ...try to generate dynamically sync code from async (by stripping async/wait keywords) with help of metaclass, maybe?

It there some better approach?

TYA for any suggestions or beautiful sampes/repos of a such dual implementation.

Extensible design patterns in iOS development - Swift

I`m working with a project where I need to analyze and evaluate extensible design patterns in Swift. There are lot of design patterns out there, that support extensibility, flexibility, portability, performance, and you name it. As I can understand there are lot more design patterns in iOS development then e.g. from the release of Gang go Four book. What I would like know is if any of you out there have experience with developing iOS applications using Swift, at same time focusing and implementing design pattens that support extensibility. Some example patterns would be great.

I`m only interested in design pattens that support extensibility.

mercredi 26 juillet 2017

Overlapping Lookahead Regex

abcdef

how to match abc & abcd?

(?=(abc|abcd))
abcdef

matches only abc for some reason, even though lookahead is non capturing. abcd doesn't get matched after matching abc.

using php if that matters.

most suitable design pattern to choose parser based on input file

I have my input file in all XML/JSON/CSV/EXCEL formats.

I have written separate parsers for all. but I wanna choose my parse at run time.

which design pattern will be most suitable ?

I have implemented such as

if(file.endsWith(".csv"))
return CSVParser();
if(file.endsWith(".json"))
return JSONParser();
if(file.endsWith(".xml"))
return XMLParser();
else
return EXCELParser();

suggestion/guidelines please .

In the context of MVC, what would you call a class that drives 3rd party API?

In context of MVC, how would you classify a class that drives an API?

That is, in MVC there is a controller, view, and model. My class specifically drives a 3rd-party PDF API that draws text or images on a PDF. You can use the API directly, and it was the case in my codebase at first. Later, certain patterns emerged, say for example a page header and a page footer essentialy had the same code, so the "API Driver" class was born, to store common bare-API patterns.

Is this PdfApiDriver a controller? a repository? a service? a library? Something else?

It doesn't strike me as Controller, because I call PdfApiDriver from my controller. It is not repository as it doesn't store any data really. Text for the footer is located in its own repository class. I'm not sure as for the rest.

It strikes me a little bit as my own custom library extension from the original library. Customizing it that way makes it easy for me to assemble my own PDF using my own custom business functions.

How do I make model in MVC for iOS app dynamic based on changed in REST-ful API?

We're building an iOS app using Realm as our model / database but we want to design the client so it can easily accommodate changes in the REST-ful API that may occur in the future. Lets say we're developing an app for sports competition organizations that accommodates different events. Each event has different types of event types based on what sports are being played. Right now the API only returns Soccer, Baseball, and Football but in the future it might expand to include Basketball too. Later it might eliminate Baseball. I've designed the Realm objects so that Events are decoupled from Event Types using a one-to many relationship like this:

class EventTypeGroup: Object {
    dynamic var name = ""
    let eventTypes = List<EventType>()
}

class EventType: Object {
    dynamic var name = ""
    dynamic var descriptionText = ""
}

An EventTypeGroup is the class describing the event types (in this case which sports) will be played at the event. I used this design because dictionaries aren't supported in Realm where we could store an event type with an associated set of properties.

In order to make the model adaptable to future changes in the API in case sports for a particular organization are added or removed, I used an abstract factory pattern like below. This way an event cannot be created without using an enum in keeping with modern Swift design principles. The problem I'm having is, assuming we only check for changes to the event types (sports) once upon the user opening the app, how do we change the model with the app already open? Will the database need to be migrated if these fields change?

protocol EventTypeGroupFactory {

    func 

}

protocol EventTypeFactory {

    func createEventTypes() -> 

}


class SportFactory: EventTypeFactory {
    //implement createEventTypes here
}


Class EventTypeGroup: Object: {

    let eventTypes = List<Int> 
    enum EventType  {
    }


}

Class EventType: Object: {


var type: int


}

Class Event: Object {

    static enum EventType   
    init(eventTypeWithRawValue:) {

    }
}

Also, how will I refer to the different variations of the classes in the code I write now if I don't know how they'll be defined. I'm guessing the abstract factory pattern may not be the best way to deal with this but am not sure what other options I should consider.

Data access and models (CQRS)

I'm creating REST API (ASP.NET Core). I decided to use CQRS (without eventsourcing) in this project.

The project will be separated to many small libs. Each library will be responsible for specific feature.

In my past projects I used repository pattern to abstract from data storage. How should I abstract from data storage using CQRS? Or I shouldn't? For example, I have small library which contains queries and commands to work with users. Should I directly write SQL inside a query or a command?

Next question is about models. In my past projects was models library. Each model inside the library had the same structure as DB tables. If I understand correctly, in CQRS I must create model for each command and query. Do I need view models in this case?

Design an web App that that wich company wil be working with an istance

Hi devs i want to design an web App that that wich company wil be working with an istance acessing just their own DataBase (app like PipeDrive). And I have no idea where to start wich tecnology to use.

I appreciate your help!

C# Resolving Base Class to Correct Repository Method Call Based on Implemented Type

In our current project, we have an abstract base user class that is implemented by multiple other user types. We have a comparison class that can compare any of these types and then needs to call a correct update api based on the implemented type. I am trying to avoid bringing an if(typeof(User)) logic tree into the code and was hoping to figure out some way to solve the issue with method overloading. Are there any design patterns that can help solve this issue with some type of interface that can be dependency injected? Here is a basic code example

using System;
using System.Collections.Generic;

namespace ConsoleApplication5
{
    class Program
    {
        static void Main(string[] args)
        {
            List<BaseUser> TestUsers = new List<BaseUser>();
            TestUsers.Add(new UserA() { Email = "test1@test.com", Location = "New York, NY" });
            TestUsers.Add(new UserB() { Email = "test2@test.com", State = "TN" });

            foreach (var user in TestUsers)
            {
                //need to invoke the correct Print repo method based on the actual user type
                dynamic u = user;
                u.Print();
            }

            Console.Read();
        }
    }

    public abstract class BaseUser
    {
        public string Email { get; set; }
    }

    public class UserA : BaseUser
    {
        public string Location { get; set; }
    }
    public class UserB : BaseUser
    {
        public string State { get; set; }
    }

    public class UserARepo
    {
        void Print(UserA user)
        {
            Console.Write($"User A Saved {user.Email}, {user.Location}");
        }
    }
    public class UserBRepo
    {
        void Print(UserB user)
        {
            Console.Write($"User B Saved {user.Email}, {user.State}");
        }
    }

}

Why is this Singleton design pattern not linking?

The following code is taken directly from "Design Patterns" by Gamma, Helm, Johnson, and Vlissides (1994), with one exception: I have added a public member function named "printOne()" for testing.

I am simply trying to instantiate the singleton object, and invoke the printOne() method thereon.

This code will not link, and I don't know why.

Thank you for your help. Sincerely, Keith :^)

SOURCE

#include <iostream>

class Singleton {
public:
    static Singleton* Instance();
    void printOne() { std::cout << 1 << std::endl; }
protected:
    Singleton();
private:
    static Singleton* _instance;
};

Singleton* Singleton::_instance = 0;
Singleton* Singleton::Instance() {
    if(_instance == 0) {
        _instance = new Singleton;
    }
    return _instance;
}

int main() {

    Singleton::Instance()->printOne();

    std::cout << std::endl;
    return 0;
}

ERROR

Ld /Users/keith/Library/Developer/Xcode/DerivedData/singleton-absganqluliwfnaibrrlstfosfsc/Build/Products/Debug/singleton normal x86_64
    cd /Users/keith/Documents/2017/working/singleton
    export MACOSX_DEPLOYMENT_TARGET=10.11
    /Applications/http://ift.tt/17KlLIW -arch x86_64 -isysroot /Applications/http://ift.tt/1jCtz97 -L/Users/keith/Library/Developer/Xcode/DerivedData/singleton-absganqluliwfnaibrrlstfosfsc/Build/Products/Debug -F/Users/keith/Library/Developer/Xcode/DerivedData/singleton-absganqluliwfnaibrrlstfosfsc/Build/Products/Debug -filelist /Users/keith/Library/Developer/Xcode/DerivedData/singleton-absganqluliwfnaibrrlstfosfsc/Build/Intermediates/singleton.build/Debug/singleton.build/Objects-normal/x86_64/singleton.LinkFileList -mmacosx-version-min=10.11 -stdlib=libc++ -Xlinker -dependency_info -Xlinker /Users/keith/Library/Developer/Xcode/DerivedData/singleton-absganqluliwfnaibrrlstfosfsc/Build/Intermediates/singleton.build/Debug/singleton.build/Objects-normal/x86_64/singleton_dependency_info.dat -o /Users/keith/Library/Developer/Xcode/DerivedData/singleton-absganqluliwfnaibrrlstfosfsc/Build/Products/Debug/singleton

Undefined symbols for architecture x86_64:
  "Singleton::Singleton()", referenced from:
      Singleton::Instance() in main.o
ld: symbol(s) not found for architecture x86_64
clang: error: linker command failed with exit code 1 (use -v to see invocation)

BOOK EXCERPT
Design Patterns - Gamma, Helm, Johnson, Vlissides (1994) - pg 129

Design Patterns - Gamma, Helm, Johnson, Vlissides (1994) - pg 129

Create an interface for heterogeneous sources

I'm studying patterns writing my own examples. But sometimes I got stuck...

I have four stores:

Store1: meat, ice cream and toilet paper.

Store2: ice cream.

Store3: meat.

Store4: ice cream, pasta, vegetables.

Sometimes I want meat from all stores.

Sometimes only ice cream from all stores.

Sometimes only ice cream from a single store.

How should I design an interface for those classes considering not every method would be implemented in every class? I mean, there's no get_ice_cream for the Store2 since there's no meat in the Store2.

Interface segregation could lead to an "interface explosion".

In other hand... people says that multiple inheritance is a bad decision in almost of cases.

I'm stuck trying to deal with that problem.

It would be very nice to have an way to add new Stores and make my IceCream concrete class be able to get all the ice cream from a list of Store objects simply executing the same get_ice_cream method.

Thanks for any help?

C++ Alternative to templetized data member

If I have a class DataManager:

class DataManager
{
 public:
   int getRecordInt( size_t i ) const;
   std::string getRecordString( size_t i ) const;

 private:
   std::vector<int> _vInt;
   std::vector<std::string> _vString;
}

I can access records with e.g.

DataManager DM;
// .. populate object ...
int iValue = DM.getRecordInt(3);

In my real application, I will have over a hundred data types (besides int and std::string), so I would like to avoid having to write a separate getter for each of the types.

Now, if C++ would support templatized variable names (which it does not), I could implement the class as:

class DataManager
{
 public:
   template<typename T>
   T getRecord( size_t i ) const
   {
      return _v<T>[i];
   }

 private:
   std::vector<int> _v<int>;
   std::vector<std::string> _v<std::string>;
}

Is there any way I can achieve the purpose in C++?

(Please be aware that although I have simplified the example to the bare minimum, my real-world problem is much more complex and calls for the existence of such DataManager class.)

How to deal with interfaces that shares part of the methods without creating too many interfaces?

I have five sources of data and all those are text files.

I would like to create an interface like IDatabase so that I can put as many source files I can get in any moment.

But... the files are like:

File1: name, age

File2: age, city

File3: name, parent_name, city

File4: city, genre, name

File5: city, country, height, weight, t_shirt_size

So, if I create a single interface, some concrete classes will have useless methods because some files doesn't have some kind of data. File1 has name and age but File2 doesn't has name, but has age.

At the same moment some data are shared among some files, which means different interfaces would lead to code duplication, or, in the best case, lead to tiny interfaces only to deal with shared data, like the name field.

Interface segregation is the most common answer when I ask to my friends, but if I segregate everything... at the end the number of interfaces and its names will make my system more confuse than clear.

I'm pretty sure there's a direct solution to create a good interface project to my situation.

Thanks for any help!

Best design pattern to skip execution of code if one of the child method throws exception

I am using core java to develop a testing framework. In my application I have a parent method which calls ten different child methods, where each method can throw its own exceptions. The requirement is to provide detailed log information about the execution of parent method which contains information like total time taken to execute the method, time taken to execute each child method, log any exceptions etc. I am using multiple try catch finally blocks for this.

My question is, What's the best way to skip the execution of remaining child methods if one of the child method throws an exception? For eg: If method 4 throws an exception, I want to log that exception and go to the end and log the time taken by parent method until then.

I tried using boolean variable initializing it to true at the beginning of parent method. I am checking if the boolean varible is true before executing each child method. Whenever an exception is thrown, I am marking the boolean variable false.

My psuedocode looks like this:

public String parentMethod(){
    boolean execute = true;
    if(execute) {
        try event1; 
        catch(Event1Exception e1)  
            log e1; execute = false; 
        finally log event 1 time taken;
    }
    if(execute) {
        try event2; 
        catch(Event1Exception e2)  
            log e2; execute = false; 
        finally log event 2 time taken;
    }
    and so on ....
    log total time taken;

In my actual code I have about ten different events which throw their own exceptions, sometimes more than one. With this approach, assigning execute = false for each exception caught and then again checking the value of execute seems clunky. Is there a better approach than this, without using any additional plugins?

controller/service/repository style, should service wrap repository for other service

My project followed a controller/service/repository style, like UserController -> UserService -> UserRepository and ShopController -> ShopService -> ShopRepository. Now I want to fetch user from ShopService, should I call UserService or call UserRepository directly from ShopService.

Difference between method chaining and fluent interface

I wanted to know the exact difference between method chaining and fluent interface. As I understand it, method chaining is just running the methods of previous method return objects while avoiding temporary variables. An example of this could be Integer.parseInt(str).intValue()?

With respect to fluent interface, each method of the object is chained by a point, without having to be related to the previous method The two techniques make modifiers methods return to host objects, so that multiple modifiers can be invoked in a single expression like this:

 

new Car().StartsEngine().OpenWindow()

is this correct?

how to represent relationship value on parent for simple entities

This question is about best practices and design patterns; I'm sure i can go with any option depending on app, but i want to develop the backend up to best practices regardless of front app/client current needs are.

what is best practice to follow during API development when a certain resource has a one-many/many-many relation with another resource, is it okay to add columns from one resource into other to represent important column that i'm sure its mandatory needed ?

#Example Database may look like:-
Event{
 id: 1,
 user_id: 1
}
User:{
 id: 1,
 name: 'Momen',
}

Now to respond to GET /Post/1

## Option 1
Event{
  id:1,
  user_id:1,
  user:{
   id:1,
   name: momen,
  }
}
## Option 2
Events{
1: Event{
  id:1,
  user_id:1,
  user_name: 'momen',// i will not include User object unless client request it.. but i will inject user_name because it's a data i'm sure that Post will always need
}
}

the User object in above example can be huge, and i don't want the whole user object, -unless app needs more info about the user- yet i still need his name to display in the list of Events. so is it okay to add this name to Event object as a fallback, so if client dont have access to User:1 in his memory, he can display this column while fetching User.

Q1 Is this acceptable or i'm polluting Object and introducing anomily bugs ?

in another case of Many-to-Many relation; I have a flag I want to set, should I set it on parent Entity or I have to include relation object as well.

EventUser{
 event_id: 1,
 user_id: 1,
}

Adding EventUsers Link table which represents a one-many relation,

Q2. I want to set a flag next event that indicates if the user who is querying those events is going to this event or not.

so in a restful-API, to respond to GET /events/1 request i can

## option 1:

Event{
 id:1,
 name: 'Event 1',
 is_going: true
}

## option 2
{
  events:{ 1:{id:1, name:'Event 1'} },
  EventUser:{1:{ event_id: 1, user_id: 1},} // or {} if not going
}

its clear that option1 is easier to implement and easier to deal with.. but this mean that again i'm introducing columns to Event Model that does not exists. plus if the client is going to cache such results for offline-first usage, and user changes then this data is simply wrong.

Design for parallel processing in the system

In current system, there are some long running processes(and sub-processes) which run for every account that exists in the system. Those processes actually fetches account data and perform some operations on that account data (account data can go from few thousands to millions). These processes are not one time process. It keeps running in every few hours.

Earlier there was only single program which performs all the above tasks picking up one account at a time, which was not a desirable solution since that way it would take days to complete the job for all the system accounts. So we ended up having separate programs for each account so that we can run the programs in parallel for each account.

Since now the account data is growing day by day, there is a need to further scale it.

To scale this, we decided to design a producer/consumer queue architecture kind of solution. For queuing system I will be using RabbitMQ, can not switch to any other alternate for this.

There are two ways I think of right now:

  1. Build a single queue(there can be other queues for other sub-task) design where all the data of multiple account is dumped for processing and the consumers will pick data from that queue and process. Number of consumers can be increased to process the record from the queue. But I am not sure whether increasing number of consumers will solve the problem. Data will be processed in FIFO by the consumers for account, so data which is added in the queue in the last will always be picked up at the end. So it can not ensure that the overall system is performing on a better speed on account level.

  2. Another is, to introduce multiple queues each for one account. So that dedicated consumers for each account queue can be initiated and perform the task. Some how I do not feel comfortable with this approach since account numbers are dynamic and creating that number of queues does not seems to be a good solution to me, as the number of account grows will increase by the time.

Any other suggestion to solve this problem.

mardi 25 juillet 2017

Where i have to create data access layer (ado.net) in MVC c#, i am not using entity framework

i am not using Entity framework, then where i have to create data access layer in mvc(c#) Architecture. if i am creating data access layer library outside of MVC project then what is benefit of MVC architecture.like


MVC_project- Dallibrary- BAL library-

unit test project-

Please help for accommodate DAL layer in MVC itself.

SSAS Tabular solution - should we limit it to one model per solution

We have a need for multiple SSAS models, though we have been in practice keeping each model in its own solution. At this time, we have a naming convention across solutions, projects, and models.

I've been asked why we're doing it this way instead of having one solution, with multiple projects for each needed SSAS model. I don't have a good answer to that question, and now he's put a bug in my head.

Since I'm anticipating that this may be a matter of opinion, I'll phrase the question safely: What are the pros and cons of each approach?

Where to put the business logic for updating tables?

Where would I put the CreateOrder() business logic?

class Order // this is an entity model for DbContext
{
    public int Id { set; get; }
    public String name { set; get; }
    .......
}

public void CreateOrder(Details details)
{
    // set up Order fields
    .........
    database_name.Order.Add(order);
}

 controller would call obj.CreateOrder(details);

Would it go in a different class in the App_Code folder? Thank you.

Understanding Borg Singleton Pattern in Python

I saw this Borg Singleton Pattern code but I couldn't get my head around how new members I add to the singleton object gets appended to the __shared_state = {} dictionary.

Here is the Singleton code

class Borg(object):
    _shared_state = {}

    def __new__(cls,*args,**kwargs):
        obj = super(Borg,cls).__new__(cls,*args,**kwargs)
        obj.__dict__ = cls._shared_state
        return obj

class Child(Borg):
    pass

if __name__ == '__main__':
    borg = Borg()
    another_borg = Borg()

    print borg is another_borg
    child = Child()

    borg.only_one_var = "I'm the only one var"    
    print child.only_one_var

So my question when the object borg.only_one_var is created how does it get appended to _shared_state dictionary

Where command pattern is used in Android SDK?

Currently I'm stydying design patterns and trying to use them in real projects. Where command pattern is used in Android SDK? And how I can use it in Android application?

How do I call a DAO method from Service layer in a J2EE web application

Generally a lot of applications these days use Spring which takes care of the life cycle of the pojo classes in their application. But what if my application cannot use Spring due to some other issues. How do I go from the Service layer of the application to the DAO layer.

Currently this is what I am doing.

public class MyServiceImpl{

    private static MyDAO daoInstance=new MyDAO();

    public void someMethod(){
        daoInstance.methodToCall();
    }

}

public class MyDAO{

   public void methodToCall(){


   }

}

Keeping the daoInstance in MyServiceImpl as static makes sure that there is only one instance across all ServiceImpl objects. But wouldn't this create concurrency issues if a lot of users access the same piece of code at the same time.

However if I don't keep it static, there would be one daoInstance with each MyServiceImpl object. Wouldn't this leave so many objects in the heap. How would the life cycle of these objects get managed.

I want to understand what is the correct way of navigating from one layer of the application to other layer keeping concurrency, performance and other such factors in mind.

Thanks for any help.

Best design pattern for collection of objects

I have the following architecture:

         +-----------------+
         |   Collection    |
         |                 |
         |                 |
         |                 |
         |                 |
         +-----------------+
           |        ^
           |        |
  Create() |        |
           |        |
           v        | GetItem(B)
+------------+      |
|   Item A   |      |
|            |      |
|            +------+
|            |
+------------+

A class managing a collection of items, creates items. And these items may need other items from the collection.

The actual code is in python, and for now the Collection passes itself as a parameter to the created Item. As I see it, it is a bad practice. The only improvement I can see it to pass the few functions of Collection needed by the Item, instead of the whole instance.

For example:

class Collection:
    GetItem(self, id):
        ...
    CreateItem(self, id):
        item = Item(id, self) # <-- pass self
        ...

class Item:
    __init__(self, id, col):
        ...
        col.GetItem(...)

How can I avoid passing self as parameter? Or is it a common usage in Python?

What is the best design pattern for RESTfull Api Design

This week I finally started with learning developing API´s.

At this moment my API is able to do simple get, post, put and delete request and return information from the database as a JSON string.

I build my current API with Slim 3, a lightweight PHP framework.

For now, I search for good blogs, articles and so on about API developing and API design.

Thank for posting interesting things.

Coding Pattern for use instance member

Suppose i have a class called CommandLineOperation. This class accesses api resources. Thus i have defined one instance member of type APIAccessor.

class CommandLineOperation {
    APIAccessor apiAccessor;
    void create() {
        apiAccessor = new APIAccessor(email,password);
        //do work for creation
    }
    void update() {
        apiAccessor = new APIAccessor(email,password);
        //do work for update
    }
}

class APIAccessor {
    String email;
    String password;
    APIAccessor(email,password) {
        this.email = email;
        this.password = password;
    }
}

The operations in CommandLine, are infrequent, is it a better approach to instantiate APIAccessor under every operations or create once using constructor of CommandLineOperation class. e.g.

CommandLineOperation(String email,String password) {
    this.apiAccessor = new APIAccessor(email,password);
}

Please let me know or suggest good coding design pattern. Or suggest me any reference book so that i can improve my coding standard based on the analysis. Thanks in advance.

lundi 24 juillet 2017

Discrete Event Simulating Embedded Firmware using Simpy

Let's say I have 3 tasks:

def task1():
    if check_if_theres_work_to_do():  #just checking takes 2us
        do_work()  #takes 10us

task2 and task3 defined similarly

and I have one CPU. A common embedded approach would be to do the following:

def round_robin():
    while True:
        task1()
        task2()
        task3()

Now, I want to simulate this in Simpy, but I don't want to constantly cycle the round_robin code if there's no work to do for any of the tasks (as this would increase simulation time), but I want only one task to be able to run at a time. Further, I want to simulate the fact that, when work becomes available, e.g. for task2, it may take some amount of time before task2() gets executed (the processor is busy checking if the other tasks have work to do / actually doing work for other tasks).

In Simpy, I've defined the tasks such that each has yielded on an event (e.g. work items coming in on a queue):

def task1():
    work_item = yield task1_work_queue.get()
    do_task1_work(work_item)

But if I use env.process(task1()); env.process(task2()); env.process(task3()), then they could all run in parallel, which does not accurately model the behavior of the while loop.

One approach I thought might be to define a resource called CPU, cpu = Resource(), and then have the tasks yield on getting a work_item and then yield on getting the cpu, and then yield a random amount of time between 0 and 2*number of other tasks:

def task1():
    work_item = yield task1_work_queue.get()
    with cpu.request() as req:
        yield req
        yield env.timeout(4)
        do_task1_work(work_item)

But this seems kinda messy since a task has to know how many other tasks the cpu is executing.

Is there a better way to model this? Should I have a process yield on requesting the cpu and then waiting on the getting work, but have the wait on work interruptible (so that a task with no work doesn't block tasks that do have work)?

Best design pattern to use with Spring

I have a problem that I am trying to solve. I need to be able to return an implementation based on a user's input. I have looked into using the Abstract Factory pattern, but am not sure if it is the best way to go or not (Or if Spring can help me a little along the way).

Here is the interface the factories will be returning:

public interface Flow {
    List<Message> execute(String sessionKey);
}

and 1 implementation of that interface:

@Component("AssignSeatFlow")
public class AssignSeatFlow implements ChatbotFlow {

    private SeatService seatService;

    @Autowired
    public AssignSeatFlow(final SeatService seatService) {
        this.seatService = seatService;
    }

    @Override
    public List<Message> execute(String sessionKey) {
        // Implementation here
    }
}

My current Factory interface:

public interface FlowFactory {

    Flow getFlow(final String intentCode);

}

and its implementation:

@Component
public class FlowFactoryImpl implements FlowFactory {

    @Resource("AssignSeatFlow")
    private Flow assignSeatFlow;

    @Override
    public Flow getFlow(final String intentCode) {
        if(StringUtils.isNullOrEmpty(intentCode)) {
            throw new IllegalArgumentException("Intent Code cannot be empty");
        }

        switch (intentCode.toUpperCase()) {
            case "AssignSeatFlow":
                return assignSeatFlow;
            default:
                throw new IllegalArgumentException("Unable to determine flow");
        }
    }
}

The reason this doesn't seem ideal is that as I add more Flows, the factory will get much larger and I would have to modify it every time I do so. I am also not a fan of field Autowiring as it makes testing more complicated and less explicit.

Thanks for any feedback.

How can I display following patterns using C (nested loops)?

Pattern 1:

*     *     *
*           *
*     *     *

Pattern 2:

*           *
*     *     *
*           *

I've been having trouble with this, kindly help me with the logic of these patterns using Nested Loops(any one of them) in C Language.

DAL using Dapper

I'm creating my first project using ASP.NET Core and Dapper. Before this project I used Entity Framework. DAL in my past projects was like this:

// Project.Data

public class BaseRepository : IDisposable
{
    public string ConnectionString { get; set; }

    protected BaseRepository()
    {
    }

    protected BaseRepository(string connectionString)
    {
        ConnectionString = connectionString;
    }

    protected string GetConnectionStringValue(string connectionStringName)
    {
        ...
    }
}

// Project.Data.EF

public abstract class EntityBaseRepository : BaseRepository
{
    private DbContext _context;
    protected EntityBaseRepository(): base("connectionString")
    {
    }

    protected DbContext Context => _context ?? (_context = CreateEntityContext(GetConnectionStringValue(ConnectionString)));
    protected abstract DbContext CreateEntityContext(string connectionString);

    protected virtual void SaveEntity<T>(T entity) where T : Entity
    {
        ...
    }

    protected virtual void DeleteEntity<T>(T entity) where T : Entity
    {
        ...
    }
}

public abstract class EntityBaseRepository<TEntity, TSearchOptions, TLoadOptions> : EntityBaseRepository
    where TEntity : Entity
    where TSearchOptions : SearchOptions
    where TLoadOptions : LoadOptions
{
    protected IEnumerable<TEntity> GetEntities(TSearchOptions searchOptions, TLoadOptions loadOptions)
    {
        ...
    }

    protected async Task<IEnumerable<TEntity>> GetEntitiesAsync(TSearchOptions searchOptions, TLoadOptions loadOptions)
    {
        ...
    }

    protected int GetCount(TSearchOptions searchOptions)
    {
        ...
    }

    protected TEntity GetEntity(long id, TLoadOptions loadOptions)
    {
        ...
    }

    protected virtual IQueryable<TEntity> ApplySearchOptions(
        DbContext context, IQueryable<TEntity> entities, TSearchOptions searchOptions)
    {
        ...
    }

    protected virtual IQueryable<TEntity> ApplyLoadOptions(
        DbContext context, IQueryable<TEntity> entities, TLoadOptions loadOptions)
    {
        ...
    }
}

I thought I can use this approach with dapper. I have created mapper for entities and query builder. After that I have created Repository:

    public abstract class EntityBaseRepository<TEntity, TKey, TSearchOptions, TLoadOptions> : EntityBaseRepository
    where TEntity : Entity<TKey>
    where TSearchOptions : SearchOptions
    where TLoadOptions : LoadOptions
{
    ...

    protected virtual Query ApplySearchOptions(QueryBuilder query, TSearchOptions searchOptions)
    {
        if (searchOptions.IDs.Any())
            query.WhereIn(FluentMapper.KeyColumnName<TEntity>().ToArray(), searchOptions.IDs);

        return query;
    }

    protected virtual Query ApplyLoadOptions(QueryBuilder query, TLoadOptions loadOptions)
    {
        if (loadOptions.SortFields.Any())
        {
            foreach (var sortField in loadOptions.SortFields)
            {
                switch (sortField.Value)
                {
                    case SortOrder.Ascending:
                        break;
                    case SortOrder.Descending:
                        break;
                    default:
                        throw new ArgumentOutOfRangeException();
                }
            }
        }

        if (loadOptions.SkipRecords.HasValue)
            query.Skip(loadOptions.SkipRecords.Value);

        if (loadOptions.MaxRecords.HasValue)
            query.Take(loadOptions.MaxRecords.Value);

        return query;
    }
}

QueryBuilder is fluent query constructor (like sqlkata). The main problem when using this approach with Dapper is applying search and load options. I don't know how to do it properly. If in derived from EntityBaseRepository class I use alias (for example QueryBuilder.From("x as A")), I will receive exception.

How would you create DAL with dapper?

Inheritance in Factory Method Vs Composition in Abstract Factory Method

I am just going through the wiki pages of Factory Method Pattern and Abstract Factory method pattern.

From Head First Design Patterns I got this

Factory method Pattern uses inheritance, Abstract Factory Pattern uses composition. Abstract Factory Pattern also does the same like Factory Method Pattern which keeps the Clients decoupled from concrete Types but in a different way.

After analyzing the wiki examples, I couldn't actually find the composition in the examples. Both of the Patterns uses inheritance.

Factory Method Pattern

enter image description here

Abstract Factory Pattern

enter image description here

Here are my questions.

  1. Does Factory Method Pattern always have just only one Abstract Product inheritance tree unlike Abstract Factory Method Pattern?
  2. Where could be composition utilized or programmed in a way? If it's just the Client with main method, then Factory Method Pattern also uses Composition. A code snippet example would clear the concept.
  3. Is my interpretation of these patterns as in sample sketch correct?

Regex Between Brackets

I have a string like this:

<random stuff between><random stuff between><random stuff between><random stuff between>

I already can match this string using this Regex Pattern :

  if (Regex.IsMatch(arg, "^(<.+>){4}$"))
                return true;

But How can I get the content between the brackets, by also using Regex?

How to understand DCI pattern

According to Wikipedia Data, context and interaction (DCI) is a paradigm used in computer software to program systems of communicating objects. Here I am not clear about the problem which DCI tries to solve. Can you explain it with simple example? What is Data, Context and Interactions in your example?

clean coding to manage project configuration?

For a Saas Project that I am working on (Angular/Django), we have noticed that we have many client segments. Since it's not DRY to clone our plateforme to have separate version for each segment, we have decided to create a configuration object for each project which enable us to customise the product quickly to adapt to client needs.

Problem : The problem we are facing on front is that code starts to be spaghetti since we need to execute each piece of code according to this configuration object. Now we have switch and if everywhere which makes code hard to read and to maintain.

Is theire any good practices to handle such a situation ?

JavaScrip module pattern function or jQuery delegate

I'd loike to know which solutions better to use module pattern or write a handle function for an input element action?

<button type="button" onClick="main.update.buttonClick">Click</button>

(function($) { 
 'use strict'; 
 window.main.update = window.main.update || ();

 main.update.init = function() { ... };

 main.update.buttonClick = function() { ... }; })(jQuery);

or

 <button id="update" type="button">Click</button>

(function($) { 
 'use strict'; 
 window.main.update = window.main.update || ();

 main.update.init = function() { 
  $("#update").on("click", functio() { ... });
 };

What is the better solution or there is another more better one, please?

Design models: search by singleton models in django

I have a model TranslationService, which has some fields and methods which should be overriden by every new service. I have three services: Google, Azure, Bing, which are the only ones in system (we have only one Google service and one Azure service etc.). I need to perform action like this: TranslationService.objects.filter(service_name=service_name).

But if i make TranslationService abstract, i can't iterate over abst class, cause it wasn't created in DB. If I make inheritance I should implement logic of overriding methods in code like model and then create GoogleService via console. Is this the only way or I can reduce creating object via console.

How can I design my models for performing search among translation_services?

class TranslationService(models.Model):
 created_at = models.DateTimeField(auto_now_add=True)
 updated_at = models.DateTimeField(auto_now=True)
 service_name = models.CharField(max_length=40)
 base_url = models.CharField(max_length=255)
 api_version = models.FloatField()

 def get_step_translation(self, pk, lang, lesson):
    pass

 def create_step_translation(self, pk, lang, type):
    pass

class GoogleTranslator(TranslationService):
 base_url = "https://google.com"
 service_name = "Google"
 api_version = 1.5

 def get_step_translation(self, pk, lang, lesson, **kwargs):
  ... some logic
 def create_step_translation(self, pk, lang, type):
  ... some logic

Where to put all code/organize code in unity?

so I am a beginner at unity and cannot grasp how you are supposed to have a pattern or architecture with unity.

I am currently making a platform game which has a character that is supposed to stay on moving platforms and not fall off the screen (very basic). On the platform there are "monsters". If you touch these monsters you also lose. There is also some trees and such on the platform.

This is what I have so far: In the "manual gameobject list" or whatever you call it: Directional light

Main camera

Background (just a sprite that is always showing)

Player (contains a JS script that has character specific code for jumping and such)

Platformspawner (Contains only a c# script. This script spawns multiple platform gameobjects, these gameobjects then use a script called platform.cs. This class spawns monsters and the trees on each platform. The monsters and trees each use their own c# file that keeps track of collisions and such.)

For me this is pretty obvious code and I do not know how to organize it much better. Any tips? I tried following an MVC tutorial but it seems like there is not much gameobject spawning in those tutorials which is what I have to do, so they confuse me.