jeudi 30 juin 2016

Android MVP optimization

I have just started using MVP in android development. As per different tutorials found on web, I am creating 5(viewInterface, presenterInterface, presenterImpl, interector, and interectorImpl) files for each fragment. Is there any way by which i can reduce the number of these files.

Thanks

C++ hierarchical class inheritance design

Suppose that I have the following application logic:

class classA
{
    classA(ConfigA config)
};

class classB
{
     classB(ConfigB config)
};

class App
{
    void initial(Config config){
        if( cond1)
            new classA(config.getConfigA());
        if( cond2)
            new classB(config.getConfigB());
     }
};

Is there good pattern to design the Config structure? Currently what I am doing is

struct BConfig
{
     int a;
     int b;
};

struct ConfigA:public BConfig
{
     int c;
};
struct ConfigB:public BConfig
{
     int d;
};
struct Config
{
    ConfigA getConfigA();
    ConfigB getConfigB();
    int a;
    int b;
    int c;
    int d;
};

I guess there is better way to do it. Any suggestion?

Wich code to put in controller/model using code igniter (mvc design pattern)

So I've been reading a lot about MVC but I still can't quite get the right way to do some things, so I am bringing here an example of a quite complex function I have in the application I'm developing (since most examples I find are simple coding) that I believe if I get the correct way of doing it, I will have a much better understanding of it. First I'll present it and then I'll talk a bit of what I understand how it should be done.

Books.php: (controller)

// Cria o registro de um livro novo ou adiciona uma avaliação ao livro encontrado
public function index_post() { // fazer os dados virem direto do google mais tarde para evitar usuários de adicionarem o que quiserem via ajax
    $auth_id = $this->post('auth_id');
    $this->user_model->setAuthId($auth_id);
    $loggedIn = $this->user_model->verifyLogin(); // Verifica se o ID de autenticação passado é válido

    if (!$loggedIn) {
        $this->response(array('response' => 'Você deve estar logado para inserir uma nova avaliação.', 'error' => 'Usuário não está logado!'));
    }

    $user_id        = $loggedIn->id;
    $hash           = $this->post('hash');
    $title          = $this->post('title');
    $subtitle       = $this->post('subtitle');
    $description    = $this->post('description');
    $author         = $this->post('author');
    $publisher      = $this->post('publisher');
    $image          = $this->post('image');
    $rating         = $this->post('rating');
    $comment        = $this->post('comment');

    try {
        $this->book_model->setHash($hash);
        $this->book_model->setTitle($title);
        $this->book_model->setSubtitle($subtitle);
        $this->book_model->setDescription($description);
        $this->book_model->setAuthor($author);
        $this->book_model->setPublisher($publisher);
        $this->book_model->setImage($image);
        $this->book_model->setRating($rating);
        $this->review_model->setUserId($user_id);
        $this->review_model->setComment($comment);
    } catch (Exception $error) {
        $this->response(array('response' => 'Algo deu errado devido ao seguinte erro: ' . $error->getMessage(), 'error' => $error->getMessage()));
    }

    $book = $this->book_model->checkRegister();

    if (is_null($book)) {
        $book->id = new StdClass();
        $book->id = $this->book_model->insert();

        if (is_null($book->id)) {
            $this->response(array('response' => 'Algo deu errado no servidor..', 'error' => 'Erro ao inserir o livro!'), 400);
        }
    }

    $this->review_model->setBookId($book->id);
    $this->review_model->setRating($rating);
    $duplicatedReview = $this->review_model->checkReview();

    if ($duplicatedReview) {
        $this->response(array('response' => 'Você já tem uma avaliação cadastrada neste livro. Use a função de editar para atualizá-la.'), 400);
    }

    $review_id = $this->review_model->insert();

    if (is_null($review_id)) {
        $this->response(array('response' => 'Algo deu errado no servidor..', 'error' => 'Erro ao inserir avaliação!'), 400);
    }

    $total_rating = $this->review_model->calculateRating();
    $this->book_model->updateRating($book->id, $total_rating);

    $this->response(array('response' => 'Avaliação adicionada com sucesso!', 'review_id' => $review_id), 200);
}

Book_model.php:

public function checkRegister() {
    $book = $this->db->where('hash', $this->getHash())->get('books')->row();

    if (!is_null($book)) {
        return $book;
    }

    return null;
}

public function insert() {
    $book = [
        'hash'          => $this->getHash(),
        'title'         => $this->getTitle(),
        'subtitle'      => $this->getSubtitle(),
        'description'   => $this->getDescription(),
        'author'        => $this->getAuthor(),
        'publisher'     => $this->getPublisher(),
        'image'         => $this->getImage(),
        'rating'        => $this->getRating()
    ];

    $this->db->insert('books', $book);

    if ($this->db->affected_rows() === 1) {
        return $this->db->insert_id();
    }

    return null;
}

public function updateRating($id, $total_rating) {
    $data['rating'] = $total_rating;

    $this->db->where('id', $id);
    $this->db->update('books', $data);

    if ($this->db->affected_rows() === 1) {
        return $this->find($id);
    }

    return null;
}

Review_model.php

public function checkReview() {
    $this->db->where('user_id', $this->getUserId());
    $this->db->where('book_id', $this->getBookId());
    $result = $this->db->get('reviews');

    if ($result->num_rows() === 0) {
        return false;
    }

    return true;
}

public function insert() {
    $data = [
        'book_id'       => $this->getBookId(),
        'user_id'       => $this->getUserId(),
        'comment'       => $this->getComment(),
        'rating'        => $this->getRating()
    ];

    $this->db->insert('reviews', $data);

    if ($this->db->affected_rows() === 1) {
        $review_id = $this->db->insert_id();
        return $review_id;
    }

    return null;
}

public function calculateRating() { // funcionando
    $ratings = $this->db->where('book_id', $this->getBookId())->select('rating')->get('reviews')->result();
    $ratingsCount = count($ratings);
    $ratingSum = 0;

    foreach ($ratings as $value) {
        $ratingSum += $value->rating;
    }

    $rating = $ratingSum / $ratingsCount;

    return $rating;
}

What this whole thing does is simply check if that book is already registered, if it is registered, it will only add a review to it, if not registered it will register the book and then register the review. After the review is registered the application must update the final rate of the book because of the new rating that was added in the review. This all works like a charm (don't mind the security issues, that's for another question), but I'm sure it's not the way it should be done.

I see everyone says the business logic should go in the model, while the controller only handles the information from the view to the model, but I can't figure out how to apply that in this real example, so I'm seeking this guidance here, if you can guide me through this function and tell me what and where I should be doing everything I would pay you with all the love I have for programming and technology learning <3

Thanks a lot!!!

what I should start learn first ooad , software development or design patterns

I study computer science and I need to improve my skills to have good job I learned java programming and I need to go deeper to understand how to use the programming language.

So what i should start first is OOAD, software development or design patterns ?

printing pattern of stars through arrays in zig zag(snake shape)

I want to print pattern of stars in ZigZag manner....i am unable to break the pattern as zigzag. please help me in doing this public class Pattern3_1 {

public static void main(String[] args) {
    Pattern3_1 pattern = new Pattern3_1();

    pattern.printPattern(5,5);***strong text***
}

public void printPattern(int rows,int coloumns) {
    int index = 0;
    for (int i = 0; i < rows; i++) {

        if (index < rows /2) {
            for (int j = 0; j < coloumns; j++) {
                System.out.print("*");
            }
            System.out.println();

            for (int k = 0; k < i + 1; k++) {
                System.out.print(" ");

            }index++;
        } 
        else {
            for (int j = 0; j < coloumns; j++) {
                System.out.print("*");
            }
            System.out.println();
            for (int k = i + 1; k < rows; k++) {
                System.out.print(" ");
            }
        }
    }
}

} output:





*****
 *****
*****




when i try this way i am not getting in ZIGZAG way.... please help me in doing this...........

Translating objects created using composite pattern with linked lists to MySQL RDBMS Schema,

a beginner programmer here.

As I'm only a hobbyist programmer, I'm not sure what the best industry practices are when you are creating a database schema given a set of class objects to play around.

I have some number of structured data sets which I exported to Excel CSVs from IBM's Rational DOORS product.

I tried to decompose the data into a structure which I think is the best fit, as shown below,

Data relationship (given),

enter image description here

Class objects for coding purposes I came up with,

enter image description here

And then to store the data into a relational db such ad MySQL, I've sketched a high level schema as shown below,

enter image description here

The questions here is really.. I don't know if I've got this right or not.

it would be really appreciated if I can get some comments from experts on,

  1. Use of design pattern - is composite common practice to describe the data?
  2. Can I use a separate linked list objects to link what are many to many relationship of the titles?
  3. is the translation of the classes into MySQL schema rightly done?

Many thanks in advance,

Can someone explain why this this for loop prints out this specific pattern?

I thought I had a good understanding of for loops, but now that I have started to try looping patterns with for loops, things have gotten a lot more confusing. For example, I know that the following code will print out:

