mercredi 31 octobre 2018

suggestion for java design pattern

i'm starting using design pattern in java .now i'm writing a java code that pass all this tests :

@Test
    public void createOrder() {
        final Restaurant restaurant = new Restaurant();
        final int tableId = restaurant.initTable(4);
        restaurant.customerSays(tableId, "Joe: Soup");
        restaurant.customerSays(tableId, "Jim: Same");
        restaurant.customerSays(tableId, "Jack: Chips");
        restaurant.customerSays(tableId, "John: Chips");
        assertEquals("Soup, Soup, Chips, Chips",
                restaurant.createOrder(tableId));
    }

    @Test
    public void failedCreationBecauseNotEveryoneOrdered() {
        final Restaurant restaurant = new Restaurant();
        final int tableId = restaurant.initTable(4);
        restaurant.customerSays(tableId, "Joe: Soup");
        restaurant.customerSays(tableId, "Joe: Spaghetti");
        restaurant.customerSays(tableId, "Jim: Roastbeef");
        assertEquals("MISSING 2", restaurant.createOrder(tableId));
        restaurant.customerSays(tableId, "Jack: Spaghetti");
        restaurant.customerSays(tableId, "John: Chips");
        assertEquals("Spaghetti, Roastbeef, Spaghetti, Chips",
                restaurant.createOrder(tableId));
    }

    @Test
    public void failedCreationBecauseNotEnoughPeopleForADishFor2() {

        final Restaurant restaurant = new Restaurant();
        final int tableId = restaurant.initTable(4);
        restaurant.customerSays(tableId, "Joe: Soup");
        restaurant.customerSays(tableId, "Jim: Same");
        restaurant.customerSays(tableId, "Joe: Fish for 2");
        restaurant.customerSays(tableId, "Jack: Chips");
        restaurant.customerSays(tableId, "John: Chips");
        assertEquals("MISSING 1 for Fish for 2",
                restaurant.createOrder(tableId));
        restaurant.customerSays(tableId, "John: Fish for 2");
        assertEquals("Fish for 2, Soup, Chips, Fish for 2",
                restaurant.createOrder(tableId));
    }

i'm starting using the Factory design pattern :

mydesign but i think its not the correct one to use ! any suggestion ?

android:gravity="center" is not working in Pre-Lollipop Android?

I have made an Android Application and I know that Pre-Lollipop devices are negligible as compared to post-lollipop devices.

I recently ran my app on Emulator and found out that the text is not aligned to center when the gravity = "center". You can see the Image attachedenter image description here

The Text Sync and the icon is not at the center but on post lollipop devices they are at the center. The xml code for the above case is :

<RelativeLayout
                        android:id="@+id/sync_layout"
                        android:layout_width="wrap_content"
                        android:layout_height="wrap_content"
                        android:layout_marginRight="10dp"
                        android:layout_alignBottom="@+id/contacts"
                        android:layout_alignTop="@+id/contacts"
                        android:layout_alignParentRight="true">


                        <ImageView
                            android:id="@+id/sync_contacts"
                            android:layout_width="24dp"
                            android:layout_height="24dp"
                            android:layout_centerVertical="true"
                            android:background="@drawable/ripplebg_viewscircle"
                            android:padding="5dp"
                            android:rotation="0"
                            app:srcCompat="@drawable/kj_sync" />


                        <ProgressBar
                            android:id="@+id/sync_progress_bar"
                            android:layout_width="24dp"
                            android:layout_height="24dp"
                            android:layout_centerVertical="true"
                            android:visibility="gone" />

                    </RelativeLayout>

                    <TextView

                        android:id="@+id/sync_text"
                        android:layout_width="wrap_content"
                        android:layout_height="wrap_content"
                        android:layout_toLeftOf="@+id/sync_layout"
                        android:layout_alignTop="@+id/sync_layout"
                        android:layout_alignBottom="@+id/sync_layout"
                        android:text="Sync"
                        android:gravity="center"
                        android:paddingLeft="5dp"
                        android:paddingRight="5dp"
                        android:textColor="#4A4A4A"
                        />

Can you tell me why this is happening and the remedy for this?

Decorator Pattern in object-oriented programming

I was studying the "Decorator pattern". Doing some tests with C# I do not understand why I do not get the expected result. This is the code:

public abstract class Drink
{
    public string description = "Generic drink";

    public string GetDescription()
    {
        return description;
    }
}

public abstract class DrinkDecorator : Drink
{
    public abstract string GetDescription();
}


public class SecretIngredient : DrinkDecorator
{
    Drink drink;

    public SecretIngredient (Drink drink)
    {
        this.drink = drink;
    }

    public override string GetDescription()
    {
        return this.drink.GetDescription() + ", SecretIngredient ";
    }
}

public class Espresso : Drink
{
    public Espresso()
    {
        description = "Espresso";
    }
}


[TestFixture]
class TestClass
{
    [Test]
    public void TestMethod()
    {
        Drink drink = new Espresso();
        System.Diagnostics.Debug.WriteLine(drink.GetDescription());

        drink = new SecretIngredient (drink);
        System.Diagnostics.Debug.WriteLine(drink.GetDescription());
    }
}

Performing the test I get:

Espresso

Generic drink

While I would have expected:

Espresso

Espresso, SecretIngredient

Why? Thanks in advance.

Is there a way to know if other method is completed?

So I have a method

internal async Task UpdateMethod(string[] commands)
{
    while (expression) {
        //some code...
        SendCommandToSomewhere(command);
        //I want to pause here to continue upon receiving a response
    }
}

Then I register following method as event

charac.ValueChanged += Charac_ValueChanged;

Command then is being received by device (in unknown time), device sends a response which rises an EventHandler

private async void Charac_ValueChanged(GattCharacteristic sender, GattValueChangedEventArgs args)
{
    //working with response
}

Basically I want to continue work in UpdateMethod() when I receive a response from the device. I suppose I can do something like boolean field, and then run Task.Delay(); in loop to check if this boolean == true, but I think that it is very wrong approach. How can I do that in the correct way?

How to allow user to configure database connection parameters in Servlets/JSP project?

I'm creating a simple Servlets/JSP based web app which connects to a MySQL database. Previously I had created a ConnectionParams class and a DBConnection class. ConnectionParams class contains hard-coded DB host, username, and password. DBConnection creates a JDBC connection based on it which is then used for database operations.

I realized the issue while deploying it to a test environment which has a separate DB of its own, and the DBA may change username/password etc. So I created a separate text file with these details as WEB-INF\dbConfig.txt. This contains the info as:

dbName=mydbschema
dbUser=myuser
dbPass=mypass
dbType=mysql

The user has to edit the file in <TOMCAT HOME>\Webapps\myproject\WEB-INF everytime the server restarts. Everytime the main servlet starts, it reads the file and stores a global ConnectionParams object. I can see that this is definitely not the best practice.

I'm looking for a more robust solution for the same.

Please edit the question if you think it is not properly worded. Add comments if I should add more details.

The property context on type ProjectName.Repositories.MyRepo is not settable?

I am creating a mvc project to learn Repository pattern. i am using DBFirst approach + Entity Framework + Unity for DI. I am following this article:

https://www.dotnetcurry.com/aspnet-mvc/1155/aspnet-mvc-repository-pattern-perform-database-operations

I have followed this article and it's working fine. But after it I

created a new table in database Teacher and update the database

Later I add TeacherInfoRepository, In unityconfig file registered the TeacherInfoRepository

Add controller and then add view

I performed above steps as it is defined in the article I mentioned above. But after I tried running /Teachers/Index view It gives the error:

The property context on type ProjectName.Repositories.TeacherInfoRepository is not settable.

I searched on google but unfortunately didn't find something like this.

Please guide me. Thanks in advance.

Abstract factory: ways of realization

I'm learning design patterns now and reading defferent resources for every pattern. I have a question about pattern Abstract Factory. I read about two ways of realization this. I'll write using this factories, withour realization. For example, I took making different doors.

First way. We have common class for Door Factory, which consists different methods for making different types of doors (which returns appropriate class of door):

$doorFactory = new DoorFactory();
$door1 = $doorFactory->createWoodDoor();

$doorFactory = new DoorFactory();
$door2 = $doorFactory->createSteelDoor();

Second way. We have parent class DoorFactory and extends classes for WoodDoorFactory and SteelDoorFactory. This classes realises same method createDoor (and return appropriate class of Door)

$woodDoorFactory = new WoodDoorFactory();
$door1 = $woodDoorFactory->createDoor();

$steelDoorFactory = new SteelDoorFactory();
$door2 = $steelDoorFactory->createDoor();

How you think, which way more optimal and canonical?

mardi 30 octobre 2018

How to make sure to avoid branch misprediction when calling a method using one of two methods based on a boolean

Let's say you have a call to a method that calculates a value and returns it :

double calculate(const double& someArg);

You implement another calculate method that has the same profile as the first one, but works differently :

double calculate2(const double& someArg);

You want to be able to switch from one to the other based on a boolean setting, so you end up with something like this :

double calculate(const double& someArg)
{
  if (useFirstVersion) // <-- this is a boolean
    return calculate1(someArg); // actual first implementation
  else
    return calculate2(someArg); // second implementation
}

The boolean might change during runtime but it is quite rare.

I notice a small but noticeable performance hit that I suppose is due to either branch misprediction or cache unfriendly code.

How to optimize it to get the best runtime performances ?


My thoughts and attempts on this issue :

I tried using a pointer to function to make sure to avoid branch mispredictions :

The idea was when the boolean changes, I update the pointer to function. This way, there is no if/else, we use the pointer directly :

The pointer is defined like this :

double (ClassWeAreIn::*pCalculate)(const double& someArg) const;

... and the new calculate method becomes like this :

double calculate(const double& someArg)
{
  (this->*(pCalculate))(someArg);
}

I tried using it in combination with __forceinline and it did make a difference (which I am unsure if that should be expected as the compiler should have done it already ?). Without __forceline it was the worst regarding performances, and with __forceinline, it seemed to be much better.

I thought of making calculate a virtual method with two overrides but I read that virtual methods are not a good way to optimize code as we still have to find the right method to call at runtime. I did not try it though.

However, whichever modifications I did, I never seemed to be able to restore the original performances (maybe it is not possible ?). Is there a design pattern to deal with this in the most optimal way (and possibly the cleaner/easier to maintain the better) ?

Pattern for a list that can contain two types of items

I'm trying to figure out a nice way to adopt an API change we've recently undergone that "weakens" a type on one of our objects.

Users used to be able to provide a list of references to "Dogs". We've made a decision that we now accept "Dogs" and "Cats".

