vendredi 31 juillet 2015

How to implement a composite pattern in Java?

I want to implement a composite pattern in Java in order to map a software development organization. So, let's assume there are multiple project managers and multiple developers. Each developer is assigned to exactly one project manager and each developer is able to code in various programming languages. The project managers lead the developers and know exactly their workload.

I am not a hundred percent sure about this design pattern, but I think that it is the perfect use case for this scenario, isn't it?

The result should be as follows:

I want to query the project manager to check the workload of all developers which are able to code in a specific programming language, e.g. Java.

Here is what I have so far:

Employee.java:

public class Employee {

    private String name = null;

    public Employee() {
        name = "Noob";
    }

    public String getName() {
        return name;
    }

    public void setName(String name) {
        this.name = name;
    }

}

ProgrammingLanguages.java:

public enum ProgrammingLanguages {
    JAVA,
    JAVASCRIPT,
    C,
    PHP,
    SWIFT,
    PYTHON
}

ProjectManager.java:

import java.util.ArrayList; import java.util.List;

public class ProjectManager extends Employee {

private List<Employee> employeeList = null;

public ProjectManager() {
    employeeList = new ArrayList<Employee>();
}

public List<Employee> getEmployees() {
    return employeeList;
}

public void setEmployees(List<Employee> employees) {
    employeeList = employees;
}

public int getTotalWorkload() {
    int workload = 0;
    for (Employee employee : employeeList) {
        workload += employee.getWorkload(); // Error! Cannot resolve method 'getWorkload()'
    }
    return workload;
}

}

Developer:

import java.util.ArrayList; import java.util.List;

public class Developer extends Employee {

private List<ProgrammingLanguages> languagesList = null;

private int workload = 0;

public Developer() {
    languagesList = new ArrayList<ProgrammingLanguages>();
}

public void setLanguagesList(List<ProgrammingLanguages> languagesList) {
    this.languagesList = languagesList;
}

public void addProgrammingLanguage(ProgrammingLanguages language) {
    languagesList.add(language);
}

public List<ProgrammingLanguages> getLanguagesList() {
    return languagesList;
}

public void setWorkload(int workload) {
    this.workload = workload;
}

public int getWorkload() {
    return workload;
}

}

Unfortunately, I get a compiler error in my ProjectManager class, any idea why?

Thanks in advance.

Some situations or cases to use Adapter pattern (examples in c# appreciated)

I am just a starter to design patterns and just learned the theoretical definition and also how to implement in code but love to know various real world situation/cases/scenarios that encourages to use Adapter pattern?

remove file starting with space in shell scripting

I'm trying to write a shell script to cleanup a directory by deleting files that match particular patterns. My code works with all patterns but if the file name starts with space. Although we can delete a file starting with space by rm \ * however if I pass this pattern to my script it won't delete files starting with space. Here is my code:

for file in *;do
 for pattern in $*; do
    if [[ -f "$file" && "$file" == $pattern ]]; then
      rm "$file"
    fi
  done
done

I also tried this simpler code, but the same problem!

for pattern in $*; do    
  if [[ -f $pattern ]]; then  
    rm $pattern
  fi
done

Could you please help!

Call a method without a reference to it from a separate jar library

I am writing a library in Java. A object in the library is referenced by the main application.

The application requires a method to be called at a certain point on one of its objects. The library object wants to invoke this method in the application, with parameters.

I do not want to pass the application object to the library object as a reference because I want it loosely coupled and the Application object is specific to that application. If I pass it just as a Object data type, it will not have the method attached as not that type without casting.

As they are separate jars, static will not work either and want it loosely coupled again.

Example

Application A is running. The library B wants to invoke a method in a object in Application A at a certain point.

Thoughts on solution

  • Was thinking maybe somehow use the notify method on the object. But then the parameters are an issue.
  • Could a generic Object type be passed, and then the type of the object is passed as an argument? Then the object can be cast and the method called?
  • Is this possible? Does a clever design pattern exist?

What is the correct place to put checking of conditions in this use case?

Here is the situation:

I have a database and a class that is basically a representation of a set of fields of different tables in it. Let's call it Message. "Message" does not know of the database and whenever I need to synchronize it to DB I use separate functions accepting instances of Message to do it.

Whenever I need to do some operation that involves synchronizing data from "Message" to database, I do not just call the Modifier1/Modifier2 functions because more often than not, I need to either pass or roll back the whole sequence. (usually when ORA- DB error occurs)

So, I have a queue of actions set up:

std::list<std::function<DBType>>

In reality there is a wrapper class around this queue that receives actions via signals/slots mechanism and executes the whole accumulated pack of actions on:

Execute();

So, it's like this : if I need to update the database in some piece of code:

   // sending update #1
   emit dbAction(std::bind<CREATE SOME FUNCTOR HERE>);
   // sending update #2
   emit dbAction(std::bind<CREATE SOME OTHER FUNCTOR HERE>;
   // flushing the queue
   emit flushDb();

the actions execute, everyone is happy. End of the story. Until now that is. Now, I realized I have to have a set of preconditions on "Message" that will prevent these actions from passing through.

Options available:

1) To inject verification code into called functions. But the conditions have nothing to do with them and entirely depend on external context.

2) To let user of the queue to check conditions in outside code. But let's be realistic - even if I am the said user, what's not enforced, is easily forgotten.

3) To use some class to emit these actions after checking preconditions on the arguments. But this will require to update its interface for any new action and will not allow to just send a lambda through.

4) My current insane solution: instead of just sending std::function with already bound arguments, create a templated functor that keeps parameters accessible until they are actually needed by the queue.

//abstract class so that I can store unrelated template instantiations in a single container in my queue
class  IMessageActionDB
{
  public:
    virtual ~IMessageActionDB();
    enum EActionTypes
    {
          noaction = 0,
      action_type_1 = 1,
      //...
      action_type_N = N
    };

    void operator()(DBType db)
    {
        if(!Verify())
            throw exception;
        BindToExecutable();
        calledFunc(db);
    };
     // will bind whatever is stored in MessageActionDB to the calledFunc
    virtual void BindToExecutable() = 0;
    // will check the action with supplied checker functor
    bool Verify() = 0;

    protected:
    std::function<void(DBType)> calledFunc;
};

// templated action that will accept any function/number of parameters for later use
template<class FunctionType, class ...Ts>
 class  MessageActionDB : public IMessageActionDB
{
  public:
    MessageActionDB(FunctionType f, std::tuple<Ts...> t);

    void BindToExecutable();
    {
        //perform template mumbo jumbo to bind func and parameterPack to calledFunc
        calledFunc = bind_tuple(func, parameterPack)
    }
    bool Verify() 
    {
        //call verifiers in order returning if action satisfies or not
        return result;
    };

  private:
     std::tuple<Ts...> parameterPack;
     FunctionType func;
     std::list<std::function<bool(Ts...)>> actionVerifier;
}; 

This way, I can assign verifier for action based on its EActionTypes type, and queue wrapper can use Verify function at invokation time to check if the action is allowed.

Is this sane? Is there a better way/place to inject checking of preconditions?

Quite frankly, my solution feels awkward, I can't shake the feeling that I've done something completely wrong.

Returning subclass instance from superclass

I have a Java class A in my SDK. I am now breaking it to two classes AParent, A without changing the APIs signature for the users. This is being done as the A class (which is now the wrapper class) would have functionality specific to the environment while AParent will have common APIs. The problem I am facing is that A initially had many methods (static and non static) returning or accepting instances of its subclass via generics. To give you an idea, these methods signature looked like this :
public static <T extends A> T create(Class<T> subclass)
public <T extends A> T fetch() throws AException
I would like to make these methods a part of the parent class, AParent but would like to change the method signature to change and instead return something like:
public static <T extends AParent> T create(Class<T> subclass)
public <T extends AParent> T fetch() throws AException
But to the end user the signature shall still be the same and he shouldn't be noticing this change in the APIs signature.

When to use multiple inheritance vs inheritance and method overriding?

I'm developing a Python framework that's used to compose logic formulas. For example, if I request mutual exclusion between a and b, the output would be the Boolean formula:

"(a --> ¬b)^(b --> ¬a)"

In addition, I want to use some formulas as building blocks for building different types of formulas, such as formulas in Linear Temporal Logic (which is a superset of Boolean logic).

The question is twofold:

  1. Do I define one base class (e.g. BooleanFormula) and then:
    • add methods for generating specific formulas (e.g. gen_mutex_formula(a, b)) ?
    • or define more classes (e.g. MutExFormula) that inherit from the fundamental class (BooleanFormula in my example) and generate the formulas in their constructors?
  2. When I want to create the new types of formulas, do I inherit from the classes in (1) and mask/override their methods or do I use multiple inheritance. Example of the latter:

    class LTLMutExFormula(LTLFormula, MutExFormula)

What are the criteria and heuristics I should be considering as I'm designing the framework?

PS. Here's what I've been doing so far: link to module on Github

Which design pattern could I use for showing dialoges?

I do sometimes show Dialoges in my Java application.

Currently the Controller classes are (expect some exceptions where only getters are called on my model) used like mediators between my model and my ui.

But my UI knows my controllers and my controllers know my ui.

Whenever I add a new dialog I add a method in a controller and in the view class.

Is there a more elegant way to extend my program with new user dialoges by using a design pattern?

To ilustrate you how my interaction looks right now I will append some code snippets.

Code from my UI

    itmEmailSettings.addActionListener( new ActionListener() {
        @Override
        public void actionPerformed(ActionEvent e) {
            controller.showEmailSettingsDialog();
        }
    } );

More UI Code

    public void showEmailSettingsDialog(String host, int port, int authMode,
            String user, String pass, String fromEMail, String fromName) {
        EmailSettingsDialog d = new EmailSettingsDialog(
                host, port, authMode,
                user, pass, fromEMail, fromName
                );
        d.createJDialog( mainFrame.getFrame() ).setVisible(true);
        if(d.isValid()){
            controller.changeEmailSettings(  d.getHost(), d.getPort(), d.getAuthMode(), d.getFromEMail(), d.getFromName(), d.getUser(), d.getPass()  );
        }
    }

