mercredi 31 août 2016

how to fit my android app to all devices

i will try to designed one android app but i got one issue i.e: i created app in android studio and once checked preview of my android app, look and feel is good and i run the app in my coolpad note-3 device so unfortunately got my app designation changed in that device once look at below image enter image description here

in android studio preivew image is below once look at image

enter image description here

Simple Closure example in Module Pattern not working

In the simple example I want to demonstrate:

1. Module Pattern
2. Closure 

I am trying to change a value of Local Variable by making use of closure. But, I cannot get it implemented (Output must be 15 in console).

HTML

<script>
function box(){
    var a;
    a=10;

    var obj = {};
    obj.func1 = function(b){
        a = a+b;
        console.log(a);
    }
    return obj;
}

box.func1(5);
</script>

Please, help me out in the example.

Also, tell me have I missed any key componenet of Module Pattern in this simple example?

Which design pattern would suite for the scenario?

My Objective is to read/write files either to local directory or on remote machine and my code contains the following components

  1. A wrapper class which contains add file and get file methods as follows
    • public static String[] addFile(params) - this returns an extended ouput stream (say ABCOuputStream) - with which we can write the data
    • public static String[] addFile(byte[] filecontent) - this method writes the file content directly to local or remote machine
    • public static byte[] getFile() - this method reads the content from local/remote machine - and it returns the file content as byte array
    • public static InputStream getFile() - this method returns an extended input stream(say ABCInputStream) - and the data would be read from this stream

2.ABCInputStream class - which is an extended input stream

3.ABCOutputStream class - which is an extended output stream

I am not convinced with the wrapper class structure which does all these things.

Sorry for too long theoretical description. I'm ready to add further details if needed.

Some one please help me to choose a pattern to improve this in a much better way.

Circuit breaker design pattern sleep vs time.AfterFunc

I am trying to create a Circuit breaker pattern, I want to execute a command exec.Command and if it fails, retry in X defined amount of time, for testing purposes, I am doing something like this for testing time.AfterFunc:

package main

import (
    "fmt"
    "time"
)

func myFunc() error {
    for i := 1; i < 10; i++ {
        fmt.Printf("i = %+v\n", i)
        if i%3 == 0 {
            return fmt.Errorf("error")
        }
    }
    return nil
}

func main() {

    run := make(chan struct{}, 1)

    run <- struct{}{}

    for {
        select {
        case <-run:
            err := myFunc()
            if err != nil {
                time.AfterFunc(3*time.Second, func() {
                    run <- struct{}{}
                })
            }
        default:
        }
    }
}

time.AfterFunc works for the above code, but not for the example below, I had to replace it with a sleep in order to achieve the expected results:

package main

import (
    "fmt"
    "os/exec"
    "time"
)

func Exec(done chan<- error) error {
    cmd := exec.Command("./start")
    if err := cmd.Start(); err != nil {
        return err
    }
    go func() {
        done <- cmd.Wait()
    }()
    return nil
}

func main() {
    var (
        run  = make(chan struct{}, 1)
        done = make(chan error, 1)
    )

    Exec(done)

    for {
        select {
        case <-run:
            err := Exec(done)
            if err != nil {
                fmt.Println(err)
                // time.AfterFunc(3*time.Second, func() {
                time.Sleep(3 * time.Second)
                run <- struct{}{}
            }
        default:
            select {
            case err := <-done:
                fmt.Println(err)
                run <- struct{}{}
            }
        }
    }
}

The content of ./sleep:

#!/bin/sh

sleep 3

And for testing, creating an error, I toggle perms:

chmod -x sleep
chmod +x sleep

Therefore wondering what are the differences between using time.AfterFunc and time.Sleep and what could be the best way of implementing this pattern.

Large class with dependant classes and shared properties

I am having trouble figuring out the best way to refactor a very large C# class and specifically how to pass shared properties/values from the large class into the extracted classes and have those modified values available in the main class.

At the start, this class was 1000 lines long and is very procedural – it involves calling methods and performing work in a specific sequence. Along the way things are persisted into the database. During the process there are multiple Lists of items that are worked on and shared in the methods. At the end of this process, there are a bunch of statistics that are presented to the user. These statistics are calculated in various methods as the processing is taking place. To give a rough outline – the process involves a bunch of random selection and at the end of the process the user sees how many random items, how many invalid records were picked, how many items came from this sub-list etc.

I have been reading Uncle Bob’s “Clean Code” and am trying to make sure as I refactor that each class does only 1 thing.

So I have been able to extract methods and classes in order to keep the file smaller (have it down to 450 lines now) but the problem I am having now is that these broken out classes require values from the main parent class to be passed to them and updated – these values will be used for other methods/class methods as well.

I am torn as to which is the cleanest approach:

1) Should I create a bunch of private member variables to store the statistical values and Lists in the main class and then after calling into the main class' dependnat class methods, receive back a complex result class and then extract these values out and populate / update the private member variables? ( lots of boiler plate code this way)

OR

2) Is it better to create a DTO or a some sort of container class that holds the Lists and statistical values and just pass it to the various class methods and child class methods by reference in order to build up the list of values? In other words I am just passing this container class and since it's an object the other classes and methods will be able to directly manipulate the values in there. Then at the end of the process, that values DTO/container/whatever you want to call it will have all of the final results in it and I can just extract them from the container class (and in that case there really is no need to extract them and populate the main class’ private member variables. )

The latter is the way I have it now but I am feeling that this is a code smell – it all works but it just seems “fragile”. I know large classes are not great but at least with everything in 1 large file it does seem clearer as to which properties I am updating etc.

Module Pattern: Restrict a module from being extended

I've been reading several articles on Design Patterns in Javascript. I found module pattern easy to read/write.

I'm wondering if there is any way to stop extending a module in Javascript.

Here is the script that I've been working with:

var MODULE = (function(){
    var increment = 0;

    var funcIncrement = function(){
        increment ++;
        console.log(increment);
    };

    return {
        incr: funcIncrement
    }
})();


var moduleTwo = (function(MODULE){
    MODULE.extension = function(){ //This module will add extension function to MODULE. I don't want this to happen
        console.log('extension method');
    }


})(MODULE || {});

If I do console.log(MODULE) after running those the above snippet, then I'll get two function for MODULE (incr, extension)

Is there a way to restrict the MODULE from being extended when declaring the MODULE for the first time ?

.NET software architecture with in-process pub/sub in mind

Is there anything like an in-process pub/sub pattern to provide lose coupling in an application? Is there a design pattern for that? Or framework?

I want all classes to know the broker and subscribe to topics. I don't want classes to know about each other. pub/sub comes to mind. Or message oriented middleware. However I couldn't find any frameworks for that.

Are there any design patterns you can recommend? Or Framework?
I did find ZeroMQ which looked rather complex.

Otherwise I'd go with a Producer-Consumer pattern and build something upon that.

How can MVC coexist with the Onion architecture?

I've seen people suggesting the implementation of MVC together with the Onion Archutecture. But how can the two coexist? Aren't they two distinct architectures? For example, where is the Controller in the Onion design?

I understand the combination of more than one design pattern, because they serve different purposes (behaviour, creation, etc), and can be independently implemented in different modules of the system, but I don't get how to implement two different architectures.

Group regex with fix part

$txt = "toto1 555.4545.555.999.7465.432.674";
$rgx = "/([\w]+)\s([0-9]+)\.([0-9]+)\.([0-9]+)\.([0-9]+)\.([0-9]+)\.([0-9]+)\.([0-9]+)/";
preg_match($rgx, $txt, $res);
var_dump($res);

I would like to simplify this pattern by avoiding repeating "([0-9]+)" because i don't know how many they are.

Any one can say me how ?

Passing "this" pointer from object constructor to setter/getter in JS

Fairly new to using a prototype design pattern so I had a quick question about the most efficient way of creating a setter/getter for multiple constructor variables.

Say I had a "trip" object :

function trip(){
    this.numberOfDays = 0
    this.price = 0
    this.activites = [] 
    this.bPacks = []
    this.pPacks = []
}

Now the setters for the activities, bPacks, and pPacks all do primarily the same thing. They will add or remove to the array that they are associated with.

so instead of writing 6 separate setters for these properties such as :

trip.prototype.addActivity = function(itemToAdd){
  var index = this.activites.push(itemToAdd)
}

trip.prototype.addBPack = function(itemToAdd){
      var index = this.bPack.push(itemToAdd)
    }

etc...

Is it possible to do something like this :

trip.prototype.addPacksOrActivity = function(item,typeOfItem){
    this.typeOfItem.push(item);
} 

where we target the specific property of the trip object we want to push to?

Any suggestions for more efficient ways of building setters/getters are welcome but I am trying to avoid transpiling from ES6 so ES5 type answers are preffered.

Command pattern use case?

What are some example use cases where the command pattern may be of use? I've been reading about it, and I have a good idea on how to implement it. But It's a big vague when it comes to knowing when to use it.

One of the problems it solves is to decouple the API of a class. But what does that imply exactly? What's the disadvantage of calling an object's methods directly?

How to organize the data analysis classes from the perspective of class design?

I give the following example to illustrate my question:

class DataGenerator
{
  public:
         Data data;
         void generator_data();
         Auxiliary info;
};

This class will initialize and generate data after calling generator_data function.In the meantime, some auxiliary information associated with the data is also generated.

class DataAnalyzer
{
  public:
       DataAnalyzer(DataGenerator &dataGenerator):data(dataGenerator)
       {

        }
       line& get_the_longest_line_in_data();

       DataGenerator &data;
}

This class will perform some analysis on the data, and generate some information after anlyzing the data. For example, line& get_the_longest_line_in_data()

class KnowledgeGenerator
{
  public:
     void generate_knowledge()
     {
            DataGenerator abc;
            abc.generator_data();

            DataAnalyzer def(abc);
            def.get_the_longest_line_in_data();

            organize_lines();

            generate_conclusion();
          }

}

This class will invoke DataGenerator and DataAnalyzer class and perform a higher level analysis, and in the end we will get some more concrete stuff. For example, it may be a decision whether the stock should be sold or not.

How to automatically bind implementations in PHP?