The client library uses strongly typed references, so the property currently looks like:

public List<IReference<Dog>> occupants { get; set; }

I considered changing it to:

public List<IReference<Animal>> occupants { get; set; }

But I don't like that what used to be compile-time validation is now run-time (and server-side) validation. I would have preferred to have something more strongly typed like:

public List<Occupant> occupants { get; set; }

public class Occupant : IReference<Animal> {
    IReference<Animal> _internalReference;
    public Occupant(IReference<Dog> dog) { _internalReference = dog }
    public Occupant(IReference<Cat> cat) { _internalReference = cat }
    //... (Implement IReference<Animal> as a pass-through to _internalReference)
}

Unfortunately, because C# does not allow implicit operators to convert from an interface, existing users updating their client library would have to undergo hundreds of lines of code changes to "wrap" all their existing Dog references in an Occupant constructor.

So next I considered creating a new class for the list with some helper methods:

public class OccupantList : List<Occupant> { 
    public void Add(IReference<Dog> newDog) => base.Add(new Occupant(newDog));
    public void Add(IReference<Cat> newCat) => base.Add(new Occupant(newCat));
    // For backwards compatibility with new list assignments
    public static implicit operator OccupantList(List<IReference<Dog>> legacy) =>
        new OccupantList(legacy.Select(dog => new Occupant(dog)));
}

Unfortunately, C# exposes no way to override the core ICollection.Add implementation behind the scenes, which is used by all sorts of reflection utilities and my JSON serializer to populate this list, so it complains when it's given objects to add that aren't already of the type Occupant. I personally encountered issues with the JSON deserializer I was using. I could write a custom deserializer for this class but I took it as a sign that trying to inherit List<Occupant> and add support for types that don't inherit from Occupant was a bad idea doomed for failure.

Does anyone have any ideas or examples that can might steer us in the right direction?

Is there a way to only use a recursive type bound field given a condition?

I'm new to Java and coming from Python, so I don't have a great grasp of generics, but I am trying to make a general Parameter class that contains a value field, which can be an int, float, string or an array of one of the previous types:

public class Parameter<T> {
    private final String name;
    ...
    private final Utils.Range<T> range;
    private final RANGE_TYPE range_type;
    private final T value;

    public enum RANGE_TYPE {CONTINUOUS, DISCREET};
    ...

    /* constructor / builder class etc */
    ...
}

It also has to have a range, which I have implemented as follows:

public class Utils {
    /**
     * Collection of helper classes
     */
    public static class Range<T extends Comparable<T>> {
        /**
         * Generic Inclusive Range (designed for int / float / double).
         */
        private final T start;
        private final T end;

        public Range(T start, T end) {
            this.start = start;
            this.end = end;
        }

        public boolean contains(T number) {
            return (number.compareTo(start) > 0 && number.compareTo(end) < 0);
        }

    }
}

However, the generic types between the range field in Parameter class and the Range class itself are incompatible. Am I coming at this from the wrong direction? In python I would implement this as a dict and not worry too much about the types of the values.

Looking for very fast fixed length string search algorithm in a fixed length string database

I would appreciate suggestions for very very fast algorithm that determine if an 8 bytes string is NOT present in a database of strings where each string is also 8 bytes in length. There are a couple of hundred millions of strings in the database. There may be clusters of strings in the database. I am thinking of using the Aho Corasick algorithm, but I hopethat there may be faster technique.

Many thanks for your help.

More Patterns in a single example

I'm looking for an example on the application of more design pattern(gof) in a single example! Could you help me? I need to have a class diagram of the example. I can't find anything!!

C++ Factory with inheritance

Currently I am in a project where I need to dynamically add and remove sensors to a hardware (Arduino).

In order to do that, I have created a base class named "Sensor" and derivated class for each sensor. This "sensor" class has a virtual method called execute, and this method in overriden on each derivated class, due that each sensor is different, so a different execution implemantation is needed for each type. In this example, I used PIR and DTH11 has derivated classes.

When a sensor needs to be added, the hardware will recieve a string from a server, and from this recieved string, it will create the appropriate sensor. In order to simplyfy things in this questions, I just did it manually on the main() method.

To store the sensors, I am using a std::list, and from time to time, the method execute() will be called.

However, the method of the base class (Sensor) is always executed instead of the delivered classes as shown on the results and expected results below.

class Sensor 
{
    protected:
        int GPIO;
        char* name;   
    public:
        virtual void execute() {std::cout << "This is sensor"} ;
        int getGPIO() const;
        void setGPIO(int);
        char* getName() const;
        void setName(char*);
        Sensor(int sensorGPIO, char* sensorName) {//};
};

class PIR : public Sensor {
    public:
        void execute(){std::cout << "This is PIR"};
        PIR(int gpio) : Sensor(gpio, "pir"){//};
};
class DHT11 : public Sensor {
    public:
        void execute() {std::cout << "This is DHT11"};
        DHT11(int gpio) : Sensor(gpio, "dht11"){//};
};

class SensorFactory 
{
    public:
        SensorFactory(){};
        Sensor createSensor(char* sensorString, int gpio)
        {
            if(strcmp(sensorString, "pir") == 0)
            {
                return PIR(gpio);
            }
            else if(strcmp(sensorString, "dht11") == 0)
            {
                return DTH11(gpio);
            }
        };
};

int main()
{
     std::list<Sensor> sensors;
     SensorFactory factory();
     Sensor s1 = factory.createSensor("pir", 10);
     Sensor s2 = factory.createSensor("dth11", 12);
     sensors.push_front(s1);
     sensors.push_front(s2);

     std::list<Sensor>::iterator i = sensores.begin();
     while (i != sensores.end())
     {
         (i)->execute();
         ++i;
     }

     /* Expected results
        This is PIR
        this is DHT11
     */

     /* Result 
        This is sensor
        This is sensor
     */
}

I have also tried this:

class Sensor 
{
    protected:
        //
    public:
        virtual void execute() = 0;
        //
};

But I get this error:

invalid abstract return type for member function 
Sensor SensorFactory::createSensor(char*, int)

Please keep in mind that I am relatively new to C++, so possibly this is not the approach (implementation) for this problem.

generic repository pattern ,any alternative?

I have read many pages regarding repository pattern,tons of them are online and each of them starts with we should use it because it makes the application testable and also separation matters,but i also see many opinions against this pattern,or also they say its depends on the application which approach to take,all in all the thing is implementation of the logic must be kept away from controller,can anyone tell me how can i do it if generic repository is not the first option?im new in entity framework

Are cascading drop down lists an example of keeping state?

If I have a page with three cascading dropdownlists, is that an example of controlling the state of a web application (assume it is part of a larger application)?

I want to make sure I understand state management and the need for a system like Vuex and Redux and having the store pattern, one singleton to run it all through, reducing complexity, and so on I know the React and Redux folks said it'd be like wearing glasses, you know if you need them, and in addition, this could be done quite easily with no framework.

But, in general, is the usage of a cascading dropdownlist an example, albeit incredibly simple, of keeping track of "state"?

For reference of a dropdownlist see, How to populate a cascading Dropdown with JQuery

jQuery(function($) {
    var locations = {
        'Germany': ['Duesseldorf', 'Leinfelden-Echterdingen', 'Eschborn'],
        'Spain': ['Barcelona'],
        'Hungary': ['Pecs'],
        'USA': ['Downers Grove'],
        'Mexico': ['Puebla'],
        'South Africa': ['Midrand'],
        'China': ['Beijing'],
        'Russia': ['St. Petersburg'],
    }

    var $locations = $('#location');
    $('#country').change(function () {
        var country = $(this).val(), lcns = locations[country] || [];

        var html = $.map(lcns, function(lcn){
            return '<option value="' + lcn + '">' + lcn + '</option>'
        }).join('');
        $locations.html(html)
    });
});

Should I avoid making private field variable public for convenience?

I have two objects, A and B. Right now, B stores A as a local class variable.

class B
{
    A myA;
} 

Now, B has a bunch of methods which uses its inner myA to do some stuff, and I can use those methods since they are public.

But sometimes, I need to use the myA itself. So what I did was to make it public, and then I could write myB.myA.someMethodFromA().

Is this okay, or is it bad style? I mean, I know that I could just provide indirect accessors to myA via methods in the B class, but that seems unnecessary when I can just directly access myA.

For example, if myA has a method doStuffviaA, I'd rather say myB.myA.doStuffViaA(), than first having to write a method in B that says

void doStuffViaB() { myA.doStuffViaB() }

But, of course making myA public means that it can be changed without B knowing about it. WHAT TO DO?

Comment to the paragraph of the book, how to design database and any code patterns applyable?

Hello to the developers!

I've came into problem, while trying to develop a commentary module of the site. The main problem is the following: I have a task - to make an ability for users to make a comments to paragraph of the text, but I have no ideas, how to create a database structure for that.

Now we have four main entities in our system, which makes matter on this block: book, chapter (which in our case is called "part"), comment and user. So, user opens a book, on particular part, selects a word or a sentence in on a pages and writes a comment, or just read the comments, which are applied to the paragraph where this word or a sentence are contained.

Thanks a lot!

lundi 29 octobre 2018

Javascript | Difference between module patterns

I have a little bit of confusion understanding these module patterns what I understand is the 1st one is just like a class whenever you need it just assign to a new variable.

In 2nd one, we encapsulated our module we don't have access to globals except that we pass to the module as an argument, we also cannot pass any argument to the module when assigning to it variable like module(args) because it is an IIFE, if we want to use it as a class then we have to return the function not object.

In 3rd I think it just works like a singleton.

It would be also good to know the use cases for these patterns.

1

const module = function(args) {
     const exports = {}

     const privateMethod = () => {}

     const exports.publicMethod = () => {}

     return exports;     
}

const instance = module(args)

2

const module = (function(globals) {
     const exports = {}

     const privateMethod = () => {}

     const exports.publicMethod = () => {}

     return exports;     
})(globals)

const instance = module;

3

const module = module || {}

(function (module) {
     const privateMethod = () => {}

     module.publicMethod = () => {}
})(module)

module.publicMethod()

tasks design pattern with condition in rust

I am creating a web server in which the interface is a JSON object that contains a type filed that indicates the task type to run. I was wondering if there is design pattern or a module that is commonly used to solve this problem.

Object-Oriented Design Principles & Patterns- looking for solution for sample paper

looking for a solution to the following sample question.... new to this site so please forgive me if this isnt the correct way to ask a question. Grateful for any help. uml diagram

The following UML diagram shows a suite of classes in an application:

link to uml diagram:

You are required to implement the design shown in the UML diagram as a set of Java classes. Please note the following: • Use the package ie.gmti.sw for all classes. • All classes should over-ride their finalize() and toString() methods to output their Object ID and class name. • The class TypeatorContainer should enforce set behavior on the fully encapsulated instances of Typeator, i.e. it should maintain a unique collection of Typeator instances. • The class DefaultTypeator should have instance variables for name and date (constructor parameters). • The class TypeatorRunner should instantiate and exercise all the methods of TypeatorContainer and TypeatorFactory

Advanced Object-Oriented Design Principles & Patterns looking for solution

Have an exam wednesday and am looking for a solution to this sample paper...would be very greatful.

Here is a link: https://learnonline.gmit.ie/pluginfile.php/219634/mod_resource/content/1/oodppAssessment1-GroupA-2017.pdf

When to use The Messenger Pattern in MVVM design

I Got confused with the role of the Messenger in MVVM, as I see contradicting articles about it.

This Article by MSDN by:

Communicating from the View-Model to the View
Observant readers will notice that Figure 1 has one arrow missing: in this figure, there is no way for the View-Model to communicate with the view. As mentioned earlier, the View-Model should ideally have no knowledge of the view that it is attached to. In fact, it is very common for a given View-Model to be attached to multiple views—for instance, because one view might become too complex and be split into two pages. To guarantee flexibility, the View-Model must have only an abstracted knowledge of what the view can do.
There are multiple ways to solve this issue. The two solutions that I propose here are using MVVM Light’s Messenger class and using view services.

generally saying that the messages should be from the View-Model to the View in case needed.

Also in this article, it warns from using the Messenger widely as it causes code to be less readable (which I agree with)

But on Another Article
It's used differently to communicate messages between View-Models

UML Diagram showing Messenger communication between View-Models

In this scenario, i didn't get the "Why VM cant have reference to another VM?"
as the referenced View-Model can easily be mocked and tested.

What should the UnitOfWork pattern be actually handling

What should a UoW be actually handling ?

The way I see it, the UoW should not be handling commits and rollbacks. It should just provide means to do so, and should only be responsible with tracking changes on objects that are about to be committed such that if they are in some inconsistent state or something has changed, the transaction should fail ?

So the way I see a UoW is something like this.

interface IUoW : IDisposable 
{
    SqlConnectionProvider Connection { get; }