Controller code:

public void showEmailSettingsDialog() {
    try{
        if(!pm.hasProjectFileAccess()){
            mainFrame.showNoProjectfileAccess();
            return;
        }
        ProgrammSettingsRepository pr = Utils.getProgrammSettingsRepository(pm);
        String host = pr.retreive(ProgrammSettingsRepository.KEY_EMAIL_HOST);
        int port = pr.retreive(ProgrammSettingsRepository.KEY_EMAIL_PORT)==null?0:Integer.parseInt( pr.retreive(ProgrammSettingsRepository.KEY_EMAIL_PORT) );
        int authMode = pr.retreive(ProgrammSettingsRepository.KEY_EMAIL_SSL_MODE)==null?0:Integer.parseInt( pr.retreive(ProgrammSettingsRepository.KEY_EMAIL_SSL_MODE) );
        String user = pr.retreive(ProgrammSettingsRepository.KEY_EMAIL_USER);
        String pass = pr.retreive(ProgrammSettingsRepository.KEY_EMAIL_PASSWORD);
        String fromEMail = pr.retreive(ProgrammSettingsRepository.KEY_EMAIL_FROM_EMAIL);
        String fromName = pr.retreive(ProgrammSettingsRepository.KEY_EMAIL_FROM_NAME);

        menuView.showEmailSettingsDialog(host, port, authMode, user, pass, fromEMail, fromName);
    }catch(SQLException e){
        throw new RuntimeException(e.getMessage(), e);
    }
}

public void changeEmailSettings(String host, int port, int authMode,
        String fromEMail, String fromName, String user, String pass) {
    try {
        ProgrammSettingsRepository pr = Utils.getProgrammSettingsRepository(pm);
        pr.store( ProgrammSettingsRepository.KEY_EMAIL_HOST , String.valueOf( host ));
        pr.store( ProgrammSettingsRepository.KEY_EMAIL_PORT , String.valueOf( port ));
        pr.store( ProgrammSettingsRepository.KEY_EMAIL_SSL_MODE , String.valueOf( authMode ));
        pr.store( ProgrammSettingsRepository.KEY_EMAIL_USER , String.valueOf( user ));
        pr.store( ProgrammSettingsRepository.KEY_EMAIL_PASSWORD, String.valueOf( pass ));
        pr.store( ProgrammSettingsRepository.KEY_EMAIL_FROM_EMAIL , String.valueOf( fromEMail ));
        pr.store( ProgrammSettingsRepository.KEY_EMAIL_FROM_NAME , String.valueOf( fromName ));
        pr.store(ProgrammSettingsRepository.KEY_EMAIL_SETTINGS_CONFIGURED, "true");
    } catch (SQLException e) {
        throw new RuntimeException(e.getMessage(), e);
    }
}

Best Listview optimized design for Android

How can we display a listview which contains row items of a string of 40words nicely with good user experience or rather what layout would be best?

With Proxy Pattern and Without Proxy Pattern

I have gone thru several examples but I didn't found any examples having displayed same example With Proxy Pattern and Without Proxy Pattern,

Any one have a generic example ? by seen such example surely will understand do we really need Proxy Pattern to be used or not

Django model structure without rows

I am new in Django and I really love it, however, I am having an issue working with models and Django admin. Usual model, like for e.g. 'users', can have unlimited users and they can be manipulated in any way. in my case, there are four links(exactly four, not more, not less) to different URL's on my landing page that can be changed any time, so it must be managed through admin environment.

At first I thought I will create a new model and add four instances, hardcode each of them into view file by ID, but it does not seem like a great approach - what if administrator delete's one of them?

Same problem could be applied, for example, for footer message (like "2015 Copyright Company Name") that administrator should be able to change at any time.

What are the best database - model design approaches / patterns in such situation? Maybe Django has some package or app for a such thing?

Thank you very much!

Proven and testable solution architecture when using Entity Framework 6

Not having used EF for a while I decided to refresh my knowledge and do some research. Doing so I came across the familiar articles praising the repository pattern.

However, more interestingly, it seems more and more articles popup which debate against the use of the repository pattern in combination with the entity framework.

What I like about the repository pattern is that it makes mocking for your unit tests trivial. What I don't like is that it hides all the queryable linq goodies from the rest of your application.

Since I'm about to setup a new solution architecture I am very interested in learning more about the latter approaches. What does StackOverflow think about them and what other resources are available that back this up?

In short: What is currently the recommended solution architecture utilizing EF6?

How to implement MVP in JavaFX

Before some time, i started looking for a pattern to decouple UI from a logic of my app. I decided to use MVP, but there is one significant problem which i cant solve. How can i inject a instance of presenter into view, if classes that implements Application, are launched from static method. There is also no choice to launch specific instance of class implementing Application, so parameters in constructor are useless. Also i do not use FXML, my view class is coded in java.

PS: Sorry for my english, as it's not my native language

Check user Login using Repository pattern c#

I'm new at design patterns and I'm trying to make some example using repository pattern (Maybe I'll ask some stupid question using stupid example and if it's so please tell me)

I have this repository in my BusinessLogicLayer

public interface IUserRepository
{
   LogIn GetByUsernameAndPassword(LogIn user);
}

and in my data access layer

class UserRepository : IUserRepository
    {
        ChatAppDBContext _db = new ChatAppDBContext();
        public LogIn GetByUsernameAndPassword(LogIn login)
        {
            return _db.Users.Where(u => u.Email == login.Email & u.Password == login.UserPassword).FirstOrDefault();
        }
    }

but it throws an error that Error:

Cannot implicitly convert type 'DataAccessLayer.User' to 'BusinessLogicLayer.Model.LogIn'

How can I solve that?

Does the following have a design pattern?

I feel like there's a design pattern for this problem, but I can't seem to find the proper one.

I have a Server class that has what you might call 3 processes to run, and then output a result. Each process has a list of "plugins" that all run at every process. Each plugin(class) has a constant, that is the name of the plugin. So it looks something like this:

<?php
// Simplified Server class.
class Server {
  protected $format = array();
  protected $service = array();
  protected $handler = array();

  public function addFormat($class, $name = '') {
    if ($name === FALSE) {
      $name = $class::NAME;
    }
    $this->formats[$name] = $class;
    return $this;
  }
  public function getFormat($name) {
    if (is_string($this->formats[$name])) {
      $this->formats[$name] = new $this->formats[$name]($this);
    }
    return $this->formats[$name];
  }

  // And then these 2 functions are repeated 2 times, one for each of the other processes.
  // So I got a addServer, getService, addHandler, getHandler function now.

  public function processEverything($service, $handler, $format) {
    $output = $this->getService($service)->getOutput();
    $this->getHandler($handler)->handle($output);
    return $this->getFormat($format)->format($output);
  }
}

// The Format base class.
abstract class FormatBase {
  const NAME = '';

  abstract public function format($output);
}

// There's also 2 other base classes, that both have the NAME constant, but different
// abstract functions.

// A simple Format class
class UppercaseFormat extends FormatBase {
  const NAME = 'test_format';

  public function format($output) {
    return strtoupper($output);
  }
}

Can I cram this into a design pattern, it feels wrong to do all that copying and pasting for my functions in Server.

And please do tell me if I need to elaborate on anything.

Service vs Facade [on hold]

What are the differences between a facade and a service? I would assume a facade would couple relevant services together and provide business logic whereas a service would only manage a single entity and provide basic validation.

Starting to confuse myself with every article I read online.

How to design a large Risk Control System with Java projects

I am building a risk control system for online payment. As a complicated system, it should have some sub projects:

  1. An admin web interface;
  2. An rpc service api for other services;
  3. A data sync system for syncing business data to risk control system DB;
  4. A data processing and merging system for process data in DB to useful values in Redis;
  5. A risk rule engine service to combine data by rules;
  6. A data access service for all the system above to write and read DB or Redis.

I am trying to build a maven project and treat the systems above as modules, but I think it is still too large. Could I split them to different projects? Is there some weak points?

Another question, I'm going to build a data access service, and other systems will use this service when they want to operate with Database or Redis. Is it good for my system? May I create a standalone service or just a maven dependence?

Somebody give me some advices?

How To find distinct URI(pattern) from logs using log Parser? (-i:Textline)

I have large size logs and need find the reverse proxy and the count of the distinct uri. The format of the log is as below:

Jan 29  0:03:07 fpp-mp-a01  127.3.0.0   -   33.42.670.281, 126.7.0.0    akman_t1    CN=U-100927121845499116,OU=K,OU=A,OU=External,OU=Persons,O=indigo   Form    [29/Jan/2014:00:03:07   +0200]  POST /amm-server-serv4/main HTTP/1.1    200 246 6454    -   Java/1.8.0_45

Jan 29  0:03:07 fpp-mp-a01  127.3.0.0   -   81.58.160.252           Not Protected   [29/Jan/2014:00:03:07   +0200]  GET /flyworld HTTP/1.1  302 494 452 -   Wget/1.11.4 Red Hat modified

Here, I want to find out all the uri after the method "GET /flyworld" i.e fly world, amm-server-serv4, etc. in the logs and the total sum of count.

Recursive checking a string for repeating pattern?

sorry if this is a duplicate but i couldnt find anything close.

i want to check recursively a string for the following pattern

[a-z0-9][:][a-z0-9][&][a-z0-9][:][a-z0-9]...

example

foo:bar&foo:bar1&foo:bar&foo:111&bar:2A2... 

is it possible with regex and if so anyone can show me a regex expression for this?

If there is a efficient java method for this, it would be also good.

How to Learn Writing or contributing to open source Frameworks/Libraries

I have always Read Open source code But It is Dificult to Perceive for me,also want to write my own Reusable code,Frameworks or Libraries, Especially in .Net or Java.How archieve this