for (var line = “#”; line.length < 8; line += “#”) console.log(line);

Output will be:

#
##
###
####
#####
######
#######

This is what I understand so far about this loop:

  1. Firstly, the loop is initialized by creating a variable “line” to store the value “#” which is only one character.
  2. Next, “line.length<8” checks that the length of the string stored in the variable “line” is less than 8 characters long.
  3. The third part “line += “#”” updates the value stored in the line variable by adding “#” for each iteration that line.length<8 is true.
  4. The length of the string (and therefore line.length) is being updated for each iteration of the loop because a “#” value is being added each time.

Can someone explain to me why # is being added once, then twice, then three times etc. From the (incorrect) understanding that I have, I keep thinking that it’ll look like:

#1
#2
#3

etc.

class designing - inheritance or abstract or interface

I have multiple classes having one common property and I am setting that property in constructor of that class.

class Expense1
{
    int _costval;

    public Expense1(int cost)
        {
            _costval = cost;
        }
    ///other properties and methods..
} 
class Expense2
{
    int _costval;

    public Expense1(int cost)
        {
            _costval = cost;
        }
    ///other properties and methods..
} 
class Expense3
{
    public int Costval;

    public Expense1(int cost)
        {
            Costval = cost;
        }
    ///other properties and methods..
} 

at some point I need to access "Costval". something like

Console.WriteLine(@object.CostVal)

That object can be of any type expense1 or expense2 or expense3..

how can I do that? should I create basic abstract class and move costval and constructor to it? please advice.

Communicating between components in Android

So I have an Activity. The Activity hosts a ViewPager with tabs, each tab holding a Fragment in it. The Fragments themselves have a RecyclerView each. I need to communicate changes from the RecyclerView's adapter to the activity.

Currently, I am using the listener pattern and communicating using interface between each of the components. i.e I have an interface between the RecyclerView's adapter and the Fragment holding it. Then an interface from the Fragment to the ViewPager's FragmentStatePagerAdapter which is creating all the Fragments. And 1 more interface between the ViewPager's adapter and the Activity hosting the ViewPager. I feel that there are too many interfaces for all the components because of how they are structured.

Currently I am not facing issues as such but I think the listener pattern is acting like an anti-pattern due to all the nested components. Instead of creating independent components I think the hierarchy will make it difficult for making code changes in future.

Am I doing it correctly or is there a better way to do it? Is this a case where I should use an Event Bus or Observer Pattern (If yes can you point me to some examples where someone overcame a similar problems using it)?

NOTE : If it matters, I need it to maintain a global object in the activity, something like a shopping cart where I can add or remove items and these items are present in RecyclerView's adapter from where I can add it to the cart and also increment or decrement the count for a particular item. The ViewPager and Tabs help segregate these items in various categories.

is it correct to send UIImage between two controllers?

Is it appropriate to send UIImage between two Uiviewcontrollers?

I'm working on assignment 4 of CS193P Spring - Smashtag.

There I have to implement Mention Table View (It's kind of additional data of tweet: mentions, hashtags, images, urls). I have to place images to appropriate cell there. For that purpose I already download it. After that If user tap on one of that images It should segue to another UIViewController where user can zoom and scroll image.

In many examples which I've seen, people send url of image and fetch it again and again (for mention controller and the same image for another one). I think It decreases perfomance. So I send UIImage object between controllers.

But is it correct?

mercredi 29 juin 2016

Singleton design pattern in Javascript

I am following this link http://ift.tt/1UyR1QI to understand design patterns in Javascript I understood constructor pattern , module pattern and module revealing pattern , now in Singleton pattern I have two doubts which are following :

1) I know c++ and I am learning JavaScript now, so I understand singleton pattern allows you only one instance of the class but in this book it's mentioned "In JavaScript, Singletons serve as a shared resource namespace which isolate implementation code from the global namespace so as to provide a single point of access for functions." What does it mean ???

2) var mySingleton = (function () {

// Instance stores a reference to the Singleton var instance;

function init() {

// Singleton

// Private methods and variables
function privateMethod(){
    console.log( "I am private" );
}

var privateVariable = "Im also private";

var privateRandomNumber = Math.random();

return {

  // Public methods and variables
  publicMethod: function () {
    console.log( "The public can see me!" );
  },

  publicProperty: "I am also public",

  getRandomNumber: function() {
    return privateRandomNumber;
  }

};

};

return {

// Get the Singleton instance if one exists
// or create one if it doesn't
getInstance: function () {

  if ( !instance ) {
    instance = init();
  }

  return instance;
}

};

})();

var singleA = mySingleton.getInstance(); var singleB = mySingleton.getInstance();

My doubt is when we call mySingleton.getInstance(); won't be the value "instance" undefined again, as it is a local variable and everytime we call the getInstance method it should set the instance value as undefined and hence if ( !instance )
should pass always and give a new instance but I don'y understand how it's working here. Kindly explain.

PHP design patterns Factories

We make heavy use of the factory pattern, its create in situations where orchestrating the creation of entities (models) that have many different relationships and parameters. Great!

Although, I'm looking for a similar pattern for updating that same entity, is there one?

At present we update models in our Repositories as much of the Laravel community does. Although this to me is a code smell. Repositories are responsible for retrieving groups of entities, nothing more... Is there a term / pattern to cover this Creator / Factory paradigm?

To cut those Laravel fan boys down before they begin: Yes we are a large enough app to warrant these considerations. It has come to the point we need to split this logic away from our repositories...

Makefile with pattern and directories

For a game I've a lot of textures to refenerate, this can take some times and so I only want to regenerate modified one instead of all of them.

I've a makefile with a structure similar to this one (which here s simplified for the example):

all:\
  wall

wall:\
  wall/red\
  wall/blue\
  wall/mixed

wall/%:\
  wall/%/top.png\
  wall/%/left.png\
  wall/%/right.png\
  wall/%/down.png\
    echo $@ $<

wall/red/%.png:\
  .source/wall/model/%.png
    convert $< -fill "rgb(255,0,0)" -colorize 15,15,15,0 -level "0%,100%,0.8" $@

wall/blue/%.png:\
  .source/wall/model/%.png
    convert $< -fill "rgb(0,0,255)" -colorize 15,15,15,0 -level "0%,100%,0.8" $@

wall/black/%.png:\
  .source/wall/model/%.png
    convert $< -fill "rgb(0,0,0)" -level "0%,100%,0.4" $@

wall/white/%.png:\
  .source/wall/model/%.png
    convert $< -fill "rgb(255,127,0)" -level "0%,70%,1.2" $@

wall/mixed/%.png:\
  wall/white/%.png\
  wall/black/%.png\
  .source/wall/mask/%.png
    convert $(word 1,$^) $(word 2,$^) $(word 3,$^) -composite $@

My problem here is that :

wall/%:
    echo $@

is working (it return me "wall/red", "wall/blue" and "wall/mixed") but :

wall/%:\
  wall/%/top.png\
  wall/%/left.png\
  wall/%/right.png\
  wall/%/down.png\
    echo $@

don't works (it return that there is no rules to build "wall/red" for "wall") and I don't know why because I've already seen rules like :

obj/%.o: %.c $(DEPS)

that works correctly.

Starting a thread from a member function while inside another class's member function

I need to start a thread that calls a public member function of the class Foo while inside of a public function that belongs to the class Bar. How do I achieve this?

I have tried the following (made trivial):

void Bar::BarFunc()
{ 
    // Do some BarFunc stuff 

    // Start a thread that needs to do stuff independently of BarFunc
    std::thread t(&Foo::FooFunc, FooFunc params,..,.., ???);
    t.detach();

    return;
}

This is my first time dealing with threading and the actual problem is a little more complex - BarFunc is a virtual function of a State class, with n-concrete classes implementing the different states my application can exist in, hence the question. I am not sure what to put as the last parameter, if anything. I have looked at this answer but cannot discern which syntax to use, if any of them even apply.

Finally, if this is bad practice all together, I would be grateful for any design advice.

Advise with Good Design Patterns When Connecting To An External Database?

I have a regular app using sqlite. I am using a singleton to have a connection to it and perform CRUD operations from it.

I do want to use this with an external database where I would download txt files. I have a database using mongolab and I do know that they have a tutorial to connect directly to the database but I am wondering if this is the right option for me.

What is a good design pattern to connect and keep a connection with an external database such as mongo.

Would it be better to connect to my hosting site and build an API and make calls from android to my API?

What would you call this design pattern?

I have been reading and researching about MVC, HMVC, PAC and MVVM design patterns and have also seen a few so-called implementations of MVC and HMVC.

This question is NOT about difference in these design patterns, I just want any expert who understands these design patterns and their implementations in apps/frameworks working in stateless enviornment (PHP on a web server) to categorize my approach.

I will use references from wikipedia and an article I read written by larry garfield on MVC vs PAC

One of the most common mistakes I see people make when talking about web architecture is with regards to MVC. Generally it comes down to a statement such as this:

It's a web app, so we have to use MVC. That way we separate the logic and presentation, which means keeping PHP out of our display layer. All the important projects do it that way.

Of course, such a statement is false. It demonstrates a lack of understanding about MVC, about web applications, about "important projects", and about software architecture in general.

My implementation:

I have controllers and models classes while I am using a template engine to handle views so views don't have their own classes per se

It all starts with a front controller which reads the http request (RESTfuly) and routes request to the relevant controller by instantiating it and then calling relevant method according to request (i.e. postSomething() or deleteThat() etc...) however if a input method is GET then a "view" method is called which tells template engine to parse its template file. (Output depends on http accept header for all methods and controller method is determined by params coming with request, etc.. etc... but what's important here that my controllers optionally have single view method for GET requests which processes HTML templates.

My models are mostly ORM layers (combination of data mapping and active records) and other sorts of abstractions

While this all works pretty well for me, and I am very much satisfied with benchmarking and everything, I am just curious how should I classify this design pattern

Why its not MVC or one of its variant (MVP, MVVM)?

In MVC, the View component has direct access to the Model. The Controller itself doesn't enter the picture unless there is actual change to the data. Simply reading and displaying data is done entirely by the View component itself.

...

On the flipside, however, that means the View component has to have some rather complex logic in it. It needs to know how to pull data out of the Model, which means it needs to know what the data structure is (or at least a rich API in front of the Model). It needs to be able to handle user interaction itself, with its own event loop.

Unlike MVC, all the intelligence in my implementation resides in controllers. Controllers manipulate data via models and then serve output or call view method. Controllers may also call other sibling methods (methods with in same controller class). Also my views (method) and models never interact with each other.

Also in most of the resources I have found that in actual, MVC/MVP and MVVM design patterns, input starts with views not controllers which is opposite of my implementation. (However frameworks that I have seen implementing MVC/HMVC, their flowchart starts with controllers receving input, which contradicts MVC)

MVC/MVP/MVVM flowchart

What about hierarchy?

In my implementation, my app has 2 interfaces, "frontend" and "backend" (operates on a different http port). Both of these interfaces have their own controllers and views (template files) while both use same models/abstractions.

  • Frontend/
    • controllers/
    • models/
    • views/
  • Backend
    • controllers/
    • models/
    • views/

Inside the interface, a controller can dispatch sub-requests to other controllers in same interface (or another) to form a main response/output but there is NO as such directory architecture:

  • Frontend/
    • module1/
      • controllers/
      • models/
      • views/
    • module2/
      • controllers/
      • models/
      • views/

Is it PAC? but how much?

The two main differences between MVC and PAC are that in PAC the Presentation component is "dumb" while all the intelligence resides in the Controller and PAC is layered. Again, see the pretty picture.

You'll notice that the Presentation and Abstraction components never speak to each other. The Controller takes input, not the display component. The Controller has all the business logic and routing information. The Presentation component is essentially just a filter that takes raw data that the Controller pushes through it and renders it to HTML (or WML, or XML, or text, or an icon in a graphical monitoring system, or whatever). It's just a templating system.

and... from wikipedia:

In contrast to MVC, PAC is used as a hierarchical structure of agents, each consisting of a triad of presentation, abstraction and control parts. The agents (or triads) communicate with each other only through the control part of each triad. It also differs from MVC in that within each triad, it completely insulates the presentation (view in MVC) and the abstraction (model in MVC).

so basically my implementation sounds more like PAC (at least flow and handling of request matches it) but does my implementation matches PAC hierarchical wise?

Also please explain this line "It also differs from MVC in that within each triad, it completely insulates the presentation (view in MVC) and the abstraction (model in MVC)."

does it mean that in PAC, a triad cannot access models and views of other triad or does it mean that in MVC models and views can interact it with eachother while in PAC they cannot.

But if so, doesn't it make most of the frameworks out there claiming to be MVC or HMVC, in fact PAC based?

Is this pattern a service locator, or something else?

I have the following class (in JEE, can be made similarly in Spring):

@Singleton
public class MyUnknownPatternClass {
    @Inject @Any Instance<SomeInterface> instances;

    public SomeInterface getMatchingInstance(Object someDiscriminator) {
        for(SomeInterface instance : instances) {
            if(instance.supports(someDiscriminator)) {
                return instance;
            }
        }
        throw new IllegalArgumentException("Could not find a matching instace for " + someDiscriminator.toString());
     }
}

Using dependency injection's discovery to locate all instances of the matching interface, this allows me to totally decouple strategies and the code using it.

For example, if I'm in a banking application, and I'm having different TransportProviders which implement a travel(Location l) method, my business logic can then focus on following regular flow, for, say a travelling salesman:

Salesman m =...;
Location l =  m.getStartLocation();
TransportProvider t = myUnknownPatternClass.getMatchingInstance(m.getTravelMethod());
for(Location d : m.getDestinationsToVisit())
    l = t.travel(d);
    m.doBusinessHere(l);
}