    IAtomicTransaction StartTransaction();
}

So the IUoW concrete implementation should handle only connection to a SQL Provider and keeping track to any changes

Committing should be something like this

interface IAtomicTransaction : IDisposable 
{
    void Commit();

    void Rolleback();
}

Is this true ? or I just didn't understand the purpose of a UoW ? The thing is that I see that UoW does everything in lots of posts and I don't fell it should do so.

Specific pattern to list files in R

I have an issue when matching a very specific pattern when using list.files. I have a set of files with this pattern "namefile_YYYY-mm-dd.csv", but also, if a file was generated more than one time then I will have something like this: "namefile_YYYY-mm-dd_something-else.csv". This is what I used:

list.files(path = "\\projects\\datasets", pattern = "^Participants_(.*)csv$",all.files = FALSE, full.names = FALSE, recursive = FALSE)

This is the output: "Participants_2018-07-18.csv" "Participants_2018-07-19.csv" "Participants_2018-07-21.csv" "Participants_2018-07-28.csv" "Participants_2018-08-04 new.csv" "Participants_2018-08-04.csv" "Participants_2018-08-11.csv" "Participants_2018-08-18 - for-analysis.csv" "Participants_2018-08-18.csv" "Participants_2018-08-25.csv" "Participants_2018-09-01.csv" "Participants_2018-09-08.csv"

But I don't want all of them. I would like the list includes only the names in this format "Participants_2018-07-18.csv" and exclude the names in any other format like this one: "Participants_2018-08-04 new.csv", "Participants_2018-08-18 - for-analysis.csv"

I tried several things like

list.files(path = "\\projects\\datasets", pattern = "^Participants_[0-9]\\.csv$",all.files = FALSE, full.names = FALSE, recursive = FALSE)]

But the list came empty. Any advise?

Python best practice for object creation

I'm stuck with the best way to create the following object:

I need a dictionary to be returned in the creation of the object. I could have used only one function, but the reality is that with the parameters that are passed in the creation of the object certain operations are performed.

This is the situation:

class Example(object):
    def __init__(self, param_a, param_b, param_c):
        self.a = param_a
        self.b = param_b
        self.c = param_c

        _tmp_1 = self._complex_function_1()
        _tmp_2 = self._complex_function_2()
        _tmp_3 = self._complex_function_3()

        # I need here to return a dictionary. Now I'm saving the 
        # result in a variable call "self.values" and then access to
        # it from the object created, but I don't like this approach...

        def _complex_function_1():
            # Make some calculations using "self"

        def _complex_function_2():
            # Make some calculations using "self"

        def _complex_function_3():
            # Make some calculations using "self"

And when I use it, I have to do the following:

e = Example(a, b, c)

dict_values = e.values

In short: What I want is for Example to return a dictionary. I do not think it's convenient to do it as separate functions because the methods are specific to Example to convert them into functions, and also because they use the parameters of self.

Any suggestions?

Modeling and entity with field uniquely identifying the state of an object

I have the following question.

I have the following case. A reservation, this reservation be canceled, it can be newly created it can be Confirmed.

There might be different reasons for cancelation. Lets say the reservation has expired, or it may have not been processed within certain timelimit or some other reason.

In order for a reservation to be confirmed a multiple sub - transactions should be performed. This mean that there is a flow within the Confirmation itself. The solution my team came with is some sort of work table holding many different statuses. Which is fine. I felt the need to uniquely identify the state of a reservation by declaring a field ReservationStatus that depicts certain variation of statuses that are already defined in the table. In this case the Reservation status would be NEW,CONFIRMED,CANCELED,REJECTED. Each state will depict certain variation of statuses in the work table.

My team was convinced that this is adding additional complexity. I think this is the opposite it simplifyes the flow. It also declares a natural discriminator and polymorphism. We are supposed to use Queues and asynchroneus processes.

How can I actualy jsutify that we should have such column it apears the arguments I already mentioned were not enough?

OLOO vs. OO in reactjs front-end web dev

I read Kyle's book, and I found it really informative. But I am a little confused on the discussion in "You Don't Know JS: this & Object Prototypes".

That series say that Object Linking to Other Object design pattern is cleaner and simpler then object oriented design pattern. I do agree with this.

But I notice that many react code snippet prefer using ES6 class keyword which represents object oriented code style.

Is injecting a Factory into consumer a bad idea?

I have a factory to build cars... It a basic factory, it accepts name of a car, looks for all classes that implement ICar, chooses the correct type based on car name and initializes the car.

public class CarFactory
{
    Dictionary<string, Type> cars;

    public ICar CreateInstance(string carName)
    {
        // choose type of class from all classes that implement ICar 
        Type t = GetTypeToCreate(carName); 

        return Activator.CreateInstance(t) as ICar;
    }

    // some more code...
}

Now, I have a service which uses CarFactory. What is the right way to initialize CarFactory in my service?

Should I inject it? I feel this is the best solution except that Factory Pattern is a form of IoC itself and I am not sure if it is a good idea to inject a factory into the consumer class?

public class SomeService : ISomeService
{
    private CarFactory _carFactory;

    public SearchService(CarFactory carFactory)
    {
       _carFactory = carFactory;
    }

    // more code...
}

If injection of a factory is a bad idea, should I use static factory? or just instantiate it in the constructor?

dimanche 28 octobre 2018

what the essential difference between akka and ThreadPool+BlockingQueue in ONE Process?

We know Akka is one implementation of actor pattern. Without Akka, I usually implement a simple actor pattern using ThreadPool+BlockingQueue. So the message is offered into the queue, and the works(actors) take the message from the Queue, then do what they should do. Of course, this kind of implementation can be only in just ONE process.

So as to in one process,

  1. What's the essential difference between these two(Akka vs. ThreadPool+BlockingQueue)
  2. Moreover, what's the difference between actor pattern and producer-consumer model?

How do you adhere to MVC model observations without making the UI feel laggy?

If you're being a stickler about MVC, you are supposed to update the views in a UI in response to changes pushed out from the model. This is usually done by setting up an observation on the model in the controller, then updating the view from the controller.

Imagine you have an iOS app with a UISlider on screen. The user is aggressively dragging the slider back and fourth. Each of these events is triggering a model change.

For every one of these events, you would need to notify the model of the change, let the model push that change out to the controller, and update the view from the controller.

  • In the best case, this whole process is synchronous. That is, a new user touch-event is not processed until the main thread is totally done handling the first event, processing the change and updating the view. I'm not even sure this statement is true (is it all synchronous?). Assuming it's synchronous, the worst thing that can happen is the slider feels laggy if this whole round trip is costly to perform.
  • Next case, assume the process is not synchronous; The touch event updates the model, then asynchronously the model notifies the controller of the change. Or perhaps the model rejects the change and does not notify at all. In this case perhaps the slider moves due to the view updating itself but then jumps to a new location due to the model->controller telling it to.
  • Worst case: Adjusting the slider actually causes the app to send a message to some other process or maybe to the network. The app then asynchronously gets confirmation of the change from the remote side at some later point and pushes this change to the controller->view.

How should apps keep their UI responsive while at the same time observing model changes to ensure views don't get stale?

Design Pattern using generics

I have a series of interfaces that represent geometry entities. I want to extend these by providing some extra functionality called Stretch.

I want a method to pass a Curve and a Boundary and then get the resulted curve stretched to that boundary or nothing.

I have developed a mechanism like this to make it a general operation.

StretchOperations gets a Curve and a list of Stretchers. Then when we run the Stretch method on this class, it goes through its list of Stretchers and tries to stretch this Curve to the given Boundary.

I have came up with this pattern myself and it seems a bit odd to me! I was wondering if there is a similar design pattern, how can I improve this design.

I do not want to change the interface of my geometry objects though.

public class StretchOperations
{
    private IList<IStretcher<object, object>> m_stretchers { get; } =
        new List<IStretcher<object, object>>();

    private readonly ICurve3D m_curve;


    public void Add<TCurve, TBoundary>(IStretcher<TCurve, TBoundary> stretcher)
    {
        m_stretchers.Add(stretcher as IStretcher<object, object>);
    }


    public Operations(ICurve3D curve)
    {
        m_curve = curve;
    }