So I am a laravel developer and even though I have worked with it for a while now, and I love how the magic happens beneath the surface, how it automatically binds implementations when instantiating classes via the IoC container, right now I am trying to go to the basics of design patters and learn how things actually work.

So I started with the Animal example:

abstract class Animal
{
    abstract function makeSound();
}

class Dog extends Animal
{
    public function makeSound()
    {
        echo "Bark!\n";
    }
}

class Cat extends Animal
{
    public function makeSound()
    {
        echo "Bark!\n";
    }
}

So I am reading Head First Design Patterns and I am trying to make the most of the book. At this point every time I create a new Animal, I will have to implement the make sound method which will differ in most cases.

So the book tells me that I should code a Soundable interface and then have implementations of that interface in the Animal extended classes.

I finally came up with something like this:

interface Soundable
{
    function sound();
}

class Bark implements Soundable
{
    public function sound()
    {
        return "Bark!\n";
    }
}

class Meow implements Soundable
{
    public function sound()
    {
        return "Meow!\n";
    }
}

class Animal
{
    public $soundable;

    public function __construct(Soundable $soundable)
    {
        $this->soundable = $soundable;
    }

    public function makeSound()
    {
        echo $this->soundable->sound();
    }
}

class Dog extends Animal
{

}

class Cat extends Animal
{

}

function makeAnimal(Animal $animal){
    return $animal; 
}

// Making a dog
$animal = makeAnimal(new Dog(new Bark()));
$animal->makeSound();

// Making a cat
$animal = makeAnimal(new Cat(new Meow()));
$animal->makeSound();

So now when I have another animal that barks or meows, I can simple instantiate that implementation while making an animal.

Now my question is how do I tell PHP to automatically pass the new Bark() while instantiating the Dog class since it will bark and I don't want to write it every time I instantiate a new Dog object.

So how do I use a similar magic that Laravel uses to pass the Bark object automatically while instantiating Dog.

PS: I am still learning so I might be going in the wrong direction altogether while understanding these principles. Please guide me if you know better.

mardi 30 août 2016

How should I be structuring my data flow in my React + React Router + PouchDB app?

I'm currently building a course scheduling app called Serif, which loads course data into PouchDB on first load. The UI is as such:

enter image description here

The "Current Term" is a dropdown list and controls the current data set being used at any given time. For example, if "2016 Fall" is selected, then the user can search, browse, select courses, and create calendars using courses from the 2016 Fall catalog. When a user switches to "2016 Spring", they would now be using the 2016 Spring data set, and so on.

I'm using PouchDB to keep everything clientside (at least for now). With that said, here's my current component structure (roughly, without components that are only for layout):

  • Serif (one of my Router routes)
    • Subnav
      • TermSelect (this is the one you see on the top right: "Current Term")
    • Search
    • Browse
    • Calendars
      • calendar selection stuff
      • the actual calendar

My question focuses on the data flow from PouchDB to the TermSelect component (but the correct answer to this will inform my structuring of all other components).

The way I've built it now, Serif has a state called currentTerm that keeps track of the current term for the app. In the constructor, PouchDB is queried for the first term and sets currentTerm to that value.

In the render method of Serif, the PouchDB is queried for the list of terms in the db and that list is formatted to the expected format and then passed as a prop to the Subnav component which in turn passes it to the TermSelect component.

The TermSelect component uses the received props to populate the dropdown list and sets its default display value to the first in the list, hence resulting in "2016 Fall" you see above. When an option is selected, a callback function passed down as part of the data is called, which changed the state of the Serif component.

Aside from a problem of the default value required a click to display, this mostly works. Is this the correct way to do things? Instead of passing the terms data down from Serif to the TermSelect component, the TermSelect component could query it directly from the PouchDB.