Thus decoupling whether the salesman travels by foot, boat, car, or any other method.

My understanding is that a factory actually instantiates objects. A servicelocator is more generic, and allows for runtime registration, and the above code seems to do neither. It is not a whiteboard pattern, as it only returns a single instance.

However, it's a very useful pattern, and it would be nice to talk about it properly.

What, then, is it?
And what would then be a proper name for the class (i.e. SomeInterfaceLocator, or SomeInterfaceFactory)?

Pythonic way to have a function return value in proper units

Objective: return a value from a function in the units (or any trivial modification) requested by the caller.

Background:

I am running Python 2.7 on a Raspberry Pi 3, and use the function distance() to get the distance a rotary encoder has turned. I need this distance in different units depending on where the function is called. How then, should this be written pythonically (i.e. short, and easily maintained).

First Attempt:

My first attempt was to use a unit of meters in the function, and have a long elif tree to select the right units to return in.

def distance(units='m'):
    my_distance = read_encoder()

    if units == 'm':
        return my_distance * 1.000
    elif units == 'km':
        return my_distance / 1000.
    elif units == 'cm':
        return my_distance * 10.00
    else:
        return -1

The nice thing about this approach is that it has a way to recognize a unit that isn't available.

Second Attempt:

My second attempt was to create a dictionary to contain various multipliers.

def distance(units='m'):
    multiplier = {
        'm': 1.000,
        'km': 0.001,
        'cm': 10.00
    }

    try:
        return read_encoder() * mulitplier[units]
    except KeyError:
        return -1

Here, unrecognized units are caught with a KeyError.

Relevance:

I know of existing libraries like Pint, but am looking for a solution to this programming problem. When you have a function in Python, and you need to make slight modifications to the output in a reusable way. I have other functions such as speed() that use 'm/s' as a base unit, and need a similar units argument. From my experience, a well-structured program does not involve a paragraph of elif branches before every return statement. In this case, if I wanted to change how I calculate the units, I would have to carefully grep through my code, and make sure I change how the units are calculated at every instance. A proper solution would only require changing the calculation once.

This is possibly too broad, but it is a pattern I keep running into.

shared-kernels implemented by web-services

With DDD (Domain Driven Design), I have learned about shared-kernels. My question is simple : are web-services good candidates to implement shared-kernels ?

How to design a returned stream that may use skip

I have created a parsing library that accepts a provided input and returns a stream of Records. A program then calls this library and processes the results. In my case, my program is using something like

recordStream.forEach(r -> insertIntoDB(r));

One of the types of input that can be provided to the parsing library is a flat file, which may have a header row. As such, the parsing library can be configured to skip a header row. If a header row is configured, it adds a skip(n) element to the return, e.g.

Files.lines(input)**.skip(1)**.parallel().map(r -> createRecord(r));  

The parsing library returns the resulting Stream.

But, it seems that skip, parallel and forEach do not play nicely togetherThe end programmer must instead invoke forEachOrdered, but it is poor design to put this requirement on the programmer, to expect them to know they must use forEachOrdered if dealing with an input type of a file with a header row.

How can I enforce the ordered requirement myself when necessary, within the construction of the returned stream chain, to return a fully functional stream to the program writer, instead of a stream with hidden limitations? Is the answer to wrap the stream in another stream?

Extensible projects with Plugins

I want to make a project which can be extensible with the help of plugins. So i want my application can detect any newly added plugins and can integrate the changes with the existing functionality.

What all things i should take care while making such application.

Layer Management Design Pattern

I am going to implement a layer manager similar to what can be found in GIMP or photoshop. I am wondering if there is a specific design pattern to implement that?

Start Fragment before hand

I have a parent fragment P which contains 10 buttons each on clicking will replace a container in P with child fragments C1 to C10. I should also be able to navigate from C1 to C2 on clicking next in action bar. I am able to achieve this but since each of the child fragment is having a heavy initialization (loading SVG, surfaceview etc..) the transition is not smooth. Is it possible to start the next fragment i.e. C2 when in C1 and put it in paused state so that it can be resumed directly when next in C1 is clicked.

This is someway similar to OffScreenLimit in ViewPager but when I have seen the view pager source code it doesn't replace the existing fragment but simply scroll the view to new fragment X.

Replacing the existing framework with ViewPager as shown here is one possible solution but that requires a lot of changes with the existing code base and is the last thing I wish to do

mardi 28 juin 2016

Java returning immutable object

Let's say I'm writing a method that should return a Map. For instance:

public Map<String, Integer> foo() {
  return new HashMap<String, Integer>();
}

After thinking about it for a while, I've decided that there is no reason to modify this Map once it is created. Thus, I would like to return an ImmutableMap.

public Map<String, Integer> foo() {
  return ImmutableMap.of();
}

Do you think it is OK to leave the return type as a regular Map?

From one side, this exactly why interfaces were created for; to hide the implementation details.
On the other hand, if I'll leave it like this, other developers might miss the fact that this object is immutable. Thus, I won't achieve a major goal of immutable objects; to make the code more clear by minimizing the number of objects that can change. Even worst, after a while, someone might try to change this object, and this will result in a runtime error (The compiler will not warn about it).

WDYT?

Thanks.

What are the objects call that transform data between layers

I have a question about what is the convention for naming objects the transform one object into another. I swear there was an elegant name for this that I'm forgetting and all my searches just end up with the difference between a DTO and and Entity or Model or DAO or POCO or POJO.

I'm not interested in using Automapper at this point either, I might convert to that later, but the code is there, I just want to name it correctly!

Find expression at start of line or after a punctuation

This has been bothering me for the past few days and I can't seem to find the answer. Consider the following:

I have a string called "options" which is in the form: "xxx=true&yxxx=true&zzz=false" (yes, like an URL query).

I have pattern matchers set up like so:

Pattern pattern1 = Pattern.compile("xxx=true");
Pattern pattern2 = Pattern.compile("yxxx=true");
Pattern pattern3 = Pattern.compile("zzz=true");

My problem comes with differentiating between the second and first pattern, since pattern1 finds a match in the yxxx=true case since it contains the "xxx=true" string. I've looked everywhere, and could get away with splitting the first pattern to "&xxx=true" and "^xxx=true" to cover the "start of line" and every other case, but I just know there must be some other way to do this.

Location services across multiple activities

I was wondering if there was an elegant way to separate google fused location services away from activities. My warning class currently implements location services but I have another activity that takes photos. When a photo is taken I want to associate a location with the image. My current idea is to just use my broadcast receiver in my Bluetooth warning class to listen for a broadcast my camera will send and associate it then with a location. I'm not a fan of the idea because it doesn't separate functionality very well so was hoping for some suggestions or patterns. Code for classes below.

CAMERA CLASS

import android.content.Intent;
import android.content.pm.PackageManager;
import android.graphics.Bitmap;
import android.graphics.BitmapFactory;
import android.net.Uri;
import android.os.Environment;
import android.provider.MediaStore;
import android.support.v7.app.AppCompatActivity;
import android.os.Bundle;
import android.widget.ImageView;
import android.widget.Toast;

import java.io.File;
import java.io.IOException;
import java.text.SimpleDateFormat;
import java.util.Date;

public class CameraOperations extends AppCompatActivity {
    ImageView mImageView;
    String photoPath;
    int REQUEST_IMAGE_CAPTURE = 1;
    File photoFile = null;

    @Override
    protected void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        setContentView(R.layout.camera_view);
        mImageView = (ImageView) findViewById(R.id.imageView);