jeudi 30 juillet 2015

Separating the Concerns of Activity and GoogleApiClient

As usual there is a lot of code in my LoginActivity and I really would prefer to separate the Activity responsibilities from the Google Play sign in concerns.

After rewriting this LoginActivity code several times, in many different apps, the easy (and not so elegant) solution was create the Google API client as a Application class object. But, since the connection state affect the UX flow, I never was happy about with this approach.

Is there an elegant way of place the GoogleApiClient outside the Activity?

What is this the name of this Java state-based design pattern?

At my work, we have surveys, and one survey involves multiple steps. I work in automation, so I design tests around the page-objects we create for these surveys. We call this particular survey a "flow" survey because it has multiple steps. So you can skip step1 (survey A), then complete or skip step 2 (survey B), then complete or skip step 3 (survey C). Naively, we could write a test that just has methods that look like this:

public void completeSurveyA() {
    //...
}
public void skipSurveyB() {
    //...
}
public void completeSurveyB() {
    //...
}
public void skipSurveyC() { 
    //...
}
public void completeSurveyC() {
    //...
}

You would use it like this

completeSurveyA();
skipSurveyB();
completeSurveyC();

However, that could be a problem because we might call completeSurveyB() before we call completeSurveyA(), call completeSurveyA twice, etc. and the test would break. To avoid this, I introduced a different approach where calling a method on surveyA would return a surveyB object, which would return a surveyC object.

public class SurveyFlow() {
    public SurveyB completeSurveyA() {
        //...
        return new SurveyB();
    }
    private class SurveyB() {
        public SurveyC skipSurveyB() {
            //...
            return new SurveyC();
        }
        public SurveyC completeSurveyB() {
            //...
            return new SurveyC();
        }
        private class SurveyC() {
            public void skipSurveyC() {
                //...
            }
            public void completeSurveyC() {
                //...
            }
        }
    }
}

You would use it like this

new SurveyFlow().completeSurveyA().skipSurveryB().completeSurveyC();

The pattern reminds me of a state machine because only certain methods are available to you in different states, but I'm wondering if there is a more specific name for this pattern.

CQRS - business validation rules

I'm creating a system using CQRS and Event Sourcing pattern (I hope so). I have to make a business decision dependent on statistics data stored by one read model and user setting data stored by different read model (both created by events in the past). What is a good place to put business logic rules that outcome of which depends on that data?

  • Is it a command (can I fetch data stored in read models in command)?

  • Other abstraction layer, like saga?

Implementing Singleton pattern results in TypeError: unbound method foobar() must be called with Singleton instance as first argument

I'm trying to implement the Singleton pattern in Python (2.7).

I've read severel posts (1, 2, 3, 4) about the implementation and I want to code my own version. (A version which I understand. I'm new to Python.)

So I'm creating the singleton with a method that will create my single object itself that will be returned on every Singleton.Instance() call.

But the error message is always the same:

Traceback (most recent call last):
  File "./test4.py", line 24, in <module>
    print id(s.Instance())
  File "./test4.py", line 15, in Instance
    Singleton._instance = Singleton._creator();
TypeError: unbound method foobar() must be called with Singleton instance as first argument (got nothing instead)

Here I roll:

class Singleton(object):

    _creator = None
    _instance = None

    def __init__(self, creator):
        if Singleton._creator is None and creator is not None:
            Singleton._creator = creator

    def Instance(self):

        if Singleton._instance is not None:
            return Singleton._instance

        Singleton._instance = Singleton._creator();

        return Singleton._instance;

def foobar():
    return "foobar"

s = Singleton( foobar )

print id(s.Instance())

Why is that? To be more specific: How do I call in a method a def stored in a class variable in Python?

How to set Immutablity to the class when reference of mutable class is present

public class ImmutabilityOfReferenceInstance {

    public static void main(String[] args) {

         MClass mc = new MClass();

         mc.setId(1);
         ImClass imc1 = new ImClass(mc);
         System.out.println("imc1 = "+imc1);

         mc.setId(2);
         ImClass imc2 = new ImClass(mc);
         System.out.println("imc2 = "+imc2);         

    }
}

final class ImClass {

    final private MClass mClass;

    public ImClass(MClass mClass) {
        this.mClass = mClass;
    }

    public MClass getmClass() {
        return mClass;
    }   

    @Override
    public String toString() {      
        return String.valueOf(mClass.getId());
    }

}


class MClass {
    private int id;

    public int getId() {
        return id;
    }
    public void setId(int id) {
        this.id = id;
    }   
}

I want to provide complete immutablity to the class IMClass, As we can see IMclass is immutable but it has an instance variable mclass that is the reference of MClass and MClass is a mutable class. I have tried changing the getter method getmClass() as below

public MClass getmClass() {
        return (MClass) mClass.clone();
    }

but it is not allowing me to do so, Could some one please correct it that where i am getting wrong. Thanks in advance

I have tried this but still getting the same result, values are getting updated
public class ImmutabilityOfReferenceInstance {

    public static void main(String[] args) {

         MClass mc = new MClass();

         mc.setId(1);
         ImClass imc1 = new ImClass(mc);
         System.out.println("imc1 = "+imc1);

         mc.setId(2);
         ImClass imc2 = new ImClass(mc);
         System.out.println("imc2 = "+imc2);         
    }
}

final class ImClass {

    final private MClass mClass;

    public ImClass(MClass mClass) {
        this.mClass = (MClass)mClass.clone();
    }

    public MClass getmClass() {
        return (MClass)mClass.clone();
    }   

    @Override
    public String toString() {      
        return String.valueOf(mClass.getId());
    }

}

class MClass implements Cloneable{
    private int id;


    public int getId() {
        return id;
    }
    public void setId(int id) {
        this.id = id;
    }   

    @Override
    public Object clone() {
        try {
            return super.clone();
        } catch (CloneNotSupportedException e) {
            throw new RuntimeException(e);
        }
    }
}

Use multiple ModelViewSet for a REST call

I'm using Django REST Framework's ModelViewSet. Inside "ModelViewSet-1", I need to break down a POST (create) request into 3 parts. The first part will be used by "ModelViewSet-1" and I need to delegate the other two parts to "ModelViewSet-2" and "ModelViewSet-3" respectively. Can someone suggest a workflow?

For now, I'm thinking of using python's 'requests' library, to send circular HTTP calls from 'ModelViewSet-1" to the other ModelViewSets. But that doesn't seem elegant.

JS Patterns Benefits

I have a quick question, for a recent app I need to namespace all functions and for that I've chosen this code:

var myObj = {
    prop: 1,
    method1: function() {
        // do something
    },
    method2: function() {
        // do else
    },
    initialize: function() {
        this.method2();
        this.method1();
    }
}

myObj.initialize();

Can someone tell if this is a pattern or other any other examples that I can use?

How Do I print following pattern in C#?

How do I print following style using c# console application?

1111111 22222 333 4

Thanks in advance.

Databases in a microservices pattern/architecture

I'm trying to understand the layout of the microservices pattern. Given that each microservice would run on its on VM (for sake of example) how does the database fit into this architecture?

Would each service, in turn, connect to the consolidated database to read/write data?

Thanks for any insight

mercredi 29 juillet 2015

Which pattern should I choose when writing a node-file parser lib?

I am writing a file-parser (in fact 2 parsers). There are two node types as follow.

node struct 1

[nodeName]
    param1 = v1;
    param2 = v2;

node struct 2

nodeName=
    (param1 = (param2=v2)(param3=v3)
    )

When I wrote two parsers, I found they have same loadFile, insertNode, deleteNode, updateNode, isNodeExist function. The difference between two parser is the core parser and serializer.

So, can I user any pattern to remove redundant?

Thanks!

RESTkit and Objects Pool pattern

Introduction

I develop iOS application. This is enterprise application. One of the key features of the app is that it must let the user to access their data while offline (bad or no network coverage). Also user should be able to create content being off-line. Eventually, when the user finds network coverage, the app syncs with the server - i.e. pulls changes from the server and then pushes local changes (and data that was merged during pull conflict resolution) back.

Server is RESTful, so I have chosen RESTkit to work with the API on the client. During the bespoken sync I have to handle myriads of objects of the same type coming from the server. As I understand RESTkit creates new object each time it maps each object from the response (i.e. JSON coming to the app on GET). I think that there could be noticeable optimization if instead of creating the new objects each time RESTkit maps I could feed RESTkit with the objects from the same pre-allocated objects pool.

The Problem

What are the ways combining RESTkit and Object Pool pattern? Would be wonderful to hear good recommendations on valid implementation.

Thank you.

What pattern can I use for partial success when calling a method which calls a proxy to aggregate data from multiple endpoints?

As an example, suppose I have the following class:

public class FruitBasket {
    private List<Apple> apples;
    private List<Orange> oranges;
    // getters and setters...
}

Now suppose I also have a method somewhere which gets the FruitBasket.

public FruitBasket getFruitBasket() {
    //...
}

Now further suppose that the getFruitBasket method aggregates data from two different sources, which are accessed via a proxy. For example, there is a server AppleTree to get objects of type Apple, and a server OrangeTree to get objects of type Orange, and both are accessed via a proxy called OrchardGate. This is the reason why I want to write a single getFruitBasket method rather than getApples and getOranges, to minimise the latency when calling from my application to the OrchardGate.

In the case where Apple objects and Orange objects were retrieved successfully, there is no problem, I can just return the FruitBasket. In the case where there was a problem accessing or inside the OrchardGate, or in both the AppleTree and OrangeTree, I can also handle this by throwing a descendant of RuntimeException (or even Exception, if I add it to the getFruitBasket throws clause as appropriate).

However, what happens in the partial success case? What happens if I can access the AppleTree server fine, but I can't access the OrangeTree server due to some transport issue between the OrchardGate and OrangeTree?