Any suggestions for improvement, or even just a confirmation that this is the correct data flow pattern would be appreciated. I'm new to React and I'm having trouble juggling all the correct patterns and antipatterns (don't use prop to set state, components should pass data from stateful to stateless, etc).

Thanks!

Redis pub sub for multiple producers and multiple consumers

Lets say there are N producers and M users which subscribes to these N producers. Here N producer produce N different types of messages e.g

producer1 produces  messageType1, 
producer2 produces  messageType2,
producer3 produces  messageType3,
.
.
. 
producerN produces  messageTypeN. 

M users can subscribe to these messages. One user can subscribe to multiple types of messages. E.g.

user1 consumes (messageType1, messageType2, messageType10)
user2 consumes (messageType14, messageType5)
.
.
userM consumes (messageType21, messageType22, messageType23, .... messageTypeN)

Users may consume same or distinct message types. My questions is how to design this scenario. It looks like pub sub pattern. For this scenario, do I have to create channels per user in redis. If yes, there is a limitation on number of redis channel one can create (10K). In that case how to handle millions of user? Any help would be appreciated.

Add a line leading space after first pattern and just above next pattern using SED/AWK

Input:

define { abcd pattern xyzs wedlenle jqwd sadjkjnd

}

define { abcd asjdanja xyzs wedlenle jqwd sadjkjnd

}

define { adkja pattern xyzs wedlenle jqwd sadjkjnd

}

expected output:

define { abcd pattern xyzs wedlenle jqwd sadjkjnd addtext

}

define { abcd asjdanja xyzs wedlenle jqwd sadjkjnd

}

define { adkja pattern xyzs wedlenle addtext

}

Need to add line(leading space) in same define block just before "}".

Appreciate your help!

Design pattern to map derived types to list of new type

I have a list of derived types I want to map to a list of another type. Each derived type maps differently to the new type.

Is there any pattern to do this without casting each types and that keeps the logic of the mapping outside of the type (in a factory).

Here's an example, I'd like to find an alternative to GetFlatSwitch, something like GetFlat :

class Program
  {
    static void Main(string[] args)
    {
      List<Base> list = new List<Base>() { new DerivedA() { A = "A" }, new DerivedB() { B = "B" }};

      List<Flat> flatList = list.Select(x => Factory.GetFlat(x)).ToList(); // not working
      List<Flat> switchFlatList = list.Select(x => Factory.GetFlatSwitch(x)).ToList(); // works, but casting each element
    }

    static class Factory
    {
      public static Flat GetFlat(Base baseObj)
      {
        return new Flat();
      }

      public static Flat GetFlat(DerivedA a)
      {
        return new Flat() { A = a.A };
      }

      public static Flat GetFlat(DerivedB b)
      {
        return new Flat() { B = b.B };
      }

      public static Flat GetFlatSwitch(Base baseObj)
      {
        switch (baseObj.MyType)
        {
          case MyTypeEnum.A:
            DerivedA a = baseObj as DerivedA;
            return new Flat() { A = a.A };
          case MyTypeEnum.B:
            DerivedB b = baseObj as DerivedB;
            return new Flat() { B = b.B };
          default:
            return new Flat();
        }
      }
    }

    enum MyTypeEnum
    {
      A, B
    }

    abstract class Base
    {
      public abstract MyTypeEnum MyType { get; }
    }

    class DerivedA : Base
    {
      public override MyTypeEnum MyType
      {
        get
        {
          return MyTypeEnum.A;
        }
      }
      public string A { get; set; }
    }

    class DerivedB : Base
    {
      public override MyTypeEnum MyType
      {
        get
        {
          return MyTypeEnum.B;
        }
      }
      public string B { get; set; }
    }

    class Flat
    {
      public string A { get; set; }

      public string B { get; set; }
    }
  }

Convert Javascript code to module pattern

How can i convert this code to the module pattern?

   var QuadTable;
    QuadTable = function () {
        this.dateFormat = 'yy-mm-dd';
        this.dateTimeFormat = 'yy-mm-dd' + " 00:00:00";
    };
    QuadTable.prototype = {
        initTable: function (parms) {
....
        },
      addTableEvents: function () {
......
      }

What's the correct way to access methods of a member variable in a class pointing to an object?

What's the correct way to define/access methods of a member variable in a class pointing to an object?

For e.g.,

I've a class Foo that has a method bar. class Foo: def bar(self): return 'bar'

Now, in another class Bar, I'd like to store an object to this class (I do not want Bar to inherit Foo).

What's the correct/recommended way to define class Bar?

class Bar:
    def __init__(self):
        self.foo = Foo()

OR

class Bar:
    def __init__(self):
        self.foo = Foo()

    def bar(self):
        return self.foo.bar()

The former will allow me to use: x = Bar() x.foo.bar()

But, with this I'm directly accessing methods of a member variable (strong coupling).

The benefits I see with this approach are:

  • I don't have to wrap every new method that gets added to class Foo.
  • Bar may contain more member variables pointing to other classes. Not wrapping them keeps Bar smaller and manageable in size.
  • The auto-completion facility from IDE (pycharm, etc.) or ipython helps look an object of bar like a menu (x.foo) followed by a sub-menu (x.foo.bar(), x.bat.foobar(), etc.) making it easier to develop code.
  • Functional programming look-n-feel (not sure if this a pro or con)

The cons are strong coupling, not encapsulating internal details of foo, etc.

I wanted to check if this a recommended practice? And/or if there are any guidelines related to this (kind of implementing a composite pattern)?

Any inputs/pointers will be highly appreciated!

Singleton Class or Class with only static fields? [duplicate]

This question already has an answer here:

what is the better approach?

Let us assume a scenario in which there is a utility class that is used by other classes. What is better to use in this case, a singleton class which can be instantiated exactly once or should i make all the fieds static?

how to design a database for a forum web-app android

i need some tips!! i want to design an android app, basically the idea aim to design a big forum structured in category, in which users can post things(text, image, etc). as you can image, a forum-based application is made by topic, comments etc. I was wandering, what are the best practices to develop an app like that. is there a framework can help me? how i have to design the database?

Alternative representation for characters in REGEX

Why can't get the same behavior when i build a Pattern from a literal regular expression than when i read the regular expression from a file?

String regex = "(?xi)(title)[\\.:;](.*) \043 Title property";
Pattern pattern = Pattern.compile(regex);
System.out.println(pattern);
// will print:

(?xi)(title)[.:;](.*) # Title property

wish is fine. But when i read the regular expression from a file to try to build the same Pattern the '\043' isn't replaced. Why? Any help?

The main reason is that I'm trying to avoid the use of the literal '#' character symbol and to use and alternate representation of it, because other conflicts.

ADO.Net Repository Pattern implementation from jgauffin not working

I am trying to implement the Repository Pattern explained by jgauffin at http://ift.tt/1ouayRg and getting crazy!

I have several problems to get it work. I have implemented a small SQL Server table called Employee:

enter image description here

I created a class for this employee:

Employee

public class Employee
{
    public int Id { get; set; }
    public string Name { get; set; }
}

IConnectionFactory

public interface IConnectionFactory
{
    IDbConnection Create();
}

Is it corect, that there is no correponding implemnetation for the IConnectionFactory interface? I couldnt find it!

AdoNetContext

public class AdoNetContext
{
    private readonly IDbConnection _connection;
    private readonly IConnectionFactory _connectionFactory;
    private readonly ReaderWriterLockSlim _rwLock = new ReaderWriterLockSlim();
    private readonly LinkedList<AdoNetUnitOfWork> _uows = new LinkedList<AdoNetUnitOfWork>();

    public AdoNetContext(IConnectionFactory connectionFactory)
    {
        _connectionFactory = connectionFactory;
        _connection = _connectionFactory.Create();
    }

    public IUnitOfWork CreateUnitOfWork()
    {
        var transaction = _connection.BeginTransaction();
        var uow = new AdoNetUnitOfWork(transaction, RemoveTransaction, RemoveTransaction);
        _rwLock.EnterWriteLock();
        _uows.AddLast(uow);
        _rwLock.ExitWriteLock();
        return uow;
    }

    public IDbCommand CreateCommand()
    {
        var cmd = _connection.CreateCommand();
        _rwLock.EnterReadLock();
        if (_uows.Count > 0)
            cmd.Transaction = _uows.First.Value.Transaction;
        _rwLock.ExitReadLock();
        return cmd;
    }

    private void RemoveTransaction(AdoNetUnitOfWork obj)
    {
        _rwLock.EnterWriteLock();
        _uows.Remove(obj);
        _rwLock.ExitWriteLock();
    }

    public void Dispose()
    {
        _connection.Dispose();
    }
}

AdoNetUnitOfWork

public class AdoNetUnitOfWork : IUnitOfWork
{
    private IDbTransaction _transaction;
    private readonly Action<AdoNetUnitOfWork> _rolledBack;
    private readonly Action<AdoNetUnitOfWork> _committed;

    public AdoNetUnitOfWork(IDbTransaction transaction, Action<AdoNetUnitOfWork> rolledBack, Action<AdoNetUnitOfWork> committed)
    {
        Transaction = transaction;
        _transaction = transaction;
        _rolledBack = rolledBack;
        _committed = committed;
    }

    public IDbTransaction Transaction { get; private set; }

    public void Dispose()
    {
        if (_transaction == null)
            return;
        _transaction.Rollback();
        _transaction.Dispose();
        _rolledBack(this);
        _transaction = null;
    }

    public void SaveChanges()
    {
        if (_transaction == null)
            throw new InvalidOperationException("May not call save changes twice.");
        _transaction.Commit();
        _committed(this);
        _transaction = null;
    }
}

AppConfigConnectionFactory

public class AppConfigConnectionFactory
{
    private readonly DbProviderFactory _provider;
    private readonly string _connectionString;
    private readonly string _name;

    public AppConfigConnectionFactory(string connectionName)
    {
        if (connectionName == null) throw new ArgumentNullException("connectionName");
        var conStr = ConfigurationManager.ConnectionStrings[connectionName];
        if (conStr == null)
            throw new ConfigurationErrorsException(string.Format("Failed to find connection string named '{0}' in app/web.config.", connectionName));
        _name = conStr.ProviderName;
        _provider = DbProviderFactories.GetFactory(conStr.ProviderName);
        _connectionString = conStr.ConnectionString;
    }

    public IDbConnection Create()
    {
        var connection = _provider.CreateConnection();
        if (connection == null)
            throw new ConfigurationErrorsException(string.Format("Failed to create a connection using the connection string named '{0}' in app/web.config.", _name));
        connection.ConnectionString = _connectionString;
        connection.Open();
        return connection;
    }
}

Repository

public abstract class Repository<TEntity> where TEntity : new()
{
    AdoNetContext _context;

    public Repository(AdoNetContext context)
    {
        _context = context;
    }

    protected AdoNetContext Context { get; }

    protected IEnumerable<TEntity> ToList(IDbCommand command)
    {
        using (var reader = command.ExecuteReader())
        {
            List<TEntity> items = new List<TEntity>();
            while (reader.Read())
            {
                var item = new T();
                Map(reader, item);
                items.Add(item);
            }
            return items;
        }
    }

    protected abstract void Map(IDataRecord record, TEntity entity);
}

EmployeeRepository

public class EmployeeRepository : Repository<Employee>
{
    public EmployeeRepository(AdoNetContext context) : base(context)
    {
    }

    public void Create(Employee employee)
    {
        using (var command = _connection.CreateCommand())
        {
            command.CommandText = @"INSERT INTO Employees (Name) VALUES(@name)";
            command.AddParameter("name", employee.Name);
            command.ExecuteNonQuery();
        }

        //todo: Get identity. Depends on the db engine.
    }
    public void Update(Employee employee)
    {
        using (var command = _connection.CreateCommand())
        {
            command.CommandText = @"UPDATE Employees SET Name = @name WHERE Id = @id";
            command.AddParameter("name", employee.Name);
            command.AddParameter("id", employee.Id);
            command.ExecuteNonQuery();
        }
    }
    public void Delete(int id)
    {
        using (var command = _connection.CreateCommand())
        {
            command.CommandText = @"DELETE FROM Employees WHERE Id = @id";
            command.AddParameter("id", id);
            command.ExecuteNonQuery();
        }
    }

    public IEnumerable<Employee> FindUsers(string name)
    {
        using (var command = _connection.CreateCommand())
        {
            command.CommandText = @"SELECT * FROM Employees WHERE Name LIKE @name";
            command.AddParameter("firstName", name + "%");
            return ToList(command);
        }
    }

    //public IEnumerable<Employee> FindBlocked()
    //{
    //    using (var command = _connection.CreateCommand())
    //    {
    //        command.CommandText = @"SELECT * FROM Users WHERE Status = -1";
    //        return ToList(command);
    //    }
    //}

    protected override void Map(IDataRecord record, Employee employee)
    {
        employee.Name = (string)record["Name"];
        employee.Id = (int)record["Id"];
    }
}

And that should be the app

    static void Main(string[] args)
    {
        // during app start
        var factory = new AppConfigConnectionFactory("RepositoryPattern");
        // during start of the current session

        var context = new AdoNetContext();
        // for the transaction
        using (var uow = context.CreateUnitOfWork())
        {
            var repos1 = new EmployeeRepository(context);
            var repos2 = new EmployeeRepository(context);
            // do changes
            // [...]
            uow.SaveChanges();
        }
    }

But i am not getting it work! I get errors in two files:

enter image description here

It tells me that the AdoNetContext has no parameter of type connectionFactory. I dont know what to add here.

And in the EmployeeRepository file i get errors for

using (var command = _connection.CreateCommand())

enter image description here

What is here wrong? Maybe someone can explaing me what i am doing wrong!? This is driving me crazy!

Find the pattern in the string with javascript [on hold]

Find the pattern match with ${any word}

Example

"Hi, my name is ${uname}, reading the book ${book}".

from above string, how many patterns are matched and what are those.

Output ${uname} ${book}

How does slack store unread message counts?

I'm building a chat application and I'm trying to identify the state architecture for indicating unread messages.

My state currently contains a list of messages. On render, I group them by conversation so I can render a list of recipients and, for the selected recipient, the messages.

The simplest approach would be to also store a lastRead hash of {recipient: lastReadTimestamp} in the state as well. On render, count the number of messages in each conversation whose timestamp is greater than the stored lastRead timestamp to get the number of unread messages. And when the recipient is selected, set the lastRead timestamp for that recipient to that of the most recent message.

The problem with this is if, while you're away, 15+ messages come in - to the point that some are beyond the viewport and you'd have to scroll to see them. Once you select that recipient, it will mark the lastRead timestamp as the most recent message, essentially marking the entire conversation as "read" even though there are messages above that haven't been seen.

Instead I was hoping to have functionality more like Slack's. in-view or an InteractionObserver could detect when a message has actually come into the viewport.

slack screenshot

But what would I store in the state? The ids of each unread message? If so, when I refresh and my app receives all the messages, how does it know any of them are read? I could store the ids of each read message instead but that sounds unwieldy.

Has anyone seen a good design pattern for this?

Angular design pattern of adding classes to body

I have a design problem. The website has two aside menus. When I click on one of them, body block needs additional classes (_openLeftAside and _openRightAside). So what is the best way to implement such behavior? Currently, I have LayoutController, that handles clicks.

function LayoutCtrl($rootScope) {    
  const vm = this;

  vm.activeAside = ASIDE_LEFT;

  vm.changeAside = () => {
    vm.activeAside = (vm.activeAside === ASIDE_LEFT ? ASIDE_RIGHT : ASIDE_LEFT);
    return vm.activeAside;
  };
}

Should it broadcast event to BodyController / $rootScope and set class on body with ng-class? Or should I create a directive, that will manipulate body classes (but I can't quite understand how to implement it properly)?

Is the singleton pattern still bad when we talk about it in a framework context?

Using the singleton pattern is usually a code smell.

However, it seems that using "singletons" in a framework such as Laravel is a popular solution to a lot of problems.

It's also worth noting that singletons in Laravel aren't really the same thing as a singleton class in the following sense:

  • The class being used as a singleton is unaware of this, there are no static methods in there, nor is there anything that would prevent you from creating a new instance of that class manually.
  • When using Laravel singletons, the container keeps track of the objects you want to use as singleton and hands these to you upon request.

Am I correct in my understanding that what is called a singleton in Laravel isn't in fact a singleton, but an implementation inspired by the singleton pattern, and therefore isn't as much as a bad practice as a real singleton because it gets rid of some of the downsides (harder to test, global state...)?

This question is loosely related to this question about design patterns in PHP but it appeared appropriate to me to create a separate question.

How can I inject a behaviour into WebServiceHost?

I'm instancing a WebServiceHost object:

var _webService = New WebServiceHost(GetType(MyWebServiceImpl), New Uri("http://localhost:8000"));

I need to inject some behaviour (i.e. a DB connection and a logger) into the object of class MyWebServiceImpl, but I don't have a reference to it, because this object is instanciated by the WebServiceHost constructor.

How can I get a reference to the MyWebServiceImpl object? Or is there some pattern I can use to get it?

Thanks

How to Convert double to Float Class into Java [duplicate]

This question already has an answer here:

I'm watching video related to design pattern for study.

This code is able to convert double to Float Class

But my code can't convert double to Float Class

My IDE is intellij IDEA, Java version is 8 Any ideas, How to fix it?

lundi 29 août 2016

How to create vertical and horizontal swipeable cards in Android?

I have created a simple app with swipecards (similar to tinder) where you scroll left and right on images of cars :) whether you like or dislike them. That all works fine using a library called Swipecards: http://ift.tt/13CJlZw

Now, what I want to do next is make it so that when you scroll down the swipecards disappear and you see the description of the car and then you can scroll down one more time to see more images. Essentially how the other dating app, bumble works. You can then scroll back up to the swipecard view.

How would I achieve the scrolling up and down effect? Would I put my swipecards in a listitem of a listview and so there would be 3 listitems in my listview: 1 for the original image that you can swipe left and right, 1 for the description, and 1 for more image tiles.

Is a listview my best approach at achieving this effect? I tried searching for similar tutorials online but couldn't really find anything for the vertical scrolling.

Thanks for the help!

Service Pattern - eliminating code repetition

Generally, all of the services in my service layer follow the same pattern:

public ApiResponseDto DoStuff (int parameter){
   var response = new ApiResponseDto();
   try{
       using (var db = new DbConext()){
           // do stuff
           // throw descriptive exceptions when needed
           return response;
       }
   }
   catch (Exception e) {
       ThrowError(e)
       response.Success = false; // etc
       return response;
   }
}

What I'm wondering is - is there a pattern that I can use to eliminate this code repetition? This same footprint is used ~200 times throughout the app I'm working on and it seems proper to try and reduce the repetition somehow.

PHP Factory Design Pattern

I am new to learning Design Patterns

I just created the following example, can i consider it as an implementation of factory design patter?

<?php

class Dove
{

}

class Falcon
{

}

class BirdsFactory
{

    function getDove()
    {
        return new Dove();
    }

    function getFalcon()
    {
        return new Falcon();
    }
}

class MainClass
{

    private $birdsFactory;

    public function __construct()
    {
        $this->birdsFactory = new BirdsFactory();
    }

    public function test()
    {
        $this->birdsFactory->getDove();
        $this->birdsFactory->getFalcon();
    }

}

Correct structure for "static" type objects in Javascript

I'm struggling to get to grips with creating "static" object types in JavaScript (I doubt I've even worded that correctly...).

In the following code, I'm trying to create a jQuery plugin (I suspect that is irrelevant, though), which creates multiple CrmQuery each with their own contextual information passed in as instance. I also want to create a "static" object for all the CrmQuery to use (it can be stateless), and was hoping to contain it within the CrmQuery namespace.

This is the structure I have, but when calling CrmQuery.searchOperator[instance.Operator].buildCondition(instance.fieldName, searchTerm), the buildCondition function doesn't have access to the oDataOperator function in CrmQuery.searchOperator. I've tried referencing it in many ways, not just searchOperator.oDataOperator, and this is a reference to the actual property, not CrmQuery.searchOperator.

Structure:

(function($) { 
...
var crmQuery = new CrmQuery(instance);
var data = crmQuery.searchCrm(searchTerm);
... 

var CrmQuery = function(instance) {
    ...
    this.oDataUrl = function() {
        ...
        oDataFilter += CrmQuery.searchOperator[instance.Operator].buildCondition(instance.fieldName, searchTerm);
        ...
        return oDataFilter;
    }();

    this.searchCrm(searchTerm) {
        ...
        url += this.oDataUrl;
    }
    ...
}

CrmQuery.searchOperator = {
    oDataFunctionOperator: function oDataFunctionOperator(fieldName, searchTerm, operator) {
        return operator + "(" + fieldName + ", '" + searchTerm + "')";
    },
    oDataOperator: function oDataOperator(fieldName, searchTerm, operator) {
        return fieldName + " " + operator + " '" + searchTerm +"'";
    },
    STARTSWITH: { 
        operator: "startswith", 
        buildCondition: function(fieldName, searchTerm) { 
                return this.oDataFunctionOperator(fieldName, searchTerm, this.operator) 
            }
    },
    ENDSWITH: { 
        operator: "endswith", 
        buildCondition: function(fieldName, searchTerm) { 
                return searchOperator.oDataFunctionOperator(fieldName, searchTerm, this.operator) 
            }
    },
    CONTAINS: { 
        operator: "substringof", 
        buildCondition: function(fieldName, searchTerm) { 
                return searchOperator.oDataFunctionOperator(fieldName, searchTerm, this.operator) 
            }
    },
    EXACTMATCH: { 
        operator: "eq", 
        buildCondition: function(fieldName, searchTerm) { 
                return searchOperator.oDataOperator(fieldName, searchTerm, this.operator) 
            }
    },
    toString: function () {
        var thisVar = this;
        var output = "searchOperator enum. ";
        output += $.map(Object.keys(this), function (i) {
            if (typeof thisVar[i] !== "function") 
                return i + ": " + thisVar[i].operator;
        }).join(", ");
        return output;
    }
}
...
}(jQuery));

What is the correct way to implement a pattern like this in JavaScript?

I hope this makes sense? Apologies if it's too verbose, but I didn't want to leave anything out that may be important.

Many thanks, James

Name of design pattern that i'm using it

i like to use in my code a design pattern that i don't know the name... actually, i only saw one guy using in my entire dev life.

Promise
  .resolve({})
  .then(someFunc1)
  .then(someFunc2)
  .then(someFunc3)
  .then(someFunc4)
  .then(someFunc5)
  .then(someFunc6)

I'm using Promises to control the flow if my program, passing the result of one operation to the second, and so on...

(I'm using like this because i have async operations, just to be clear)

I would like to know the name of this design pattern, to read more about how to improve it.

Thanks!

Resource Acquisition Is Initialization vs Dependency injection

What is the difference between these two software design patterns?

  • Resource Acquisition Is Initialization
  • Dependency injection

Please suggest good design pattern for event-loop with file-descriptors and fabrics

Please suggest good design pattern for event-loop (or any functional equivalent) with file-descriptors and fabrics (libfabric).

Regex - filter out specific pattern of string

I'm trying to filter out this specific pattern out of a string

myAttribute="myValue"

But I can't seem to figure out on how to ignore the quotes / symbols found inside the 'main' quotes.. If this doesn't make sense, here are few examples:

Examples:

1) onclick="console.log("Hello world"));"   <  must ignore the double quotes in onclick, must return match 1: onclick, match 2: console.log("Hello world"));
2) onclick='console.log('Hello world'));'   <  must ignore the single quotes in onclick, must return match 1: onclick, match 2: console.log('Hello world'));
3) onclick="console.log('Hello world'));"   <  must return match 1: onclick, match 2: console.log('Hello world'));
4) onclick="console.log(\"Hello world\"));" <  must return match 1: onclick, match 2: console.log(\"Hello world\"));
5) onclick="document.querySelector('[data-uniqueid=\"my-id\"]').outerHTML = '';"
   ^ must return (NOTE THE '=' SYMBOL) match 1: onclick, match 2: document.querySelector('[data-uniqueid=\"my-id\"]').outerHTML = '';