        if (!getPackageManager().hasSystemFeature(PackageManager.FEATURE_CAMERA)) {
            Toast.makeText(CameraOperations.this, "No Camera", Toast.LENGTH_SHORT).show();
        } else {
            dispatchTakePictureIntent();
        }
    }

    @Override
    protected void onActivityResult(int requestCode, int resultCode, Intent data) {
        if (requestCode == REQUEST_IMAGE_CAPTURE && resultCode == RESULT_OK){
            if(data == null){
                Toast.makeText(this, "Data is null", Toast.LENGTH_SHORT);
                Bitmap pictureMap = BitmapFactory.decodeFile(photoFile.getAbsolutePath());
                mImageView.setImageBitmap(pictureMap);
            }else {
                Toast.makeText(this, "Error Occurred", Toast.LENGTH_SHORT).show();
            }
        }
    }

    private File createImageFile() throws IOException {
        String timeStamp = new SimpleDateFormat("yyyyMMdd_HHmmss").format(new Date());
        String imageFileName = "JPEG_" + timeStamp + "_";
        File storageDir = getExternalFilesDir(Environment.DIRECTORY_PICTURES);
        File image = File.createTempFile(imageFileName, ".jpg", storageDir);

        photoPath = "file:" + image.getAbsolutePath();
        return image;
    }

    private void dispatchTakePictureIntent() {
        Intent takePictureIntent = new Intent(MediaStore.ACTION_IMAGE_CAPTURE);
        try{
            photoFile = createImageFile();
        }catch(IOException e){
            e.printStackTrace();
        }

        if(photoFile != null){
            Uri photoUri = Uri.fromFile(photoFile);
            takePictureIntent.putExtra(MediaStore.EXTRA_OUTPUT, photoUri);
        }
        startActivityForResult(takePictureIntent, REQUEST_IMAGE_CAPTURE);

    }
}

BLUETOOTH WARNING CLASS

import android.Manifest;
import android.bluetooth.BluetoothGattCharacteristic;
import android.bluetooth.BluetoothGattService;
import android.content.BroadcastReceiver;
import android.content.ComponentName;
import android.content.Context;
import android.content.DialogInterface;
import android.content.Intent;
import android.content.IntentFilter;
import android.content.ServiceConnection;
import android.content.pm.PackageManager;
import android.location.Location;
import android.os.Build;
import android.os.Bundle;
import android.os.IBinder;
import android.support.v4.app.ActivityCompat;
import android.support.v7.app.AlertDialog;
import android.support.v7.app.AppCompatActivity;
import android.support.v7.widget.Toolbar;
import android.util.Log;
import android.view.KeyEvent;
import android.view.Menu;
import android.view.MenuInflater;
import android.view.MenuItem;
import android.widget.Toast;

import com.google.android.gms.common.ConnectionResult;
import com.google.android.gms.common.GoogleApiAvailability;
import com.google.android.gms.common.api.GoogleApiClient;
import com.google.android.gms.location.LocationRequest;
import com.google.android.gms.location.LocationServices;

public class Warning extends AppCompatActivity implements GoogleApiClient.ConnectionCallbacks, GoogleApiClient.OnConnectionFailedListener {
    private final static String TAG = Warning.class.getSimpleName();
    private String mDeviceAddress;
    private HandleConnectionService mBluetoothLeService;
    private boolean quitService;
    private final int PLAY_SERVICES_REQUEST_TIME = 1000;
    private Location mLastLocation;
    private GoogleApiClient mGoogleClient;
    private boolean requestingLocationUpdates = false;
    private LocationRequest locationRequest;

    private int UPDATE_INTERVAL = 10000; // 10 seconds
    private int FASTEST_INTERVAL = 5000; // 5 seconds
    private int DISTANCEMOVED = 10; //In meters


    private final ServiceConnection mServiceConnection = new ServiceConnection() {
        @Override
        public void onServiceConnected(ComponentName componentName, IBinder service) {
            mBluetoothLeService = ((HandleConnectionService.LocalBinder) service).getService();
            if (!mBluetoothLeService.initialize()) {
                Log.e(TAG, "Unable to initialize Bluetooth");
                finish();
            }
            mBluetoothLeService.connect(mDeviceAddress);
        }

        @Override
        public void onServiceDisconnected(ComponentName componentName) {
            mBluetoothLeService = null;
        }
    };

    private final BroadcastReceiver mGattUpdateReceiver = new BroadcastReceiver() {
        @Override
        public void onReceive(Context context, Intent intent) {
            final String action = intent.getAction();

            if (HandleConnectionService.ACTION_GATT_DISCONNECTED.equals(action)) {
                if (!quitService) {
                    mBluetoothLeService.connect(mDeviceAddress);
                    Log.w(TAG, "Attempting to reconnect");
                }
                Log.w(TAG, "Disconnected, activity closing");
            } else if (HandleConnectionService.ACTION_GATT_SERVICES_DISCOVERED.equals(action)) {
                getGattService(mBluetoothLeService.getSupportedGattService());
            } else if (HandleConnectionService.ACTION_DATA_AVAILABLE.equals(action)) {
                checkWarning(intent.getByteArrayExtra(HandleConnectionService.EXTRA_DATA));
            }
        }
    };

    @Override
    protected void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        setContentView(R.layout.second);

        Toolbar myToolbar = (Toolbar) findViewById(R.id.my_toolbar);
        setSupportActionBar(myToolbar);

        if (checkGoogleServices()) {
            buildGoogleApiClient();
        }

        quitService = false;
        Intent intent = getIntent();
        mDeviceAddress = intent.getStringExtra(Device.EXTRA_DEVICE_ADDRESS);

        Intent gattServiceIntent = new Intent(this, HandleConnectionService.class);
        bindService(gattServiceIntent, mServiceConnection, BIND_AUTO_CREATE);
    }

    @Override
    protected void onResume() {
        super.onResume();
        registerReceiver(mGattUpdateReceiver, makeGattUpdateIntentFilter());
    }

    @Override
    public boolean onCreateOptionsMenu(Menu menu) {
        MenuInflater inflater = getMenuInflater();
        inflater.inflate(R.menu.mainmenu, menu);
        MenuItem connect = menu.findItem(R.id.connect);
        connect.setVisible(false);
        MenuItem disconnect = menu.findItem(R.id.disconnect);
        disconnect.setVisible(true);
        return true;
    }

    @Override
    public boolean onOptionsItemSelected(MenuItem item) {
        Intent intent;
        switch (item.getItemId()) {
            case R.id.home:
                new AlertDialog.Builder(this)
                        .setIcon(android.R.drawable.ic_dialog_alert)
                        .setTitle("Return Home")
                        .setMessage("Returning home will disconnect you, continue?")
                        .setPositiveButton("Yes", new DialogInterface.OnClickListener() {
                            @Override
                            public void onClick(DialogInterface dialog, int which) {
                                quitService = true;
                                mBluetoothLeService.disconnect();
                                mBluetoothLeService.close();

                                Intent intent = new Intent(Warning.this, Main.class);
                                intent.setFlags(Intent.FLAG_ACTIVITY_CLEAR_TOP);
                                startActivity(intent);
                            }
                        })
                        .setNegativeButton("No", null)
                        .show();

                return true;
            case R.id.connect:
                Toast.makeText(this, "Connect Pressed", Toast.LENGTH_SHORT).show();
                return true;

            case R.id.disconnect:
                disconnectOperation();
                intent = new Intent(Warning.this, Main.class);
                intent.setFlags(Intent.FLAG_ACTIVITY_CLEAR_TOP);
                startActivity(intent);
                return true;

            case R.id.profiles:
                Toast.makeText(this, "Profiles Pressed", Toast.LENGTH_SHORT).show();
                return true;


            case R.id.camera:
                Toast.makeText(this, "Camera Pressed", Toast.LENGTH_SHORT).show();
                intent = new Intent(Warning.this, CameraOperations.class);
                startActivity(intent);
                return true;

            default:
                return super.onOptionsItemSelected(item);
        }
    }

    @Override
    public boolean onKeyDown(int keyCode, KeyEvent event) {
        if (keyCode == KeyEvent.KEYCODE_BACK) {
            quitService = true;
            mBluetoothLeService.disconnect();
            mBluetoothLeService.close();

            Intent intent = new Intent(Warning.this, Main.class);
            intent.setFlags(Intent.FLAG_ACTIVITY_CLEAR_TOP);
            startActivity(intent);
            return true;
        }
        return super.onKeyDown(keyCode, event);
    }

    @Override
    protected void onDestroy() {
        super.onDestroy();
        mBluetoothLeService.disconnect();
        mBluetoothLeService.close();

        System.exit(0);
    }

    public boolean disconnectOperation(){
        this.quitService = true;
        mBluetoothLeService.disconnect();
        mBluetoothLeService.close();
        return true;
    }

    private void checkWarning(byte[] byteArray) {
        if (byteArray != null) {
            for (int i = 0; i < byteArray.length; i++) {
                if (byteArray[i] == 48) {
                   findLocation();
                }
            }
        }
    }

    private void getGattService(BluetoothGattService gattService) {
        if (gattService == null) {
            return;
        }

        BluetoothGattCharacteristic characteristicRx = gattService.getCharacteristic(HandleConnectionService.UUID_BLE_SHIELD_RX);
        mBluetoothLeService.setCharacteristicNotification(characteristicRx, true);
        mBluetoothLeService.readCharacteristic(characteristicRx);
    }

    private static IntentFilter makeGattUpdateIntentFilter() {
        final IntentFilter intentFilter = new IntentFilter();
        intentFilter.addAction(HandleConnectionService.ACTION_GATT_CONNECTED);
        intentFilter.addAction(HandleConnectionService.ACTION_GATT_DISCONNECTED);
        intentFilter.addAction(HandleConnectionService.ACTION_GATT_SERVICES_DISCOVERED);
        intentFilter.addAction(HandleConnectionService.ACTION_DATA_AVAILABLE);

        return intentFilter;
    }

    private boolean checkGoogleServices() {
        GoogleApiAvailability googleAPI = GoogleApiAvailability.getInstance();
        int available = googleAPI.isGooglePlayServicesAvailable(this);
        if (available != ConnectionResult.SUCCESS) {
            if (googleAPI.isUserResolvableError(available)) {
                googleAPI.getErrorDialog(this, available, PLAY_SERVICES_REQUEST_TIME).show();
            }
            return false;
        }

        return true;
    }

    public void findLocation() {
        int REQUEST_CODE_ASK_PERMISSIONS = 123;
        double latitude = 0.0;
        double longitude = 0.0;

        if(Build.VERSION.SDK_INT >= 23){
            boolean fineLocationAccess = ActivityCompat.checkSelfPermission(this, android.Manifest.permission.ACCESS_FINE_LOCATION) == PackageManager.PERMISSION_GRANTED;
            boolean courseLocationAccess = ActivityCompat.checkSelfPermission(this, Manifest.permission.ACCESS_COARSE_LOCATION) == PackageManager.PERMISSION_GRANTED;
            boolean accessGranted = fineLocationAccess && courseLocationAccess;

            if (accessGranted) {
                mLastLocation = LocationServices.FusedLocationApi.getLastLocation(mGoogleClient);
                if(mLastLocation != null) {
                    latitude = mLastLocation.getLatitude();
                    longitude = mLastLocation.getLongitude();

                    Toast.makeText(this, "latitude: " + latitude + " longitude: " + longitude, Toast.LENGTH_LONG).show();
                }else{
                    Log.i("Warning", "Unable to get Location");
                }
            }else{
                Log.i("Connection", "Request permission");
            }
        }else{
            mLastLocation = LocationServices.FusedLocationApi.getLastLocation(mGoogleClient);
            if(mLastLocation != null) {
                latitude = mLastLocation.getLatitude();
                longitude = mLastLocation.getLongitude();

                Toast.makeText(this, "latitude: " + latitude + " longitude: " + longitude, Toast.LENGTH_LONG).show();
            }else{
                Log.i("Warning", "Unable to get Location");
            }
        }
    }

    public void buildGoogleApiClient() {
        mGoogleClient = new GoogleApiClient.Builder(this)
                .addConnectionCallbacks(this)
                .addOnConnectionFailedListener(this)
                .addApi(LocationServices.API).build();
    }

    @Override
    public void onConnected(Bundle bundle) {
        Log.w("Connected", " : " + mGoogleClient.isConnected());
    }

    @Override
    public void onConnectionSuspended(int i) {
        Toast.makeText(this, "Location Services Stopped", Toast.LENGTH_SHORT).show();
    }

    @Override
    public void onConnectionFailed(ConnectionResult connectionResult) {
        Toast.makeText(this, "Location Services Connection Fail", Toast.LENGTH_SHORT).show();
    }

    @Override
    protected void onStart() {
        super.onStart();

        if (mGoogleClient != null) {
            mGoogleClient.connect();
        }
    }
}