As far as I can see there are only four options, and all are absolutely horrible:

  • I could throw an exception, meaning that even though the Apple objects were received successfully, the FruitBasket would not be returned due to the lack of Orange objects.
  • I could ignore the error and just return an empty list of Orange objects. This would mean that the client would not be able to see an error when looking for the Orange objects, instead it would just look as if no Orange objects existed on the OrangeTree server.
  • I could add a field to FruitBasket called errorCodes which contained a list of the errors encountered when accessing the FruitBasket. Then I could add an error code to that list called PATH_FLOODED to signify the error I had encountered. However, this field errorCodes does not belong on the FruitBasket domain object at all. This field is not relevant to a FruitBasket, but only in the transaction to retrieve the FruitBasket.
  • I could throw an exception, but attach the incomplete FruitBasket to the exception. This is also horrible because exceptions should only contain error information - they should not contain any fruit baskets.

I have described this problem in Java but I imagine this problem extends to multiple languages. I was quite surprised to not find a discussion of it already. Is there any standard pattern for writing methods which can return a partial success? Or anything I have missed?

How to Generalizing batch call on list in java

I have following repeated code.

  1. Give a list, other api parameters and max item supported in list.
  2. Divide list in sub partions.
  3. For each partition call api with given parameters.

So I have following repeated code for each api:

final List < List < GivenType >> partions = Lists.partition(givenListObject, batchSize);
final Iterator < List < GivenType >> iter = partions.iterator();
while (iter.hasNext()) {
    final APIResponse response = this.performSingleBatch(iter.next(), .....argument which need to be passed, argument count can differs from api to api);

    // Some custom processing with response object

    if (iter.hasNext()) {

        Thread.sleep(sleepTime);

    }
}

I was thinking to use callable. to reduce this repeated code. So I will have a function: performBatchRequest(callable,requestType,requestList,batchSize,timeToSleep)

So my code will look like: {Not 100% java syntax}

public void batchProcess(callable,GivenType,givenListObject,batchSize,sleepTime)
    final List < List < GivenType >> partions = Lists.partition(givenListObject, batchSize);
    final Iterator < List < GivenType >> iter = partions.iterator();
    while (iter.hasNext()) {
        callable.call();
        if (iter.hasNext()) {
            Thread.sleep(sleepTime);
        }
    }

A consumer can use it by:
batchProcess((list)-> {
 // there logic
}, GivenType,givenListObject,batchSize,sleepTime )

I have following question:

  1. Is it worth to avoid this code repetition ?
  2. Do you see problem with purposed solution?
  3. Any suggestion to improve purposed solution?

How to handle multiple exit points in Java

Sometimes I'm faced with a routine that will test some conditions and either continue or exit, something like the following code:

public void execute() {
    if (context.condition1()) {
        LOGGER.info("Condition 1 not satisfied.");
        return;
    }
    doSomeStuff();

    if (context.condition2()) {
        LOGGER.info("Condition 2 not satisfied.");
        return;
    }
    if (context.condition3()) {
        LOGGER.info("Condition 3 not satisfied.");
        return;
    }

    doRestOfStuff();
}

Let's assume there is no way to test these conditions before entrying this method. Maybe this is a servlet or a controller with this single entry point. From my experience (which is far from vast), this seems to be a common situation.

Now, this code doesn't smell good, does it? What would be the best strategy to handle this?

What's the correct way to implement a web service with the repository pattern

I'm about to start a project which will require a web site, connected to a web service. The web service will retrieve data from a database, and return it to the website.

My question is about how to properly separate business concerns with data access.

The service can be separated by utilizing the repository pattern. Then in the service calls implementations I can get the required data from the repository in the form of entities, then return it over the wire.

Similarly I can do the same on the website. Use the repository to hide the implementation details of getting the data from the service and serializing it into an entity or entities.

However, my main issue with this approach is that both the service and the website will both have definitions for their entities. Is there a pattern I can use that will allow me to define these entities once, or is this architecture way off from what is common / best practice.

I should mention that the technologies I'm using are asp.net with c# and I'm not using an entity framework.

Benefits from factory method pattern

I am reading Head First Design Patterns now, and i have a question. In the beginning of book i saw this principle:

Favor 'object composition' over 'class inheritance

And then i saw Factory Method with

abstract class Creator{
   abstract Product create(String type);
}

and subclassing

class ConcreteCreator extends Creator{
    Product create(String type){
     //creation
    }
}

But we can compose our class with Simple Factory, like

class OurClass{
     SimpleFactory factory;
     void ourMethod(){
        Product product = factory.create(String type);
     }
}

where SimpleFactory may be interface. So why we need Factory Method pattern?

Preventing overwrites from concurrent forms in PHP

We're setting up a system which allows a department to make edits to a record here. Their division of labor isn't clear, and they've had problems in the past where more than one individual loads data into a web form, makes edits, and then sends those edits to the record. Inevitably, the slower editor over-writes the faster editor's freshly edited data with the old data that had been loaded when the page loaded.

Currently, we have a white-board solution that would use changes to the last modified time of the data to reject the second request to write data and deliver an error message when that data POSTED.

The members of the department, however, would prefer a file-lock styled system--one where they were notified that another user was in the dataset prior to being allowed to access the data. Timeouts will inevitably be too short or too long depending on the day, and these particular users cannot be relied upon to "log out" somehow.

I'm just wondering if anyone else has implemented a solution to this, and, if so, how?

We're running PHP 5.6 on Apache 2.2 and building in Zend Framework 2.4. Not that any of that has any bearing on the question, but someone will inevitably ask.

Should i have Exception-Types in Interface-Assembly? Best practices?

I have an assembly which contains only interfaces to avoid unnessesary dependecies. Now i have an exception-type named UndefinedIHttpMacTokenException. So as you can see the exception concerns an interface-type of IHttpMacToken. Now i thought it would be best to include the exception-type in the interface-assembly. But this is a bit contradictory. If you hear the assemblys name (somenamespace.Interfaces). You would not expect it to contain class-types(exceptions).

So can you help me out? What is best practice in such cases? Thanks for your effort.

design an abstract class so that any one can extend it and use the extended class polymorphically

I want to have an abstract class like this:

public abstract Operator {

    public int[] operands;

    public Operator(int[] operands) {
        this.operands = operands;
    }

    public abstract int getOperatorResult();
}

And some operators to extend from it like:

public class Add extends Operator {

    public Add(int[] operands) {
        super(operands);
    }

    public int getOperatorResult() {
        return operands[0] + operands[1];
    }
}

And an OperatorCreator which gets an expression like "1+1" and returns the appropriate Operator's sub-class(in this case Add):

public class OperatorCreator {

    public static Operator getInstance(String expr) {
        ...
    }
}

The main problem: And I want to let others to design their own operators by extending Operator class. And use their operators polymorphically. something like this:

public class Main {

    public static void main(String[] args) {
        Operator op = OperatorCreator.getInstance("1-2");
        System.out.println(op.getOperatorResult());
    }
}

How can I do this? Suppose that I know the location of .class file in which the new Operator's sub-class is compiled.

Thanks!

MVVM Best practice in Swift

I have serious doubts on how in deep we have to use view model.

Let me explain with an example, simple view controller with a table view inside and a related view model.

class FooViewController: UIViewController, UITableViewDelegate, UISearchBarDelegate {

     let viewModel = FooViewModel()

     @IBOutlet var tableView: UITableView!

     override func viewDidLoad() {
        super.viewDidLoad() 
        tableView.delegate = self
        tableView.dataSource = self
     }

    // MARK: - Table view delegates -

    func tableView(tableView: UITableView, heightForRowAtIndexPath indexPath: NSIndexPath) -> CGFloat {
        return viewModel.heightForRow()
    }    
}

class FooViewModel {

    // MARK: - Table view management -

    func heightForRow() -> CGFloat {
        return 60
    }

}

Is a correct practice to delegate to the view model, for example, the height of each cell?
Generally, is ok delegate to view model UI "decision" on its aspect?

Android, Singleton, context

I am stuck in a problem. I am creating a helper class that needs to be Singleton. And that class has a global context variable. I am not able to do this since context is available only from onCreate and this Singleton instance is created much before since it is static.

Can someone help me on how to solve this issue. Context is needed for the Singleton instance finally.

Where to find solution architecture project samples

I have an assignment from work to write the ideal mvc.net project architecture for me. Now I know there is no such thing and architecture depends on the project and the stuff it has to do and so on, but I find it very hard to find some code samples of projects. Where I can see if code does this it goes here and if it looks like that better write it there and so on. I'm reading "Microsoft Application Architecture Guide, 2nd Edition" and I can find a lot of other stuff on the topic online, but its all dry theory and no actual code. I need to see it to believe it. If someone can point me to some project sample code or share some projects with me I will be more than thankful.

mardi 28 juillet 2015

Implement observer pattern in Java Servlet

Is it possible to implement a observer pattern (i.e., get notification from server) using only Java Servlet?

Maybe a more generic question would be, is it possible to implement observer using HTTP protocol?

How to call this JS function that is set to a variable in console?

I have a function like below:

var funct = (function(){

   var foo = 1;

   function getPrivateVariable(){
      return foo;
   }

return {
   getFoo: getPrivateVariable
};

})();

Then I try to type funct.getFoo(); into the console of firebug and it says "funct is undefined". How come or how can I call this function in console. If it is not possible in this form(I am using a module design pattern), then why is it not possible?

Polymorphism vs Strategy pattern

What is the difference between the Strategy pattern and Polymorphism in Java?

I'm confused that whatever is achieved via Strategy Pattern is basically possible by polymorphism. Correct me if I'm wrong in this regard.

Please, also provide me example to eradicate my confusion.

Command pattern implementation or adaption

I have different commands that all share some common data, so I extracted that to a super-class Command. All the concrete commands operate on an object of Foo when they implement the execute method. The actual invoker of the command is a client TheClient that creates a new object of the required command and directly executes it.