    public TCurve Stretch<TCurve, TBoundary>(TBoundary boundary) where TCurve: class 
    {
        foreach (var stretcher in m_stretchers)
        {

            var res = stretcher.Stretch(m_curve, boundary);
            if (res != null)
                return (TCurve) res;
        }

        return null;
    }
}

public interface IStretcher<TCurve, in TBoundary>
{
    TCurve Stretch(TCurve curve, TBoundary boundary);
}

public class ArcStretcher : IStretcher<IArc3D, ILine3D>
{
    public IArc3D Stretch(IArc3D curve, ILine3D boundary)
    {
        // Extends the arc till it reaches the boundary.
        return null;
    }
}

samedi 27 octobre 2018

How to reconcile microservice "share nothing" principle with "independence"

Let's say my entire domain has entities like

[
   {
      id: 1,
      name: "Joe",
      age: 16,
      hometown: "Los Angeles",
      friends: [2]
   },
   {
      id: 2,
      name: "Jack",
      age: 83,
      hometown: "Phily",
      friends: [1, 3]
   },
   {
      id: 3,
      name: "Susy",
      age: 50,
      hometown: "Dayton",
      friends: [2]
   }
]

and I decide to have 2 separate services

  1. Person Info Manager
  2. Friend Manager

to deal with these entities. The way I would literally interpret "share nothing" would be have that each service has storage like

[
   {
      id: 1,
      name: "Joe",
      age: 16,
      hometown: "Los Angeles"
   },
   {
      id: 2,
      name: "Jack",
      age: 83,
      hometown: "Phily"
   },
   {
      id: 3,
      name: "Susy",
      age: 50,
      hometown: "Dayton"
   }
]

for 1. and

{
    1: [2],
    2: [1, 3],
    3: [2]
}

for 2. So basically the overall information has been partitioned into being stored in 2 places (except the ids which I guess are shared).

Here are some potential problems that I see with this:

  • In the case of the Friend Manager service, since all you have is ids, there is probably nothing useful that can be done in overall system without combing information from this service with information from Person Info Manager service.
  • To follow the previous point, let's say that we want a UI where users can manage friend ships. Then we will need to query the Friend Manager Service to get this information and perform "joins" by id. This means that Friend Manager Service has a dependency on Person Info Manager service, or there is some third service that has a dependency on both.

To remedy those potential problems (I'm not sure they are real problems; that's why I am asking S.O.) we could have that they share more data. Let's say that you need at minimum to know a person's name in order to manage friendships. Then we could have

{
    info: {
        1: {
          name: "Joe"
        },
        2: {
          name: "Jack"
        },
        3: {
          name: "Susy"
        }
    },
    friendships: {
        1: [2],
        2: [1, 3],
        3: [2]
    }
}

so that now the Friend Manager service can work independently. Some potential downsides with this are

  • Extra storage cost from duplicate data
  • The names in in Friend Manager service could be stale because of lag in receiving updates from the Person Info Manager service or because of error. Whereas if the Friend Manager service were to query Person Info Manager service for names whenever needed, then it would always have the up-to-date info (the query could also account for persons who have been removed).

What is meant by run time dynamically in Decoaration Design pattern?

While studying more than one article about Decoration Design Pattern, I noticed that all of the articles talk about Decoration enables us to create additional features dynamically at runtime and create objects dynamically at runtime. I totally understand the Decoration pattern, But I can't find a clear way for understanding what is meant by dynamically? and if it not made in runtime, how it originally made?

Second Question, what is meant by this sentence? I need example telling me that this is dynamic and this is static, and this is runtime and this is a compile time.

Inheritance is the first solution that comes to mind when you need to extend class behaviors. However, the inheritance is static. You can not add new subclasses to a program when it is already compiled and executed.Ref

Third question : I need an article or description of for example this is a way object made in runtime or not and this is a way it made dynamically and this isn't

Refs :

  1. Tutsplus
  2. Laracsts video
  3. Wiki

Singleton Polymorphism

Let's assume that i have singleton respresentation of chess board consist of double dimnesion array of cells. Sometimes I want that representation to be consider as board of rows, sometimes as colmumns, sometimes as grids, but every of this case must work on the same underlying singleton of board

So i have 4 class to implement:

class CheesBoard : singleton consist of just a stright dd array of cells
class CheesBoardAsGrids : consist of that same cells but presented by grids
class CheesBoardAsRows : strigtforward as above but rows
class CheesBoardAsColumns : ... you already get it

And i dont know how to implement it to be the most readable and reusable

javascript good way to create or design Singleton class

I think in javascript it could create Singleton class like below

test.js
class Container {
    constructor() {
      this.map = new Map;
    }

    set(key, value) {
      this.map.set(key, value);
    }

    get(key) {
      return this.map.get(key);
    }
  }
module.exports.Container = new Container();

so that I could use that other files like in index.js

import container from './test'

However the constructor of Container need some other parameters so that it could do better. And the Container also need to be Singleton class , because it is a common class . And i do not know how to create it?

constructor(servie) {
      this.map = new Map;
      this.servie = servie;
    }

by the way the service variable is created when application starts

Implementation of Adapter Design Pattern with C#

I am trying to implement Adapter Design pattern with C# on example of coffee App which A student is trying to develop a small app where as soon as his alarm rings, the coffee machine automatically prepares a cup of coffee for him. Use Adapter pattern to design this app.

I tried some code which are available online but i failed to execute them . could some one help me out .

How can python find decorated functions within it?

In the following code how does app.run() find that hello() exists? I browsed the code and couldn't find the answer. I think the hello() doesn't get added to a list of routes until it is called, but how does it get called?

from flask import Flask
app = Flask(__name__)

@app.route("/")
def hello():
    return "Hello World!"

if __name__ == "__main__":
    app.run()

I'm not interested in Flask in particular. I'd just like to implement something similar myself.

What is this design pattern called?

vendredi 26 octobre 2018

Creating a tokenizer using the method Split

I'm trying to create simple tokenizer that splits on whitespace, lowercases tokens, removes all nonalphabetic characters, and keeps only terms with 3 or more characters. I write this code, it´s all ready work on lowercases, nonalphabetic characters and only keeps 3 or more characters. But I want to use the method split, but I don't know how. Please suggest something.

public class main {

 public static final String EXAMPLE_TEST = "This Mariana John bar Barr "
        + "12364 FFFFF aaaa a s d f g.";
public static void main(String[] args){


   Pattern pattern = Pattern.compile("(\\s[a-z]{3,20})");
    Matcher matcher = pattern.matcher(EXAMPLE_TEST);
    //
    while (matcher.find()) {
        System.out.print("Start index: " + matcher.start());
        System.out.print(" End index: " + matcher.end() + " ");
        System.out.println(matcher.group());

    }

}

}

BASH Pattern in IF-Then_Else

I have a Regex that I got to work in a sed search/replace line, but I can't get the Regex to work in an If-Then-Else. This is my sed line:

YELLOW="\033[1;33m"
OUTPUT[0]="$YELLOW ==================================+==================================="
cLEN=${OUTPUT[0]}
cLEN="$(echo $cLEN | sed 's/\\[[:digit:]]\+\[[[:digit:]];[[:digit:]]\+m//g')"

However now I am trying to make an if condition and I can't get the syntax right. I need it to evaluate from the beginning of the line $cLEN

if [[ $cLEN  =~ '^\\[[:digit:]]\+\[[[:digit:]];[[:digit:]]\+m\s' ]]; then
        echo true
    else
        echo error
        exit 1
fi

Loop through Interfaces of an object

I'm creating a generic Service Locator, but have a problem. I have a method to add or replace a service. The service has to be replaced if there is only 1 candidate in the current service list.

// IA  - TestA
// IB  - TestB
// IA/IB - TestAB
// <IB> TestAB 
public static void AddOrReplaceService<T>(T serviceToAdd) where T:  class
{
    if (serviceToAdd == null)
        throw new ArgumentNullException(nameof(serviceToAdd));
    List<T> foundServices = new List<T>();
    int index = -1;
    for (int i = 0; i < _services.Count; i++)
    {
        if (!(_services[i] is T) 
            && !_services[i].GetType().IsAssignableFrom(typeof(T))
            && !_services[i].GetType().IsInstanceOfType(serviceToAdd)
            && !serviceToAdd.GetType().IsInstanceOfType(_services[i]))
            continue;
        foundServices.Add((T) _services[i]);
        if (index == -1)
            index = i;
    }
    switch (foundServices.Count)
    {
        case 0:
            AddService(serviceToAdd);
            break;
        case 1:
            _services[index] = serviceToAdd;
            return;
        default:
            throw new MultipleServicesAlreadyExistsException("Multiple services found with " + typeof(T).Name
                                                + foundServices.ToStringCollection(", "));
    }
}

To test my Service Locator I have 2 interfaces IA and IB and 3 classes, TestA : IA, TestB : IB and TestAB : IA, IB

The thing is if both TestA and TestB are in the list and you try to add TestAB it should give an exception because both TestA and TestB are implementing interfaces of TestAB.

I tried to add a bunch of AssignableFrom etc. logic. However, I can't get it to work.

Help would be much appreciated! Thanks in advance.

Pattern JavaScript to validate password strength in Angular

form: FormGroup = new FormGroup({
   clave: new FormControl('', [Validators.required, Validators.pattern("^(?=.*?[A-Z])(?=.*?[a-z])(?=.*[0-9])(?=.*[$@$!%*?&\\.\\-\\_])[A-Za-z\d$@$!%*?&\\.\\-\\_].{7,}$")])
});

This pattern validates the strength of a password, regardless of the order in which the conditions are met.

Minimum requirements:

  1. A character in lowercase
  2. A Character in uppercase
  3. A number
  4. A special character
  5. Minimum 8 characters

I hope it will be you useful.

regards.

Resource Management Design Patterns

Various APIs require calls to initialization and finalization methods. Most recently I've come across this while using the Python C++ API, where all API calls must be between calls to Py_Initialize and Py_FinalizeEx. My current solution is to put such calls at the beginning and end of the main method. This does not seem ideal, as it separates the actual usage of the API from it's resource management. That is, the software components which make API calls rely on the main method to acquire and destroy the resources.

Is there a pattern that is usually applied in such a scenario?

Constructive comments requested for the following Akka design pattern

I have recently joined an organisation using Akka for a major project. The organisation is not rich in experience with Akka but has been using it for a year. I have been working on the project for 3 months.

We are proposing to implement the following pattern using Akka.

enter image description here

Essentially we are looking to use Akka to provide thread safety and good concurrency . But we wish to separate the handling of business logic entirely from actors by placing all of it in delegates across a Task interface. The Task interface will correspond directly to the messages handled by the actor with a 1 to 1 mapping between messages the actor receives and methods on the interface. This interface will sit in front of the delegate and in front of the Actor thereby hiding the knowledge of messages sent between actors entirely. The Actor and delegate form a 'Parent - Child' relationship. Where the delegate needs to invoke Akka behavior it can do so by calling its 'Parent' across a Parent interface specifically for that purpose. The Actor inherits from ParentActor which implements the Parent interface. All classes in the system will follow this pattern and collaborate across these Task interfaces. The way we see it is that we have the flexibility to swap implementations of the Task interface and when new messages need to be implemented the act of adding a new method to the Task interface enforces the implementation of it in the delegate and the actor. We can also unit test the delegate completely independently of Akka.

May I respectfully request some thoughtful opinions on the pros and cons of this approach.

Java Design Pattern for different variation of same input to be converted into common output

I have a scenario where there is a service aggregator, lets take for example skyscanner or kayak or Google flights. If you see, they all ask basic details like what is source, destination, date and number of passengers, once you select the flight from a particular service provider, let's say for example expedia, you are are redirected to expedia with prefilled details that was sent across by service aggregator

Now the name of parameters sent from the source system may vary and on the destination we have to convert it into same POJO.

One option I was thinking of was Factory pattern, based on channel, I would return an object which would transform the source params to a common POJO.

Other design pattern that I feel similar is Strategy Design Pattern, to create a ExtractionStrategy based on Context

Is there any other apt design patter to solve this problem?

jeudi 25 octobre 2018

Creating a Wrapper for MongoDB POJO

So I want to take advantage of the MongoDB drivers ability to store PJOS. Example Here. But I plan on having multiple classes stored to the database, and I don't want to have to retype all of the connection code every time, nor do I want to copy and paste and then minorly modify the code for each class. I had the idea to make a "Collection" class, and then extend that, but it's not quite working how I intended. Here is my code:

public class Collection {
    private MongoCollection<Collection> collection;

    public Collection(){}

    public Collection(String databaseName){
        databaseName = databaseName.toLowerCase().replaceAll(" ", "");
        CodecRegistry pojoCodecRegistry = fromRegistries(com.mongodb.MongoClient.getDefaultCodecRegistry(),
                fromProviders(PojoCodecProvider.builder().automatic(true).build()));
        MongoClientURI connectionString = new MongoClientURI("my-mongo-connection-string");
        com.mongodb.MongoClient mongoClient = new com.mongodb.MongoClient(connectionString);
        MongoDatabase database = mongoClient.getDatabase(databaseName);
        database = database.withCodecRegistry(pojoCodecRegistry);
        collection = database.getCollection(this.getClass().getName(), Collection.class);
    }

    public Collection findOne(Document document){
        return collection.find(document).first();
    }

    public void save(){
        collection.insertOne(this);
    }

}

As you can see, I want to be able to pass in the database name to any class that inherits from this class (Or whatever the right thing to do is.), and have my code connect to the database and find or save a POJO of the respective sub-class properly. So for example, if I had a Person class with a phone number, I could just extend my Collections class and count on everything to work. Right now, when I call the save function on a child class, it tries to save the parent Collection, and I get an error Can't find a codec for class Utils.MongoDb.Collection. (My Collection class is in my own Utils.MongoDb namespace). Am I just missing something? Is there a better way to go about this? The only way I can think to get this to work is copy and paste the code in my Collection constructor into each class, and modify it with the right class variables. I hope all of this is clear. Thanks in advance!

why in singleton, check class==null?

    static CMyStatic* myStatic = nullptr;