Repository inheritance refactoring

I have two repositories (PostRepository and AlbumRepository) and both inherit from another PublicationRepository.

In PostRepository I have these projections

return queryBase.Select(x => new NewsFeed
                             {
                                 Id = x.PublicationID,
                                 Title = x.Title,
                                 Content = x.Content,
                                 CreatedDate = x.CreatedDate,
                                 Link = x.Link,
                                 Type = NewsFeedType.Post,
                                 PostType = x.PostType,
                                 OwnerId = x.UserID.HasValue ? x.UserID.Value : 0,
                                 OwnerFirstName = x.User != null ? x.User.FirstName : "",
                                 OwnerLastName = x.User != null ? x.User.LastName : "",
                                 OwnerProfilePicture = x.User != null ? x.User.PhotoPath : "",
                                 CommentsCount = x.PublicationComment.Count(),
                                 ILike = x.Consultation.Any(c => c.ViewedByID == userId && c.ILike == true && c.DeletedFlag != true),
                                 IsSignaled = x.Consultation.Any(c => c.ViewedByID == userId && c.IsSignaled == true && c.DeletedFlag != true),
                                 RecommendationCount = x.Consultation.Count(c => c.DeletedFlag != true && c.ILike == true),
                                 TargetPopulations = x.Access.Select(a => a.Population.PopulationName).ToList(),
                                 OwnerIsMyManager = promoManagerIds.Contains(x.UserID)
                             });

And In AlbumRepository I have these

return queryBase.Select(x => new NewsFeed
                             {
                                 Id = x.PublicationID,
                                 Title = x.AlbumName,
                                 CreatedDate = x.CreatedDate,
                                 Type = NewsFeedType.Album,
                                 OwnerId = x.UserID.HasValue ? x.UserID.Value : 0,
                                 OwnerFirstName = x.User != null ? x.User.FirstName : "",
                                 OwnerLastName = x.User != null ? x.User.LastName : "",
                                 OwnerProfilePicture = x.User != null ? x.User.PhotoPath : "",
                                 CommentsCount = x.PublicationComment.Count(),
                                 ILike = x.Consultation.Any(c => c.ViewedByID == userId && c.ILike == true && c.DeletedFlag != true),
                                 IsSignaled = x.Consultation.Any(c => c.ViewedByID == userId && c.IsSignaled == true && c.DeletedFlag != true),
                                 RecommendationCount = x.Consultation.Count(c => c.DeletedFlag != true && c.ILike == true),
                                 TargetPopulations = x.Access.Select(a => a.Population.PopulationName).ToList(),
                                 AlbumPhotoPaths = x.AlbumPhoto.Where(a => a.DeletedFlag != true).Select(a => a.AlbumElementPath).ToList()
                             });

As you can see, there is a lot of repeated code here. Is there a way to move all the common projections to the base repository and keep only the specific ones in the specific repositories?

Open/Close principle violates YAGNI principle

I have been developing a piece of library in C#, The primary aim of this library is to wrap all the versions of default linux binaries like ifconfig, dmidecode etc, assuming at least any one of their version will be present in any linux distribution.

All the wrappers are expected to return Tuples of the type Tuple<string, ExtractedInfoType> where string is the original string resulted from the execution of the command and ExtractedInfoType is the data which we expect from the wrapper in the form of class or struct.

The reason why I chose to return Tuple which contain both original information and the extracted information rather than just returning the extracted information is I want to throw away the original information as lazy as possible, so that if I have any other means to extract more information I can just extract from left string to right ExtractedInfoType in the tuple by just decorating the class with another class which I believe enforces open/close principle, Since I don't want to change the original class when I need to extend the functionality.

On a side note I feel it violates YAGNI principle since I may not extend the class altogether it may be the one and only class which will never be decorated again. In that case I am writing some code say this in quotes"Tuple<string",ExpectedInfoType> is the extra code that I may never need.

I may be taking things too literally, but for me both principles are in some contradiction here.

Handling common data between framework and app

I have designed myself in a bit of a pickle here. My workspace contains the following projects:

  • App. The UI of the app itself, containing the launch target.
  • API. The API project, which builds the API framework used in the App project.
  • Shared. The shared project, which builds a framework with commonly used code in both the API and the App.
  • Pods. The cocoapods project.

When the app needs data from the api, it will call the API.framework's corresponding data provider, which in its turn will use the APIManager class to make the GET/POST/DELETE ect. call and return the data to the dataprovider, whom in its turn will return the appropriate answer to the requester.

The App project withholds a class called EventManager which job it is to log data to Mixpanel, AppsFlyer, Google ect.

Now, my problem is the following: The external API will start returning an extra data object which I need to send on towards Google Tag Manager from the app side. The problem is that none of the solutions I come up with seem perfect to me.

The solutions I came to think of are (in order of worst to best):

  • Let every request to the data providers check themselves wether there is a GTM object and then log it.
    • Pro: least amount of work in the API framework
    • Con:
      • It is anything but DRY. Every request would have to check for the GTM object, or let another method check the JSON and log it.
      • If any method "forgets" this, GTM data might be lost.
      • Make the code and process harder to read.
  • Let the API framework check wether there is an item called GTM in the returned data and send that as a seperate object to the dataprovider, whom in its turn sends it to the requester, whom in its turn logs this to the EventManager.
    • Pro:
      • Better readability
      • Less likelihood of forgetting to handle the GTM data
    • Cons:
      • There is still a likelyhood of forgetting something
      • Still not fully DRY, every request will have to handle the check of GTM callback.
  • Change the APIManager into a singleton. Add a protocol called APIManagerDelegate with function didRecieveGTMData(gtmData: AnyObject). Let the APIManager check the result of the request for GTM data, if any exist, send it to the delegate. Subscribe to the delegate in (e.g.) AppDelegate and if data is returned from the didRecieveGTMData() call, handle it and send it to the EventManager. An alternative to using protocol/delegates is to use a closure variable instead, and subscribe to that one on AppDelegate.
    • Pro:
      • This is by far the best solution I came to think of. It is DRY and doesn't require anything more from the data providers.
      • No possibility for it to be "forgotten" to log.
    • Con:

The reason for not having the API send the data directly to Google would be because the API itself should not have a dependency towards an external service. Would I later like to implement the API in another app (TVOS, Apple watch, macOS), I would not have to worry about setting up a google account for it.

I would like to know wether there is another alternative that I haven't thought off or practice when working with frameworks and common data.

lundi 27 juin 2016

Is Java Apache Commons an example of bad design? [on hold]

The Apache Commons library have a tons of utils classes with different purposes, from string formatter to FTP connection. IMO the library must to have cohesion, not a bunch of unrelated features/modules.

C# Repository Pattern with Multiple/Different Data Sources

In my application, I have to create a repository which will give me the data objects. Now based on the application mode(user input) I have to get the data from file or from db. So it involves two data sources inside the repository.

What would be the best approach for handling multiple data sources in a repository ?

Thanks!!!

Where to create interface implementation?

I'm gonna ask perhaps simple an OO design question.

Imagine we inversed a dependency between two concrete classes ( Foo and Hoo ) using an interface (IHoo) where Hoo implements the interface and Foo uses that implementation.

At that point, I wondered where excatly I should attach that implementation ( Hoo ) to it's client ( Foo ). Obviously, if we add Hoo in the client class Foo, then we have not inversed the compile-time dependency ( with respect to runtime dependency ) and we have only made a bit more modular code, but not less-rigid.

So perhaps, we associate client and the interface implementation in a master ( or higher-level ) class like a controller or so? What's your approach would be ?

Thx.

c# Builder Pattern

I have below class which builds reference data for my app, do you think it's a good implementation of builder pattern. What can I change to improve it?