This is my current Regular Expression:

(\S+)=["'].*["']$

NOTE: It actually has to ignore every single character found between the 'main' quotes and support multiple attributes (so onclick="myValue" onmouseover="alert('hello world!');") as one string).

Multiple "finally" clauses/"with" statements added on the fly?

Let's say that I am writing code where I need a fail-safe section that - in case of a failure - will save me from wasting money. For example, code that buys virtual servers via AWS API and since those are paid per hour, it's preferable to shut them down as soon as they stop being useful.

The problem is, I don't know how many such instances I would use and I would create them on the fly, adding them to some list or whatnot. The "destructor" of each of the instance might have an unexpected exception and because of that, I'm afraid that any code with a finally clause would be ugly. I cannot also think of how I would use with because I would be introducing objects on the fly. What are other fail-safe solutions I could use with Python?

dimanche 28 août 2016

pattern or framework to implement 4-eye (dual control) principle

I am trying to develop a 4-eye (dual control) functionality for one of my application modules. If an administrator has created a account, then another administrator will approve that account, then only it will be active. Or, if an administrator has created a transaction, another administrator will approve that transaction. It's for additional review and fraud prevention.

I am thinking to add columns like CREATED_BY, APPROVED_BY, STATUS (APPROVED|UNAPPROVED) for each entity which i want to be 4-eye enabled. Then i will add a logic to display the unapproved records as tasks in administrator dashboard, so that they can approve.

However, this looks like very old & manual way.

Is there any design pattern or any framework which i can use in a generic manner instead of the logic i described above? Or is there any better way?

Thanks,

In the real-life application, in which situation, the proxy design pattern will be used

I am just wondering in the real-life application, where should the proxy design pattern be used? Could you provide some example?

I read some articles about proxy design pattern, based on my understanding, proxy provides additional logic. But why the additional logic will be added in the proxy instead of the original object?

For example, a movie star has an agent, the agent will decide which movie the star will take based on payback, why the movie star can not make the decision by himself?

How to use inversion of control to create plug and play code in java?

I want to create a Java SDK for my team which creates the ability for them to create say a simple Java Class ( a plugin of sorts), register it somewhere and have Java choose, during run time which java class plugin to use.

Let's take a trivial example: I have 3 Java classes. Inside each is a function that takes a string and prints out "Short Greeting" + inputStr, "Long Greeting" + inputStr, and "Blah" + inputStr) respectively. Say they all implement an interface.

I wanted a design where these classes would be registered somewhere and tomorrow someone else can write a 4th class which would print something else out (also implements same interface). The decision for which class to choose should be based on say a input from a user?

ie. I can say java -jar my.jar -inputString "John" -pluginName="long"