I have implemented it in such a way that the client and inovker is independent from the implementation details in the commands, and more importantly, independent from the class Foo.

I have the following questions:

1) Is this an implementation of the command pattern, or somehow an adoption of it?

2) From my understanding of the command pattern, in this example Foo is the receiver. Is this correct?

3) In contrast to the pure command pattern, I have merged the invoker and client into the same class. Some people say that this is OK in the command pattern, since both are a theoretical construct and in an actual implementation they can be in the same class. Is this correct?

public abstract class Command {
  protected String a;
  protected Foo foo;
  public Command(String a) {
    this.a = a;
    this.foo = new Foo(a);
  }
  public abstract void execute();
}

public class StartCommand extends Command {
  private String b;
  public StartCommand(String a, String b) {
    super(a);
    this.b = b;
  }
  public void execute() {
    this.foo.doSomething("start " + a + " with " + b);
  }
}

// ... other commands ...

public class Foo {
  protected String name;
  public Foo(String name) {
    this.name = name;
  }
  public void doSomething(String action) {
    // does something...
  }
}

public class TheClient {
  public static void main(String[] args) {
    Command command = new StartCommand("x", "y");
    command.execute();
  }
}

Right pattern and dependency injection

I have a problem with deciding the right way or writing a module. I THINK I know the theory behind the dependency injection and what are it's advantages but perhaps I am mixing something or do not have a very clear image.

A rather simplified example would be :

I have a model for my object and here I inject a validator class that handles the various validations :

// index.php
// ......
$model = new Model();
$model->setValidator(new Validator());
$model->getValidator()->exampleValidateCall();
// ......

// validator.php
class Validator implements ValidatorInterface {

   //.....

   public function exampleValidateCall() {
      // code goes here
   }
}

My problem here is that I need for instance access to the settings entity witch defines the behaviour of the model. Because the settings define the model, I do not think that I should pass theese settings inside the validator.

One option would be that the validator will extend the model, but I think that would be bad practice ( because the whole dependency injection concept goes kaboom... or not ? ). I could do something like :

$model->setValidator(new Validator($model->getSettings()));

but this looks even more idiotic from my point of view.

One better solution, again from my point of view, would be to pass a new object to the validator constructor

$model->setValidator(new Validator(new Settings()));

because in reality settings do not have dependency with the model, but that seems to complicate a little too much. And also the settings entity is constructed inside the model because it defies some of the behaviours.

What would be the best practice in writing these objects / dependencies ?

Design Approach and Using Reflection to run methods in Java

I have a question. I have multiple classes in a package: Let's say package is

com.myPackage.first

And this package has the following classes:

firstGood
secondGood
thirdBad
fourthGood

Each of these classes have a method with the same name but different implementation. So say each have a one particular function called:

public void runMe(){

}

For now I want to come up with a way to given a class name, it'll go inside the class and run that particular method.

So conceptually, my method will look like those:

ArrayList<Class> classList ; // where classList is a list of classes I want to run 

public void execute(){
 for(Class c : classList){
  // Go inside that class, (maybe create an intance of that class) and run     the method called run me
 }
}

or

public void execute(Class c, String methodToRun){
 for(Class c : classList){
  // Go inside that class, (maybe create an intance of that class) and    run     the method called run me
 }
}

For now. what I have been able to do is get the name of the classes I want to run the

runMe() 

method. So I have been able to come with a way to get the arraylist of classes I want to run. So what I need help with is coming up with a method such that it takes a class name and run the method I want it to. Any help is appreciated. Thanks

Alert pattern to handle repetitive tasks

Context

I m actually developping an application in which people have tasks to make in a day. It's just like "wash the window, clean the floor" etc.. etc...

Each task has a recurrence, and needs to be done at least one time in this period.

Example :

Task 1 has to be done every 15 days. Actually, it's been 16 days that it has not been done. So an event should be emitted.

My client needs to be alerted when something hasn't been done , on a time event, with a proper manner

I know that cron tasks exist for this, I could run one at midnight everyday, and send a mail alert with this. But what if I need to be exactly 15 days ? seconds by seconds ?

I really need efficiency without running this kind of scripts every days.

Does it exist a better way ?

Two Interface with Same Method Name - Implementation of Methods

Suppose I have two interface -

interface IOne{

   public void method();

}

and -

interface ITwo{

       public void method();

}

A concrete class implements both of the interface -

public class A implements Ione, ITwo{

    public void method(){
       //some implementation
    }
}

My questions are: -

1 Does the single implementation of method() one suffice for both interface IOne and ITwo?

2. If the answer of 1 is yes, is there any way to get both the method in a single class? In this case it is not necessary we have to implement both interface in a single class.

Audit history for changes in Db Row

Scenario:

I have a database table, any changes on data of any column of this table needs to be audit logged for comparison purposes.

What I have tried:

I have a history table with the same values columns as the parent table and any change to the database gets recorded into the new table using triggers and I eventually achieve what I want.

Problem

The issue is multi-fold:

  • I am using triggers which I do not want to use.
  • If I have to have audit comparison for n more tables, then I need to have one history table per parent table and which just swells my database and makes it bulky with so many tables.

Is there a better approach of achieving this, please suggest?

Builder for Linked list with two types

Here is what I am trying to solve:

I need to model a Route from Location A to Z via many other locations B, C...Y. A location is connected only to the next location via exactly one Road.

So I have two entities: Location and Road

Location implements RouteElement{
   String name;
   BigDecimal lat;
   BigDecimal long;

   RouteElement nextElement; // optional
}

Road implements RoutElement{
   Length howLong;
   Boolean hasTolls;

   RouteElement nextElement; // mandatory
}

And finally,

Route {
   // some properties
   RouteElement startingElement;
}

Now, All these entities are immutable, so once a nextElement is set to null in Location, it can not be "set" unless I create a copy on the first object.

So, I was thinking if I can come up with a RouteBuilder to build a Route gracefully!

Could someone please suggest how to write a Builder for this?

Thanks!

lundi 27 juillet 2015

Best pattern for loading resources (files) into memory and then reuse

I'm in the process of writing an application that uses a 3rd party library (NPOI) to read/write data to excel spreadsheets. My application needs to load 25 (or more) spreadsheets into memory, and then input values into each spreadsheet, and then read values from calculated cells within the spreadsheet. Because all files are 40MB in total, it takes 3-4 seconds to load all of them into memory and then performance my calculations.

I want to design my app so that it loads the files into memory at startup, and then only references the file stream of each file in memory when it needs to do calculations. I've been looking at Memory Mapped Files, but im not sure this will work for me.

Any advise as to what the best way is to manage these files in memory?

Design Patter for numerical API

This is a conceptual question rather than code question. In the process of abstracting basic implementation of numerical solver, i wanted to explore the different suitable approaches to designing an abstract version of my naive code by hiding the basic algorithms.

I looked at the different design patterns, it appears that Builder design pattern maybe suitable ...i also saw that the facade design may be suitable. what other or better suitable patters suitable for this ?

the lib should have a set of modules : interpolation , integration, orthogonolization of object "vector quantity"

pipe blocks (|x,y|) in ruby methods [duplicate]

This question already has an answer here:

I'm very new to ruby, and still fairly novice to OOP languages in general so I apologize in advance if this question is poorly worded. I've noticed a pattern in ruby methods where the first argument is a block and within that block is something like |x,y| I noticed it first in the .each method

@some_hash.each do |key, value|
    puts "#{key} => #{value}"
end

my understanding of do and end is that they are just like any other block in ruby, so in theory the code above could be written like so

test_hash.each {|k,v| puts "#{k} => #{v}"}

Sure enough this also works. So my question is what's actually happening under the hood here? What is the .each method doing with this block and how to the values k and v get assigned? How could I write a method that would do something similar?

Better way to handle many if conditions?

We have many different types of feeds. And one feed has many feed_comments..

And on the basis of feed type I want to return a specific string..

if feed.type == 1
  if nested_comment
    str = "test"
  else if comment
    str = "test1"
  else
    str = "test2"
  end 
else if feed.type == 2
  if nested_comment
    str = "test3"
  else if comment
    str = "test4"
  else
    str = "test5"
  end 
else if feed.type == 3
  if nested_comment
    str = "test6"
  else if comment
    str = "test7"
  else
    str = "test8"
  end 
else if feed.type == 4
  if nested_comment
    str = "test9"
  else if comment
    str = "test10"
  else
    str = "test11"
  end 
end

What is the better way to write the above code?

So, I don't have to change my existing code in future if we have many more conditions here..

Composite Design Pattern Leaf Management

Most of the descriptions of the composite design pattern I have seen have the Composite implement the add() and remove() methods and leave those methods unimplemented in the Leaf objects. For example, the diagram in the Wiki Page on the subject suggests this, which is more or less the same as the GoF diagram.

Regarding implementing these in the parent Component class, the GoF have the following to say:

Defining the child management interface at the root of the class hierarchy gives you transparency, because you can treat all components uniformly. It costs you safety, however, because clients may try to do meaningless things like add and remove objects from leaves.

I agree that having a Leaf implement remove() is strange to handle. (Do you delete yourself? Do you have to implement some sort of NullLeaf object?) But since the point of the pattern is to make Leafs and Composites behave the same way I don't see why add() could be implemented in Component.

My question: Why can't Component at least implement add()? Would doing so violate any key design principles? Does doing so no longer make this a composite design pattern? Below is an example in Python which captures the essence of what I tried to implement in my own work:

class Component:
    def add(self, other):
        # in Python, may be more natural to define __add__
        c = Composite()
        c.children = self.children + other.children
        return c

class Leaf(Component):
    def __init__(self):
        self.children = [self]  # possibly strange?

    def operation(self):
        # operation specific to this leaf

class Composite(Component):
    def __init__(self):
        self.children = []

    def operation(self):
        for child in self.children:
            child.operation()

With an "example usage":

>>> l1 = Leaf()
>>> l2 = Leaf()
>>> c = l1.add(l2)  # c is a `Composite` instance
>>> c.operation()