public class ReferenceDataBuilder
    {
        private readonly List<Task> _builderTasks;
        private IDataProvider _dataAccess;
        private ReferenceData _referenceData;
        private bool _withPersistence;
        private string _persistenceDirectory;

        public ReferenceDataBuilder(IDataProvider dataAccess)
        {
            ValidationUtils.ArgumentNotNull(dataAccess, "dataAccess");

            _dataAccess = dataAccess;

            _referenceData = new ReferenceData();
            _builderTasks = new List<Task>();
            createBuilderTasks();
        }

        public virtual ReferenceData BuildAsync()
        {
            Parallel.ForEach(_builderTasks, (task) => { task.Start(); task.Wait(); });
            return _referenceData;
        }


        private void createBuilderTasks()
        {
            _builderTasks.Add(new Task(() => _referenceData.Object1 = _dataAccess.GetObject1()));
            _builderTasks.Add(new Task(() => _referenceData.Object2 = _dataAccess.GetObject2()));
            _builderTasks.Add(new Task(() => _referenceData.Object3 = _dataAccess.GetObject3());
            _builderTasks.Add(new Task(() => _referenceData.Object4 = _dataAccess.GetObject4());
        }
    }

Usage:

new ReferenceDataBuilder(dataAccess).BuildAsync();

Thanks

C# Implementing concrete factory (derived from an abstracf factory) for Generic Interface type

I have an abstract factory that I use to implement some other concrete factories. This factory is implemented this way:

    public class AbstractFactory<T> {

    public delegate List<T> AbstractProductCreator();

    private Dictionary<string, AbstractProductCreator> _creators = new Dictionary<string, AbstractProductCreator>();

    private static AbstractFactory<T> _instance = null;
    public static AbstractFactory<T> Instance {
        get {

            if( _instance == null ) {

                _instance = new AbstractFactory<T>();
            }

            return _instance;
        }
    }

    private AbstractFactory() { }

    public bool registerProduct( string setName, AbstractProductCreator creator ) {

        if( !_creators.ContainsKey( setName ) ) {

            _creators[setName] = creator;
            return true;
        }

        return false;
    }

    public List<T> getProduct( string setName ) {

        if( _creators.ContainsKey( setName ) ) {

            return (_creators[setName])();
        }

        return null;
    }
}

On the other hand, I have a generic interface for managing different entities of a DB:

    public interface IEntitySetMgr<T> {

    /// <summary>
    /// The columns involved in the query. Only fields in those columns
    /// will be retrieved from the db.
    /// </summary>
    List<ColumnInfo> Columns { get; set; }

    /// <summary>
    /// The number of entities found in the last query to db.
    /// </summary>
    int EntityCount { get; }

    bool Init();

    bool Synch( QueryFilter queryFilter = null );

    /// <summary>
    /// Retrieves the entities build from data of db.
    /// </summary>
    ObservableCollection<T> GetEntities();
}

It is possible to have a concrete factory for registering classes that implement that interface? I've tried this without success:

    public class EntitySetMgrFactory : AbstractFactory<IEntitySetMgr<T>> {

}

But it is going no where. I remember have made something similar in C++ with templates. I know that generics are not the same as C++ templates, but I thought there should be a way of doing this. I have also tried to create an abstract implementation of IEntitySetMgr and creating a concrete factory for this instead of the interface. I've also tried to define another abstract factory for this case with two parameters, but cannot reach a solution the compiler does not complains and work.

Any help would be appreciated.

Regards,

David.

How to implement async and await in embedded system?

I would like to know how can I achieve equivalent behavior of async and await in boost for embedded system using microcontroller (STM32) in C?

Is there any good design pattern to achieve this?

Restricting a user to access only his/her entities In Entity framework6 Repository pattern

I am working on an ASP.NET MVC5 project with Repository pattern for the first time. It has lots of roles and there will be number of user in each role. Till now, I have created various model entities and add, update, delete scenarios are working fine. During testing things, I found that a user is able to update those entities that do not belong to him/her.

I want to restrict the user to access, edit, update, delete only those entities (Rows in db) that belong to the user itself, not the other ones.

I know, I need to check somewhere the userId of the current logged in user, but where should I put this where condition in case of Repository pattern with Entity Framework.

Two ways that come to my mind are: Changing the models to have userId property in each entity or joining each entity with it's parent entity to get the related user details (The complete chain of entities to get the userId).

What would be the preferred way to implement this? Thanks!

dimanche 26 juin 2016

ruby pattern for file data collection and individual records

I'm looking for a suitable pattern for an application that uses various data files. The basic process will be, run the script, load the data file(s), do stuff, output a report or new data file (no alteration of input files).

The files are various formats but for arguments sake, say they are CSV - the format is not a factor here.

I am attracted to the ActiveRecord style pattern where you have a class representing a dataset. There are class methods through which you can retrieve data, and each record is an instance, with instance methods for each field.

In my case that would look something like

class People
  attr_accessor :first_name, :last_name, :addresss, :city, :country
  def self.load(file)
    rtn = self.new
    @cache = []
    # load data into @cache instance var, each row of data is an instance of self
    rtn
  end
  def all_people
    @cache
  end
  def people_in_city(city)
    # search @cache for matching records
  end
  def people_with_last_name(name)
    # search @cache for matching records
  end
  # etc, etc
end

This kind of works but it feels clunky. Each instance not only has an individual record data, but also a reference to all the data in the file (i.e. @cache). So this is a big break from ActiveRecord, where the actual data is stored elsewhere (i.e. in the database). In my case I want to load all the data, query it this way and that, and then drop out.

My other approach is to use two classes, one for the individual record and antother for the collection, e.g.

class Person
  attr_accessor :first_name, :last_name, :addresss, :city, :country
end
class PeopleCollection
  def initialize(file)
    @cache = []
    # load file and place each record into @cache as a Person instance
  end
  def all_people
    @cache
  end
  def people_in_city(city)
    # search @cache for matching records
  end
  def people_with_last_name(name)
    # search @cache for matching records
  end
  # etc, etc
end

I realize I could just use CSV::Row for my record class, or Hash, but I want to provide dot notation accessors. I also looked at OpenStruct by it relies on method_missing which bugs me in terms of performance impact (but not a deal breaker) and also a I want an exception raised when I hit record.some_missspelled_attribute_accezzor

Any tips appreciated...

Mystical downcast failure

It is a simple, template-less Factory design pattern implementation as part of a hobby project. The goal is to implement it as clean as possible, with the restriction that templates can't be used, and the library classes need to be able to be inherited virtually.

My problem is, that downcasting in Factory.cc:73 (in the line A* a = dynamic_cast<A*>(r);) doesn't work, but it should.

My factory.h:

#ifndef factory_h
#define factory_h

class IAmPolymorphicNow {
  private:
    virtual void iAmPolymorphicNow();

  protected:
    IAmPolymorphicNow();
};

namespace Factory {
  class Factory : private IAmPolymorphicNow {
  };

  class Mediator;

  class Result : private IAmPolymorphicNow {
    public:
      Result();
      Result(Mediator fm);
  };

  typedef void (*MakeMethod)(Factory* factory, Result* result);

  class Mediator {
    private:
      Factory* factory;
      MakeMethod makeMethod;

    public:
      Mediator(Factory* factory, MakeMethod makeMethod);
      void call(Result* result);
  };
};

#endif

My factory.cc (contains also the minimal test case):

#include <iostream>
#include "factory.h"

using namespace std;

void IAmPolymorphicNow::iAmPolymorphicNow() {
  // nothing now
};

IAmPolymorphicNow::IAmPolymorphicNow() {
  // nothing now
};

Factory::Result::Result() {
  cout << "Factory::Result::Result()\n";
};

Factory::Result::Result(Mediator fm) {
  cout << "Factory::Result::Result(Mediator)\n";
  fm.call(this);
};

Factory::Mediator::Mediator(Factory* factory, MakeMethod makeMethod) {
  cout << "Factory::Mediator::Mediator(Factory*, MakeMethod)\n";
  this->factory = factory;
  this->makeMethod = makeMethod;
};

void Factory::Mediator::call(Result* result) {
  cout << "Factory::Mediator::call(Result*)\n";
  (*makeMethod)(factory, result);
};

class A;

class B : public virtual Factory::Factory {
  private:
    int v;

  public:
    B(int v);
    int getV() const;
    static void makeCb(Factory* f, ::Factory::Result* a);
    ::Factory::Mediator make();
};

class A : public virtual Factory::Result {
  friend class B;

  private:
    int v;

  public:
    A();
    A(Factory::Mediator fm);
    int getV() const;
    void setV(int v);
};

B::B(int v) {
  cout << "B::B()\n";
  this->v = v;
};

int B::getV() const {
  cout << "B::getV()\n";
  return v;
};

void B::makeCb(Factory* f, ::Factory::Result* r) {
  cout << "B::makeCb(Factory*, Factory::Result*)\n";
  B* b = dynamic_cast<B*>(f);
  A* a = dynamic_cast<A*>(r);
  a->setV(b->getV()+1);
};

Factory::Mediator B::make() {
  cout << "Factory::Mediator B::make()\n";
  return ::Factory::Mediator(static_cast<Factory*>(this), &B::makeCb);
};

A::A() {
  cout << "A::A()\n";
  v = 0;
};

A::A(Factory::Mediator fm) : Factory::Result(fm) {
  cout << "A::A(Factory::Mediator)\n";
};

int A::getV() const {
  cout << "A::getV()\n";
  return v;
};

void A::setV(int v) {
  cout << "A::setV(" << v << ")\n";
  this->v = v;
};

int main(int argc, char **argv) {
  B b(42);
  A a = b.make();
  cout << "a.v = " << a.getV() << "\n";
  return 0;
}

How the problem can be reproduced:

$ g++ -o factory factory.cc -g -Wall -std=c++11
$ gdb ./factory
Reading symbols from ./factory...done.
(gdb) run
Starting program: ./factory
B::B()
Factory::Mediator B::make()
Factory::Mediator::Mediator(Factory*, MakeMethod)
Factory::Result::Result(Mediator)
Factory::Mediator::call(Result*)
B::makeCb(Factory*, Factory::Result*)
B::getV()
A::setV(43)

Program received signal SIGSEGV, Segmentation fault.
0x0000000000400da6 in A::setV (this=0x0, v=43) at factory.cc:98
98        this->v = v;
(gdb) bt
#0  0x0000000000400da6 in A::setV (this=0x0, v=43) at factory.cc:98
#1  0x0000000000400b7a in B::makeCb (f=0x7fffffffe610, r=0x7fffffffe600) at factory.cc:74
#2  0x0000000000400a08 in Factory::Mediator::call (this=0x7fffffffe590, result=0x7fffffffe600) at factory.cc:31
#3  0x0000000000400990 in Factory::Result::Result (this=0x7fffffffe600, fm=...) at factory.cc:20
#4  0x0000000000400d0e in A::A (this=0x7fffffffe600, fm=..., __in_chrg=<optimized out>, __vtt_parm=<optimized out>) at factory.cc:87
#5  0x0000000000400ded in main (argc=1, argv=0x7fffffffe718) at factory.cc:103
(gdb) frame 1
#1  0x0000000000400b7a in B::makeCb (f=0x7fffffffe610, r=0x7fffffffe600) at factory.cc:74
74        a->setV(b->getV()+1);
(gdb) print a
$1 = (A *) 0x0
(gdb) print b
$2 = (B *) 0x7fffffffe610
(gdb) list
69
70      void B::makeCb(Factory* f, ::Factory::Result* r) {
71        cout << "B::makeCb(Factory*, Factory::Result*)\n";
72        B* b = dynamic_cast<B*>(f);
73        A* a = dynamic_cast<A*>(r);
74        a->setV(b->getV()+1);
75      };
76
77      Factory::Mediator B::make() {
78        cout << "Factory::Mediator B::make()\n";

Note:

  1. The question is "Why is it unable to downcast?", and not "Which stl/boost/... template should I use?".
  2. This code is a minimal sanitized example. For ask, I will be glad to further shorten it, but afaik it will be already on the border on the obfuscation.

What is the practical use of delegate objects?

I am currently going through the gradle tutorial and we have just been exposed to delegate objects in groovy. Although I understood how to create them, I have a hard time trying to figure out why we might need to use them in a project. Is there any kind of design pattern or standard where the use of delegate objects might come in handy?

How to make event of instance work?

i'm trying to implement decorator pattern using Windows Forms and have some questions here. When I call event of previous decorated instance it partly doesn't work and i can't figure out why. Part that doesn't work includes actions with Windows.Forms.Form i implement, but Console.WriteLine work perfectly. You may test my code below, but you need 11.txt file on your desktop (or change path) to make it work;

using System.Windows.Forms;
using System.IO;
using System;

class Decorator
{
    class UpgradedStream : Form
    {
        public TrackBar trbRead;
        public Button btnRead;
        public TextBox txtBox;

        public UpgradedStream()
        {
            this.Width = 600;
            this.Height = 600;
            this.Text = "Decorating Stream class";

            trbRead = new TrackBar();
            trbRead.Width = 300;
            trbRead.Value = 2;

            btnRead = new Button();
            btnRead.Click += new EventHandler(ReadFile);
            btnRead.Text = "&Slide bar abowe!";
            btnRead.Top = 40;
            btnRead.Width = 150;

            txtBox = new TextBox(); ;
            txtBox.Multiline = true;
            txtBox.Top = 75;
            txtBox.Width = 550;
            txtBox.Height = 450;
            txtBox.ScrollBars = ScrollBars.Vertical;

            this.Controls.Add(btnRead);
            this.Controls.Add(trbRead);
            this.Controls.Add(txtBox);
        }

        public virtual void ReadFile(Object source, EventArgs e)
        {
            Text = "123"; //doesn't work in decorator chain
            Console.WriteLine("works"); //works
        }
    }

    class DecoratedStream : UpgradedStream
    {
        public UpgradedStream previous;
        public FileStream fin = null;
        public int i, count = 0;

        public DecoratedStream(UpgradedStream us)
        {
            previous = us;


            fin = new FileStream("11.txt", FileMode.Open);
        }

        public override void ReadFile(Object source, EventArgs e)
        {
            previous.ReadFile(source, e);
            try
            {
                fin = new FileStream("C:\\Users\\Vitaliy\\Desktop\\11.txt", FileMode.Open);

                do
                {
                    count++;
                    i = fin.ReadByte();
                    if (i != -1) txtBox.Text += (char)i;
                } while (i != -1 && count < fin.Length * (trbRead.Value * 0.1));
            }
            catch (IOException exc)
            {
                txtBox.Text += ("Error Input-Output:\n" + exc.Message);
            }
            finally
            {
                txtBox.Text += "\r\n";
                txtBox.Text += String.Format("WRITED: {0} SYMBOLS\r\n", Convert.ToInt32(fin.Length * (trbRead.Value * 0.1)));
                txtBox.Text += "\r\n";

                if (fin != null) fin.Close();
                count = 0;
            }
        }
    }

    class PasswordForm : Form
    {
        private Label lblPassForm;
        private Button btnPassForm;
        private TextBox tbxPassForm;

        public PasswordForm()
        {
            this.Text = "Enter password";
            lblPassForm = new Label();
            lblPassForm.Text = "password - 123";

            tbxPassForm = new TextBox();
            tbxPassForm.Top = 30;

            btnPassForm = new Button();
            btnPassForm.Text = "&OK";
            btnPassForm.Top = 50;
            btnPassForm.Click += new EventHandler(ClosePassForm);
            btnPassForm.DialogResult = DialogResult.OK;

            this.Controls.Add(lblPassForm);
            this.Controls.Add(tbxPassForm);
            this.Controls.Add(btnPassForm);
        }
        public void ClosePassForm(Object source, EventArgs e)
        {
            password = tbxPassForm.Text;
            this.Close();
        }

        public String password { get; set; }
    }

    class AskPassword : UpgradedStream
    {
        public PasswordForm PassForm;

        private string password;

        protected internal UpgradedStream previous;

        public AskPassword(UpgradedStream us)
        {
            previous = us;
        }

        public override void ReadFile(Object source, EventArgs e)
        {
            previous.ReadFile(source, e);

            using (PassForm = new PasswordForm())
            {
                if (PassForm.ShowDialog() == DialogResult.OK)
                {
                    if (PassForm.password == "123")
                        previous.ReadFile(source, e);
                }
            }
        }
    }


    static void Main()
    {
        Application.EnableVisualStyles();

        UpgradedStream up = new UpgradedStream();
        DecoratedStream dk = new DecoratedStream(up);
        AskPassword ask = new AskPassword(dk);

        Application.Run(ask);
    }
}

for exapmple

public virtual void ReadFile(Object source, EventArgs e)
{
    Text = "123"; //doesn't work in decorator chain
    Console.WriteLine("works"); //works
}

How to sync dynamic and static views in Angular SPA?

I'm building simple Angular Single page app. I'll try to describe it in minimal and abstract way:

App has three main sections:

  • header - page header, which describes state to user, e.g. "Type your username".
  • view - which is dynamic and has different functional depending on app state. (e.g. There can be a form, or just buttons to choose something)
  • next/prev buttons - Which let user navigate through app.

Problem is, I dont want to repeat header and next/prev buttons in every view, I want to include them once and then dynamically update them.

here is an example markup:

<body ng-controller="MainCtrl">
    <header>
        <h1 ng-bind="mainHeader">
    </header>

    <div ng-view></div>

    <footer>
        <button type="button">Prev</button>
        <button type="button">Next</button>
    </footer>
</body>

This is sample view:

<div ng-controller="UsernameCtrl">
    <input type="text" ng-model="username">
</div>

Flow is the following: When user clicks the next button, data from the dynamic view, should be sent to the service and in case of specific type of response, next view should be loaded.

The question is, What is the correct Design for this flow?

Repository Pattern Class Generator

I have some Entity class and now needed to create Repositories for this classes, Witch Tools Help me to Create Repository Class for my entity classes?

samedi 25 juin 2016

Java Reg Exp for Word not followed by another word

Basically, I am writing a program in java where I have to categorize a String in any of three buckets.

  • Category 1 - String with both 'AND' and 'AND NOT'
  • Category 2 - String with 'AND NOT'
  • Category 3 - String with 'AND'

I need some regex to match string having AND followed by NOT if not skip.

A AND B AND NOT C - Fail
A AND B AND C - Fail
A AND NOT B AND NOT C - Pass

Below is sample code snippet

public static void main(String[] args) {
    String X = "A AND B AND C AND D AND NOT E";
    String Y = "A AND NOT C ";
    String Z = "A AND B AND D";
    ArrayList<String> sampleString=new ArrayList<String>(Arrays.asList(X,Y,Z));

    //Category 1 - String with both 'AND' and 'AND NOT'
    //Category 2 - String with 'AND NOT' only
    //Category 3 - String with 'AND' only

    for(String s:sampleString){
        if(s.contains("AND") && s.contains("NOT")){
            System.out.println("Category 1 -"+s);
        }
        // This condition is invalid - I need some regex to match this condition. I need to consider only AND followed by NOT if not skip

        if(s.contains("AND NOT") && !s.contains("AND")){
            System.out.println("Category 2 - "+s);
        }
        if(s.contains("AND") && !s.contains("NOT")){
            System.out.println("Category 3 - "+s);
        }
    }

OUTPUT -

Category 1 -A AND B AND C AND D AND NOT E
Category 1 -A AND NOT C 
Category 3 - A AND B AND D

I tried some regex questions but doesn't resolve mine. I tried with below

String regex="AND(?!\\s+NOT)";

public static void main(String args[]){
        String x= "A AND B AND C AND NOT D"; 
        String regex="AND(?!\\s+NOT)";
        if(Pattern.compile(regex).matcher(x).find()){
            System.out.println("X MATCHED");
        }
    } 
//Returns - X MATCHED

Any help would be much appreciated!

How to stop infinite pattern-matching in Haskell?

I am doing Exercise 3 from Homework 2 in http://ift.tt/1YrZUO2

build :: [LogMessage] -> MessageTree
build [x] = Node Leaf x Leaf
build [x,y] = Node (build [x]) y Leaf
build [x,y,z] = Node (Node (build [x]) y Leaf) z Leaf

I have a problem where I do not know how to end the pattern matching. It would just keep expanding to [x,y,z,_] and then [x,y,z,_,_] and so on. How do I stop this?

Creating view-model for UITableViewCell

I'm stuck on a design decision with creating view-model for table view's cells. Data for each cell is provided by a data source class (has an array of Contacts). In MVVM only view-model can talk to model, but it doesn't make sense to put data source in view-model because it would make possible to access data for all cells, also it's wrong to put data source in view controller as it must not have reference to the data. There are some other key moments:

  • Each cell must have it's own instance of view-model not a shared one
  • cellForRowAtindexPath must not be placed in a view-model because it shouldn't contain any UI references
  • View/ViewController's view-model should not interact with cell's view-model

What's the right way to "insert" data source for cells in MVVM's relationship ? Thanks.

Attaching an object method to an event while retaining the element reference

function MyObject() {
  this.name = "";
  this.elements = document.getElementsByClassName('myClass');
}

MyObject.prototype.attachEventHandlers = function() {
  for (var i = 0; i < this.elements.length; i++) {
    this.elements[i].addEventListener('click', this.myEventHandler);
  }
};

MyObject.prototype.myEventHandler = function() {
  // Here "this" referst to the element that the event invoked on:
  console.log(this.innerHTML);

  // Is there a way to get the name property like:
  // console.log(this.name);
  // without passing the instance as an argument?
};

var myObject = new MyObject();
myObject.name = "Foo";
myObject.attachEventHandlers();

I would like to use the myEventHandler method as an even handler, but as you know in event handlers this refers to the element that that the event was invoked on.

I would like to both keep a reference to the element that the event was invoked on, and also keep a reference to the object instance.

There are two ways I can think of:

  1. Passing the object instance as an argument to the event handler, like:

    // ...
        var that = this;
        this.elements[i].addEventListener('click', function() {
          that.myEventHandler(that);
        }
    // ...
    
    MyObject.prototype.myEventHandler = function(that) { // ...
    
    
  2. The same as above, but instead of using the prototype method, using an inline function.

I'd rather not use an inline function, as it clutters the code. And I'd rather not pass the object instance as an argument, if I don't have to.

Is there a more idiomatic and simpler way to achieve this?

Python api design using factory and builder pattern

I am new to python and I have to design a Python API(version - 2.7) similar to an existing Java API

Python version - 2.7

The Java API is as follows

There is a Process interface

public interface Process<T> {

  Future<T> create(Client<T> client)

}

There are two implementations of Process . For simplicity I have shown the implementation of one 1) FirstProcess
2) SecondProcess

public class FirstProcess implements Process {

   Future<T> create(Client<T> client) {

   }
}

There is a ProcessFactory

public interface ProcessFactory {

  Process createProcess()
}

There are two implementations of ProcessFactory
1) FirstProcessFactory
2) SecondProcessFactory

For simplicity I have just shown the implementation of one

public class FirstProcessFactory implements ProcessFactory {

  Process createProcess() {

     return new FirstProcess()
  }
}

There is a builder for the Process

ProcessBuilder

public class ProcessBuilder {

   // Has a lot of methods for config setup and validation

   public Process build() {

      //Based on the config uses the ProcessFactory to return 
      // either FirstProcess or SecondProcess
   }
}

I have a few questions

1) I have already read about how I could use the named parameters instead of the Builder pattern.

2) If I use the named parameters how I can implement the Factory Pattern, how can I decide about instantiating FirstProcess or SecondProcess based on the config. The existing java logic is present in the build() method of ProcessBuilder and uses the ProcessFactory