and the jar would instantiate the correct class and implement the correct logic.

I know that I can have a simple switch case statement or if else if and else logic but this was a trivial case and in reality I want my code to be modularized so future additions of plugins are completely separate from each other.

I was told to look into IOC and dependency injection but I didn't find any good tutorials online. Any help would be appreciated, thanks in advanced.

Storing and comparing grid patterns

I have a 2 dimensional array that stores pattern information. The data may look something like this:

enter image description here

var testGrid = [["blank", "red", "blank"],
/* row 2 */ ["blank", "yellow", "green"],
/* row 3 */ ["blank", "blue", "blank"]];

The max pattern size is a 3 by 3 grid, however, not all spaces have to be used. Since blanks basically mean that there is no information there, I regularly encounter scenarios where two patterns are structured differently, but are functionally the same. Like this:

[["red", "red" "blank"],
["red", "red", "blank"], 
["blank", "blank", "blank"]

[["blank", "blank", "blank"],
["blank", "red", "red"],
["blank", "red", "red"]]

All patterns would have 4 possible representations due to orientation. However, some patterns like this one below:

enter image description here

[["blank", "blank", "blank"],
["blank", "yellow", "green"],
["blank", "blue", "blank"]]

would have 8 possible representations in a 3 by 3 grid.

So I have a few questions:

  1. What would be the best way to store this data? I was thinking I could store the more simple patterns as a 2 by 2 grid, which would reduce the amount of checks I would have to do on those to the normal 4.

  2. What is the best way to check against patterns already in the database? Just loop through a function that compares the newly created pattern to every other entry in the database? (I'm using a mongoDB by the way).

Single responsibility principle of a class when processing a queue in a thread

I am using a library which provides me a callback everytime a message is received. But within this callback I cannot publish a message to whoever the object that sent the message. So what I've done is I created another class "ReceivedMessageHandler" and created a Queue in that class. Then from the callback method I call the insertToQueue method of ReceivedMessageHandler and process the messages there. Now there is a ScheduledExecutor in the ReceivedMessageHandler class that processes the queue. So according to single responsibility of a class, is what I've done correct or should I create another class which has the Queue object and has getters setters for it. Then process the items in that queue in the ReceivedMessageHandler. Is that how it should be done or is what I've done correct? Any advice would be much appreciated.

Swift, Observer pattern with closures

I'm trying to implement the Observer pattern in swift using only functions:

var closures: [() -> Void] = []

class A: NSObject
{
    static var c = 0
    var i = 0

    override init()
    {
        super.init()
        self.i = A.c
        A.c += 1
    }

    func foo()
    {
        print("Hi: \(i)")
        print("\(A.c)")
    }
} // class

var aa:A? = A()

closures.append(aa!.foo)

for item in closures
{
    item()
}

aa = A()

for item in closures
{
    item()
}

this prints:

Hi: 0
1
Hi: 0
2

First question, it looks like the instance variable i is never modified, do you know why?

Second question, will it leak memory? Since I have an array of functions, will aaever be released without emptying the array?

Third question, any better idea for an Observe pattern using just functions? (I don't want to use protocols)

Reactjs Redux should we create sub reducer for every object in the state tree?

redux app as far as i have learned, proper way to maintain your state tree is to normalize it, flaten data as far as possible and use combinereducer to create slices of the state tree.

example App that has posts and users

const rootReducer = combineReducers({
  user:userReducer,
  posts:postsReducer,
});
const store = createStore(rootReducer);

given posts array keep all posts init, State.posts can look like

let initialState =   {
    byId:{1:{id:1,title:'post1'}},
    ids:[1],
    meta_data:{unread:1,old:0}
    }

now if we have around 10,000 posts we would end up with state.post.ids.length === 10000 and this is fine,

Question is. since our reducer returns a new state every time it needs to update for example we need to update the meta_data.unread to be equal 0, we will return a new Post object.

return object.assign({},state,{meta_data:{unread:0,old:1}})

which will re-render all Selectors and components that consume any attribute of state.post tree !

which sound like a problem right ?** all we wanted is updating unread counter.. why recalculate all selectors and components of Posts ?

so i had this idea that may be the state.posts should also be composed used combineReducers so that every attr. of posts should have a reducer it self.

splitting postsReducer into multiple

postsMainReducer, ==> deal with adding or removing posts
postMeta_dataReducer, ==> deal with meta_data of posts
singlePostReducer ==> Now this is dynamic !! how can i create such ??

is this correct ?, i'm adding more complexity than needed ?

-->can someone point show us a picture of an already running enterprise app state tree ? so we can learn how from it how to organize state ?

Any guidelines or books for coding native and web applications for desktops and mobile devices?

After using so-called cross-platform tools, developers have had to code for each platform when applications get just a little sophisticated:

Why you should stay away from Appcelerator’s Titanium:
http://ift.tt/2brB5SN

We all know about the MVC design pattern, but I am wondering about the many other pitfalls you may encounter while coding i18n applications for various devices.

Most guidelines out there are just about particular mobile devices. I am also interested in the differences between Swing/Java FX and IcedTead. Most users would access a web-based app. Power users while using their mobile devices will go native and while sitting on their desktop will be able to access lots of more functionality. So, in a sense it is not just a MVC, more like the adapter/facade design pattern.

Golang MVC structur

I searched many sites and I saw a lot of sources in github and i haven't solution.

I created mvc website pattern in Golang:

  • app
    • controllers
    • models
    • lib (All the features class/functions)
    • middleware
    • router.go
  • resources
    • views
  • main.go

My question is: How to inject config to have everywhere settings and other implemented class that will always be needed (like load speed single page)

One more thing(additionally): Can anyone recommend me a good material or transcribe MVC tricks idea works MVC with golang (General useful information)

what is the need of Adapter Design pattern?

In the below adapter design pattern sample code, why a new class is introduced instead of using multiple interface in the client?

interface ITarget
{
  List<string> GetProducts();
}


public class VendorAdaptee
{
   public List<string> GetListOfProducts()
   {
      List<string> products = new List<string>();
      products.Add("Gaming Consoles");
      products.Add("Television");
      products.Add("Books");
      products.Add("Musical Instruments");
      return products;
   }
}


class VendorAdapter:ITarget
{
   public List<string> GetProducts()
   {
      VendorAdaptee adaptee = new VendorAdaptee();
      return adaptee.GetListOfProducts();
   }
}


class ShoppingPortalClient
{
   static void Main(string[] args)
   {
      ITarget adapter = new  VendorAdapter();
      foreach (string product in adapter.GetProducts())
      {
        Console.WriteLine(product);
      }
      Console.ReadLine();
   }
}

I have the below queries related to the above code.

  • What, if ShoppingPortalClient directly inherits VendorAdaptee?
  • In which scenario we need adapter class?
  • why instead of simple inheritance a needed class, creating this pattern to access another class method?

samedi 27 août 2016

Design pattern for parsing text

I have a kind of logical problem. I have to write a program which should parse messages of different types. Below I show an example how those messages look like:

MESS1

DATE=06.06.2016
CAR_MODEL=OPEL

#Total_Number3
#Max_HP123


MESS2

DATE=12.01.2016
CAR_MODEL=FORD

MARTIN/SMITH
JOHN/PUTIN


MESS3

DATE=13.12.2016
CAR_MODEL=BMW

1/3/4

I know its not a difficult to code in a simple way, but I would like to implement this using design patterns which allow me to easily modify it when new type of message appears, some type of message changes or a message contains data in different order.

P.S I was thinking about Builder but messages does not contain the same fields so in my opinion it does not fit.

Greetings and thanks in advance!

Dependency Inversion Principle's second statement elaboration

Following two statements are core of the Dependency Inversion Principle(DIP):

"High-level modules should not depend on low-level modules. Both should depend on abstractions." "Abstractions should not depend on details. Details should depend on abstractions."

I read different books and article about DIP; all of them explained the first statement but none of them explain the second statement: "Abstractions should not depend on details. Details should depend on abstractions". Please explain what exactly are the meaning of this second statement.

SOLID principle exceptions

I try to apply SOLID principles in my project's class design.Are there any exceptions of SOLID principles? Do we HAVE to apply these principle DEFINITILY.For example i prepared a factory class.

class XAdderFactory
{
    private Person _person;
    public bool PersonHasNoRecords
    {
        get
        {
            return string.IsNullOrEmpty(_person.HasXRecords);
        }
    }
    public XAdderFactory(Person person)
    {
        this._person = person;
        if (PersonHasNoRecords)
        {
            new XListMakerAFactory(person);
        }
        else
        {
            new XListMakerB(person);
        }
    }
}

This class never confirms the OCP principle.
New type list makers maybe required in future and i must add new else if block .
Is my design bad?
Or are there exceptions of SOLID princples that not mentioned too much?
I am not sure but my example comply "Strategic Closure" of OCP? If you have another examples about SOLID exceptions,i think it would be helpfull for designers.

How to tackle system design interview questions asked in a Software dev Interview?

What are the important things which we need to keep in mind while answering these kind of questions. How much weight age is given to these kind of questions in any interview. Does the interviewer expect the candidate to answer the questions correctly ?

Scala: Companion object with arguments

I am looking for a way to initialize a singleton object with arguments for configuration. I tried this, it has the risk for re-instantiation.

class A(in:Int) {
  def method = {}
}

object A {

  var singleton: Option[A] = None

  def getInstance(): A = {
    if(singleton.isDefined)
      singleton.get
    else {
        throw InitializationException("Object not configured")
      }
  }

  def getInstance(in:Int): A = {
    singleton = Some(new A(in))
    singleton.get
  }
}

Is there a better way?

design pattern, a vector of objects, each of two possible types

I need to store objects of exactly 2 types in a vector, the both types have almost nothing in common ...

After storing them in the vector, i want to iterate over that vector and perform an action, depending on the type

my thoughts so far ...
(1) polymorphism :
overkill, and wouldnt help me much, as i probably would do a

if(dynamic_cast<T1>() != nullptr) {
    ...
} else {
   ...
}

(2) merge both types (methods and fields) and add a boolean, representing if its type 1 or 2

both patterns seem totally clumsy to me, there is propably a total simple solution, i simply wont see ...

The first type is something like this :

struct PatternMatch {
  int length;
  int indexInDict;
}

the second

struct NoMatch {
  std::string rawChars;
}

Project(MVC) layers confusion

I am writing a web application using MVC and Entity Framework. My current structure includes Service layer, Business Layer (Domain Model), Data Layer, Presentation Layer and Mapper. Flow is like this. Presentation Layer makes request to Service Layer like service.GetSomeData(). Service layer forward it to Data layer and data layer maps the object to entity using mapper layer and return a DTO back to service layer which sends it back to presentation layer. Service layer implements Facade pattern and Data Layer is DTO pattern. Things are good so far.

Now Serious Problem Came Up: My controllers are getting fatter and fatter by doing additional work which should be in business layer and data layer has also started doing business logic stuff. In short i am all over the places. By business logic stuff in data layer i mean if my DTO object needs some additional information to load or need to make some decision for some behavior it does all weird and stupid if checks and adds it to the object after the data is retrieved from table with in data layer. It has also start doing bunch of 'IF this then this IF that then that things' which in my thoughts should not happen at data layer. I have started working in design patterns and really wanted to make it better, but i think i have failed at this point. So i decided i should move my business logic from controller and data layer to business layer. However, I am not able to figure out how i can do this? I mean, suppose my one controller is making 10 calls to database using data layer and getting data and what not. Do i have to create same 10 methods in business layer and make a call to data layer from business layer, get the object back from data layer, perform the business logic and send it back to presentation layer Or I should do something with Service Layer that does this business logic processing before passing the DTO back to presentation layer?

I have completely hit the wall and it's not letting me sleep either :(.

I will really appreciate if somebody just guide me towards the right path

vendredi 26 août 2016

Problems or examples to practice concepts presented by Head First Design Patterns book

I am currently reading Head First Design Patterns book. I am finding it very interactive and simple to learn. But I think there is a need for practice. Could anyone please tell me where I can get good practice problems which relates with the concepts presented in this book?

Is there a design pattern for modelling a group of complex processes?

I've become responsible for a Java/Tomcat site that manages sales orders. It is largely a collection of static functions that happen to use objects for orders, customers, vendors and the like. I am looking for patterns for a replacement architecture.

My block to understanding things is that I don't have an overarching concept. I could say "This is an order processing factory, using instances of order, customer, etc.", but that seems to be merely a weak wrapper for a set of static functions.

I'm looking for links to discussions on how to define focused classes within complex processes. I already have database mapped classes for orders, etc. Can something like "validate order" really be a class?

Android: what is the best way to send presence?

I want to send that the user is currently using the app to my server in regular interval.

User is active,

  • When he is on any activity of my app and the user should see it in screen.

User is Inactive,

  • If the user is not in any of my app's activity
  • If the user has minimized the app
  • If the user is in my app's activity only, but screen is locked

For this, I have implemented Android's ActivityLifecycleCallbacks and trying to send user is active in onActivityResumed() and inactive in onActivityPaused()

It works as expected, but there are many activities in my app, so transition between Activities also send this presence status, which is very bad for end user.

How can I control this ? How can I send only at regular intervals instead of flooding the presence ?

Generally what is the best way to do something at regular intervals in Android ? which means, the task should be done only on particular intervals even it has called any number of times.

Generic operations using Command and Specification Pattern

In current project I need implement some generic Operations infrastructure.

In a example:

An entity can have X operations , each operation will have these methods:

IsAvaliable - perform some check if I can execute operation above entity, bool

Execute - perform some logic if result of methos IsAvaliable is true, void

Also I need to get all avaliable operations for concrete Entity - these list will be shown to user, based on which entity is user currenty editing in UI

I decided to combine Command Patterm and also Specification Pattern for IsAvaliable logic.

I created Generic abstract OperationBase class for all Operations:

public interface IOperation
{
    void Execute();
}

public interface IOperation<T> : IOperation
{
     bool IsAvaliable(T o);
}        

public abstract class OperationBase<TEntity> : IOperation<TEntity>, ITransientDependency
    {
    private ISpecification<TEntity> specification;
    protected TEntity entity;
    public OperationBase(TEntity entity)
    {
        this.entity = entity;
    }

    public abstract void Execute();
    public virtual bool IsAvaliable(TEntity entitySpec)
    {
        return specification.IsSatisfiedBy(entitySpec);
    }

    public void SetSpecification(ISpecification<TEntity> specification)
    {
        this.specification = specification;
    }

}

Then I also created base class for Operations which specified Entity Type:

    public abstract class TestOperationBase<TestEntity> : OperationBase<TestEntity>
{

    public ODUOperationBase(TestEntity entity) : base(entity)
    {
    }

    protected Action Operation { get; set; }

    public override void Execute()
    {
        if (base.IsAvaliable(entity))
        {
            Operation?.Invoke();
        }
    }

}

After that I creted concete operation above entity:

public class TestConceteOperation1 : TestOperationBase<TestEntity>
{

    public TestConceteOperation1(TestEntity entity) : base(entity)
    {
        base.Operation = MethodImplementation;
        base.SetSpecification(OperationSpecs.TestEntitySpec);
    }

    public void MethodImplementation()
    {
        Console.WriteLine("Custom operation invoking");
    }


}

And there is example of useage of this logic:

    public void ExecuteTestOp()
    {
        TestEntity testEntity= new TestEntity();
        TestConceteOperation1 oper = new TestConceteOperation1(testEntity);
        oper.Execute();
    }

Also smaple code for Operation specification:

  public static ISpecification<ODUZaznam> TestEntitySpec = new Specification<TestEntity>(
        o =>
        {

            return (o.Param1== 1 &&
                    o.Param2 == 2 &&
                    o.Param3 > 0 &&
                    o.Param4 == false
                );
        }
    );

Now what I need to know is How to get list of avaliabe operations. Reflections is a solution (find all interfaces IOperation which has generic parameter with concrete type e.g.

        private List<Type> GetAllAvalibleOperationTypesFor<TEntity>()
    {
        List<Type> operationsTypes = new List<Type>();

        Type tOperation = typeof(IOperation<TEntity>);
        Type tConcrete = null;
        foreach (Type t in Assembly.GetExecutingAssembly().GetTypes())
        {
            // Find a type that implements IOperation<TEntity> and is concrete.
            // Assumes that the type is found in the executing assembly.
            if (tOperation.IsAssignableFrom(t) && !t.IsAbstract && !t.IsInterface)
            {
                tConcrete = t;
                operationsTypes.Add(tConcrete);
            }
        }

        return operationsTypes;
    }

Now I need to check if operation is IsAvaliable, to do that I need to create instances for each operation and invoke IsAvaliable method. I don´t like this idea of creating instances. Specification method is static and only need to know concrete entity, which I know when i get OperationsTypes collection.

I have no idea how to solve this situation. Maybe some static method inside TestConceteOperation1 class with TEntity as parameter which call static specification method. But this appropoach will lead to that Develepoper must remeber implement this static class in every operation.

Do have anybody some idea (how get List of avaliable operations for concete entity based on Specification = true result) how to do it better way ?

Thanks for any ideas, and sorry for my english.

how to minimize number of classes to modify when interface is changed

There is an interface Accountable which has 2 methods. There are nearly 9 classes which implement the Accountable interface.

public interface Accountable{
    boolean isAccountable();
    float getWorth();
}

We have got a new requirement as follows: Two more methods declarations to be added to the interface. But we need to minimize the effect on the existing classes. I was told that we can use Adaptors to resolve the issue. But I am not sure how to do it. Could anyone please help me solve the issue?

Initialize a POJO dynamically from another method

Let's say I have these set of POJO class that implement an interface but there are no common attributes here.

public interface MainIfc {}

class Ifc1 implements MainIfc {
    private String a1;
    public String getA1() {
        return a1;
    }
    public void setA1(String a1) {
        this.a1 = a1;
    }
}

class Ifc2 implements MainIfc {
    private String x1;
    private String x2;
    public String getX1() {
        return x1;
    }
    public void setX1(String x1) {
        this.x1 = x1;
    }
    public String getX2() {
        return x2;
    }
    public void setX2(String x2) {
        this.x2 = x2;
    }
}

And in conjunction with these POJO classes I have a couple of methods which I can use to retrieve the type of POJO being returned based on another value and the actual POJO with values.

public class GetIfc {
    public Class getIfcType(int code) {
        if (code==1)
            return Ifc1.class;
        else
            return Ifc2.class;
    }
    public MainIfc getIfc(int code) {
        if (code==1) {
            Ifc1 thisIfc = new Ifc1();
            thisIfc.setA1("Ifc1");
            return thisIfc;
        } else {
            Ifc2 thisIfc = new Ifc2();
            thisIfc.setX1("Ifc2");
            thisIfc.setX2("Ifc2");
            return thisIfc;
        }
    }
}

Is there a way using which I can read the concrete POJO safely in my code and use the getters/setters? I have gone through quite a few questions which provide answers based on Reflection but that isn't working for me. The getters/setters aren't visible and when I call .getClass() on the returned Object I see it is the MainIfc interface.

Make gradient background pattern fill width of div and repeat vertically automatically

I'm trying to modify a code that I got from this CSS3 Pattern Gallery. The modification I'm trying to achieve is for the background tiles to be resized according to the div size. It's for a lazy loading feature where I want the background to always contain the div it's contained in, no matter what size the div is (regardless of if the width is measured in px or %).

I want the squares of the grid to be filled by 5% of the div width, which is easy. In that way the background pattern will never be cut by the width of the div, since it's always filling the tiles of the pattern by 5% across the div.

But I also want the height of the squares to have the same measurements as the tile's width, in order to make it a square pattern. I'm fine with the tiles being cut on the vertical, as long as the tiles are not cut on the horizontal. And that's what I'm having trouble with. For now, I tried to put auto to the height of the background-size. But that isn't working, obviously.

Does anyone have any idea of how to work this out? Maybe it's achievable through SASS variables?

JSFiddle of the current stage I'm in now: http://ift.tt/2bls6CQ

How can be controled / coordinated algorithm

Below picture is a simple part of complex algorithm.enter image description here I try to prepare some classes in accordance with algorithm.

abstract class Person
{
    public string HasXRecords { get; set; }
    public int PersonAnotherFeature { get; set; }
    public List<X> Xs { get; set; } = new List<X>();
}
abstract class X
{
    //There will more than 1000 type subX classes
}

interface IAdder
{
    void AddXToList();
}

interface IRemover
{
    void RemoveXFromList();
}

class XAdderFactory
{
    private Person _person;
    public bool PersonHasNoRecords
    {
        get
        {
            return string.IsNullOrEmpty(_person.HasXRecords);
        }
    }
    public XAdderFactory(Person person)
    {
        this._person = person;
        if (PersonHasNoRecords)
        {
            new XListMakerAFactory(person);
        }
        else
        {
            new XListMakerB(person);
        }
    }
}

class XListMakerB: IAdder
{
    private Person _person;
    public XListMakerB(Person person)
    {
        this._person = person;
        AddXToList();
        new PersonXListEvaluator(person);
    }
    public void AddXToList()
    {
        //Dynamic instance of X will be added in to person Xlist.
    }
}

class XListMakerAFactory
{
    public XListMakerAFactory(Person person)
    {
        switch (person.PersonAnotherFeature)
        {
            case 1:new XListMakerA1(person);
                break;
                //there will be XListMakerA2,XListMakerA3 etc.
        }
        new XRemoverFactory(person);
    }
}
class XListMakerA1: IAdder
{
    private Person _person;
    public XListMakerA1(Person person)
    {
        this._person = person;
        AddXToList();
        new PersonXListEvaluator(person);
    }
    public void AddXToList()
    {
        //_person.Xs.Add(new X1());
        // According to business logic,X2,X3 etc. will be added manually.
    }
}

class XRemoverFactory
{
    public XRemoverFactory(Person person)
    {
        new XRemoverFromList1(person);
        new XRemoverFromList2(person);
    }
}

class XRemoverFromList1 : IRemover
{
    private Person _person;
    public XRemoverFromList1(Person person)
    {
        this._person = person;
        RemoveXFromList();
    }
    public void RemoveXFromList()
    {
        //According some business logic some Xs will be removed.
    }
}

class XRemoverFromList2 : IRemover
{
    private Person _person;
    public XRemoverFromList2(Person person)
    {
        this._person = person;
        RemoveXFromList();
    }
    public void RemoveXFromList()
    {
        //According some business logic some Xs will be removed.
    }
}
 class PersonXListEvaluator
{
    public PersonXListEvaluator(Person person)
    {
        //According to business rules evaluation will be cordinated.
    }
}

My question; 1) Do you think clasess compliy with SOLID principels? 2) How can be designed flow better?

jeudi 25 août 2016

C++ Use Function Preconditions Or Wrapper Classes with Invariants?

I find myself writing a lot of functions that begin with many preconditions, and then I have to figure out how to handle all the invalid inputs and write tests for them.

Note that the codebase I work in does not allow throwing exceptions, in case that becomes relevant in this question.

I am wondering if there is any C++ design pattern where instead of having preconditions, input arguments are passed via wrapper classes that guarantee invariants. For example suppose I want a function to return the max value in a vector of ints. Normally I would do something like this:

// Return value indicates failure.
int MaxValue(const std::vector<int>& vec, int* max_value) {
    if (vec.empty()) {
        return EXIT_FAILURE;
    }
    *max_value = vec[0];
    for (int element : vec) {
        if (element > *max_value) {
            *max_value = element;
        }
    }
    return EXIT_SUCCESS;
}

But I am wondering if there is a design pattern to do something like this:

template <class T>
class NonEmptyVectorWrapper {
  public:
    static std::unique_ptr<NonEmptyVectorWrapper>
             Create(const std::vector<T>& non_empty_vector) {
        if (non_empty_vector.empty()) {
             return std::unique_ptr<NonEmptyVectorWrapper>(nullptr);
        }
        return std::unique_ptr<NonEmptyVectorWrapper>(
            new NonEmptyVectorWrapper(non_empty_vector));
    }

    const std::vector<T>& vector() const {
        return non_empty_vector_;
    }

  private:
    // Could implement move constructor/factory for efficiency.
    NonEmptyVectorWrapper(const std::vector<T>& non_empty_vector)
            : non_empty_vector_(non_empty_vector) {}
    const std::vector<T> non_empty_vector_;
};

int MaxValue(const NonEmptyVectorWrapper<int>& vec_wrapper) {
    const std::vector<int>& non_empty_vec = vec_wrapper.vector();
    int max_value = non_empty_vec[0];
    for (int element : non_empty_vec) {
        if (element > max_value) {
            max_value = element;
        }
    }
    return max_value;
}

The main pro here is that you avoid unnecessary error handling in the function. A more complicated example where this could be useful:

// Finds the value in maybe_empty_vec which is closest to integer n.
// Return value indicates failure.
int GetValueClosestToInt(
    const std::vector<int>& maybe_empty_vec,
    int n,
    int* closest_val);

std::vector<int> vector = GetRandomNonEmptyVector();
for (int i = 0; i < 10000; i++) {
    int closest_val;
    int success = GetValueClosestToInt(vector, i, &closest_val);
    if (success) {
        std::cout << closest_val;
    } else {
        // This never happens but we should handle it.
    }
}

which wastefully checks that the vector is non-empty each time and checks for failure, versus

// Returns the value in the wrapped vector closest to n.
int GetValueClosestToInt(
    const NonEmptyVectorWrapper& non_empty_vector_wrapper,
    int n);

std::unique_ptr<NonEmptyVectorWrapper> non_empty_vector_wrapper =
    NonEmptyVectorWrapper::Create(GetRandomNonEmptyVector());
for (int i = 0; i < 10000; i++) {
    std::cout << GetValueClosestToInt(*non_empty_vector_wrapper, i);
}

which can't fail and gets rid of the needless input checking.

Is this design pattern a good idea, is there a better way to do it, and is there a name for it?

Design pattern for many if statement and Boolean condition?

I am wondering if there is any design pattern for such situation:

private static boolean check(String s) {
    if(isBook(s)) {
        System.out.println("Book");
        return false;
    }else if(isEmail(s)) {
        System.out.println("Email");
        return false;
    }
    return true;
}

private static boolean isBook(String s) {
    if(s.equals("B")) return true;
    return false;
}

private static boolean isEmail(String s) {
    if(s.equals("E")) return true;
    if(s.length() > 4) return true;
    return false;
}

There will be many isXXX in check method, but I don't wanna to have many if-else statement.

Which creational pattern best describes this code?

I am studying design patterns (no, this is not for school, but my own edification and self-improvement). A project that I have worked on has the following architecture for one of its components:

class ProductFactory {
    static AbstractProduct * getProduct() {
        #ifdef ANDROID
            return new AndroidProduct;
        #elif defined IOS
            return new IOSProduct;
        #endif
            return 0;
    }
};

I'm having a terrible time trying to classify this code according to my readings on Abstract Factory and Factory Method. For example, the creator class is concrete and only one kind of product is created (as opposed to the canonical window, scrollbar, etc.). But which product-by-platform is created is not deferred to sub-classes -- rather, different sub-classes are created by the one creator class.

So my question is very simple: what pattern does the above code most/best conform to, and why?

Much appreciated!

Good tutorial(s) explaining code organization concepts in javascript

I am working in a team of java developers and I am looking for a complete tutorial to explain them the core concepts of javascript.

More precisely, I am looking for a tutorial explaining the different ways to organize a javascript code (Prototype pattern, Constructor pattern, Object literals, Module Pattern, Revealing Module Pattern etc.).

Then, it would be a good thing if it could talk about the following related concepts : this, namespaces, variables scope/hoisting, closures, IIFE, module augmentation, module dependencies (AMD/CommonJs).

For the time being I found these different ressources :

Module Pattern : http://ift.tt/135lixg

Module Pattern : http://ift.tt/1n2yLER

JS Design Patterns : http://ift.tt/2bm7NXH

Constructor/Prototype Pattern (by example) : http://ift.tt/OefEWE

Other Usefull link : http://ift.tt/1abKVUF

my Class.forName is giving som issue in java 8

package designpattern.Singelton;

import java.lang.reflect.Constructor;

public class ReflectionIssueSingelton {

    public static void main(String[] args) throws Exception {
        Singelton s1 = Singelton.getInstance();
        Singelton s2 = Singelton.getInstance();

        print("s1", s1);
        print("s2", s2);
    }

    //Reflection

    //Load the class to be reflect
    @SuppressWarnings("unchecked")
    Class clazz =  Class.forName("designpattern.Singelton.Singelton");

    //getting degault declared constructor i.e default constructor
    Constructor<Singelton> ctor = clazz.getDeclaredConstructor();
    ctor.setAccessible(true);
    Singelton s3 = ctor.newInstance();


    private static void print(String name, Singelton object) {
        System.out.println(String.format("Object: %s, Hashcode: %d", name, object.hashCode()));

    }

}

enter image description here

Pattern search in a string and replace with *sometext* | VB.NET

I'm new to VB.net development, as i'm making an application, i'm wondering how to search for a specific pattern and replace the result with sometext

eg.

original string : the name of my application is abcdef_ghi. its my first project

Pattern: abcdef_

replacement text: abcdef_xyz123

output: the name of my application is abcdef_xyz123. its my first project

neo4j : crosstab values

I am looking for a design pattern regarding crosstable value I would like to store in Neo4j. I have contributors voting at the intersection of a set of items in lines and columns. the lines have a certain weight inputed by the contributor.

How do we deal with the designs of nodes and relationships in this case?

Best,

instance specific code to run in nodejs

In node application which have three different instances running (not using cluster module). I need to implement a scheduler-like-task to run only one of these instances.

  1. I though of creating a variable a environment variable which will be passed in one of these instance and other 2 instances will not have this env-variable to the scheduler function will run in this instance.

  2. opening a file which will acquire the lock and only those instance will execute the scheduler-like code which have this file lock.

Question: What will be the best approach/design-pattern of solving this problem in nodejs?

What component should fetch data in angular 1.5, 2, react? root or child?

I'm working at new project with angular 1.5 (starting component path of building), but question is not about angular, it's about design pattern.

Lets say i have complex website with this main page:

<header></header>
<sidebar-left></sidebar-left>
<sidebar-right></sidebar-rigth>
<mainSection>
  <news></news>
  <movie-list></movie-list>
  <random-quotes></random-quotes>
</mainSection>
<footer></footer>

News, movie list and quotes blocks displaying data from server. Each from their own method/api. So WHO is responsible for fetching data? Should main component fetch data and pass it to children? Or news, movieList and randomQuotes components should fetch data by itself?

1) Main component fetching data map it to scope and pass to children

<mainSection>
  <news items="$ctrl.news"></news>
  <movie-list items="$ctrl.movies"></movie-list>
  <random-quotes items="$ctrl.quotes"></random-quotes>
</mainSection>

VS

2) Every child component should fetch data