    CMyStatic* CMyStatic::getInstance(){
        if(myStatic==nullptr)
                myStatic = new CMyStatic;
        return myStatic;
    }

if I make singleton, in getInstance() function,

check class pointer is null. like this code.

I understandiong static object is only making one, isn't it?

then, if i didn't check myStatic==nullptr,

always make myStatic = new CMyStatic,

myStatic isn't making, isn't it?

or my understanding is wrong?

Is JavaBean an Anti-Pattern? [on hold]

I read using JavaBeans have serious disadvantages. JavaBeans may be in an inconsistent state partway through its construction. JavaBeans pattern precludes the possibility of making a class immutable and also requires added efforts on the part of the developer to ensure thread safety.

So should we avoid using Java Beans?

Combine Inheritance and Composition - Design Pattern

Sorry for the unclear Title. I have a following scenario:

I have 4 types: Type1, Type2, Type3, Type4. (which have same structure: name and children)

I have other 4 types of children: Child1, Child2, Child3, Child4. (which in turn have the same structure: parent and value).

Condition: Type1 can have only children of type: Child1; Type2->child2 and so on.

If I use Inheritance for this case: all of types inheritate from SuperType and all of children inheritate from Children.

public class Children{

}
public class SuperType{
private List<Children> children;
}
public class Type1 extends SupperType{}
public class Child1 extends Children{}

Type1 can have children from Child2, Child3, Child4. That's not what I want.

Do you have any idea about pattern designs which I could use for this case?

mercredi 24 octobre 2018

Setting object values in php factory or factory method

I have a little question, is setting values in factory method correctly ?

Something like this:

class ObjectFactory {
     public static function create($config)
     {
          $object = new Object();
          $object->setDependency(// something);
          $object->setValue(// something);
          return $object;
     }
}

Is it correctly? Maybe it should be builder? How should i call it? ObjectBuilder, ObjectFactory, or maybe ObjectCreator?

Please explain me cases of creating object with some dependencies or initial values. I know it should be builder pattern but i heard that builder is something advanced than just returning object with few initial values or dependencies. So... what's the solution?

which design pattern to use in this case?

Users separate waste by types and place it in the specific containers. Users can be small, medium or large. Users are organized by the streets. In a particular street, users are not individually assigned, but their number per category (small,medium,large) in the street is based on the share of a particular category in the total number of places in the street. The user, based on his own category, uses bins (cans or containers) for certain types of waste. The user charges some types of containers independently while others are shared with a certain number of users (groups) of their categories

Number of users of each category is determined for each street (users are created and unique identifier is assigned to each user). After that, types of containers are assigned to an individual user or group of users. Unique identifier is assigned to every container, as well as which user or group of users is going to use it.

I have to choose between Abstract Factory, Factory Method, Builder, and Prototype, does anyone know which one can I use??

Python3: How to improve a complicated class hierarchy to better access some objects buried in there?

I have a complicated class hierarchy in which the classes are similar to each other but every class contains a bunch of more or less complicated stateful variables. To give you an impression, please have a look at this minimal working example:

class OptVar:
    """
    Complicated stateful variable
    """
    def __init__(self, **kwargs):
        self.parameters = kwargs


class OptVarContainer:
    """
    Class which contains several OptVar objects and nested OptVarContainer
    classes. Is responsible for OptVar management of its sub-OptVarContainers
    with their respective OptVar objects.
    """
    def __init__(self, **kwargs):
        for (key, value_dict) in kwargs.items():
            setattr(self, key, OptVar(**value_dict))


class C(OptVarContainer):
    """
    Specific implementation of class OptVarContainer
    """
    def __init__(self):
        super(C, self).__init__(
                **{"my_c_a": {"c1": 1, "c2": 2},
                   "my_c_b": {"c3": 3, "c4": 4}})


class B(OptVarContainer):
    """
    Specific implementation of class OptVarContainer
    """
    def __init__(self):
        super(B, self).__init__(**{"b": {"1": 1, "2": 2}})
        self.c_obj = C()


class A(OptVarContainer):
    """
    Specific implementation of class OptVarContainer
    """
    def __init__(self):
        super(A, self).__init__(
                **{"a1": {"1": 1, "2": 2},
                   "a2": {"a": "a", "b": "b"}})
        self.b_obj = B()


def main():
    # creating OptVarContainer with some nested OptVarContainers.
    my_a_obj = A()
    # It is intended behaviour to access the OptVar objects via
    # scoping within the class hierarchy.
    print(my_a_obj.b_obj.b.parameters)
    my_a_obj.b_obj.b.parameters["2"] = 3
    print(my_a_obj.b_obj.b.parameters)
    print(my_a_obj.b_obj.c_obj.my_c_a.parameters["c1"])
    my_a_obj.b_obj.c_obj.my_c_a.parameters["c1"] = 6
    print(my_a_obj.b_obj.c_obj.my_c_a.parameters)
    # Two major problems:
    # a) Serialization (with compatibility between different versions)
    # b) Access to all OptVar objects at once


if __name__ == "__main__":
    main()

The question is now: How to access the OptVar objects the best. I already thought about to use some kind of pool object and use some proxy within the class hierarchy to have a link to the pool. This pool should not be a singleton, since it should be possible to manage more than one pool at a time. Up to now the access to the OptVar variables within my own code are via some Python black magic and tranversing the classes in an recursive manner avoiding infinite loops by maintaining an id list. This is quite ugly and only considered temporary.

I am aware that no unique solutions exist for this design problem, but I need further input on that from you.

The full context of this question is here but after some discussions I separated the design part.

Design Patterns Question: Different types of filters for "Image Processor"

This is a strictly theoretical, architectural design patterns question:

Say we want to design a system that allows for different kinds of filters to be applied to images. In other words, an image processor.

What kind of design would you use?

I was thinking of the following: some kind of Factory for creating the concrete classes that extend/implement an abstract Filter object.

I'd appreciate any ideas about this job interview question.

(Another idea: template method for the filtering).

Best pattern to check conditions and show related messages in a ASP.NET MVC

I have a ASP.NET MVC 5 project including following parts:

Index View

@model IEnumerable<BusinessLogic.Process>
@*do something ...*@

Controller

public ActionResult Index(int processId)
{           
    return View(Fac.GetChildrenProcess(processId));
}

Facade class

public List<Process> GetChildrenProcess (int processId)
{
    Process process = new ProcessContoller().GetInfo(processId);
    if (process == null)
      return null;
    List<Process> children = new ProcessContoller().GetListByParentId(processId);
    return children;
}

ShowMessage

private ActionResult ShowMessage(string messageText, DisplayMessageType messageType)
{
    ViewBag.CssClass = messageType.ToString();
    ViewBag.MessageContent = messageText;
    return PartialView("_ShowMessage");
}

According to follow SOC pattern, I tent to check if condition if (process == null) in a class like Facade not in my controller (Index action).

But I cope with a problem to show message to user in best pattern. For example if processId is invalid in action, if (process == null) is true and I should show a message like Selected process is invalid. To show a message, I have a Partial view like _ShowMessage.

  • I can't check the condition if (process == null) in my controller because of following SOC pattern.
  • I can't show my message in Facade because is a class not a controller.
  • I can't return some Boolean value from GetChildrenProcess because it should return a List.
  • I can pass a Boolean value by ref and if (process == null) is false, I show my message. (I think it's bad pattern)

So, I am curies about best pattern for checking a condition that is similar to validation and showing a message.

Thanks in advance.

mardi 23 octobre 2018

C# Partial Class Usecases, Why/When to use it? [duplicate]

This question already has an answer here:

The partial class primary purpose I see is being able to split a class in many files. But what I am not able to visualize is what benefit would that do?

I would be really happy to see some comments and links to any articles.

Are there any implications in the design patterns, or any technical benefit of using it?

How can I access the payment date field which is inside 'paid' class in Linq

There is a field called factor statebase which we implemented using pattern strategy. This field has a default value of pendingfactorstate. We wish to access all factors that in paid state and their dates fall within a specific time interval. This payment time interval is 'new'ed inside the paidfactorstate when the payment is actually done and the new class is assigned to the state field.

My question is how can I access the payment date field which is inside 'paid' class in Linq?

Thank you,

public Factor(long id)
{
    Id = id;

    FactorStateBase = new PendingFactorState(Guid.NewGuid());
}

public void PayFactor(Guid id, string messageNumber, Guid paymentId, string transactionCode)
{
    FactorState=FactorState.Paid;
    FactorStateBase = new PaidFactorState(id, messageNumber, paymentId, transactionCode);
}

Clips pattern matching

I have a school project in CLIPS and I ecountered few problems with pattern matching. It is a Sokoban game in Rule Based System. Robot must push the box into warehouse, it can move up, down, right and left - those are the rules move-right etc. Then, if it ecounters a box next to itself, it is supposed to push it. If the box is next to warehouse, it should be pushed into it.

My code:

(defglobal ?*nod-gen* = 0)
(defglobal ?*sizex* = 0)
(defglobal ?*sizey* = 0)


(defrule board-fit
    ?f <- (board ?sizex1 ?sizey1)
   =>
   (bind ?*sizex* ?sizex1)
   (bind ?*sizey* ?sizey1))

(defmethod float ((?s STRING))
   (float (string-to-field ?s)))

(defrule move-right
    ?f1<-(robot ?x ?y boxes $?b1 ?bx ?by $?b2 warehouses $?w1 ?wx ?wy 0 $?w2 level ?lvl)
    ?f2<-(wall ?wl1 ?yl1)
    (max-depth ?prof)
    (test (< ?lvl ?prof))
    (test (not (> ?x ?*sizex*)))
    (test (and (neq (+ ?x 1) ?wl1) (neq ?y ?yl1)))
    (test (and (neq (+ ?x 1) ?bx) (neq ?y ?by)))
    (test (and (neq (+ ?x 1) ?wx) (neq ?y ?wy)))
    =>
    (retract ?f1)
    (assert (robot (+ ?x 1) ?y boxes $?b1 ?bx ?by $?b2 warehouses $?w1 ?wx ?wy 0 $?w2 level (+ ?lvl 1)))
    (bind ?*nod-gen* (+ ?*nod-gen* 1)))


(defrule move-left
    ?f1<-(robot ?x ?y boxes $?b1 ?bx ?by $?b2 warehouses $?w1 ?wx ?wy 0 $?w2 level ?lvl)
    ?f2<-(wall ?wl1 ?yl1)
    (max-depth ?prof)
    (test (< ?lvl ?prof))
    (test (neq ?x 0))
    (test (and (neq (- ?x 1) ?wl1) (neq ?y ?yl1)))
    (test (and (neq (- ?x 1) ?bx) (neq ?y ?by)))
    (test (and (neq (- ?x 1) ?wx) (neq ?y ?wy)))
    =>
    (retract ?f1)
    (assert (robot (- ?x 1) ?y boxes $?b1 ?bx ?by $?b2 warehouses $?w1 ?wx ?wy 0 $?w2 level (+ ?lvl 1)))
    (bind ?*nod-gen* (+ ?*nod-gen* 1)))


(defrule move-up
    ?f1<-(robot ?x ?y boxes $?b1 ?bx ?by $?b2 warehouses $?w1 ?wx ?wy 0 $?w2 level ?lvl)
    ?f2<-(wall ?wl1 ?yl1)
    (max-depth ?prof)
    (test (< ?lvl ?prof))
    (test (> ?y ?*sizey*))
    (test (and (neq ?x ?wl1) (neq (+ ?y 1) ?yl1)))
    (test (and (neq ?x ?bx) (neq (+ ?y 1) ?by)))
    (test (and (neq ?x ?wx) (neq (+ ?y 1) ?wy)))
    =>
    (assert (robot ?x (+ ?y 1) boxes $?b1 ?bx ?by $?b2 warehouses $?w1 ?wx ?wy 0 $?w2 level (+ ?lvl 1)))
    (bind ?*nod-gen* (+ ?*nod-gen* 1)))


(defrule move-down
    ?f1<-(robot ?x ?y boxes $?b1 ?bx ?by $?b2 warehouses $?w1 ?wx ?wy 0 $?w2 level ?lvl)
    ?f2<-(wall ?wl1 ?yl1)
    (max-depth ?prof)
    (test (< ?lvl ?prof))
    (test (not (= ?y 0)))
    (test (and (neq ?x ?wl1) (neq (- ?y 1) ?yl1)))
    (test (and (neq ?x ?bx) (neq (- ?y 1) ?by)))
    (test (and (neq ?x ?wx) (neq (- ?y 1) ?wy)))

    =>
    (assert (robot ?x (- ?y 1) boxes $?b1 ?bx ?by $?b2 warehouses $?w1 ?wx ?wy 0 $?w2 level (+ ?lvl 1)))
    (bind ?*nod-gen* (+ ?*nod-gen* 1)))


(defrule push-right
    ?f1<-(robot ?x ?y boxes $?b1 ?bx ?by $?b2 warehouses $?w1 ?wx ?wy 0 $?w2 level ?lvl)
    ?f2<-(wall ?wl1 ?yl1)
    (max-depth ?prof)
    (test (< ?lvl ?prof))
    (test (< ?bx (- ?*sizex* 1)))
    (test (and (neq (+ ?x 2) ?wl1) (neq ?y ?yl1)))
    (test (not (and (neq (+ ?x 1) ?bx) (neq ?y ?by))))
    (test (and (neq (+ ?x 2) ?wx) (neq ?y ?wy)))
    (test (neq ?x 0))
    =>
    (retract ?f1)
    (assert (robot (+ ?x 1) ?y boxes $?b1 (+ ?bx 1) ?by $?b2 warehouses $?w1 ?wx ?wy 0 $?w2 level (+ ?lvl 1)))
    (bind ?*nod-gen* (+ ?*nod-gen* 1)))

(defrule push-left
    ?f1<-(robot ?x ?y boxes $?b1 ?bx ?by $?b2 warehouses $?w1 ?wx ?wy 0 $?w2 level ?lvl)
    ?f2<-(wall ?wl1 ?yl1)
    (max-depth ?prof)
    (test (< ?lvl ?prof))
    (test (eq (- ?x 1) ?bx))
    (test (> 0 ?bx))
    (test (eq ?x 0))
    (test (not (and (neq (- ?x 2) ?wl1) (neq ?y ?yl1))))
    (test (and (eq (- ?x 1) ?bx) (eq ?y ?by)))
    (test (not (and (eq (- ?x 2) ?wx) (eq ?y ?wy))))
    =>
    (retract ?f1)
    (assert (robot ?x (+ ?y 1) boxes $?b1 ?bx (+ ?by 1) $?b2 warehouses $?w1 ?wx ?wy 0 $?w2 level (+ ?lvl 1)))
    (bind ?*nod-gen* (+ ?*nod-gen* 1)))

(defrule push-up
    ?f1<-(robot ?x ?y boxes $?b1 ?bx ?by $?b2 warehouses $?w1 ?wx ?wy 0 $?w2 level ?lvl)
    ?f2<-(wall ?wl1 ?yl1)
    (max-depth ?prof)
    (test (< ?lvl ?prof))
    (test (eq (+ ?y 1) ?by))
    (test (< 0 ?by))
    (test (neq ?y 0))
    (test (not (and (eq ?x ?wl1) (eq (+ ?y 2) ?yl1))))
    (test (and (eq (- ?x 1) ?bx) (eq (+ ?y 1) ?by)))
    (test (not (and (eq ?x ?wx) (eq (+ ?y 2) ?wy))))
    =>
    (retract ?f1)
    (assert (robot ?x (+ ?y 1) boxes $?b1 ?bx (+ ?by 1) $?b2 warehouses $?w1 ?wx ?wy 0 $?w2 level (+ ?lvl 1)))
    (bind ?*nod-gen* (+ ?*nod-gen* 1)))

(defrule push-down
    ?f1<-(robot ?x ?y boxes $?b1 ?bx ?by $?b2 warehouses $?w1 ?wx ?wy 0 $?w2 level ?lvl)
    ?f2<-(wall ?wl1 ?yl1)
    (max-depth ?prof)
    (test (< ?lvl ?prof))
    (test (eq (- ?y 1) ?by))
    (test (< ?by (- ?*sizey* 1)))
    (test (neq ?y 0))
    (test (not (and (eq ?x ?wl1) (eq (- ?y 2) ?yl1))))
    (test (and (eq (- ?x 1) ?bx) (eq (- ?y 1) ?by)))
    (test (not (and (eq ?x ?wx) (eq (- ?y 2) ?wy))))
    =>
    (retract ?f1)
    (assert (robot ?x (- ?y 1) boxes $?b1 ?bx (- ?by 1) $?b2 warehouses $?w1 ?wx ?wy 0 $?w2 level (+ ?lvl 1)))
    (bind ?*nod-gen* (+ ?*nod-gen* 1)))


(defrule push-right-to-wh
    ?f1<-(robot ?x ?y boxes $?b1 ?bx ?by $?b2 warehouses $?w1 ?wx ?wy 0 $?w2 level ?lvl)
    ?f2<-(wall ?wl1 ?yl1)
    (max-depth ?prof)
    (test (< ?lvl ?prof))
    (test (< ?bx (- ?*sizex* 1)))
    (test (and (eq (+ ?bx 1) ?wx) (eq ?wy ?by)))
    (test (and (eq (+ ?x 1) ?bx) (eq ?y ?by)))
    =>
    (retract ?f1)
    (assert (robot (+ ?x 1) ?y boxes $?b1 (+ ?bx 1) ?by $?b2 warehouses $?w1 ?wx ?wy 1 $?w2 level (+ ?lvl 1)))
    (bind ?*nod-gen* (+ ?*nod-gen* 1)))

(defrule push-left-to-wh
    ?f1<-(robot ?x ?y boxes $?b1 ?bx ?by $?b2 warehouses $?w1 ?wx ?wy 0 $?w2 level ?lvl)
    ?f2<-(wall ?wl1 ?yl1)
    (max-depth ?prof)
    (test (< ?lvl ?prof))
    (test (> ?bx 0))
    (test (and (eq (- ?x 1) ?bx) (eq ?y ?by)))
    (test (and (eq (- ?bx 1) ?wx) (eq ?wy ?by)))
    =>
    (assert (robot (- ?x 1) ?y boxes $?b1 (- ?bx 1) ?by $?b2 warehouses $?w1 ?wx ?wy 1 $?w2 level (+ ?lvl 1)))
    (bind ?*nod-gen* (+ ?*nod-gen* 1)))


(defrule push-down-to-wh
    ?f1<-(robot ?x ?y boxes $?b1 ?bx ?by $?b2 warehouses $?w1 ?wx ?wy 0 $?w2 level ?lvl)
    ?f2<-(wall ?wl1 ?yl1)
    (max-depth ?prof)
    (test (and (< ?lvl ?prof) (< ?by (- ?*sizey* 1))))
    (test (and (eq ?x ?bx) (eq (- ?y 1) ?by)))
    (test (and (eq ?bx ?wx) (eq (- ?wy 1) ?by)))
    =>
    (retract ?f1)
    (assert (robot ?x (- ?y 1) boxes $?b1 ?bx (- ?by 1) $?b2 warehouses $?w1 ?wx ?wy 1 $?w2 level (+ ?lvl 1)))
    (bind ?*nod-gen* (+ ?*nod-gen* 1)))

(defrule push-up-to-wh
    ?f1<-(robot ?x ?y boxes $?b1 ?bx ?by $?b2 warehouses $?w1 ?wx ?wy 0 $?w2 level ?lvl)
    ?f2<-(wall ?wl1 ?yl1)
    (max-depth ?prof)
    (test (and (< ?lvl ?prof) (> (float ?by) -1.0)))
    (test (and (eq ?x ?bx) (eq (+ ?y 1) ?by)))
    (test (and (eq ?bx ?wx) (eq (+ ?wy 1) ?by)))
    =>
    (retract ?f1)
    (assert (robot ?x (+ ?y 1) boxes $?b1 ?bx (+ ?by 1) $?b2 warehouses $?w1 ?wx ?wy 1 $?w2 level (+ ?lvl 1)))
    (bind ?*nod-gen* (+ ?*nod-gen* 1)))


(defrule goal
    ?f<-(robot $? warehouses $?w1 ?wx ?wy 1 $?w2 level ?lvl)

   =>
    (printout t "SOLUTION FOUND AT LEVEL " ?lvl crlf)
    (printout t "NUMBER OF EXPANDED NODES OR TRIGGERED RULES " ?*nod-gen* crlf)
    (printout t "GOAL FACT " ?f crlf)

    (halt))

(defrule no_solution
    (robot $? level ?lvl)
    =>
    (printout t "SOLUTION NOT FOUND" crlf)
    (printout t "NUMBER OF EXPANDED NODES OR TRIGGERED RULES " ?*nod-gen* crlf)

    (halt))     

(deffunction start ()
        (reset)
    (printout t "Maximum depth:= " )
    (bind ?prof (read))
    (printout t "Search strategy " crlf "    1.- Breadth" crlf "    2.- Depth" crlf )
    (bind ?a (read))
    (if (= ?a 1)
           then    (set-strategy breadth)
           else   (set-strategy depth))
        (printout t " Execute run to start the program " crlf)


    (assert (max-depth ?prof))

)

and I got an error all the time (for every rule that has comparison of variables):

[ARGACCES2] soktest.clp, Line 186: Function '>' expected argument #1 to be of type integer or float.

How can I correct it, so it might work? I tried converting variables into float with an overwritten function, but it is stil not working properly. Robot is going only up and down.

Design question. Separate layouts for mobile and desktop?

I'm relatively new to web design (I come from the programming side of things) and I am wondering how I would make a adaptive site that works on mobile and desktop.

The first thing that comes to mind is that I would make separate HTML markups for each client. Android would have a more material design to it. iOS would have whatever standards they like and same with desktop. I would then use the user agent to effectively determine what the client is using and select the proper HTML/CSS bundle to feed to them.

Is that how it works in the world of web design? Am I being naive? Is there a better more efficient way to go about doing this?

Thanks for your help.

How to apply Design Patterns from Use Case

I need to solve an exercise for the university. The exercise is about the the application of design patterns from real scenario. From an use case I have to draw UML class diagrams exploiting different design patterns. I don't understand the steps to follow to rich the purpose.

This is my approach:

1) I read the use case

2) I extract from it all explicit entities with their attributes

3) I sketch an UML class diagrams with previous information

4) I add some classes which is not mentioned in the use case but it's necessary, such as classes for the collections.

5) At this point I analyze if is useful the use of a specific pattern and draw the final UML class diagram.