3) Would it be a good python design if I have the same Java API design with both builder and the factory patterns ?

Pattern for Multi User ASP.NET with SQL/LINQ

I have a SQL+ASP.NET situation for which I suspect there might exists a design pattern.

I have a site where users can register and then enter their own data. The users can only see their own data and never anything else.

My question is: Is there a way to somehow simplify this process. All SQL commands clearly need to be filtered based on the user ID, and ASP Web Forms doesn't really allow this in a simple way. Is there a way to maybe produce LINQ objects or something similar that can automatically extend every SQL command sent to the SQL Server with a User ID parameter?

Using closures or the underscore convention for private members

Douglas Crackford and many others suggest using closures for private members as follows:

function Container(param) {

    function dec() {
        if (secret > 0) {
            secret -= 1;
            return true;
        } else {
            return false;
        }
    }

    this.member = param;
    var secret = 3;
    var that = this;
}

The upside of this is that these members are not accessible outside the constructor function, but the downside is that it's not possible to use the private members in the prototype. So you end up putting everything that uses the private members in the constructor, which is not good for memory purposes.

Some others recommend using underscores when naming the private members:

function Container(param) {
    this.member = param;
    this._secret = 3;
}

Container.prototype.dec = function {
    if (this.secret > 0) {
        this.secret -= 1;
        return true;
    } else {
        return false;
    }
}