Android: Parsing of ics file using Pattern/Regex not working

I am confused, the following work on Eclipse, so I assumed it'll work on Android too. Apparently not.

In .ics file, generally, each line follows either one of the following format:

  • FIELD;miscellaneousstring:VALUE
  • FIELD:VALUE

I'm interested in obtaining all possible information, FIELD, VALUE, and miscellaneousstring (if possible). Each line is separated by a colon, or a colon and a semicolon (although there are rare cases where they end with another colon too).

Here is my code:

//Pattern to determine if string follows the format:
// (a) FIELD;miscellaneousstring:VALUE
// (b) FIELD:VALUE
private static final String withSemiColon = "^([A-Z]+);(.*):([^:]+):?";
private static final String withColon = "^([A-Z]+ ):([^:]+):?";

Pattern stringWithSemiColon = Pattern.compile(withSemiColon);
Pattern stringWithColon = Pattern.compile(withColon);

String line;
//line is each line of the ics file

Matcher matchWithSemiColon = stringWithSemiColon.matcher(line);
Matcher matchWithColon = stringWithColon.matcher(line);

if (matchWithSemiColon.matches()) {
    field = matchWithSemiColon.group(1);
    intermediate = matchWithSemiColon.group(2);
    value = matchWithSemiColon.group(3);
}
//Otherwise, split string as per normal
else if (matchWithColon.matches()) {
    field = matchWithSemiColon.group(1);
    value = matchWithSemiColon.group(2);
    //Clear value of intermediate
    intermediate = null;
} else {
    Log.i("UNMATCHED", line);
    continue;
}

It appears that no matter what I do, I will always log UNMATCHED for every single line of the file.

To put things in perspective, here is an extract of an ics file:

BEGIN:VCALENDAR
CALSCALE:GREGORIAN
PRODID:-//Cyrusoft International\, Inc.//Mulberry v4.0//EN
VERSION:2.0
X-WR-CALNAME:PayDay
BEGIN:VTIMEZONE
LAST-MODIFIED:20040110T032845Z
TZID:US/Eastern
BEGIN:DAYLIGHT
DTSTART:20000404T020000
RRULE:FREQ=YEARLY;BYDAY=1SU;BYMONTH=4
TZNAME:EDT
TZOFFSETFROM:-0500
TZOFFSETTO:-0400
END:DAYLIGHT
BEGIN:STANDARD
DTSTART:20001026T020000
RRULE:FREQ=YEARLY;BYDAY=-1SU;BYMONTH=10
TZNAME:EST
TZOFFSETFROM:-0400
TZOFFSETTO:-0500
END:STANDARD
END:VTIMEZONE
BEGIN:VEVENT
DTSTAMP:20050211T173501Z
DTSTART;VALUE=DATE:20040227
RRULE:FREQ=MONTHLY;BYDAY=-1MO,-1TU,-1WE,-1TH,-1FR;BYSETPOS=-1
SUMMARY:PAY DAY
UID:DC3D0301C7790B38631F1FBB@ninevah.local
END:VEVENT
END:VCALENDAR

I've applied what I read from Mastering Regular Expression, by Jeffrey E. F. Friedl, I've tested the above with Eclipse and it works. So I'm not sure where I went wrong.

Testing functions through I/O in Haskell

I'm playing codewars to sharpen my Haskell skills, and running into a problem that I haven't had in imperative languages.

Let's say I'm writing a function foo() in javascript, which takes an int, adds two, squares it, subtracts one, and returns the square root of that number.

var foo = function(n) {
  n += 2;
  n = n * n;
  n -= 1;
  n = Math.sqrt(n);
}

I want to check on the state of the data being processed in the function at various points to help me troubleshoot/revise/debug code, so I will insert console.log() statements whenever I want to see where I'm at. For example, am I, in fact, squaring the sum of n+2 correctly halfway through the function? Let's see...

var foo = function(n) {
  n += 2;
  n = n * n;
  console.log("n = " + n);
  n -= 1;
  n = Math.sqrt(n);
}

While this example should be simple enough for a Haskeller to write in one line, if you have a complex function and want to check the state at different points, how do Haskellers do it? Is there a standard practice using the IO() monad? Do they get around it some other way?

Unit Testing Principles and Approaches

Introduction

Recently I have moved from an environment where I am not unit testing, into one where I need to.

I have been a developer for many years and get core development concepts, as well as unit testing ones such as DI/Ioc, Mocking etc. I also understand the values, importance of unit testing and writing good tests, as well as asking myself often: "What Would Roy Do?".

I am however slightly unsure on some approaches and principles to follow, and am not 100% sure of what I should be looking for; I am using NSubstitute and NUnit.

Questions

  1. How should the value generation be done? I'm not sure how we should make it react to different input parameters. I've implemented a way it could be done, but part of me feels this isn't right. What happens when I have more people added to it as I went to test, for example? Should I expand this section?

  2. Where should the value generation be done? Leaving it in the function feels wrong, but is clear as to how the values are generated/returned. Moving it to a function would make the test cleaner, and therefore easier to read (?), and usable in other tests? Or should I inject it (maybe with NInject?) but this would require the creation of another service?

Code Sample

Imports NSubstitute
Imports NUnit.Framework

Namespace Services

    <TestFixture()>
    Public Class ImportantServiceTests

        <TestCase("userA")>
        <TestCase("userB")>
        Public Sub GetImportantItems_WithValidUser_ItemsForThatPerson(user As String)
            ' Arrange
            Dim importantService = New ImportantService()

            ''''''''''''''''''''''''''''''''''
            ''''''vvv Value Generation vvv''''
            Dim importantItem = Substitute.For(Of IImportantItem)
            importantItem.Id.Returns(1)

            Dim subImportantService = Substitute.For(Of IImportantService)()

            subImportantService.GetImportantItems("userA").Returns(
                    New List(Of IImportantItem) From {importantItem}
                )

            subImportantService.GetImportantItems("userB").Returns(
                    New List(Of IImportantItem)
                )

            ''''''^^^ Value Generation ^^^''''
            ''''''''''''''''''''''''''''''''''

            ' Act
            Dim importantItems = importantService.GetImportantItems(user)

            ' Assert
            CollectionAssert.AreEqual(importantItems, subImportantService.GetImportantItems(user))
        End Sub

    End Class
End Namespace

Extension

An extension to the above (which I hope is still classed as related, due to following a similar theme of principles and approaches), is about testing against a database accessed through the EntityFramework DatabaseFirst.

There are other posts talking about mocking the entire framework, but this to me feels overkill? Is there a better way than creating hand-written substitutions for every single table and value within there?

Footnote

I'm wanting to make the tests lean and independent as I can, so when new developers join the team it is easy and straightforward for them to pick up. As a result of this I have created this post, after searching around for similar questions and articles. I hope the question does not appear too broad, or not a good fit. I hope it will prove useful for others having a problem with this topic.

Design pattern suggestion for storing the client information in map in server application

My application is server, and my client will give some request for processing. Client will contact me(server) for multiple times for handling the same request .

map<clientId,ClientInformation>

Usually i will store some information which i received from the client in STL Map for processing the client request next time.

Once client was satisfied in my servings, i will clear the entry in the map for the respective client Id.

This is my sample ClientInformation class

class ClientInformation
{
int NotRequiredForNextTime;  // Information Not required for  processing the client request next time
int requiredforNextTime;  // Information required for  processing the client request next time
int requiredforNextTime;  // Information required for  processing the client request next time
int NotRequiredForNextTime;  // Information Not required for  processing the client request next time
int NotRequiredForNextTime;  // Information Not required for  processing the client request next time

UserDefinedClass Class1;
};

Class UserDefinedClass
{
int requiredforNextTime;
int NotRequiredForNextTime;
}

In the above class, i require only requiredforNextTime to be stored in the map. other information is required only at the time of processing the current request. ClientInformation class can have userdefined class as member(UserDefinedClass), and some of the UserDefinedClass members are not required for next time.

Is there is any design pattern, which provided optimized solution for this problem.

All Behavioral Design pattern in C# with Implementation (CODE) and Scenario

Please Describe it in a flow and write easy examples, write program with comments.

Strategy Pattern with strategies contains similar code

In most examples, strategy pattern is usually good for compression algorithms/ codec algorithms, where these algorithm might have quite different code.

However, in my case, the statistics algorithms I want to refactor to strategy pattern, have 50% code similar or exactly the same. I was wondering how do people deal with this? If I use strategy pattern, there could be 50% of the code copied around, which is not desired. If not refactor, the code is ended up with many sets of if-else all around to handle different types of statistics algorithms. How to evaluate the trade-off? What could be other possible solutions?

Choose which subclass to extend from at runtime in java

I have two classes (say B & C) that both derive from a class (say A). Now I need to write a class (say D) that should dynamically derive either from B or C at runtime.

B, C & A are classes provided to me through libraries and the only class in my control is D class. How do I write D with respect to constraints mentioned above. Obviously B and C have come from different vendors and hence would need different methods to be overridden in D depending on which is its parent class.

I cannot write different versions of D that would subclass from B & C since the override methods would have same code under different method names.

dimanche 26 juillet 2015

Class hierarchy: Is there a cleaner pattern for this?

I'm writing this in EcmaScript 6, but this problem can also be taken to other languages.

In my situation, I have a Chat class like this:

// Chat.js
import { socket, config } from "./Util.js";
import User from "./User.js";
class Chat {
    constructor(socket, config) {
        // …
    }
    roomExists(room) {
        // …
    }
    createRoom(room) {
        // …
    }
}
// Make sure to export the same instance to every other module,
// as we only need one chat (resembling a singleton pattern)
export default new Chat(socket, config);

Now, this class makes use of User somewhere in createRoom(). The problem is that the User class needs to make use of the Chat instance that we export:

// User.js
import chat from "./Chat.js";
export default class User {
     join(room) {
         if (chat.roomExists(room)) {
             // …
         }
     }
}

But now we have a dependency loop between Chat.js and User.js. This script won't run. One way to solve this would be to never import Chat.js directly, but do something like this:

// Chat.js
import { socket, config } from "./Util.js";
import User from "./User.js";
class Chat {
    constructor(socket, config) {
        // Pass `this` as a reference so that we can use
        // this chat instance from within each user
        this.userReference = new User(this);
    }
    roomExists(room) {
    }
    createRoom(room) {
    }
}
// No need to export a singleton anymore, as we pass the
// reference to the chat in the User constructor

But now, every other class depends on Chat and must be given a reference to a chat instance once we instantiate it. This isn't clean, either, is it? Chat is now a single point of failure and very hard to exchange later on.

Is there a cleaner way of managing this?

Ruby: Can anyone tell me why this test is failing?

I'm learning some Ruby at the moment and I decided to re-teach myself some design patterns from online tutorials (http://ift.tt/1JHMRPS). So I have two class files:

Car

require_relative 'Notifier'
require 'observer'

class Car
include Observable
attr_reader :mileage, :service

def initialize(mileage = 0, service = 3000)
    @mileage, @service = mileage, service
    add_observer(Notifier.new)
end

def log(miles)
    @mileage += miles
    changed
    notify_observers(self, miles)
end
end

And Notifier:

class Notifier
def update(car, miles)
    puts "The car has logged #{miles} miles, totalling #{car.mileage} miles traveled."
    puts "The car needs to be taken in for a service!" if car.service <= car.mileage
end

end

Here is my test:

require_relative 'car'
require "test/unit"

class CarTest <
Test::Unit::TestCase

def test_simple
    assert_equal("The car has logged 100 miles, totaling 2400 miles traveled.", Car.new(2300, 3000).log(100))
end

end

But whenever I run the test I receive this failure message, wondered if anyone knew of why this is happening?

[1/1] CarTest#test_simpleThe car has logged 100 miles, totalling 2400 miles traveled.
= 0.00 s
1) Failure:
test_simple(CarTest) [car_test.rb:8]:
<"The car has logged 100 miles, totaling 2400 miles traveled."> expected but was
<false>.

Pattern for multiple requests to REST server

So let's say I have a typical REST server that queries some data in a very specific manner, like: GET accounts, GET prices, GET inventory, GET settings, GET user_history, etc...

A single view, let's say, needs to fetch N different specific resources like this. What's the best technique/library/pattern for combining N HTTP requests into one without too much hassle?

Maintaining the "REST" idea would require writing new server code for every view because no two views would need the same set of resources. Doing this would become unnecessarily cumbersome in my opinion.

What's the best alternative to writing new response code for every possible combination of a given view's resource requirements?

Selenium Exception Handling Design

In Order to prevent exception handling in each method in selenium page objects, i thought to have a general exception handling, a try catch in the test block, other handlers only if more specific handling required,

Now the issue is that this process needs to be written in each test... is there a way to make the test methods have this common test handling written once for all tests?

@Test
public void test(WebDriver driver) {        
    try {
        // common code in the try block
        // using testNG may be moved to @BeforeMethod And @AfterMethod
        Logger.log("Test Started....");

        Logger.log("Test Ended....");
        Assert.assertAll();
    }
    catch() {
        // in Case Automation Fails, common operations required 
        ScreenShoot.getScreenShoot(); 
    }
    finally 
    {   
        // finally for all tests    
        driver.close();
    }
}

samedi 25 juillet 2015

ObserverPattern - Web implementation example (Twitter)

ObserverPattern
Define a one-to-many dependency between objects so that when one object changes state, all its dependents are notified and updated automatically.

I understand the definition, and I understand it from the windows forms perspective. For example we have three forms and we can update three forms at the same time (different observers) while subjects state changes.

But if we want to implement observer pattern on website(example Twitter), how does it work?

Let's say we have a subject Bill Gates, and 20 followers join him(20 new observers).

Each time new follower joins, isn't this stored in database who is which follower? So in case Bill Gates tweets something, operation checks in database who is his follower and updates wall of followers with Bill Gates tweet(which goes again into database under followers ID).

So how is Twitter using observer pattern (Subject-Observers) from the design pattern perspective? Do we still use observer pattern, and while someone new follows, we use method registerObserver to insert observer in database of observers for Bill? And then when Bill tweets something new, it loops through all observers of Bill from database and notifies them?

I am trying to understand this pattern in real life code usage on Twitter example.

I checked this video about Observer Pattern: https://www.youtube.com/watch?v=YIX9Bkl3ZPE

I understand when we are implementing directly in WinForms(I am talking about usage). But what happens when database comes in? For example for web. Is it the same, and when is the best to use it, I would need one web example.

Structural pipeline in Spark Streaming

I'm actually building a streaming module in my system that read and write from/to Kafka. It's done using Spark Streaming. My need is to structure the code in a clean and modular way: I have several chained steps and I would like to compose them. Is there a library that already gives the right abstractions for Spark Streaming? Otherwise, I would like to read something on a design pattern that solve this problem and I could write the abstractions myself.