This is my problem:

SCENARIO:

A software system must manage the assignment of classrooms for university course exams. The classrooms are located in different plexuses. Each plexus contains 10 to 20 classrooms. Each classroom of a plexus is identified by a name, by the plane in the plexus, by a number progressive with respect to the plane and is characterized by the number of available places in it and by a state (free, reserved, occupied) with respect to a date and a schedule. Each classroom can be equipped with different types of teaching tools (eg blackboard, projector, projection screen, computer, network connection, test benches). The exams are related to the teachings of a university course. Each exam session held in a classroom is characterized by the day of the session, the teaching and the timetable. Each lesson is held by the teacher, belonging to the course of study which belongs to the teaching of the lesson, identified by the surname of the name and type of teacher (ordinary, associate, charge). The reservation is made by the teacher in charge of the course. The teacher in the reservation indicates the date and time of the exam, the teacher, the expected number of candidates for that session, any necessary teaching tools. The administrator of the classrooms is responsible for processing requests for classrooms for the maintenance of exam sessions as reported in the following use case.

Use case: classroom assignment for exams

Actor: administrator classrooms

Description:

  1. The system displays a form with the list of unanswered requests for classrooms for exams made by the various teachers; the list is sorted in ascending order with respect to the date and time of registration of the request. The list shows the name of the teacher, the name of the course, the date and time of the beginning and the end of the exam session, the expected number of candidates for that session.
  2. If the list is empty, the message "There are no requests for reservations" is displayed and the use case ends.

  3. If the list is not empty, the actor selects the request at the top of the list.

  4. The system displays a list of the free classrooms with a number of places adequate to that of the candidates scheduled for the date and times indicated in the booking request. This list shows the name of the plexus in which the room is located, the number of the floor in the plexus, the progressive number of the room relative to the floor, the number of available places in it, its status with respect to the date and time indicated in the reservation request. The list is sorted in ascending order with respect to the number of classroom seats.

  5. If the list is empty, the system displays the message "No room available for the indicated date and time", the list scrolls in one place and the use case continues from point 3);

  6. If the list of available classrooms is not empty, the system proposes, by highlighting in bold the respective lines of the list, the classrooms with a number of places equal or close to that of the expected number of candidates for that session.

  7. The actor selects the room corresponding to one of these lines (but can also select a room that does not correspond to one of the lines in bold).

  8. The system asks the actor to confirm the selection.

  9. If the actor confirms the selection, the system:

    a. register the room reservation on the date and time required for the exam session of the teacher's teaching, reporting the date and time when the booking is registered,

    b. sets the status of the selected room equal to "booked" for that date and time

    c. it sets the status of the booking request to "evasa"

    d. records a notification to the teacher of the reservation made with indication of the room booked for the exam session specified in his reservation request.

  10. If the actor does not confirm, the system asks the actor sc to select a different classroom or if he wants to end the use case.

  11. If the actor indicates he wants to make a new selection, the use case continues from point 7), otherwise the use case ends.

  12. The system updates the list of reservation requests displayed, deleting the list just completed, and the use case continues from point 1) until the list is empty.

  13. The use case ends

The candidate designs a UML Design Class Diagram defining the classes necessary to realize the use case, showing all the components (of the application domain, for interaction with the user, and for the management of persistent data) constituting the static structure of the software to be implemented (explicitly indicate any architectural pattern c design that should be used, motivating the choices). In particular, the candidate indicates which design pattem he intends to adopt

MY PROCESS

1) I read the use case

2) I extract from it all explicit entities with their attributes

ENTITIES

classroom, tool, plexus, state, teacher, teaching, course, exam, reservation

3) UML

uml

4) I can add classes for collections the list of classrooms, exams, reservation

5) I can use The SINGLETON DP for the classes on point 4

I can not continue I'm stuck. You could help me? My English is bad I hope it was clear.

Smart constructor pattern while proving with Isabelle

While studying chapter 3 of Concrete Semantics my instructor mentionned that some of the functions there were built using the smart constructor pattern and stated that this pattern was beneficial for theorem proving.

I googled smart constructors and they seem to be used in languages like Haskell with which I'm not familiar with. Furthermore, there are not that many references of smart constructors in theorem proving.

So, what is smart constructor pattern in Isabelle and how can it help theorem proving? Maybe you can even explain it with chapter 3 of the book...

Best Practice To access couple of parameters in different classes

I have this scenario; accepting a set of values from main method argument and which has to be used in multiple classes and multiple methods. Could you suggest, what is the best practice or design pattern needed to make these params available in the classes anything other than passing as method argument?

Terminology of a client/module agnostic system where a parent doesn't know existent of child scenario.

I have a system that is self-sufficient/client agnostic and does not know about modules that can be plugged into it, the system has no module code and the modules use an API to extract data from the main system.

What is the technical phrase for a system that doesnt know about or need to know subsequent 'child' modules?

plug and play is not the one Im thinking of.

Im trying to find a way for a module to inherit characteristics/sections of the parent without the parent knowing about the module and then overriding the those it needs/wants with its own if necessary.

For example permissions, I dont want to maintain 2+ permissions matrices for parent and module, however, I dont want the Parent to contain any matrices that the module needs as that implies the parent knows of the module.

Any pointers on the terminology or the design patterns of the above as I have been out of the coding world for 3 years and cant quite remember what I used to call the above.

Which pattern to use for case when necessary to recovery state of application?

I have some observer methods that return data from server. This result is applied to filters (HTML form with data inputs). These filters are related each others. It means when I choose one filter it loads another.

Brief illustration is:

Load data from server -> 
Assign response to variable and assign to filter -> 
Choose value from filter -> 
Fill others filters -> 
Load content on the page based selected filter

User can leave this page and return after.

How to provide user statement of page with selected filters and content avoiding repedly server request?

C++ need help regarding the right choice of architectureal/design patterns

I am duing my own research project, and I am quite struggling regarding the right choice of architectural/design patterns. In this project, after the "system" start, I need to do something in backgroud(tasks, processing, display data and so on) and at the same be able to interact with the system using, for example, keyboard and send some commands, like "give me status of this particular object" or "what is the data in this object". So my question is - what software architectural/design patterns can be applied to this particular project? How the interraction between classes/objects should be organized? How should the objects be created? Can, for example, "event-driven architecture" or "Microkernel" be applied here? Some references to useful resources will be very much appreciated! Thank you very much in advance!

Store Firestore objects in Android ViewModel

I'm creating a new Android project, using Kotlin, ViewModels, DataBinding and Firestore. I'm a bit confused how I should go forward with this, mainly how to handle/store Firestore documents/references. As example, I will use a GroceryList app, in which you can add items to your list.

At some point, you select one of your lists, and go to some DetailFragment. I store my selected GroceryList in a selectedGroceryList object in my ViewModel. In my xml, I can use this object in ViewModel to display the name, the items in the list, etc. For instance, I can display the name in a textview with android:text="@{viewModel.selectedGroceryList.name}".

Up to this point, I'm a happy! However.. what if we want to write?

Imagine I want to add 'Apples' to my grocerylist. I can add it to the groceryList in the ViewModel, but that doesn't add it to my Firestore. To do that, I would need the Firestore Documentreference. So what is the best way to save this Firestore docref? Should I save this ref to my ViewModel next to the groceryList, and always store the object itself, and the reference to it? Or should I only store the reference, and fetch the object from my Firestore db every time I need it?

Implementation to subclasses java

How to forward the implementation to subclasses without implement the function from interface?

interface A { void function f();}

class B implements A {/* some functions and attributes **/
    @Override
    void function f(){/* empty , i don't need it*/}
}
class C extends B{
   @Override
   void function f(){/* implementation*/}
}
class D extends B{
   @Override
   void function f(){/* implementation*/}
}

How can i remove the override in class B ?

Join in repository pattern confusion

Im using a generic repository which has a following Get mthod:

 public virtual IEnumerable<TEntity> Get(
        Expression<Func<TEntity, bool>> filter = null,
        Func<IQueryable<TEntity>, IOrderedQueryable<TEntity>> orderBy = null,
        string includeProperties = "")
    {

I want to have a join and then apply my filter,here are my classes :

 public class A
{
    [Key]
    public string stID { get; set; }
    public System.DateTime  m_date { get; set; }
    public Boolean presentAbsent { get; set; }
}

 public class B
{
    [Key]
    public string courseID { get; set; }
    public System.DateTime  m_date { get; set; }
    public string  stID { get; set; }
}

here is my filter:

 Expression<Func<A, bool>> whereClause = t => t.presentAbsent == false && t.m_date>=dt1;

now i dont know how should join these two through lambda and apply the filter,join should be on stID:

Repository<A> repo1= new Repository<A>(cr);
Repository<B> repo2= new Repository<B>(cr);

lundi 22 octobre 2018

Disposing of context in the Unit Of Work / Repository pattern

Hello I implemented UoW/Repository pattern in my application, following inter alia MSDN tutorials. I am confused however when it comes to disposing of the context (which admittedly is because of the fact that I yet have a lot to learn about memory management in C#).

Anyway, I have a context which is passed to:

  • unit of work
  • generic repositories
  • specific repositories

My question: when exactly I should dispose of that context and which of the interfaces I have should derive from IDisposable / which classes should implement IDisposable?

Currently, I derive from IDisposable in IGenericRepository and IUnitOfWork and then implement the Dispose method in GenericRepository and UnitOfWork. But in the MSDN tutorials the implementation of the Dispose method is in the specific repositories rather then in the generic repository which is the reason for my confusion. If I am working with the same instance of context passing from base class (generic repository) to a specific repository which gets the context using base constructor, should it not be enough if I dispose it in the generic repository?

Interfaces:

public interface IUnitOfWork : IDisposable
{
    IAccountsRepository Accounts { get; }
    ITransactionsRepository Transactions { get; }
    IAccountGroupsRepository AccountGroups { get; }

    void Complete();
}

public interface IGenericRepository<TEntity> : IDisposable where TEntity : class
{
    void Add(TEntity entity);
    void Edit(TEntity entity);
    IEnumerable<TEntity> GetAll();
    TEntity GetById(object id);
    void Remove(object id);
    void Remove(TEntity entity);
}

public interface IAccountsRepository : IGenericRepository<Account>
{
    IEnumerable<Account> GetForUser(string applicationUserId);
    string GetAccountName(int accountId);
}

Implementation:

public class UnitOfWork : IUnitOfWork
{
    private readonly TinyBooksDbContext _context;
    private bool _disposed;

    public IAccountsRepository Accounts { get; }
    public ITransactionsRepository Transactions { get; }
    public IAccountGroupsRepository AccountGroups { get; set; }


    public UnitOfWork(TinyBooksDbContext context)
    {
        _context = context;
        Accounts = new AccountsRepository(_context);
        Transactions = new TransactionsRepository(_context);
        AccountGroups = new AccountGroupsRepository(_context);
    }

    public void Complete()
    {
        _context.SaveChanges();
    }

    protected virtual void Dispose(bool disposing)
    {
        if (!_disposed)
        {
            if (disposing)
            {
                _context.Dispose();
            }
        }
        _disposed = true;
    }

    public void Dispose()
    {
        Dispose(true);
        GC.SuppressFinalize(this);
    }
}

public class GenericRepository<TEntity> : IGenericRepository<TEntity> where TEntity : class
{
    private readonly TinyBooksDbContext _context;
    private readonly DbSet<TEntity> _dbSet;
    private bool _disposed;

    public GenericRepository(TinyBooksDbContext context)
    {
        _context = context;
        _dbSet = _context.Set<TEntity>();

    }

    // C
    public virtual void Add(TEntity entity)
    {
        _dbSet.Add(entity);
    }

    public virtual IEnumerable<TEntity> GetAll()
    {
        return _dbSet.ToList();
    }

    // R
    public virtual TEntity GetById(object id)
    {
        return _dbSet.Find(id);
    }

    // U
    public virtual void Edit(TEntity entity)
    {
        _dbSet.Attach(entity);
        _context.Entry(entity).CurrentValues.SetValues(entity);
    }


    // D
    public virtual void Remove(object id)
    {
        var entity = _dbSet.Find(id);
        Remove(entity);
    }

    public virtual void Remove(TEntity entity)
    {
        if (_context.Entry(entity).State == EntityState.Detached)
            _dbSet.Attach(entity);

        _dbSet.Remove(entity);
    }

    protected virtual void Dispose(bool disposing)
    {
        if (!_disposed)
        {
            if (disposing)
            {
                _context.Dispose();
            }
        }
        _disposed = true;
    }

    public void Dispose()
    {
        Dispose(true);
        GC.SuppressFinalize(this);
    }
}

public class AccountsRepository : GenericRepository<Account>, IAccountsRepository
{
    private readonly TinyBooksDbContext _context;
    private bool _disposed;

    public AccountsRepository(TinyBooksDbContext context) : base(context)
    {
        _context = context;
    }

    public IEnumerable<Account> GetForUser(string applicationUserId) =>
        _context.Accounts.Where(a => a.ApplicationUserId == applicationUserId).ToList();

    public string GetAccountName(int accountId) =>
        _context.Accounts.SingleOrDefault(a => a.Id == accountId).Name;
}

How a rest server should manage user enabling?

I have a rest java backend that use javaee 7 and a react/redux application. The same application is used by n different customer. Each customer can ask for m roles that are different from the roles of the other customers. One customer can, for example, pay to see a column in a list that shouldn't be visible for another customer. The question is.. Is there a pattern or a method to handle in a light way the possibilities to hide or show columns in a list, or hide/show field in a form ? (user enablings)

CUSTOMER X pay to see the phone number in customer list

CUSTOMER Y should not see at all, the phone number.

The application released for both is the same.

How the server should give this information to the frontend application without coupling with it?

Thanks.

Inter service communication in Microservices

I understand the Event-Driven Architecture where a service subscribes to the events for inter-service communication. An event can be triggered when an entity is created/updated/deleted.. but how can inter service communication be achieved in case of GET requests.

For instance: A notification microservice which returns the list of product notifications for the end user - needs to read User's notification preferences (to which products he wants notifications), needs to get the basic product information (product name, price) and the notification service for the notification data itself.

This can be easily achieved by orchestrating all the services (preference service, product service) inside the notification service - but that would result into tight coupling there.

What's the proper way to implement inter-service communication in microservices when the data needs to be fetch from multiple services?

JPARepository in spring-boot maven multi-module application

My next application is a maven multi-module application with this structure:

main-app

model sub-project
service sub-project
front-end sub-project

In the model sub-project there are all entities for application domain, in service sub-project the are the Spring Boot Controller and RestController and front-end sub-project is a simple web application with thymeleaf template engine.

Now i've a question about JPARepository (from spring boot implementation) interfaces for entities! Where should this object be? In service or model sub-project?

Swift: pattern for ViewController that can be acessed from many places

In my app, I've a "details" screen/VC that can be accessed from 3 different screens.

I'm currently using constructor dependency injection and 3 different initializers to setup correct variables based on where user comes from.

Still, most of logic is in ViewDidLoad under pretty ugly ifs

Wrote a little sample to give you an idea of how it looks like now:

if object != nil {

    WebApi.fetchDropDown1 { items in
        dropdown.selectedItem = items.first{$0.id == object.UnitId}
    }

    currentDateLabel = object.date
} else if object == nil && currentDate == nil {
    // came to add from list of objects

    // object doesn't exist yet

    WebApi.fetchDropDown1 { items in
        dropdown.selectedItem = items[0] // select first availabile
    }

    currentDateLabel = Date() // set today as default date
    deleteButton.isEnabled = false
    // something like that for every element

} else if { currentDate != nil && object == nil} {
    // came here from calendar pick

    WebApi.fetchDropDown1 { items in
        dropdown.selectedItem = items[0] // select first availabile
    }

    currentDateLabel = currentDate

}

This isn't actual code, but just to clarify what I'm trying to solve.

Many tutorials on design patterns just do the simplest use-cases and I haven't been able to find some useful advice for more complex cases.

Thanks.