class MovieListController {
  constructor(MovieService) {
    this.movieService = MovieService;
  }
  $onInit() {
    this.movies = [];
    this.movieService.getAll().then(response => this.movies = response);
  }
}

export const movieList = {
  template: '<movie-item ng-repeat="movie in $ctrl.movies"></movie-item>',
  controller: MovieListController,
};

Safely passing around references to an abstract class in C++

I am developing an application for a data-collection controller. It has to interface with lots of different other devices, which in turn might provide different types and amounts of data. To this end the following hierarchy was devised (it's a bit lengthy but bear with me):

  • The basic unit of information is the Datum. Datum itself is an abstract class, the descendants of which represent different types of [physical] quantity: temperature, pressure, energy, power, relay state, etc. Each Datum instance represents a single reading (at some moment in time).

  • Data are collected by Devices, which in turn contain several IOs. A Device instance represents a concrete physical data-gathering device; its class (a descendant of the abstract Device class) represents the model of device and contains all the model-specific code necessary to interface with it and extract readings from it. This is done by calling the virtual function void Device::update().

  • Each IO instance represents a variable which a device collects. For example, if the device is a multi-channel temperature monitor, then an IO represents a single sensor connected to the device. The IO can be queried for a value by calling IO::get_value(), which returns a Datum.

  • Finally, the Node class keeps a list of all devices attached to the controller, another list of all IOs in those devices, and provides methods for polling all devices at once, individual devices, individual IOs, etc.

These relationships are reflected in the following diagram:

Diagram of class relations

Now, for the problem itself:

In all of this, a lot of instances of descendants of abstract classes must be passed around and stored all the time: the Node stores its Devices and their IOs, the devices themselves store their own IOs as well, Data get created and returned and passed around and destroyed, the device and IO list gets updated in place, etc. But it is unclear how to implement all this passing around:

  • passing instances of abstract classes by value is obviously out of the question, and even it they were not abstract, it might result in object slicing.
  • passing them by reference works for arguments of a function, but what about creating and returning Datum instances? they get created as local variables in the IO::get_value method, and so are destroyed when it returns. Additionally, it is not possible to store references, e.g. in an std::map.
  • finally, passing pointers is dangerous. In order to return something as a pointer one must allocate memory in the method, and then it is the caller's business to free the memory after the returned value is no longer used. In addition to being inconvenient, it presents a danger of getting a memory leak, doing a double free, or having some other part of the program dereference a now-empty pointer that has been stored there beforehand.

So I am at a loss as to how one might implement a robust system of exchanging objects like this, with more-or-less foolproof ways of ensuring that the objects behave as a variable passed by value (stay in existence as long as they are needed, but not longer) while retaining the duck-typing provided by inheritance of a common interface.

How to genericize uint_t based functions

I created a utility function here for demonstration, which take an unsigned 16-bit integer. I have multiple use cases where I want to reuse this function for say uint8_t, uint32_t, and uint64_t. My first approach was to remove the type, and instead pass a void pointer. This however did not work because in order to perform any sort of arithmetic I would need to dereference the pointer. With that said, the only way to do that with void* is to cast the associated type. Aside from a nasty switch statement checking for types, I’m not sure how else to get the job done. I did find a tagged union approach which I was not familiar with, but that still shares the same concern above. The function in question can be found below:

#define MAX_BYTE 0xFF
#define BITS_PER_BYTE 8
static void encodeToUint16(uint16_t *num, uint8_t *buffer, size_t len) {

    uint8_t bytePos = 0;

    for (int i = len; i >= 0; i--) {
        buffer[i] = (i == len) ? (*num & MAX_BYTE) : ((*num >> bytePos) & MAX_BYTE);
        bytePos += BITS_PER_BYTE;
    }
}

My goal is to try and find a safe, generic way for this function to be shared across different unsigned int types. Although this question seems specific to encodeToUint16, the end pattern is something that can shared throughout the project in general.

Practice to ensure ViewModel state doesn't change after validation

If Controller first validates ViewModel properties and then uses ViewModel properties, there may be small chance that ViewModel state may change to invalid between validation and usage, resulting in exceptional control flow.

Is there any common practice or pattern to ensure ViewModel state doesn't change and / or properties can be safely used after validation?

Why there are no destructor patterns?

I have seen and used many times creational patterns like Builder or Factory. I think there many advantages to control the creation of (business) objects and not let users create these objects in whatever way they see fit.

I think that these concerns apply also when you wish to destroy such objects. For example, to ensure that resources are properly closed and freed. Despite this, I have never seen any mention of patterns related to the destruction of objects.

Do you know if any such patterns exist and, if not, why is it not reasonable to have such patterns?

Design pattern to use for Null check through Reflection

What we are doing - Annotation driven null and empty values check for Object values.

How we are doing - Creating one annotation and putting that annotation on the variables

I am not sure what design pattern i need to use to make it work best.

C++ simple singleton implementation return statement for constructors

I am trying to implement a simple singleton pattern in C++.

#include <iostream>

class simpleSingleton
{
private:
    static simpleSingleton * pInstance;
    simpleSingleton(){}
    simpleSingleton(const simpleSingleton& rs) {
        pInstance = rs.pInstance;
    }
    simpleSingleton& operator = (const simpleSingleton& rs)
    {
        if (this != &rs)
        {
            pInstance = rs.pInstance;
        }
        return *this;
    }
    ~simpleSingleton(){};

public:
    static simpleSingleton& getInstance()
    {
        static simpleSingleton theInstance;
        pInstance = &theInstance;

        return *pInstance;
    }
    void demo()
    {
        std::cout << "simple singleton."
                  << std::endl;
    }
};
simpleSingleton *simpleSingleton::pInstance = nullptr;


int main()
{
    /*Version 1 */
    simpleSingleton * p = &simpleSingleton::getInstance(); // cache instance pointer p->demo();
    p->demo();

    /*Version 2 */
    simpleSingleton::getInstance().demo();

    return 0;
}

My question is about the multiple constructors available for simpleSingleton class

simpleSingleton(){}' 'simpleSingleton(const simpleSingleton& rs)

A constructor is expected to return an object of the class. In the above example neither of the constructors have a return statement. Yet this seems to be standard simpleton implementation. why is that?

mercredi 24 août 2016

Server as Service in background for Android?

I have a notification hanler, which manages to notifiy the user by means of various ways (Snachbar, NotificationManager).

I would like to enhace tihs functionality by adding a service to that notification manager, which runs always in the background and waits/listens for notifications from the backend.

When I trigger a message from my backend like "Please update your app from PlayStore" it should be shown to the user. (I know how to do this, when I triger that from the mobile by a REST call to my endoint.) But I dont know, if it is possible to listen (on a port or something) as a server?

Designing a generic query builder interface (Design Pattern)

This going to be a very long question.

Introduction

I want to design a service for my project. I want to design it properly using the right design patterns and following good coding techniques wherever required and make it such that it is easy to understand, read, modify, extend..... in short it should comply with the design principles in general. I am a beginner programmer and have recently started reading the OOP concepts and design.

Brief details of what we are doing...

In our project, we want to show graphs related to various information that we gather. We are designing various types of graphs like the hour's graph, the day's graph, the month's graph and the year's graph. Each graph shows aggregated data for the respective granularity and each graph being generated using different queries. As we move forward, more and more types of graphs would be needed with further analytic.....

Data storage

The data is stored simply in one table ---> with the details and a column for the date, a column for the hourOfTheDay and the value. This way, we have hourly data for various things. We also have one more table: aggregatedThingData_month. As the name says at the end of each month, we run a cron(we may move to more sophisticated scheduling tools like quartz etc further ) job aggregating the data for the month and storing the value in this table.....

What I want to design & the problem in short

A service/ API for the generation of the graphs. I want to serve different types of requests for different graphs. The request will have the required granularity of the graph and then I have to parse the request, build the appropriate query, get the result set (each type of graph will include different information), process the result set, and send the response(JSON) in the required format.

What I want to achieve (From whatever I understand about a good design)?

From what I understand about good design, it is basically that the code should be re-usable, it should be generic, it should easily be extended and easy to read/ understand (clear....), it should not be tightly coupled etc etc.

From the tasks mentioned above, I think my should have following things:

  1. Depending upon the granularity level, the query should be appropriately generated, dynamically. As we grow with different types of graphs, it should be easily extensible. There should be a class like Query which will have some details and then the QueryBuilder or something like that. There must be concrete QueryBuilders. (may be a Factory/ Builder and Strategy pattern can be used here)....

How can I dynamically build queries and make these interfaces generic.....?(Code to interface, not to implementation....)

  1. Currently we are using Postgres, but there is a high possibility that we move over to MongoDb I want to design it into layers, such that just changing the underlying logic about building the queries, obtaining db Connections etc for different types of db without affecting upper layers.... I need not change everything if need arises to switch among the dbs.

When db is switched, appropriate queries for that db are built -> executed -> resultset processed -> response sent

I want to model such that, no matter what query we require, just providing the appropriate parameters like required fields, joins, conditions, grouping etc will be able to build the necessary query. So a generic Interface for Query Generation and their concrete implementations.....

i.e

"building the specific query" will be a concrete class?.

  1. Just as it is with building query and executing it, I want it to be generic with processing of the result set. How should I define the interface. How should It implement concrete classes for processing of result sets different graphs? Response format may also change from JSON to XML dynamically or may be any other format.

As I am new to programming and have just started to learn designing I need a bit of help and guidance in application of what I have learnt. Simple hints or pointers will help me a lot. This exercise will help me improve my designing skills and help me understand how to think and take decisions and considerations while designing an application.