(Then, is it just me or good resources about idiomatic design patterns in Scala are hard to find on the internet?

vendredi 24 juillet 2015

Repository pattern and combined/joined entities as optimised SQL

I'm working on building a repository system on top of a system that is a bit harder to work on than usual (ref. a previous question by me).

Anyway.

My data model is fairly simple at this point: I have several countries, and each country has 0 or more airports. Here's my base Repository:

public abstract class Repository<T> : IRepository<T> where T : Entity, new()
{
    protected SimpleSQLManager SQLManager = DatabaseManager.Instance.SQLManager;

    public virtual IQueryable<T> GetAll()
    {
        IQueryable<T> all = SQLManager.Table<T>().AsQueryable();

        return all;
    }

    public virtual IQueryable<T> GetAll(Expression<Func<T, bool>> predicate)
    {
        IQueryable<T> all = SQLManager.Table<T>().Where(predicate).AsQueryable();

        return all;
    }

    public T GetById(string tableName, int id)
    {
        return SQLManager.Query<T>( "SELECT * FROM " + tableName + " WHERE Id = ?", id )[0];
    }
}

Please ignore the ugly GetById() implementation; I'm running this on Unity3D's (Mono's) .NET libraries, and there's seemingly a bug in there which makes it impossible at the moment to do it properly. Either way, that's not the problem. :)

Now, a normal EntityRepository looks like this (CountryRepository in this case):

public class CountryRepository : Repository<Country>
{
    public override IQueryable<Country> GetAll()
    {
        return base.GetAll().OrderBy( c => c.Name );
    }

    public Country GetById(int id)
    {
        return base.GetById( "Country", id );
    }
}

The Country entity looks like this:

public class Country : Entity
{
    public IQueryable<Airport> Airports()
    {
        return RepositoryFactory.AirportRepository.GetByCountry( this );
    }
}

Then, in my application I can do something like this:

foreach ( Country c in RepositoryFactory.CountryRepository.GetAll() )
{
    foreach ( Airport a in c.Airports() )
    {
        // ...
    }
}

...and this works just fine; I'm happy with how everything is abstracted away etc. etc. :)

The problem is that the above code creates one database SELECT per country, which is highly ineffective. This is where I'm not sure where to go forward. I know how to do this with plain old SQL, but I want to go the Linq (or otherwise "non-SQL") way.

Can someone point me in the right/correct direction?

Thanks!

Should I create a builder for a Class wich has large number of required attributes

If I have a class with Fairly large number of attributes, say 10, all of which are required [non null or non optional] to construct the entity correctly, then what is the best way to instantiate this class?

  • Should I create a Builder with no args constructor which has withers/setters for all the attributes and check for "non null" in the private constructor of the entity being constructed

    OR

  • should I have a public constructor with all the 10 arguments and create NO Builder?

Having a builder makes the client code look cleaner while having an all args public constructor conveys the message that all the arguments are required [say, I annotate all the parameters with @javax.annotations.Nonnull annotation]

How should I decide?

Managing UI feedback in React.js

Is there an established pattern used to manage user interactions with individual components, such as displaying loader spinners, disabling input fields while a form is saving/loading, etc.?

I'm finding myself doing the following in my stores in order to keep components somewhat decoupled from any implied state:

function CampaignStore() { EventEmitter.call(this);

AppDispatcher.register(payload => {
    switch (payload.type) {
        // [#1] ---------------v  (main action)
        case CampaignContants.SAVE:
            // [#2] ------------------------v  (prepare for the main action)
            this.emit(CampaignContants.WILL_SAVE);

            const data = payload.data;
            if (data.id) {
                // [#3] ---v  (perform main action in store)
                updateCampaign(payload.data).then(_ => {
                   // [#4] ------------------------v  (after main action)
                   this.emit(CampaignContants.DID_SAVE, 0)
                });
            } else {
                insertCampaign(payload.data).then(campaignId => this.emit(CampaignContants.DID_SAVE, campaignId));
            }
            break;
        // ...
    }
}

Basically, I just fire an event saying that some action is about to take place, then I perform the action (make API call, etc.), then emit another event when the action completes.

Inside a component, I can just subscribe to a WILL_ event, render all the spinners and such, then clear up the screen when the DID_ is fired. While this seems to work, it does feel pretty boilerplattie and repetitive, as well as super messy (way too much state that only exists to tweak the UI based on where an action is (between WILL_ and DID_

// some component
var MyComponent = React.createClass({
   getInitialState: function () {
       return {
           items: [],
           loading: false,
           saving: false,
           checkingPasswordStrength: fase,
           // ...
       };
   },
   render: function(){
      return (
          <div>
             {this.state.loading && (
                 <p>Loading...</p>
             )}

             {!this.state.loading && (
                 // Display component in not-loading state
             )}
          </div>
      );
   }
});

Design solution for working with multiple instantiations at the same time

I don't know if my title is correct. But here's what I want to know.

I have a Downloader class that returns certain events and has a couple of methods. Each instance of Downloader class can download a single file. And all those events and methods are related to the file being downloaded.

As it's a multi file downloader, multiple instantiations are required when more than a single file needs to be downloaded.

Each download has a download id, but that is not supplied to the downloader class, to keep it independent from the other classes.

Now getting all the info from each instance of the file download and being able to control a single download, is the problem. How do I know which download is which?

Any solutions? Or design patterns you could recommend? I've hit a roadblock.

Data Source Patterns - Where's to put table's level methods?

At my company we work with models based on "Active Record Pattern", the model methods are always related to operations of a single record from the database, for example:

Class User {
    int id;
    string Name;

    public boolean Find (id); // SQL / ORM to return the object based on the user's Id;
    public boolean Save (); // SQL / ORM to save / update a user
    public boolean Delete (); // SQL / ORM to delete a user.
}

// Create the user "John"
Set objUser = new User ();
objUser.Name = "John";
objUser.Save ();

My question is that in relation to the database entity "User", we have methods that are to table level and not record, such as a method "getAllActiveUsers", which returns me a query object of all active users. This type of situation ends up in own ActiveRecord model, which in my opinion does not make sense .. Could you help me to understand what would be the most advisable / elegant to treat this type of situation? I read something about Gateway and Repository Patterns that may be useful for this, but was wondering if anyone has this same trouble and how did you solve ..

Thank you!!

Reacting to patterns of (UI) events over time

What is an expressive way of looking for patterns of events over time, and triggering new events?

For example, user interface events are often built up patterns of simpler events, such as mousedown/up, mousemove, or keyup/keydown.

A drag and drop interaction requires listening for a mousedown event, followed by a number of mousemove events, followed by a mouseup, and looking for if draggable/droppable UI objects are targeted by the different events. Additionally, you might want to have a timing and distance threshold to avoid triggering a drag when the user might have tried to click, and you might want to look for modifier keys, or escape to cancel the interaction.

Dealing with these things as number of individual event listeners quickly gets complex and error prone, tricky to debug, and often leads to conflicts between different events.

What abstractions are common for expressing these patterns succinctly and clearly?

I think I finally understood what means "favor composition over inheritance" can anyone confirm [on hold]

I know there are other questions that ask about what is favor composition over inheritance. I have read examples that use Animals, Ducks, Lions and Fruits, Vegetables examples but they never seem to sink in for me.

However, what I want to ask here is if the following example is a good example of favor composition over inheritance.

The Example: in the context of Java we have class Thread and interface Runnable. If I extend Thread then I can't extend anything else in the future and this might be a problem (making my subclass highly coupled to Thread class). But if I implement interface Runnable I'm leaving my class (that implements Runnable) open to extend any needed superclass in case I need it. This gives more flexibility and makes code less coupled.

Difference between abstract class whose constructor requires arguments, and abstract class with abstract get-only properties

public abstract class BaseProcessor
{

    public abstract void Initialize();

    private readonly string _executerPluginName;
    private readonly ILogService _logService;

    public BaseProcessor(string executerPluginName, ILogService logService)
    {
        this._executerPluginName = executerPluginName;
        this._logService = logService;
    }

    protected void CallExecutor()
    {
        this.Initialize();
        //common logic
    }
}

public class ConcreteProcessor : BaseProcessor
{

    public override void Initialize()
    {
        //concrete logic
    }

    public ConcreteProcessor(string executerPluginName, ILogService logService) : base(executerPluginName, logService)
    {
    }
}

AND

public abstract class BaseProcessor
{

    public abstract void Initialize();

    protected abstract string ExecuterPluginName { get; }
    protected abstract ILogService LogService { get; }

    protected void CallExecutor()
    {
        this.Initialize();
        //common logic
    }
}

public class ConcreteProcessor : BaseProcessor
{
    protected override string ExecuterPluginName { get{ throw new NotImplementedException(); } }
    protected override ILogService LogService { get{ throw new NotImplementedException(); } }

    public override void Initialize()
    {
        //concrete logic
    }

}

What kind of inheritance more preferable ? I'm going to use second solution, but i have some doubts about quantity of abstraction. Can you give some explanation about these approaches?

Dilemma Cash Flow Modeling

I'm studying a modeling form to be the most generic and reusable I can with the cash flow design, but there's many variables in the model.

So the fir question I'm on the right way? My model It is too fragmented? Is sometih missed?

Just an observation, this model does not have all the attributes.

Thanks for the help.

enter image description here

Missing argument label when calling a method in "strategy design pattern" -SWIFT

I am recently venture myself into Swift but I could not understand why my codes does not work when im returning an Int in a method.

protocol StrategyProtocol
{
    func calculate(num1:Int, num2:Int) ->Int
}

class Context
{
    var _strategyProtocol: StrategyProtocol!

    init(_strategyProtocol: StrategyProtocol)
    {
        self._strategyProtocol=_strategyProtocol
    }

    func Calculate(num1: Int, num2: Int) ->Int
    {
        return _strategyProtocol.calculate(num1, num2)
    }
}

class Add: StrategyProtocol
{
    func calculate(num1: Int, num2: Int) -> Int
    {
        return num1 + num2
    }
}

class Minus: StrategyProtocol
{
    func calculate(num1: Int, num2: Int) -> Int
    {
        return num1 - num2
    }
}

apparently this line of code does not work and prompt out missing argument label 'num2:' in call

//return _strategyProtocol.calculate(num1, num2)

can anyone show me how to fix it and explain to me.

Observer Pattern Across websites

Recently I've been reading alot regarding design patterns, and I've seen at least one that, in theory I can use on my job.

We have a couple of websites that just parse XML feeds from other websites inside the website network and display them to the users. The current implementation is, in my opinion rather dull, since when one VM with a website flips out, the sites that get the feeds are either halted or slow to a crawl.

Upon reading about the observer pattern, I thought that this would be a great idea to implement but I have some questions:

1- how would I go about implementing this "logic" across websites?

2- Would each site that provides the feeds be an observer and the sites that read the feed observables?

3- related to 2: Would it be wise to have a "central" observer that gathers the feeds of all of the websites and the sites that need it would just plug into that observer?

Thanks for the help

How to implement html5 pattern to validate input that contains specific letters?

I would like to implement a html5 input pattern to validate if input text contains " - (" characters. There can be characters before and after this text.

Did a lot of internet search however couldn't find a pattern which can behave like Contains method of string class.

Furthermore, I couldn't find a documentation to describe all the features of pattern attribute. Please pass the link if you know one.

Any help would be appreciated.

Thank you.

Qt5: MultiLanguage (Q)translator in a Monostate pattern design

I am using Qt5 under Windows 7.
Few days ago somebody requested the app should have the so called "internationalization" feature, i.e. to allow app-messages in more than one language...
So I started with QTranslator class (provided by Qt) and my approach was to use Monostate pattern design in order to implement the requested feature.
For the moment I only have 2 languages (default=Portuguese and English)...
The code is listed below :

#include <QVariant>
#include <QCoreApplication>

#include "translator.h"
#include "settingsmanager.h"


int Translator::currentLanguage = Translator::Language_Unknown;
QTranslator Translator::translator;


// Prefiro "Monostate" porque "Singleton" é muito feio :(
Translator::Translator(QObject * parent) : QObject(parent)
{
    if(currentLanguage == Language_Unknown)
    {
        changeLanguage();
    }
}

Translator::~Translator()
{
}

void Translator::changeLanguage()
{
    SettingsManager settings;
    int language = settings.readSetting("Language").toInt();
    //
    if(language != currentLanguage)
    {
        QString translationFile;
        QCoreApplication::removeTranslator(&translator);
        switch(language)
        {
          case Language_English:
               translationFile.append("language_en.qm");
               translator.load(translationFile);
               QCoreApplication::installTranslator(&translator);
          break;

          default: // Português
               // nada, it's the default
          break;
        }
        currentLanguage = language;
    }
}

Finally, my question is:
Do you think it is a good approach?
Would it be flexible enough to allow me to add other/new languages in the future?
Is there another way (better way) to implement it?

How to add a plugin-architecture in my Java application?

I have a Java command-line-application, which creates a report file after running some steps defined in the source-code. Now I want to separate those steps from the core functionality of my application, because I want that the application can run dynamically loaded "steps". This means, the core functionality of my application is to create the report file. And the separated "steps" should provide the content of the report.

I decided to realize those steps as plug-ins in my application. Everyone, who uses the application can extend it with already existing or own written plug-ins.

Now my question is, what is the best way - in my case - to develop a plug-in system for my application? I researched a lot and got to much input. I can't decide how should I resolve the problem.

Interesting question from SO:

During my research I collected some informations how i could resolve it:

  • Using ServiceLoader: a simple service-provider loading facility.
  • Using org.openide.util.Lookup from NetBeans(dynamic registration and lookup of components)
  • Defining a own Plug-in interface, which must be implemented from the plug-ins. And then using the Java ClassLoader to load those classes and create instances of them.
  • Using OSGi, but I think it is to "big" for my purpose.

What is the best way to solve my problem with: - a elegant plug-in architecture (perhaps with use of some design patterns), - easy to maintain source-code, - and easy to develop plug-ins.

Is my approach with a plug-in system correct? Or is there something else what could i use?

Java: caching collections

Lets support we develop application in java and have a big table. And in order to increase performance we want to cache data. And here we have two ways of caching:

  1. object cache - by id.
  2. collection cache - caching collection of ids(!)

Example of collection cache. We have a sql query SELECT * FROM person WHERE birhddate=A AND age<B ORDER BY firstName,lastName. And for this query we cache collection of ids. Now, for the same query we can use cache. However, the problem of such caching is that if there is any updates/creates/deletes all collections caches become old and can't be used any more.

These are questions -

  1. is collection cache used in practice?
  2. are there any patterns/solutions/lib for java/algorithms to work with collection caches?