mercredi 25 mai 2016

How to handle with data not IEntity?

How do you implement class for data received via the api , but at the same time non-IEntity? there is for example a method.

public async Task<IList<NewsSentimentIndexes>> getNewsSentimentIndexes(NewsRequest request)
    {
        var res = await _client.getList<NewsSentimentIndexes>(request);
        return res.Value;
    }

There are news entity and news service, but on it I get some data that do not have ID, so it is not Entity.respectively can no longer implement the IEntity interface for it, and use for NewsApiRepository. How to deal with such data?

Spot problems with circular dependency

I am designing a system where two modules, one which gestions files and another users. For certain logic operations, they need the services offered by each other.

Each module is represented by a singleton which implements a interface offering some services to each other, with abstract factories to provide them, like so:

public class UserMain implements UserInternalService {

/*
 * Internal interfaces
 */
/**
 * Allows interaction with the projects database.
 */
FilesInternaService fileSystem;

/**
 * Constructor is private, as this is a singleton.
 */
protected UserMain() {
}

private static UserMain singleton = null;

/**
 * Singleton factory. Returns a reference to the singleton. If there is no
 * reference yet, creates it.
 */
protected static synchronized UserMain getReference() {
    if (singleton == null) {
        singleton = new UserMain();
        singleton.fileSystem = FileMain.getInternalService();
    }
    return singleton;
}

/**
 * Factory method for the singleton as a UserInternalService
 */
public static UserExternalService getUserExternalService() {
    return getReference();
}

}

And the file module main class is like so:

public class FileMain implements FilesInternaService{

/**
 * Interface to user subsystem for request validation, etc.
 */
UserInternalService userSystem;

/**
 * Creation of instances aside from singleton disallowed.
 */
protected FileMain(){};

private static FileMain singleton = null;

/**
 * Singleton factory.
 * Returns a reference to the singleton.
 * If there is no reference yet, creates it.
 */
protected synchronized static FileMain getReference(){
    if(singleton == null)
        singleton = new FileMain();
        singleton.userSystem = UserMain.getUserInternalService();
    return singleton;
}

/**
 * Abstract factory for Internal Services singleton.
 * @return
 */
public static FilesInternaService getInternalService(){
    return getReference();
}
}

I am not enterely sure that I am correctly handling the circular dependency. Is there any way this may break unexpectedly?

Java: replacing a substring with other string [duplicate]

This question already has an answer here:

Problem:-

"hello.java".replaceAll(".","$");

when I compile this, it gives regex illegal argument. I can escape special characters, but I want to take both arguments as input from user. So I want another solution.

In other words, I am asking for a method so that javac will treat both arguments of replaceAll method as normal string, not as regex patterns. Such that

Output should be : hello$java

Javascript Augmented Modules: Why assign IIFE to module when passing module in as argument?

I'm new to the augmented module pattern and I've seen this example a lot:

var MODULE = (function (my) {

    my.method = function () {
        // added method...
    };

    return my;
}(MODULE));

I was wondering why I need to assign this IIFE to MODULE in the first place, when I'm passing in MODULE as an argument to the IIFE.

For example, this gives the same result:

(function (my) {

    my.method = function () {
        // added method...
    };

    return my;
}(MODULE));

(provided MODULE has already been declared).

So my question is: is either fine? If so, why do all the examples I see use the first one? It seems to me like MODULE is assigned 'method' twice. Is it just the case that MODULE is declared like this in the first example, in case it doesn't already exist?

Thanks!

iOS Singleton class inside MVC architecture

Most of the iOS apps are based on MVC Design pattern, and we are using Singleton classes inside our apps from many years. I know that Singleton itself is a design pattern and many consider it as anti-pattern and all that good bad stuff about singletons.

But if you consider MVC as a overall architecture to your app development I would like to understand where does a singleton be categorised in it. Is it a Model, or View or Controller? if so why? if it does not belong to any of these three then what it is?

This might seem a silly question but it keeps bothering me as I was asked this question in an interview in a reputed company.

Pattern for custom operator >> istream

It is often required for some non-scalar structure X to provide input operator std::istream & operator >> (std::istream &, X &);. I tried to implement it in a 3 slightly different ways:

#include <istream>
#include <ostream>
#include <tuple>

#include <cstddef>

struct rectangle
{

    std::size_t l, t, r, b; // left, top, right, bottom