The downside of this is that those members are easily accessible publicly, and the only thing stopping people is the convention.

My questions are:

  1. When do you decide to use one over the other?
  2. Is one way preferred more commonly than the other?
  3. What are some famous libraries that use one of these methods?
  4. Is there a better method than these two?

Unit testing Application design, Design Pattern, Best Practices

In general mostly I write unit test for testing the functionality of the application/methods. In my recent reading, I've come across concept of Unit testing the "Loose Coupling" of the application components. I noticed a Unit test written to check the reference of unexpected assemblies (e.g Presentation layer directly referring DataAccess Classes instead of Business Logic classes), This unit test will immediately fail if it encounters the unexpected references that breaks "loosely coupled" design.

I like this concept of writing unit testing to test the best practice/design of the application. Just want to see if there are any pointers/resources which will help us write Unit test to test the application design/architecture.

Please share if you know anything more about this area.

This is the sample code.

[Fact]
public void SutShouldNotReferenceSqlDataAccess()
{
// Fixture setup
Type sutRepresentative = typeof(HomeController);
var unwanted = "Ploeh.Samples.Commerce.Data.Sql";
// Exercise system
var references =
sutRepresentative.Assembly
.GetReferencedAssemblies();
// Verify outcome
Assert.False(
references.Any(a => a.Name == unwanted),
string.Format(
"{0} should not be referenced by SUT",
unwanted));
// Teardown
}

What kind of javascript design pattern was used in facebook website?

I've trying to study with Javascript design patterns to improve my practice but I simply confused with all kind of those patterns special I found a style which was used in facebook script (study) it simple and may be easy to use if I've much understand about those design patterns so I would like to ask all expert here about the kind of patterns that facebook used with the Javascript library (react js)as below code

__d('StaticUFI.react',
    ['getElementPosition', 'getElementRect', 'getUnboundedScrollPosition',
    'shallowEqual', 'throttle'],
    function a(b, c, d, e, f, g, h, i) {
    'use strict';
    var j = c('UFIConstants').UFIFeedbackSourceType,
        k = c('UFIConstants').UFIStatus,
        l = c('React').PropTypes,
        m = c('React').createElement('div', {className: "UFICommentsLoadingSpinnerContainer _48pi UFIRow"},
            c('React').createElement(c('XUISpinner.react'), {size: 'large'})),
        n = c('React').createElement('div', {
            className: "_xtv",
            role: 'presentation'
        }, c('React').createElement('i', null)), o = c('React').createClass({
            displayName: 'StaticUFI',
            contextTypes: {dispatch: l.func},
            getInitialState: function () {
                var p = this.props.focusReply;
                return {focusReply: p, viewerHasClickedCommentComposer: false, viewerHasClickedSeeMore: false};
            },
            getDefaultProps: function () {
                return {
                    commentIDToFocusOnMount: null,
                    focusReply: null,
                    canReplyMap: {},
                    isActiveLoading: {},
                    repliesExpandedMap: {},
                    hasPagedToplevel: false,
                    viewerHasInteractedWithComments: false,
                    loadingSpamIDs: {}
                };
            },
            componentDidMount: function () {
                c('Arbiter').inform('UFI/displayDone-' + this.props.contextArgs.instanceid);
                if (this.props.feedback.isqanda && this.props.feedback.infinitescroll) {
                    var p = c('throttle')(this.loadMoreComments, 20);
                    this._scrollEventListener = c('Event').listen(window, 'scroll', p);
                    this._resizeEventListener = c('Event').listen(window, 'resize', p);
                }
                if (c('BlueBar').hasFixedBlueBar())this.setState({oldBoundingClientRect: c('getElementRect')(c('ReactDOM').findDOMNode(this))});
                this._resolveFocus();
            },
            loadMoreComments: function () {
                if (this.isMounted() && this.refs.topLevelBottomPager && !(this.props.contextArgs.ftentidentifier in this.props.isActiveLoading)) {
                    var p = c('ReactDOM').findDOMNode(this.refs.topLevelBottomPager),
                        q = c('getUnboundedScrollPosition')(window).y,
                        r = q + document.documentElement.clientHeight + c('UFIConstants').infiniteScrollRangeForQANDAPermalinks;
                    if (p.offsetHeight && p.offsetTop < r)this.refs.topLevelBottomPager.props.onPagerClick();
                }
            }
        });
    f.exports = o;
}, null);

Why Service Locator is referred as AntiPattern?

I read from many Articles that Service Locator is Antipattern, but I couldnt clearly understand why it is called out as AntiPattern. I appreciate any examples pointers over this.

Design patterns in Programming Languages and design patterns in Cloud computing

I have a confusion what are the exactly design patterns in cloud computing are? what exactly is the difference between these two design patters and programming language design patterns. I know design patterns in Programming languages are used for the problems Which are reoccurring again and again. but what is the purpose of design patterns in cloud computing. Some companies are providing services for hardware, web application development. can anyone explain

what actually is the purpose of design patterns coding techniques in cloud computing..

vendredi 24 juin 2016

Mark modified object and unmark it from outside

This is kind of a follow up of this question of my own.

I have a Tournament class which has a List<Event>, the categories of the event. You can instantiate a tournament and then make changes on its events:

Event event = new Event(...);
Tournament tournament = new Tournament(..., new ArrayList<>(Arrays.asList(event)));
event.setProperty(property);

However, the Tournament class is part of a resolution process that calculates all the possible schedules it has, one by one. The model the solver class uses to compute the schedule is based on the state of the tournament (and its events) in the moment the resolution process begins (calling tournament.solve()).

We can retrieve subsequent schedules (the next solution) by invoking tournament.nextSchedules(). And here's the problem. As I said the solver holds the configuration of the tournament from the instant that solve() was called. If now we start changing properties of any event (which is allowed), the current model of the tournament, the instance, will be no longer consistent with the model the solver holds. This has to be managed, otherwise I will be getting wrong schedules, or even errors.

Now to the point: as I was suggested in the previous question, I tried implementing a solution to track any modifications made in the events. For that I made the Event class extend Observable and setChanged() is being called from every method that modifies properties (or those relevant to the model in the solver anyway). Here's a sample:

public Event extends Observable implements Validable {
    public void setProperty(Property property) {
        //...
        setChanged();
    }
}

Having done that, now I need a way to reset the changes flag on the observable event when they're considered in a final form. And when does this happen? Well, whenever tournament.solve() is called. When trying to solve the problem and retrieve the schedules, the tournament (therefore, its events) are in a consistent state. The problem is that to clear the changed flag on a event, I need to use the clearChanged() method and it is not public, which kind of makes sense because it should be up to the observable object to determine if it's changed or not anymore. In my scenario though, it's actually up to a different class, the Tournament class, to say if an event has changed or not.

I could very well define a public method in the Event class wrapping the clearChanged() method, but this would break the whole point of the Observable interface as I understand it.

What changes should I make in order to allow a Tournament to notify its events that they have no longer changed?