    friend
    std::istream &
    operator >> (std::istream & in, rectangle & R)
    {
#if 0
        // v1
        do {
            if (!(in >> R.l)) {
                break;
            }
            if (!(0 < R.l)) {
                break;
            }
            if (!(in >> R.t)) {
                break;
            }
            if (!(0 < R.t)) {
                break;
            }
            if (!(in >> R.r)) {
                break;
            }
            if (!(0 < R.r)) {
                break;
            }
            if (!(in >> R.b)) {
                break;
            }
            if (!(0 < R.b)) {
                break;
            }
            return in;
        } while (false);
        in.setstate(std::ios::failbit);
        return in;
#elif 0
        // v2
        if (in >> R.l) {
            if (0 < R.l) {
                if (in >> R.t) {
                    if (0 < R.t) {
                        if (in >> R.r) {
                            if (0 < R.r) {
                                if (in >> R.b) {
                                    if (0 < R.b) {
                                        return in;
                                    }
                                }
                            }
                        }
                    }
                }
            }
        }
        in.setstate(std::ios::failbit);
        return in;
#elif 0
        // v3
        if (!(in >> R.l)) {
            return in;
        }
        if (!(0 < R.l)) {
            in.setstate(std::ios::failbit);
            return in;
        }
        if (!(in >> R.t)) {
            return in;
        }
        if (!(0 < R.t)) {
            in.setstate(std::ios::failbit);
            return in;
        }
        if (!(in >> R.r)) {
            return in;
        }
        if (!(0 < R.r)) {
            in.setstate(std::ios::failbit);
            return in;
        }
        if (!(in >> R.b)) {
            return in;
        }
        if (!(0 < R.b)) {
            in.setstate(std::ios::failbit);
            return in;
        }
        return in;
#else
#error do select body!
#endif
    }

    friend
    std::ostream &
    operator << (std::ostream & out, rectangle const & R)
    {
        return out << R.l << ' ' << R.t << ' ' << R.r << ' ' << R.b;
    }

    bool
    operator == (rectangle const & R) const
    {
        return std::tie(l, t, r, b) == std::tie(R.l, R.t, R.r, R.b);
    }

};

// main.cpp
#include <iostream>
#include <sstream>

#include <cstdlib>
#ifdef NDEBUG
#undef NDEBUG
#endif
#include <cassert>

int
main()
{
    std::stringstream ss;
    rectangle lhs{1, 2, 3, 4};
    ss << lhs;
    rectangle rhs;
    ss >> rhs;
    assert(lhs == rhs);
    return EXIT_SUCCESS;
}

Live example.

Every way has its own advantages and disadvantages:

  • v1:
    • pros:
      • plain code
      • minimal duplication of code (1 setstate())
      • just two return statements
    • cons:
      • (semantically) goto-like do {} while (false); construction (is it really a bad practice?)
  • v2:
    • pros:
      • minimal duplication of code (1 setstate())
      • just two return statements
    • cons:
      • too deep nesting of if statements
  • v3 (naive):
    • pros:
      • plain code
    • cons:
      • duplication of code (setstate() euqal to number of constituents)
      • plenty of return statements

I like v1 way, but are there better patterns to implement operator >>?

How to implement a method for multiple strategies having completely different logic?

I find it hard to give this question a concret title, as I'm not really aware of how to name my type of problem. Any suggestions welcome.

I have a service to run logic that literally performs the same action (eg save a thumbnail), but contains completely different logic for different providers:

@Service
public class ThumbnailService {
    public void saveForProvider1(Prov1 url) {

    }

    public void saveForProvider2(Prov2 url) {
        //completely different logic than Provider1; also a different parameter Object "Prov2"
    }
}

Problem 1: for any new provider I have to create an additional method in that ThumbnailService.

Now at a specific point, I want to run those methods async:

@Service
public class ThumbnailServiceAsync {
    @Autowired
    private ThumbnailService delegator;

    @Async
    public class asyncSaveForProvider1(Prov1 url) { 
        delegator.saveForProvider1(url);
    }

    @Async
    public class asyncSaveForProvider2(Prov2 url) { 
        delegator.saveForProvider2(url);
    }
}

Switching by anInteger variable where I know which number stands for which provider:

int provider;
switch (provider) {
    case 1: thumbServiceAsync.asyncSaveForProvider1(url); break;
    case 2: thumbServiceAsync.asyncSaveForProvider2(url); break;
    default: throw NotSupportedException();
}

Problem 2: as you see I'm writing lots of code just for the sake of delegation to the specific provider routine. And I also have to touch at least those 3 classes mentioned when introduction any additional provider.

Question: how could I optimize this process? Especially regarding that by time more providers may be implemented. And also not only a thumbnail routine, but furhter methods that have to be implemented for every provider, but are different from their logic. Like "create a user for providerX", or "run some cleanup routine for providerX".