问:
should I test this public method
I have the following simple implementation:

```<code>var VALIDATION_TYPES = {
    ERROR: 1,
    WARNING: 2
};
var validationRules = {};

this.addErrorRule = function (event, rule) {
    addValidationRule(event, VALIDATION_TYPES.ERROR, rule);
};

var addValidationRule = function (event, type, rule) {
    if (!validationRules[event]) {
        validationRules[event] = {};
        validationRules[event][VALIDATION_TYPES.ERROR] = [];
        validationRules[event][VALIDATION_TYPES.WARNING] = [];
    }

    validationRules[event][type].push(rule);
};
</code>```

I'm wondering whether addErrorRule should be unit-tested and if so how? Should I expose validationRules object to unit-tests?

EDIT:

I could modify my addValidationRule to return the number of rules added and check for that number in my test:

```<code>var addValidationRule = function (event, type, rule) {
    var countAddedRules = 0;

    if (!validationRules[event]) {
        validationRules[event] = {};
        validationRules[event][VALIDATION_TYPES.ERROR] = [];
        validationRules[event][VALIDATION_TYPES.WARNING] = [];
    }

    var originalCount = validationRules[event][type].length;
    validationRules[event][type].push(rule);
    countAddedRules = originalAddedRulesCount - validationRules[event][type].length;
    return countAddedRules;
};
</code>```

答:
You definitely should be unit-testing addErrorRule. You can do this by testing for the side-effects of the addValidationRule call. Make sure there is a validation rule added to the right list (errors, not warnings).

Yes, you must expose the validationRules variable to be able to unit-test addErrorRules.

Here's example code for how the unit test might look like:

```<code>assertEquals(validationRules.length, 0);

addErrorRule('an error event', 'this is the rule');
assertEquals(validationRules['an error event'][VALIDATION_TYPES.WARNING].length, 0);
assertEquals(validationRules['an error event'][VALIDATION_TYPES.ERROR].length, 1);
assertEquals(validationRules['an error event'][VALIDATION_TYPES.ERROR][0], 'this is the rule');
</code>```

You don't have to go further than that because then you're just testing the general side-effects of the addValidationRule function (which you say you're already doing).

Don't use Mocks or Mock Objects for This!

It's possible to use mocks for this but then you have to question what you're really testing here: does addErrorRule produce the correct side-effects, or is it enough that it calls the addValidationRule method and we can safely assume the side-effects will be correct?

If it's the latter, if you're testing with a mock method, you cannot check for the correct result in validationRules because it will be filled with whatever return value you supply in the mock which defeats the purpose of testing addErrorRule entirely.

The only time you would use a mock for this case would be if you were using a library or API which are difficult to test or time-consuming to test (for example, you would want to mock out database or filesystem calls or remote REST API calls and assume they give the correct side-effects).

Title: should I test this public method

Body:
You definitely should be unit-testing addErrorRule. You can do this by testing for the side-effects of the addValidationRule call. Make sure there is a validation rule added to the right list (errors, not warnings).

Yes, you must expose the validationRules variable to be able to unit-test addErrorRules.

Here's example code for how the unit test might look like:

assertEquals(validationRules.length, 0);

addErrorRule('an error event', 'this is the rule');
assertEquals(validationRules['an error event'][VALIDATION_TYPES.WARNING].length, 0);
assertEquals(validationRules['an error event'][VALIDATION_TYPES.ERROR].length, 1);
assertEquals(validationRules['an error event'][VALIDATION_TYPES.ERROR][0], 'this is the rule');

You don't have to go further than that because then you're just testing the general side-effects of the addValidationRule function (which you say you're already doing).

Don't use Mocks or Mock Objects for This!

It's possible to use mocks for this but then you have to question what you're really testing here: does addErrorRule produce the correct side-effects, or is it enough that it calls the addValidationRule method and we can safely assume the side-effects will be correct?

If it's the latter, if you're testing with a mock method, you cannot check for the correct result in validationRules because it will be filled with whatever return value you supply in the mock which defeats the purpose of testing addErrorRule entirely.

The only time you would use a mock for this case would be if you were using a library or API which are difficult to test or time-consuming to test (for example, you would want to mock out database or filesystem calls or remote REST API calls and assume they give the correct side-effects).


问:
Greedy algorithms - minimising "parentheses rotatons" in order to get a valid expression
I'm preparing for an exam on which there will be problems solvable by DP, greedy algorithms. And one of the problem is - given a string containing parentheses in no particular order return a minimum number of "rotations" needed to make a valid expression, for example ())) is not a valid expression but you can "rotate" second paren to get (()) which is a valid expression (the answer would then be 1).

I've been told this can be solved with some greedy algorithm. It's quity easy to find O(n^3) DP solution so we're looking for something else (possibly O(n)?). What is the strategy when trying to find a greedy solution for such problem?

答:
Greedy means take the action that immediately tries to improve the problem.

You replace each \() pair that encloses only periods . with periods. Then eventually you will end up with the a sequence of closing parens followed by a sequence of open parens (interspersed by periods).

Then you just need to rotate the first half of the closing parens and the second half of the open parens.

The last step will be to fix the )( case so it becomes the proper ().

This is O(n²) with a naive matching algorithm. Though it can be sped up by thinking of the replace step as expanding the period runs.

ContentLicense: CC BY-SA 3.0


问:
Large volume report operations, how best to replicate transactional data
We are overhauling a legacy accounting app that has some large reports. One concern that has been raised is due to the transactional nature of the data, if we start a long running report how do we ensure the data is not modified before we get around to processing it?

Locking everything on the transaction db is out, what has been suggested is maintaining a replication db that can be locked, this seems sledgehammery to me.

I'm wondering if anyone has some perspective you can share, for example what is the cost of dynamically creating a replication db at report time and replicating just what we need, then blowing the temp db away?  What is the cost of dynamically creating a db and/or table schema just for a single report?  How to handle the same report being run concurrently? Is there an easier way?

答:
if we start a long running report how do we ensure the data is not modified before we get around to processing it?

That's not a typical requirement.  What are you afraid of that affecting?  The report that is currently running, or the transactional workload?

If you are worried about the reporting getting different versions of data that could pollute the report or make is a misrepresentation of the data, then you would have to ensure a point-in-time view of the database right before the report kicks off.

Note: I am a SQL Server professional so my further guidance speaks on behalf of SQL Server technology pertaining to my particular RDBMS

Database snapshots are a great solution here.  When you create a database snapshot it uses a sparse file to record changed pages from the moment the snapshot is created.  The snapshot itself is a transactionally-consistent static view of the database at the time of the snapshot creation.  It harnesses a copy-on-write operation every time the original database is modified.

If you want to offload this to a separate server, you could leverage transactional replication for a subset of the source database (the publisher), by specifying particular articles to replicate, as opposed to the whole database.  Consider this a narrow and offloaded approach, as well as a data-focused approach (vs the whole database) to reporting.  You can pause the distribution of the data to the subscriber(s) when you are ready to run your report workload, and then resume when complete.

The easier solution here would be the database snapshot.  Create the snapshot before you run your report.  Run your report against the snapshot.  Then when the report is done and you no longer need the static view of your database from that snapshot time, drop the snapshot.


答:
I haven't solved this particular problem, but there's a general approach to take.  The first thing to look at is what information you can calculate in O(n).  In this case:

The count of open and close parens.

The absolute minimum number of rotations, based on uneven count.

The current depth of nesting of each paren, starting from the right and left side of the string.

The maximum allowed nesting depth at any point, based on the remaining opposite parens available, starting from the right and left side of the string.

Which parens are already properly balanced.

Then you solve a bunch of test cases manually, and look at the above calculated information for the parens you flip.  Try comparing, subtracting, adding, etc. the parameters you calculated.  Are there any patterns you can discern?   Can you figure out how to adjust the calculated information in O(1) after you perform a flip?

This part takes a certain amount of practice.  It can help to go through the exercise for known algorithms, trying to "reverse engineer" them.

Title: Greedy algorithms - minimising "parentheses rotatons" in order to get a valid expression

Body:
I'm preparing for an exam on which there will be problems solvable by DP, greedy algorithms. And one of the problem is - given a string containing parentheses in no particular order return a minimum number of "rotations" needed to make a valid expression, for example ())) is not a valid expression but you can "rotate" second paren to get (()) which is a valid expression (the answer would then be 1).

I've been told this can be solved with some greedy algorithm. It's quity easy to find O(n^3) DP solution so we're looking for something else (possibly O(n)?). What is the strategy when trying to find a greedy solution for such problem?


问:
How does the Properties Pattern work?
I'm referring to the pattern (aka Universal Design Pattern) as discussed in this blog post

Universal Design pattern

I guess I'm not entirely clear how to use this in practice.  And how it works to accomplish operations or tasks.

In particular regarding this explanation

It's the core API for any collection that maps names to values:

```<code>get(name)
put(name, value)
has(name)
remove(name)
</code>```

There are typically also ways to iterate over the properties, optionally with a filter of some sort.

Are the keys the name? And what are the values?

And how do you perform operations?  Where are instructions for performing tasks and operations on data stored? and how are they called?  Are the embedded into the 'values' as classes?

答:
Yes, the Keys are the name or identifier of each property.

You may add a changeValue method.

This pattern is also known a the Dynamic Object Design Pattern.

Example (Pseudocode):

```<code>void Example()
{
  KeyValueList MyControl = new KeyValueList();
    MyControl->put("id", "MyControl");
    MyControl->put("x", 34);
    MyControl->put("y", 125);
    MyControl->put("height", 200);
    MyControl->put("width", 250);
    MyControl->put("filled", false);

  MyWindow->insertControl(MyControl);
} // void Example()
</code>```

As you may check in the previous example, is common to use a list that store key value items, where there the keys are of string types, and cannot be duplicated. The values may be stored as an type specific for each value, like integer or logical.

Or can be used as string, similar to H.T.M.L. or X.M.L. attributes, like this example:

Example (Pseudocode):

```<code>void Example()
{
  KeyValueList MyControl = new KeyValueList();
    MyControl->put("id", "MyControl");
    MyControl->put("x", "34");
    MyControl->put("y", "125");
    MyControl->put("height", "200");
    MyControl->put("width", "250");
    MyControl->put("filled", "false");

  MyWindow->insertControl(MyControl);
} // void Example()
</code>```

Both, cases are optional.

The example is generic, identifiers and types, can change from library or programming language.

This Design Pattern is commonly used in programming languages that are not Object Oriented, (like "functional" or "procedural"), to emulate objects.

Is also used in Programming Languages that are already Object Oriented, but, the properties are statically designed, and cannot be added or removed at execution.

Cheers.

Title: How does the Properties Pattern work?

Body:
Yes, the Keys are the name or identifier of each property.

You may add a changeValue method.

This pattern is also known a the Dynamic Object Design Pattern.

Example (Pseudocode):

void Example()
{
  KeyValueList MyControl = new KeyValueList();
    MyControl->put("id", "MyControl");
    MyControl->put("x", 34);
    MyControl->put("y", 125);
    MyControl->put("height", 200);
    MyControl->put("width", 250);
    MyControl->put("filled", false);

  MyWindow->insertControl(MyControl);
} // void Example()

As you may check in the previous example, is common to use a list that store key value items, where there the keys are of string types, and cannot be duplicated. The values may be stored as an type specific for each value, like integer or logical.

Or can be used as string, similar to H.T.M.L. or X.M.L. attributes, like this example:

Example (Pseudocode):

void Example()
{
  KeyValueList MyControl = new KeyValueList();
    MyControl->put("id", "MyControl");
    MyControl->put("x", "34");
    MyControl->put("y", "125");
    MyControl->put("height", "200");
    MyControl->put("width", "250");
    MyControl->put("filled", "false");

  MyWindow->insertControl(MyControl);
} // void Example()

Both, cases are optional.

The example is generic, identifiers and types, can change from library or programming language.

This Design Pattern is commonly used in programming languages that are not Object Oriented, (like "functional" or "procedural"), to emulate objects.

Is also used in Programming Languages that are already Object Oriented, but, the properties are statically designed, and cannot be added or removed at execution.

Cheers.


答:
I think that both of the testing method proposed so far are bad.

omouse suggest exposing validationRules an internal implementation detail. In doing so, he is suggesting that you test the implementation when you should be testing the interface. See this blog for discussion.

The op then proposed returning the number of added rules. But as far as I can tell it will always return 1. Even if the method did return varying values, you'd only be testing the values it returned, not the actual functionality you are interested in.

So how do you test this method? Firstly, don't think of it in terms of how to test that method. Instead, think about what behavior you want to test. Don't think about the internal state, or how it does it. Think about how the method will be used in the rest of your program.

Presumably, you want to be able to do something like this:

```<code>validator.addErrorRule('foobar', function(payload) {
   if (payload.cost > 50) {
        return "No. Price Too High";
   }
});
validation_results = validator.validate(payload)
</code>```

All we need in order to turn that into a test is to say:

```<code>assert.deepEqual(validation_results, [
    {validator: 'foobar', error: 'No. Price Too High'}
])
</code>```

This actually tests the functionality we care about and avoids introducing implementation details.

Many coders have gotten the idea that they need to test each method independently. That's why people think they need to test addErrorRule separately from validate. Don't fall into this trap. Methods within the same object are usually tightly interconnected and attempting to test them independently is a fool's errand. Furthermore, you miss out on testing the interaction between the methods which is usually the entire point of the functionality you wanted.

Title: should I test this public method

Body:
I have the following simple implementation:

```<code>var VALIDATION_TYPES = {
    ERROR: 1,
    WARNING: 2
};
var validationRules = {};

this.addErrorRule = function (event, rule) {
    addValidationRule(event, VALIDATION_TYPES.ERROR, rule);
};

var addValidationRule = function (event, type, rule) {
    if (!validationRules[event]) {
        validationRules[event] = {};
        validationRules[event][VALIDATION_TYPES.ERROR] = [];
        validationRules[event][VALIDATION_TYPES.WARNING] = [];
    }

    validationRules[event][type].push(rule);
};
</code>```

I'm wondering whether addErrorRule should be unit-tested and if so how? Should I expose validationRules object to unit-tests?

EDIT:

I could modify my addValidationRule to return the number of rules added and check for that number in my test:

```<code>var addValidationRule = function (event, type, rule) {
    var countAddedRules = 0;

    if (!validationRules[event]) {
        validationRules[event] = {};
        validationRules[event][VALIDATION_TYPES.ERROR] = [];
        validationRules[event][VALIDATION_TYPES.WARNING] = [];
    }

    var originalCount = validationRules[event][type].length;
    validationRules[event][type].push(rule);
    countAddedRules = originalAddedRulesCount - validationRules[event][type].length;
    return countAddedRules;
};
</code>```

Body:
I think that both of the testing method proposed so far are bad.

omouse suggest exposing validationRules an internal implementation detail. In doing so, he is suggesting that you test the implementation when you should be testing the interface. See this blog for discussion.

The op then proposed returning the number of added rules. But as far as I can tell it will always return 1. Even if the method did return varying values, you'd only be testing the values it returned, not the actual functionality you are interested in.

So how do you test this method? Firstly, don't think of it in terms of how to test that method. Instead, think about what behavior you want to test. Don't think about the internal state, or how it does it. Think about how the method will be used in the rest of your program.

Presumably, you want to be able to do something like this:

validator.addErrorRule('foobar', function(payload) {
   if (payload.cost > 50) {
        return "No. Price Too High";
   }
});
validation_results = validator.validate(payload)

All we need in order to turn that into a test is to say:

assert.deepEqual(validation_results, [
    {validator: 'foobar', error: 'No. Price Too High'}
])

This actually tests the functionality we care about and avoids introducing implementation details.

Many coders have gotten the idea that they need to test each method independently. That's why people think they need to test addErrorRule separately from validate. Don't fall into this trap. Methods within the same object are usually tightly interconnected and attempting to test them independently is a fool's errand. Furthermore, you miss out on testing the interaction between the methods which is usually the entire point of the functionality you wanted.


问:
How to choose DB and/or DBMS for own application?
I'm creating application in C++ and found out that storing information in XML file was very prodigally. Despite the possibility to read it without any specific application, random access via DOM or VTD library and possibility to backup by simple copying XML file, it's very RAM-expensive (even while using VTD it's necessary 17GB of RAM). Now, there are 12000 entries and I'm planning to store up to million ones. Each entry contains 37 fields (now, maybe more in future) with different types: string, double, float and 128-bit float. These fields are distributed into 5 groups (hierarchy which is possible by XML tags). I tried to find something more productive with the same benefits. Unfortunately, googling didn't help me because there are so many DBs and DBMSs that I'm totally confused.

The XML file structure:

```<code><paient>
   <analysis name="">
      <result type="">some_data</result>
  </analysis>
  <diagnosis>
     <preliminary></preliminary>
     <final></final>
   <diagnosis>
...
<patient>
</code>```

So could advise me a solution for my problem?

答:
First of all. Do not bother much about it. When you separate your concerns well, retrieve data, from processing and displaying it, you will always have the chance to switch to a "better" system.

Sizes of about 10,000 entries is nothing a database will complain about, even million sets aren't a big deal. Your database will have to grow as your application/system grows. Think about the most common usecases and which data is presented together and which data is used together. This should lead you, whether to use a column-database, a document database, a graph database or simply a relational database.

Do not think too long about performance issues or theoretical problems which might occur, define what's important and select a system, which you can get most support for it. Remember to decouple your data(model) from your application(logic) and presentation(view), then you can always make a better informed guess next time. When making your application open source a decoupled design will propably encourage others to provide a database implementation when required which might be better suited the (or your) needs.

There is much knowledge around - Think first of good enough. Be pragmatic.

Please check the link i shared in the comment section. This is a nice overview about pro and cons about the type of database you might need.


问:
Using SQL queries in loops
Is it a bad idea? I need to compare each entry.Key value in a Dictionary of strings to a SQL table. If there is a match, then I pull the data from that row.
I was originally going to use a foreach loop to query each entry.Key value.
I was told by someone that doing this is a bad idea.
Is it bad because I'm doing too many queries?
Each Dictionary could have thousands of values (which probably means thousands of queries)...
Can anybody suggest a better way? (compare the dictionary to a datatable of results?)</p>

答:
You can use an IN clause for this.

```<code>SELECT someFields FROM yourDictionaryTable WHERE key IN (List of values)
</code>```

You'll need to build your list of values as a string with single quotes and commas, like this:

```<code>'value1', 'value2', 'value3'
</code>```

This will give you a single, high-performing SQL query which will return the data set you want.

Title: Using SQL queries in loops

Body:
You can use an IN clause for this.

SELECT someFields FROM yourDictionaryTable WHERE key IN (List of values)

You'll need to build your list of values as a string with single quotes and commas, like this:

'value1', 'value2', 'value3'

This will give you a single, high-performing SQL query which will return the data set you want.


答:
It's not always bad to put queries in loops, but when you can express the "loop logic" in SQL itself, doing it that way is usually more efficient and more readable.

In this case, you can easily use a single query with the IN operator (as Robert said), and that expresses what you're actually trying to do much better than a for loop of smaller queries. Both you and the SQL query optimizer benefit from that.

Title: Using SQL queries in loops

Body:
Is it a bad idea? I need to compare each entry.Key value in a Dictionary of strings to a SQL table. If there is a match, then I pull the data from that row.
I was originally going to use a foreach loop to query each entry.Key value.
I was told by someone that doing this is a bad idea.
Is it bad because I'm doing too many queries?
Each Dictionary could have thousands of values (which probably means thousands of queries)...
Can anybody suggest a better way? (compare the dictionary to a datatable of results?)</p>


问:
Why do companies tell me they want me as an in-house employee, not as a contractor?

Context

I am looking for work as a contractor in my field of expertise and would prefer to earn less money and have less benefits working as a short-term contractor.

The problem:

Companies say I need to be an in-house employee for intellectual property reasons.

The question:

Wouldn't it be easy for them to just have me sign a contract saying all my work is owned by them?

If I work as a contractor, they can let me go when my value diminishes and save lots of money.

What am I missing here?

答:
I've been a contractor all my life (In the UK). I've literally never had a 'real job'.

Companies have always asked me to go permanent for them, and they've always tried to come up with reasons to do with intellectual property and long term loyalty.

And I've always said "OK, as long as you pay me the same". Which tends to end the conversation.

Just once in my whole life, that has also been the end of the contract, although even then the option was still open to become a permanent employee (at about half the amount they were paying me as a contractor). I think the company in question really needed to cut its budget.

Now I am old, a lot of my friends have gone into management. I've asked them why companies always try to get their contract staff to go permie. To a man they say "It's because it's much cheaper".

If the real reason was anything else, then they would be prepared to pay you more as a permanent employee than as a contractor. Because you'd be worth more to them.

It's just part of the negotiating game. Stick to your guns. If they can find someone of your quality willing to go permanent then they may replace you with him, and fair enough. But good people are thin on the ground, and the longer you've worked for them the harder it will be to replace you.

Unless they're about to go bust, if they find someone good, they'll employ him as well as you, because in any company that's not about to go bust, there's always more work than there are people to do it.

Since they've broken the ice and started talking about money, why not ask them for an extra £5/hour? Remember it's only a game. No one will take offence if you play too.

Also talk to some friendly purchasing people, or if you've got friends who are managers at other firms talk to them. They can explain how to play. In the worst case buy a book about negotiating. "Getting to Yes" is good, and a bit of a classic. Negotiating is great fun, and not at all the scary thing most people think it is.

And business is all about negotiation. If you negotiate well and in a friendly and decent manner, you'll get nothing but respect for it. If you play the game badly or spitefully, you'll just get classified with all the other clueless losers.

Honestly, if you play chess with someone and they keep losing their queen by making terrible moves, do you think 'Hey, he's loyal. I want him on my side?'


答:
I suspect that this is very frequently NOT about either "the money" or "intellectual property", I suspect that it it frequently more about your committment to that company and your loyalty.

As a full-time employee, generally you (not necessarily YOU but generally...) are much more likely to become connected and attached to that company.  Your are more likely to dedicate yourself to the mission of the company not just "code for this week".

You are more likely to be more invested emotionally and/or financially when you are an employee and the future of the company is about the future of your employment and working conditions and not just about "this months work".

Title: Why do companies tell me they want me as an in-house employee, not as a contractor?

Body:
Context

I am looking for work as a contractor in my field of expertise and would prefer to earn less money and have less benefits working as a short-term contractor.

The problem:

Companies say I need to be an in-house employee for intellectual property reasons.

The question:

Wouldn't it be easy for them to just have me sign a contract saying all my work is owned by them?

If I work as a contractor, they can let me go when my value diminishes and save lots of money.

What am I missing here?


问:
Should I use one class that calls Several static methods or several classes each calling one static method
I need to use instances which represent mathematical functions along with their parameters end enable their evaluation. I can take 2 approaches:

1: have a single class representing all the math functions:

```<code>class TrigonometricFunction extends Function {

    private double param;

    private String name;

    public TrigonometricFunction(double param, String name) {
        this.param = param;
        this.name = name;
    }

    public double evaluate() {

        double radParam = toRadians(param);

        if ("sin".equals(name)) {
            return Math.sin(radParam);
        }

        if ("cos".equals(name)) {
            return Math.sin(radParam);
        }

        // about 10 more functions would go here...

    }
}
</code>```

Advantages of this approach:

have to create and test just a single class

no code duplicity (conversion of param to radians)

Disadvantages:

inefficient evaluation (have to do a lot of String comparisons in evaluate() depending on the function name), but would this even be an issue?

looks ugly and just doesn't feel right

2: have a separate class for each math function:

```<code>class SinFunction extends Function {

    private double param;

    public SinFunction(double param) {
        this.param = param;
    }

    public double evaluate() {

        double radParam = toRadians(param);

        return Math.sin(radParam);
    }
}

class CosFunction extends Function {

    private double param;

    public CosFunction(double param) {
        this.param = param;
    }

    public double evaluate() {

        double radParam = toRadians(param);

        return Math.cos(radParam);
    }
}
</code>```

Advantages:

small classes, single responsibility, just seems better

more effective evaluation as in the first solution (no String comparisons) (?)

Disadvantages:

have to implement and test a lot of small classes which look basically the same

duplicate code (calling conversion to radians in each class)

more expensive to create instances (have to do the String comparison here).

Which approach is better and why? Or do you have a better solution?

答:
I'm assuming that the input that your code receives is the string representation of the function anyway, so there's no avoiding a string checking. There is, however, ways to avoid some of the other problems you've noted.

I would go with your option #2, with the following caveats:

Shared code should be shared

Rather then extending Function, create an intermediate base class called TrigonometricFunction that encompasses the shared code - specifically, the conversion to radians:

```<code>public abstract class TrigonometricFunction extends Function {

    protected double radians;
    protected TrigonometricFunction(double paramDegrees) {
        radians = toRadians(paramDegrees);
    }

    abstract double evaluate();
}
</code>```

And extend that for specific functions.

```<code>public class SinFunction extends TrigonometricFunction {
    @Override
    public double evaluate () {
        return Math.sin(radians);
    }
}
</code>```

This way you keep type safety while also reusing code.

Use a dispatcher/factory pattern to avoid if/else string checks

Instead of doing if (name == "sin") { return new SinFunction(params); }, you can use a Factory object to create the relevant Function object, and choose the relevant Factory using a Hashmap keyed to the function name:

```<code>public interface TrigonometricFunctionFactory {
    TrigonometricFunction buildFunction(double paramDegrees);
}

public SinFunctionFactory implements TrigonometricFunctionFactory {

    @Override
    public TrigonometricFunction buildFunction(double paramDegrees) {
        return new SinFunction(paramDegrees);
    }
}
</code>```

and so on for other Functions.
Now, create this dispatch table:

```<code>HashMap<string, TrigonometricFunctionFactory> dispatchTable = new HashMap<>();
dispatchTable.add("sin", new SinFunctionFactory());
dispatchTable.add("cos", new CosFunctionFactory());
</code>```

and now you can do this:

```<code>String functionName = "sin";
result = dispatchTable[functionName].createFactory(param).evaluate();
</code>```

Body:
I'm assuming that the input that your code receives is the string representation of the function anyway, so there's no avoiding a string checking. There is, however, ways to avoid some of the other problems you've noted.

I would go with your option #2, with the following caveats:

Shared code should be shared

Rather then extending Function, create an intermediate base class called TrigonometricFunction that encompasses the shared code - specifically, the conversion to radians:

public abstract class TrigonometricFunction extends Function {

    protected double radians;
    protected TrigonometricFunction(double paramDegrees) {
        radians = toRadians(paramDegrees);
    }

    abstract double evaluate();
}

And extend that for specific functions.

public class SinFunction extends TrigonometricFunction {
    @Override
    public double evaluate () {
        return Math.sin(radians);
    }
}

This way you keep type safety while also reusing code.

Use a dispatcher/factory pattern to avoid if/else string checks

Instead of doing if (name == "sin") { return new SinFunction(params); }, you can use a Factory object to create the relevant Function object, and choose the relevant Factory using a Hashmap keyed to the function name:

public interface TrigonometricFunctionFactory {
    TrigonometricFunction buildFunction(double paramDegrees);
}

public SinFunctionFactory implements TrigonometricFunctionFactory {

    @Override
    public TrigonometricFunction buildFunction(double paramDegrees) {
        return new SinFunction(paramDegrees);
    }
}

and so on for other Functions.
Now, create this dispatch table:

HashMap<string, TrigonometricFunctionFactory> dispatchTable = new HashMap<>();
dispatchTable.add("sin", new SinFunctionFactory());
dispatchTable.add("cos", new CosFunctionFactory());

and now you can do this:

String functionName = "sin";
result = dispatchTable[functionName].createFactory(param).evaluate();


问:
How to reconcile "misc fix" commits with pull requests?
I work in a small company, where I used to be the only developer. We recently welcomed a few other people on the team, and started thinking about how to organize development efforts.

I am pretty much a novice in terms of code management, as this is my first job out of college. As part of a test, I tried working using pull requests last week (we use GitLab). It made discussing code changes related to a single feature much easier, and I'd love to continue using them.

However, we found that there were tons of little improvements that by themselves didn't look worth a pull request. Typos, small comments, very small bug fixes, sometimes completely unrelated things we just noticed as we were implementing the large features.

How are those cases generally handled?

Should we add "fix" commits directly on our dev branch?

Should we create and merge a PR with just one small fix?

Should we group a bunch of those commits into one big "misc fixes" PR?

(Added) Should we allow small commits at the beginning of each PR?

Any other option?

答:
I like grouping code cleanup into a single commit and then going from
there.  Make sure you apply the code cleanup PR before dealing with
the other ones -- you'll reduce your headaches.</p>


问:
Insertion sorting Algorithm comparison
I recently came across sorting techniques and of particular, 'insertion sorting'.

Although the logic and method is fairly understandable, the actual function seemed a bit complex (given  below).

```<code>void InSort(int AR[], int size)
{
    int tmp,j;
    AR[0]=INT_MIN;  //defined in limits.h , basically the smallest possible value

     for(int i=1;i<size;i++)
     {
       tmp=AR[i];
       j=i-1;

        while(tmp<AR[j])
         {
           AR[j+1]=AR[j];
           j--;
          }

       AR[j+1]=tmp;
     }

}
</code>```

Please note that the elements for the above function are entered from AR[1].

I then tried my own attempt to perform the sort in a more simple way as illustrated below.
(ascending)

```<code>void iSort(int Arr[] , int size)
{
  Int temp;
  for(int i=1 ; i<size ; i++)
  {

    for(int j=0 ; j<i ; j++)
    {
       if(Arr[i]<Arr[j])
       {
        temp=Arr[i];
        Arr[i]=Arr[j];
        Arr[j]=temp;
        }
    }
  }
}
</code>```

To my dismay, someone told me that although this method will perform the sort, it does not qualify as an 'Insert Sort', but I still believe that it does follow the same principle.

Is this so?
Then, what is particularly wrong with my attempt?
More Importantly, does the second function qualify as an insertion sort?

--

I would like to mention that I'm relatively very new to programming in general, so do forgive my seemingly primitive attempt, all I want to do is learn! Also, this isn't the recent C++ version, its actually stone age old, so apologies in advance!

I'd be happy for any inputs received , thanks in advance!

答:
The second algorithm is called Bubble Sort, not Insertion Sort.

The idea is that in Insertion Sort, you take an element in the array, look for where it should be in the whole array, then "insert" it at that spot, shifting all the elements once. You only do this insertion once per element.

With Bubble Sort, you always look at two adjacent elements, and swap them if needed. The name comes from the idea that the highest elements will slowly "bubble up" to the top of the array, since they're only moving up one step at a time.

Then, what is particularly wrong with my attempt?

Nothing. You just happened to write a different algorithm by accident. Both of these algorithms have O(n^2) worst-case and average-case time complexity (since they do more or less the same comparisons and assignments in different orders), so it's not like you made it any worse.

I agree that Bubble Sort is usually a simpler algorithm to read and write in code, so if performance is a non-issue (and your language doesn't have a sort() function for some reason) then feel free to use that. However, Insertion Sort often performs better on arrays where most of the elements are already in the right place.

Of course, heapsort and mergesort are O(n log n) worst-case, and quicksort is O(n log n) average-case, so if you ever do care about sort performance you should probably look at one of those.

Title: Insertion sorting Algorithm comparison


答:
First of all, where you see hierarchy, a database expert sees relations. Take some time understanding the relational database model and make a simple model that fits your data. This classical model is tried and tested, based on mathematical foundations and is the basis for virtually every large system out there. Do not be misled by people claiming a graph database or NoSQL database will solve your immediate problems. Most often they are oblivious of proper database design and medium to long-term maintenance. Graph databases and NoSQL databases shine in very specific niches of software engineering, but the choice to use them should generally be made after conventional solutions prove insufficient.

Performance should clearly be taken into account as one million records might already pose a problem when dealing with certain request-response scenario's. E.g., you might want to deliver a response within 200 milliseconds, which would likely entail the use of indices.

To choose a DBMS, you should start with PostgreSQL. It has a very good track record, comes with a performant query optimizer, is reasonably SQL standard and is used in many (larger) production settings. I've personally designed and implemented PostgreSQL settings containing tens of billions of records, hundreds of tables and probably around thousands of indices, driving SaaS applications with very respectable performance characteristics.

Title: How to choose DB and/or DBMS for own application?

Body:
I'm creating application in C++ and found out that storing information in XML file was very prodigally. Despite the possibility to read it without any specific application, random access via DOM or VTD library and possibility to backup by simple copying XML file, it's very RAM-expensive (even while using VTD it's necessary 17GB of RAM). Now, there are 12000 entries and I'm planning to store up to million ones. Each entry contains 37 fields (now, maybe more in future) with different types: string, double, float and 128-bit float. These fields are distributed into 5 groups (hierarchy which is possible by XML tags). I tried to find something more productive with the same benefits. Unfortunately, googling didn't help me because there are so many DBs and DBMSs that I'm totally confused.

The XML file structure:

```<code><paient>
   <analysis name="">
      <result type="">some_data</result>
  </analysis>
  <diagnosis>
     <preliminary></preliminary>
     <final></final>
   <diagnosis>
...
<patient>
</code>```

So could advise me a solution for my problem?


问:
Do iOS frameworks require the same internal versioning as OSX frameworks?
I have been reading through the apple documentation for creating frameworks for OSX and iOS.

Reading about the structure of frameworks, I began to wonder if there is really any need to create the symlinked folder structure described if you are targeting iOS only.

The structure supports multiple internal major versions of a framework. This is intended to allow programs to share a single copy of a framework, whether they are using the current version or an older version. Frameworks are all installed into a single location in OSX

It seems this structure was created to allow maximum code reuse.

However, on iOS each application will be installed into its own sand box with its own copy of any frameworks.

Considering this, I'm not convinced the same symlinked directory structure is necessary for an iOS only framework.

What are the advantages of keeping the suggested OSX framework directory structure?

答: It's not necessary. iOS libraries are statically linked, so you don't have to worry about versioning issues.</p>


答:
Yes it is, because if you have thousands of records then it will execute thousands of queries which will be heavy on the database.

There are 2 approaches I can think of to avoid this,

Use in statement as mentioned by Robert Harvey
One consideration is there is a limit in parameters that can be passed into IN clause in      depending on the database. So If you have more than that amount, you might want to split your set of keys to few statments.

Use a temporary table to insert keys and join it with your table to obtain a result set

Title: Using SQL queries in loops


问:
What is the correct way to bind few classes with similar functionality?
I want to do this in the right way to learn

I have a few classes which have only one method. For example:

```<code>public class RedColorText
{
   public void AddRedColorText(string text)
   {
      //something here
   }
}

public class WhiteColorText
{
   public void AddWhiteColorText(string text)
   {
      //something here
   }
}
</code>```

Normally I could just create instance of each one of them based on the method I want to use but what if I got requirement to use only one class and call methods based on condition? Can I do this like below using constructor and switch? Or should I use something else like interfaces etc?

```<code>public class ColorText
{
    public ColorText(enum condition, string text)
    {
        switch(condition)
        {
            case 1:
                new RedColorText().AddRedColorText(text);
                break;
            case 2:
                new WhiteColorText().AddWhiteColorText(text);
                break;
        }
    }

}
</code>```

答:
You could always use an interface or an abstract class to define the contract where you have generalized behavior for the ColorText class, but you need to keep the method name the same (AddColorText)

```<code>public interface IColorText
{
    public abstract void AddColorText(string text);
}

public class RedColorText : IColorText
{
   public void AddColorText(string text)
   {
      //something here
   }
}

public class WhiteColorText : IColorText
{
   public void AddColorText(string text)
   {
      //something here
   }
}
</code>```

And then define a factory to create instances based on your type

```<code>public class ColorTextFactory
{
    public static IColorText Create(enum condition)
    {
        switch(condition)
        {
            case 1:
                return new RedColorText();
            case 2:
                return new WhiteColorText();
            default :
                return null;
        }
    }
}
</code>```

If you want to create red ColorText class and add some text, following code can be used

```<code>var colorText = ColorTextFactory(1);
colorText.AddColorText("Red Color Text");
</code>```

Body:
You could always use an interface or an abstract class to define the contract where you have generalized behavior for the ColorText class, but you need to keep the method name the same (AddColorText)

public interface IColorText
{
    public abstract void AddColorText(string text);
}

public class RedColorText : IColorText
{
   public void AddColorText(string text)
   {
      //something here
   }
}

public class WhiteColorText : IColorText
{
   public void AddColorText(string text)
   {
      //something here
   }
}

And then define a factory to create instances based on your type

public class ColorTextFactory
{
    public static IColorText Create(enum condition)
    {
        switch(condition)
        {
            case 1:
                return new RedColorText();
            case 2:
                return new WhiteColorText();
            default :
                return null;
        }
    }
}

If you want to create red ColorText class and add some text, following code can be used

var colorText = ColorTextFactory(1);
colorText.AddColorText("Red Color Text");


问:
How to add rigor to my testing?
I work on a small/medium sized Java application. Over time, I've tried to ensure that the tests which I write are "good" tests, and that there's plenty of them. Hence I've been looking into various, more rigorous, testing methodologies, such as boundary value analysis, combinatorial tests, and other testing methods.

However, most of these have examples that are very dry, and the examples don't map very well to my domain, as the examples are mostly functions of numerical data. My functions are almost never concerned with numerical data, they're about enforcing business rules.

The application is hibernate/spring, and my testing strategy is as follows:

Every single class gets a unit test. Collaborators of each class are entirely mocked away at this point, and as far as is reasonable, the contract of that class is exercised. Usually with hand-picked test cases. These tests often run in seconds.

A full spring context is fired up by TestNG. All of a class' collaborators are therefore present, and even the database access layer is active (with a real, on-disk database that is trashed at the end of the test). Once again, the system is exercised using hand-selected test-cases. The start up time for these tests often stretches into 20 - 30 seconds apiece, and there's enough of them to seriously impact the build time.

The system is booted up, usually against a blank database, and then a copy of an end-user database. A developer "clicks around" each booted system in an attempt to elicit a failure. This takes a while, easily over 30 minutes.

I worry that my testing regimen is insufficient, and that my tests are not as effective as their metrics would imply (it's quite easy to get close to 100% coverage with this scheme). There is no formal guidance on how to select test cases, aside from "what the developer thinks are good tests."

I've considered trying to express the behaviour of the system in something roughly like Z notation, and using that specification to drive test case production, but that is likely to be very costly in terms of time. Similarly, convincing my colleagues that there will be a reasonable return on investment of such an activity would be a very hard sell, and even I'm not convinced it's worth it for our system.

There have been discussions relating to randomised tests, but they've been vague and very general; and we rarely bump into run time errors/exceptions (NullPointerException, ArraysOutOfBounds, etc.), it's usually that the behaviour of the system is unacceptable to the client (i.e. in corner/degenerate cases, the system behaves in a counter intuitive manner, but which is completely consistent)

I would like to get the most "bang for my buck" with my tests; that is, how does one design test cases which are likely to exercise a defect in the systems similar to the one above?

答:
I have always found if you put tests into the running code, even in production (ones that do not degrade performance), gives you more results for your testing money, than the heavily isolated unit tests that are currently in fashion. The tests I speak of are based on the design of each method and class. In each important, externally accessed method:

Test preconditions.

Test postconditions.

Test class invariants.

If you don't know what the preconditions, postconditions, or invariants should be, then the problem is in the design phase. In this case, I recommend to read more about these concepts, and why they are important.

While this breaks the ideal that some strive for (isolated tests), any testing of a higher level component will test lower level components as well, so you get more testing accomplished overall. Specifying preconditions, etc, is also good for designs in general. It is never good to throw code to customers without understanding its limitations.

Title: How to add rigor to my testing?


答:
If your application is local (doesn't support remote access) you could use an embedded DB engine.

It gives you the easy installation and independence from other installed programs. So you need to choose the appropriate library. What to look for when choosing?

As I said, the library should be embedded. It lets you create the single executable file without any difficult configurations.

The library should support C/C++ to integrate with your existing code.

The library should be well-known and widely-used. It ensures the most terrible errors have been discovered and fixed already.

It's optional, but it would be cool if you could write SQL queries.

It's optional, but... open-source!

Well, what's the choice?

I propose to pay attention to SQLite and Berkeley DB. Both are embedded, both are open-source, both supports C/C++ (also Java, Python, etc.)

SQLite is a relational DB engine, since Berkeley DB is not. My opinion, SQLite is quite easier to learn, but I could be wrong.

Try both. Use the one that will work earlier.


问:
Multiple users using the same script for their websites
I'm working on a project, I have a question regarding the architecture:

Say I have a many python scripts on my server and there's main.py
which contains all the classes. And there's a script called
copymain.py

A user named alex signs up and the url of his site is stored in
mariadb

copymain.py checks if a user has signed up every 5 min using cron

when copymain.py detects that alex has signed up, it creates a copy of main.py rename it to alex.py, moves alex.py to scriptFolder, and writes the url of alex's site to alex.py

Cron or Celery (haven't decided yet) will run all the .py files inside scriptFolder every lets say 15 mins

Why I picked this design?

This design will let me get rid of many stack and queues and
threading in my script and make it simpler, it is a simple solution, and it works perfectly. If I need to edit main.py, all I have to do is edit the modules imported, so I don't need to edit individual copies.

I think that by copying the files, I could easily deploy it on many
servers. Move some .py files to this server, others to that and I'm
done. These are the two main reasons.

Say you have to generate RSS for websites, for some reason there's a user called fred that has a problem, there's an issue that needs a special script, because we all know that every website has its own design and many errors occur when scrapping and dealing with html, you can go to fred.py and edit your script for that user.

Is it the most efficient architecture? Or should I use one file, get the users from database? My script currently does that, but I prefer to copy for the reasons stated above, a simple scheduling would do. I need to make sure that no matter how many users I have, the website of every user will be processed at exactly the time I promised when they signed up, when there's too many of them and I notice it's being slow, I just buy upgrade or buy another server. I'm afraid of creating too many threads and having to worry about it as it scales. Copying seems the simplest solution, Linux uses cron all the  time for entire directories.

Edit

Please forget about the scrapping part, say you have to do some task for each user in your database, like sending him a message, or whatever, is my solution as good as queuing and threading, in terms of time spent on the process and in terms of being lightweight on the server? Is there a better solution that I have not considered?

答:
It's not uncommon to do what you described. In fact, when you create a new database for your user, you basically creating a new file for that user. So, it just adding a file to the set of per user files.

The choice of when to do the work begs explanation though. Doing the sign up process in batch periodically can create load spikes on the servers. It's better and simpler to copy all the files for new users straight away. If the process is long enough (e.g. creating a vm for user), you show them an "setup in progress" page.


问:
Should I accept pull requests that are behind master?
Sometimes my project has multiple pull requests.
I don't know what is the proper process to handle it.

Currently what I do is

Review each pull request.

check code looks ok, and all comments were treated

check if travis-ci passed and if github can auto-merge the request

if all of the above is correct, I accept the pull request.

However, there is a problem.
Once I accepted the first pull request, all other pull requests are actually outdated.

This process encourages mistakes because:

Travis should check the pull request again, but doesn't

The developers should update their branch and reverify things work.

But, this process is not perfect too.

The process creates a bottleneck on merging pull requests.

There is no way for me to know when branch was merged - github does not indicate that "this pull request is 1 commit behind". So it requires me to do a manual comparison.

It is hard to enforce or to define as best practice.

My question is - what is the proper way to handle accumulated pull requests on my project?

Should every pull request be updated if master changes?

How to make the CI tool (in my case travis) to run again if the destination branch changed as well..

答:
Accepting pull requests that are slightly behind master seems perfectly fine to me, unless there's a strong reason to believe that conflicts are likely.

Ideally most of your pull requests should be on different parts of the codebase, and those parts should be decoupled enough that any one of them is very unlikely to break most of the others. In this case, forcing all but one of the requesters to update their pull requests is little more than red tape.

Also, in many cases it should be possible for you to verify things work when you accept these requests, because 1) you have automated tests (right?) and 2) pull requests should come with a minimal code example that is either fixed or enabled by that pull request, or at least a detailed enough description to produce such an example.

But what if you have several pull requests that clearly will conflict with each other? If they're all trying to do the same thing, pick the best one and ask the other requesters to test it to make sure it fixes the problem for everyone. If they're all trying to do different things to the same piece of code, and there's no sane way to detangle them (this should be very rare!), then I would bite the bullet and try doing some git surgery to combine them into a single pull request that you can ask everyone to test before accepting.


问:
S3 image urls in database
I have an application where users will be able to upload multiple images for one Product (via something like Ryan Bates nested fields, so you'd click "Add Image", and a file upload would appear on the same page). I'm planning on using jQuery File Upload, and Amazon S3, and nested fields.

The thing I'm confused about, is how people usually associate many images with a single model.

For example, if for every Product, there can be many Images, how do I store the images to be associated with the Product?

I was thinking of having jQuery File Upload return the s3 url for each image. So if 10 images were uploaded, then 10 hidden fields were created for each image-url, which I then JSON serialize and store in the Product model?

But this doesn't seem like a pretty solution? What's a better method?

答:
Your main question is,

The thing I'm confused about, is how people usually associate many images with a single model.

So I'll focus on that:

In practice, Rails devs do this by using one of the gems for uploading and attaching images. E.g., Paperclip is maintained by Thoughtbot, is very well tested and supports S3.

But if you're more interested in experimenting and writing your own, you should take a look at Paperclip's source code to see what the current state-of-the-art is.

Title: S3 image urls in database


问:
Design pattern for canceling a long task in a sub-thread
Suppose we have a file copy program. It has two threads, a UI thread displaying the progress of the copy operation and a work thread copying the file.
The UI has a button for canceling the process. Which pattern are you suggest here for transfering cancel event to copy thread?
I want an object-oriented solution.</p>

答:
The Command pattern comes to my mind. You have a Command interface/trait/abstract class and create for example a StopCopyingCommand and send it to the copy thread.

The copy thread btw. could be implemented using the State pattern so that it accepts different kinds of commands for different states.


答:
If you're using Java, use Thread.interrupt - this is exactly the scenario that system was designed for.

Otherwise, you'll need to look at what synchronisation primitives your language provides. If it has an Event synchronisation class, use that (periodically poll the event in the worker thread and terminate if it is fired, signal the event if the user clicks the button). Events are sometimes called Condition, so check for that name too.

If not, you'll have to implement one yourself, using whatever memory barrier primitive your language provides. All you need is a class with a boolean variable initialised to false and two methods: set, which sets the variable to true and executes a write barrier, and get, which executes a read barrier and returns the variable. In most languages, if you don't have explicit memory barrier operations, then you can use whatever mutual exclusion operation is provided instead.

Title: Design pattern for canceling a long task in a sub-thread

Body:
Suppose we have a file copy program. It has two threads, a UI thread displaying the progress of the copy operation and a work thread copying the file.
The UI has a button for canceling the process. Which pattern are you suggest here for transfering cancel event to copy thread?
I want an object-oriented solution.</p>


答: Generally, this is not a good set up, because it's not DRY ("Don't Repeat Yourself"). If it were me, I'd work very hard to figure out how to have one well tested script which can generate the feeds needed by the individual users. Perhaps the script would get per-user information from the database.</p>

Title: Multiple users using the same script for their websites

Body:
I'm working on a project, I have a question regarding the architecture:

Say I have a many python scripts on my server and there's main.py
which contains all the classes. And there's a script called
copymain.py

A user named alex signs up and the url of his site is stored in
mariadb

copymain.py checks if a user has signed up every 5 min using cron

when copymain.py detects that alex has signed up, it creates a copy of main.py rename it to alex.py, moves alex.py to scriptFolder, and writes the url of alex's site to alex.py

Cron or Celery (haven't decided yet) will run all the .py files inside scriptFolder every lets say 15 mins

Why I picked this design?

This design will let me get rid of many stack and queues and
threading in my script and make it simpler, it is a simple solution, and it works perfectly. If I need to edit main.py, all I have to do is edit the modules imported, so I don't need to edit individual copies.

I think that by copying the files, I could easily deploy it on many
servers. Move some .py files to this server, others to that and I'm
done. These are the two main reasons.

Say you have to generate RSS for websites, for some reason there's a user called fred that has a problem, there's an issue that needs a special script, because we all know that every website has its own design and many errors occur when scrapping and dealing with html, you can go to fred.py and edit your script for that user.

Is it the most efficient architecture? Or should I use one file, get the users from database? My script currently does that, but I prefer to copy for the reasons stated above, a simple scheduling would do. I need to make sure that no matter how many users I have, the website of every user will be processed at exactly the time I promised when they signed up, when there's too many of them and I notice it's being slow, I just buy upgrade or buy another server. I'm afraid of creating too many threads and having to worry about it as it scales. Copying seems the simplest solution, Linux uses cron all the  time for entire directories.

Edit

Please forget about the scrapping part, say you have to do some task for each user in your database, like sending him a message, or whatever, is my solution as good as queuing and threading, in terms of time spent on the process and in terms of being lightweight on the server? Is there a better solution that I have not considered?


问:
Is address 0000000C a special address?
When programming sometimes things break. You made a mistake and your program tries to read from a wrong address.

One thing that stands out to me that often those exceptions are like :

```<code>Access violation at address 012D37BC in module 'myprog.exe'. Read of address 0000000C.
</code>```

Now I see a lot of error logs and what stands out to me is the : 0000000C. Is this a "special" address? I see other access violations with bad reads but the addresses just seem random, but this one keeps coming back in totally different situations.

答:
00000000 is a special address (the null pointer). 0000000C is just what you get when you add an offset of 12 to the null pointer, most likely because someone tried to get the z member of a structure like the one below through a pointer that was actually null.

```<code>struct Foo {
    int w, x, y; // or anything else that takes 12 bytes including padding
    // such as: uint64_t w; char x;
    // or: void *w; char padding[8];
    // all assuming an ordinary 32 bit x86 system
    int z;
}
</code>```

Title: Is address 0000000C a special address?

Body:
00000000 is a special address (the null pointer). 0000000C is just what you get when you add an offset of 12 to the null pointer, most likely because someone tried to get the z member of a structure like the one below through a pointer that was actually null.

struct Foo {
    int w, x, y; // or anything else that takes 12 bytes including padding
    // such as: uint64_t w; char x;
    // or: void *w; char padding[8];
    // all assuming an ordinary 32 bit x86 system
    int z;
}


问:
Is this a feature envy smell?
In my Application, I wanted to seperate GUI and business logic with some kind of ModelViewPresenter-Design.

Therefore I made some Presenter classes, which have not much more code than the properties my forms are databound to.

To provide persistance (load and save) I made new classes with methods setting the properties of the above mentioned presenter classes to seperate concerns (present data to GUI and persist data).

Since my presenter classes are now only datacontainers without any behavior, I wonder if I should better merge persistance and presenter to simplify my code. It seems very overdone to me as it is at the moment.

Here is some C# snippet from one of the Persistance classes:

```<code>public override void LoadData()
{
    Presenter = (PersonalColorSettingsPresenter) PresenterFactory.GetPresenter(m_User, "ColorSettings");
    loadData();
}

private void loadData()
{
    var color = Settings.GetSelectionColor(m_User);

    Presenter.ActiveRowBackColor = color.BackColor;
    Presenter.ActiveRowBackColor2 = color.BackColor2;
    Presenter.IsActiveRowBackgroundGradientActive = color.GradientActive;
    Presenter.ActiveRowForeColor = color.ForeColor;
}
</code>```

答:
No, you should not merge persistence into your presenter. It may not seem important right now, but doing so would be a violation of the Single Responsibility Principle, and if such decisions were made repeatedly in the long term would lead to code that is difficult to maintain.

As a side note, if you're using the MVP pattern, your persistence layer should interact with your model objects, not with your presenter. The presenter should read data out of the model to pass to the view, and then write the results back to the model after it has finished. A data storage module (e.g.some kind of repository or DAO - please don't use active record here as this violates SRP too) is used to load and save the model objects. The presenter should know as little about how this works as possible, I.e. if possible it shouldn't interact with the data storage at all (have that happen at a higher level) but if it must then have it do so through an abstract interface.

Title: Is this a feature envy smell?


问:
Implementing a VM for simulation
I am aware of this question, and I think I know why it has been closed. I hope that my question manages to be more specific.

My skill level: I have a "Computer Science" degree. I have programmed in many languages. Back in the day I programmed in C on an embedded microcontroller (TI MSP430), and in Python and Prolog. I have absolutely no experience in programming in assembly language, although I think I understand the concept. I had to embed assembly for my microcontroller work, but this was on the level of initializing some of the attached hardware; nothing that even involved implementing an algorithm.

I am aware of the fact that Knuth's "The Art of Computer Programming" shows all algorithms in assembly. Going through this book is a huge investment and I'd do it if someone recommends it.

I realize this question is very general, but since I have absolutely no prior experience, I find it really difficult to put it into any context.

My "problem":

I have to implement a simulator for a project that is part of my thesis work. I tried doing it in two different high-level languages: Python and Prolog. I could not model the "things" I am simulating (autonomous, very simple units without any complex logic, but too many of them) without incurring too much overhead. I even considered using Erlang and Erlang processes, but the messaging between them is definitely a bad way to model how the things interact with each other.

I did consider using C or C++. The simulation involves changing the behaviour of the things I am modeling, and doing this in C or C++ would mean actually implementing a "virtual" machine (the simulator) that allows me to do this. It seems that assembler will make it slightly easier. I have to admit that the architecture I have written (very limited) assembly on had a flat address space, which is why I thought that would be an option.

It feels as if Assembly language might be the way forward. However, I am at a loss at:

which assembly language to pick

how to chose an architecture

Things I considered:

GNU Assembler

Knuth's MMIX

The questions:

Can I actually use any of the two for a (more or less) efficient implementation on an already existing architecture?

Does this sound like a completely misguided attempt?

答:
MMIX isn't the solution you're looking for. It's primary purposes is to enable standardised implementations of algorithms and data structures so that they can be compared with each other in terms of efficiency. It is not intended to run on real hardware, and run-time efficiency was never its goal.

I also don't recommend using the GNU assembler, at least not if you are targeting an 80x86 processor. It uses a syntax that is somewhat different to the syntax Intel use to describe their processors, and it is the latter syntax that most educational resources for assembly programming are aimed at. NASM is I believe the most commonly used assembler for hand-coded intel assembly, and I would recommend it because of this (even if I hadn't been involved in writing it!).

That said, however, I'm not sure assembly language is the best approach to your problem.

(update after question edited: I originally suggested C/C++ here)

It may be that Java is actually your best bet - it has a handful of libraries available (asm.jar, BCEL, javassist) that are intended to make dynamic generation of java code at run time easy. You would program the dynamic parts of your system in Java bytecode, which is conceptually similar to assembly language, but much simpler, and this would then be converted to native machine code by the JVM. I think this is probably the best balance between simplicity and efficiency available. If it isn't efficient enough, LLVM can be used to achieve similar results in C++, but is harder to use.

Title: Implementing a VM for simulation


问:
How do you take advantage of your whiteboard in your development team?
Today we got our own website design. The theme is the "whiteboard".

I'm a big fan of them. I would like you to share with me how you use it. I'm sure I don't exploit its potential enough.

I will really enjoy answers that will come with pictures of your own whiteboard as an illustration ;)

I use it as an information radiator to support a light version of scrum.

How do you use this essential development tool?

Please note that I'm also interested in people using a virtual whiteboard or even big touchscreen whiteboard emulator.

答: We don’t use a whiteboard anymore since we have started with JIRA, I send a picture that show the development phases. Two table one for development cases and one for production bugs which are prioritised high. We run a mixture of Kanban & Scrum. Each column can have at most x cases at the same time. Each case is signed to a person.

ContentLicense: CC BY-SA 2.5


答:
In Windows it is illegal to dereference the entire first and last page, in other words the first or last 64 KiB of the process memory (the ranges 0x00000000 to 0x0000ffff and 0xffff0000 to 0xffffffff in a 32-bit application).

This is to trap the undefined behavior of dereferencing a null pointer or index into a null array. And the page size is 64 KiB so Windows just has to prevent the first or last page being assigned a valid range.

This won't guard against uninitialized pointers that could have any value (including valid addresses).

Title: Is address 0000000C a special address?

Body:
When programming sometimes things break. You made a mistake and your program tries to read from a wrong address.

One thing that stands out to me that often those exceptions are like :

```<code>Access violation at address 012D37BC in module 'myprog.exe'. Read of address 0000000C.
</code>```

Now I see a lot of error logs and what stands out to me is the : 0000000C. Is this a "special" address? I see other access violations with bad reads but the addresses just seem random, but this one keeps coming back in totally different situations.


问:
Best way to keep consistent data in model across devices?
I have a model for an app that is fairly large, all of which needs to be on a users' device at the same time. For example, a spreadsheet. If a user makes a change to the model on one device, I want this change to propagate to all other users, via updating a centralised server.

I'm not quite sure the best way to achieve this. I have a couple of ideas:

Each change of the model results in notifying the server of the change, where it updates it's database, and the change event is emitted via a socket to all connected devices. Each device then updates it's model when it receives the message from the server.

My worry with this option is that if something goes wrong on the server and the event is not emitted, we lose consistency.

Each change of the model results in notifying the server of the change, where it updates it's database. It then tells all devices that they will need to update their model. Devices then pull a new copy of the whole model from the server.

Here there may be performance issues associated with downloading large amounts of data to devices repeatedly.

I am wondering what an approach to addressing this issue might be?

答:
What you suggest is the usual way to achieve this - the alternative is to directly communicate with the other devices in a per-to-peer topology, but that breaks down quickly as devices are added.

So your requirement is to check and detect errors. You could implement a heartbeat to the server so you know its alive, and/or you can add a version number that is incremented every time a device sends an update, then other devices can tell if an update is late or if they've missed an update or two (and then force the user to re-sync)

You should be sending just the changes required from the server to the devices, in much the same way as each device sends a delta change to the server. With big documents the propagation time is likely to be prohibitive - a device may not be able to keep up with the rate of changes that are being sent otherwise (think a game where player positions are sent as change packets, not the entire game world downloaded each frame)


问:
How to remove a middle element from queue?
I had a question, about how to remove an element from middle of the queue , without disturbing the order of other elements.

E.g.

Queue before operation:-    <| a b c d e |<

Queue after operation:-     <| a b d e|<

Note:- I know the generic way of removing a,b and inserting on queue again, followd by d and e.
But I Need a more faster and efficient way.

答:
Queues are generally considered to be an abstract data type that only has enqueue and dequeue operations. So in the general case, we can't use any other functions.

Let's look at the case of a FIFO queue that only supports these two operations and additionally has a size property. Getting and removing the middle element is trivial by also removing all earlier elements:

val q: Queue[Item] = ...;
val half_size: Int = q.size / 2;

var result: Item = null;
while (q.size > half_size) {
    result = q.dequeue();
}
```

<p>But replaying the removed items in the correct order requires us to remove all elements, since we cannot push items back onto the end! We <em>have</em> to do something like this:</p>

<pre class="lang-scala prettyprint-override"><code>val q: Queue[Item] = ...;
val temp: Queue[Item] = new Queue();
val half_size: Int = q.size / 2;

var result: Item = null;
while (q.size > 0) {
    val item = q.dequeue();
    if (q.size == half_size) {
        result = item;
    } else {
        temp.enqueue(item);
    }
}

while (temp.size > 0) {
    q.enqueue(temp.dequeue());
}
</code>```

Of course, this only works if the input queue is not changed while this algorithm is executed.

For LIFO queues (i.e., stacks), we only have to remove half of the elements as we can replay the items in the correct order. For a stack, we usually call enqueue push and dequeue pop.

val q: Stack[Item] = ...;
val temp: Stack[Item] = new Stack();
val half_size: Int = q.size / 2;

var result: Item = null;
while (q.size > half_size) {
    result = q.pop();
    temp.push(result);
}

while (temp.size > 0) {
    q.push(temp.pop());
}
```

Some implementations of queues are actually fully-featured linked lists (e.g. in Java, the java.util.LinkedList fulfils the java.util.Queue interface). If we have access to such implementation details of a queue, we can splice out the element more easily. So if we have a LinkedList rather than a Queue, we can simply list.remove(indexOfTheMiddleElement). Depending on what language you are using, you may be able to take some shortcuts.

Body:
Queues are generally considered to be an abstract data type that only has enqueue and dequeue operations. So in the general case, we can't use any other functions.

Let's look at the case of a FIFO queue that only supports these two operations and additionally has a size property. Getting and removing the middle element is trivial by also removing all earlier elements:

val q: Queue[Item] = ...;
val half_size: Int = q.size / 2;

var result: Item = null;
while (q.size > half_size) {
    result = q.dequeue();
}

But replaying the removed items in the correct order requires us to remove all elements, since we cannot push items back onto the end! We have to do something like this:

val q: Queue[Item] = ...;
val temp: Queue[Item] = new Queue();
val half_size: Int = q.size / 2;

var result: Item = null;
while (q.size > 0) {
    val item = q.dequeue();
    if (q.size == half_size) {
        result = item;
    } else {
        temp.enqueue(item);
    }
}

while (temp.size > 0) {
    q.enqueue(temp.dequeue());
}

Of course, this only works if the input queue is not changed while this algorithm is executed.

For LIFO queues (i.e., stacks), we only have to remove half of the elements as we can replay the items in the correct order. For a stack, we usually call enqueue push and dequeue pop.

val q: Stack[Item] = ...;
val temp: Stack[Item] = new Stack();
val half_size: Int = q.size / 2;

var result: Item = null;
while (q.size > half_size) {
    result = q.pop();
    temp.push(result);
}

while (temp.size > 0) {
    q.push(temp.pop());
}

Some implementations of queues are actually fully-featured linked lists (e.g. in Java, the java.util.LinkedList fulfils the java.util.Queue interface). If we have access to such implementation details of a queue, we can splice out the element more easily. So if we have a LinkedList rather than a Queue, we can simply list.remove(indexOfTheMiddleElement). Depending on what language you are using, you may be able to take some shortcuts.


问:
How to make significant technical decisions given very little time
I have got 2 days for making a very serious decision about the tools and platforms that my company is going to use in order to port its WPF application to Linux / Android / iOS whatnot.

Obviously I can point to my seniors that 2 days is hardly enough for reading about all possible options, and what about trying, making prototypes etc. I can say it, it won't help me a bit, I have got 2 days, and after 2 days the decision would be made. Period.

From one side I am frustrated, from other side I think there is a grain of truth in this approach, otherwise I can easily find myself buried under dozens of downloaded SDKs, frameworks,  APIs, blog articles etc etc doing bench-works, running samples and forgetting in the process what it all was for.

Still I am afraid that a wrong decision will cost the company dearly.
So what do you think is an "ideal" process for making such decisions?

答:
If all you have is 2 days and no time to prototype or even read upon all the alternatives then there's really only 2 options:

ask someone who knows and follow their advice. This may not necessarily mean asking an individual but spend the 2 days searching through blogs and articles to glean enough information to make a slightly-better-than-uninformed decision.

Do a little research into all the mainstream options and then pick one. Sometimes leadership means not being afraid to make the wrong decision, its often more important to make a firm decision than to vacillate.

You can cover yourself by coming up with architectures that are more decoupled and therefore easier to change - eg a client/server model will allow you to replace your UI technology with another with minimal disruption.


答:
gbjbaanb makes some very good points.  I just thought I'd add a bit.

It's obvious you don't have enough time to make a perfectly informed decision.  Your only option is to try and make a decision that will minimize future pain.  I'd suggest:

Clearly document the nature of the situation:  Send an email to your manager(s) and CC their managers and the stakeholders.  Explain that the problem you've been assigned is a tricky one but that you're willing to give it your all.  But note that, given the strict time constraints, you can't guarantee your findings to be optimal.

Find a framework/platform with a large and active online community.  The last thing you want is to be stuck debugging an obscure framework alone.

As previously mentioned by gbjbaanb, mitigate your porting pains and risks by using a loosely coupled architecture.  If everything goes pear shaped with one of your technology choices, this will make it easier to swap it out.

I've been in your situation before and it eventually turned into a political nightmare.  When the system didn't magically work people began pointing fingers and things got ugly.  That's why my #1 recommendation is to clearly document that you did your best against impossible odds.

Good luck :)

Title: How to make significant technical decisions given very little time

Body:
I have got 2 days for making a very serious decision about the tools and platforms that my company is going to use in order to port its WPF application to Linux / Android / iOS whatnot.

Obviously I can point to my seniors that 2 days is hardly enough for reading about all possible options, and what about trying, making prototypes etc. I can say it, it won't help me a bit, I have got 2 days, and after 2 days the decision would be made. Period.

From one side I am frustrated, from other side I think there is a grain of truth in this approach, otherwise I can easily find myself buried under dozens of downloaded SDKs, frameworks,  APIs, blog articles etc etc doing bench-works, running samples and forgetting in the process what it all was for.

Still I am afraid that a wrong decision will cost the company dearly.
So what do you think is an "ideal" process for making such decisions?


问:
How to manage scope creep?
We often receive last minute requests from the business asking for an extra feature to be implemented.  The project manager is usually responsible for filtering out these requests as "must haves" or "nice to have", but there are cases where the business wants to squeeze all these features into a release.   Is there a good way to say NO to the business?  What steps can be taken to stop or minimize scope creep?</p>

答: What we do is provide a revised due date and cost estimate every time.  You add functionality X on Monday and it will take 20 hours and the due date is Friday, then we automatically slip the due date by 20 hours. Once we got to where we did this every time (no exceptions) we stopped getting so many scope creep requests. But you must do it every time, give them a time estimate (and cost estimate if need be) and then tell them what the new deadline will be if we add this feature.</p>

Title: How to manage scope creep?


答:
2 days is a very short period for making that kind of decision, but since you have to do it in 2 days list following,

What are the target platforms

What are the custom / third party components used in current app where it might require considerable effort to port.
for example : chart components, grid components, reporting components, etc..

How is the current app connecting to the world and how is the security is handled (database connections / web services / etc...)

How it's distributed and how updates provided

Now you need find alternatives you can use for all the target environments

For each alternatives find out the support for each to use the connectivity / security that current app is using.

then for each custom / third party components find out if there are easy to use alternatives for each.

And then think of how the distribution can be done for each alternative you found.

I think for 2 days this should be the scope you should be able to cover and based on the results you can provide a solution.


答:
Since they've effectively given you little time to do more than pick candidates out of a hat, I'd adopt the following approach.

Select technologies that:

Have a large user base

Have active support (via whatever channels)

Are being actively developed

By definition, this would rule out any bleeding edge technology, however good it may be.

Also, resist the urge to go with technology X without further analysis simply because Fred the developer has used it in the past. It is unlikely to be a perfect fit, and if Fred moves on to pastures greener, there goes your domain expert.


问:
Why sacrificing good software engineering practices is typically the first choice for software development projects assuming "good enough" quality
I have observed a correlation between a customer ordering software of "good enough" quality and the same customer not willing to pay for good engineering practices (unit testing, code reviews and the like) that many times that I would call it causality. Still, I am having hard time coming up with any logical reasoning behind such thinking so I would appreciate some insights from the community here.

As I see it, the engineering practices mentioned above have effect on only two quality attributes: maintainability and, to a lesser degree, reliability. Except for throw-away prototypes, I can hardly imagine a customer in their right mind who would want to get software that

crashes every now and then (although I realize that MTBF expectations vary depending on the cost of error), and/or

incurs considerable maintenance costs down the road.

On the other hand, other quality attributes such as scalability or performance are not directly affected by the engineering practices (if we don't count architecture reviews which are kind of from another league). What's more interesting, relaxing one or more of these could lead to way more considerable cost reductions, while not following proper engineering practices might as well lead to increasing project costs due to so called "endless debugging / stabilization cycle"

I should be missing something important since the preference to "save" on not doing software development properly is so prevalent among customers.

Please enlighten me :)

答:
I've never yet seen a customer who asked for poor-quality software.  However, what they do want is the cheapest software, and they want it as soon as possible.

The cheapest and quickest way to develop software is to throw something together as quickly as possible, then debug it until it does pretty much what you wanted, and doesn't crash too often.

At that point the developer can ship the software and bill the customer.  The seller is happy because they get paid.  The purchaser is happy because they got what they ordered very quickly at a low price.

The end-user gets buggy and unreliable software.  But the end-user isn't the one who makes purchasing decisions.

Long-term maintenance costs are not a consideration at any point in this cycle.


答:
From what I have encountered, usually, to build what can be considered as good software, one needs to have a clear set of requirements, maybe not all of them, but at least a set of core rules which will not change. From this, you then choose your architecture, design patterns, languages and frameworks.

The problem with this is that most of the times, the client themselves do not really know what they want. They will usually know what they will want to achieve, but when you start asking questions as to why they want certain functionality as opposed to other functionality, most of them usually blank out. To add insult to injury, some clients could get offended with all your questions since they deem them to be excuses so that you do not do the work and as a waste of time.

Clients usually want solutions fast and they want them cheap (in the short run at least). They do not really care what you did as long as you deliver what they asked for. From my experience, clients will always go for the quick solution even if it will require loads of maintenance. Taking months to properly design a system which is easy to upgrade is something which, from experience at least, does not happen.

Title: Why sacrificing good software engineering practices is typically the first choice for software development projects assuming "good enough" quality

Body:
I have observed a correlation between a customer ordering software of "good enough" quality and the same customer not willing to pay for good engineering practices (unit testing, code reviews and the like) that many times that I would call it causality. Still, I am having hard time coming up with any logical reasoning behind such thinking so I would appreciate some insights from the community here.

As I see it, the engineering practices mentioned above have effect on only two quality attributes: maintainability and, to a lesser degree, reliability. Except for throw-away prototypes, I can hardly imagine a customer in their right mind who would want to get software that

crashes every now and then (although I realize that MTBF expectations vary depending on the cost of error), and/or

incurs considerable maintenance costs down the road.

On the other hand, other quality attributes such as scalability or performance are not directly affected by the engineering practices (if we don't count architecture reviews which are kind of from another league). What's more interesting, relaxing one or more of these could lead to way more considerable cost reductions, while not following proper engineering practices might as well lead to increasing project costs due to so called "endless debugging / stabilization cycle"

I should be missing something important since the preference to "save" on not doing software development properly is so prevalent among customers.

Please enlighten me :)


问:
Where should I place business logic validations?
We are having a heated discussion about this at work:
For sake of simplicity, I will use examples in the question.

Assume there is an application with an account request form, for which we have these requirements:

Dates and Email must match a regex

If the user already has an account request, he should not request for another

The problem is: where to verify the second requirement?

If we check on the controller, we would have to access the database from there and it is a business logic, so it doesn't seem right.

If we validate on the business layer, we would have to somehow return the validation information in case of a failed validation. Doing this would require either:

Each business method to have an "out" parameter;

We to encapsulate our return object into a "response" object with the validation information

The use of exceptions in case of failed validations (which, to me, falls in the anti-pattern of using exceptions for programm flow).

How should we design this?

答:
Go for the second solution. Your AccountRequestValidator uses the db information and some rules to determine of the request is valid or not. Then use a "response" object, but don't create one yourself if you use a language that has already implemented that for you like Scala or Haskell. This type is usually called Either. It should throw an Exception if it is not able to check if the validation is valid, for whatever reasons there might be.

Your code would therefore look similar to:

```<code>AccountRequestValidator validator = new AccountRequestValidator(db)
AccountRequest request = //...
try {
    Either<RequestAllowed, RequestForbidden> validationResult = validator.validate(request )
    //Do sth. with validationResult
}
catch (Exception e) {
    //Was unable to check if the request is valid...
}
</code>```

If you use Java, consider using Googles Functional Java. It has its own Either type defined.

Body:
Go for the second solution. Your AccountRequestValidator uses the db information and some rules to determine of the request is valid or not. Then use a "response" object, but don't create one yourself if you use a language that has already implemented that for you like Scala or Haskell. This type is usually called Either. It should throw an Exception if it is not able to check if the validation is valid, for whatever reasons there might be.

Your code would therefore look similar to:

AccountRequestValidator validator = new AccountRequestValidator(db)
AccountRequest request = //...
try {
    Either<RequestAllowed, RequestForbidden> validationResult = validator.validate(request )
    //Do sth. with validationResult
}
catch (Exception e) {
    //Was unable to check if the request is valid...
}

If you use Java, consider using Googles Functional Java. It has its own Either type defined.


答:
Validating for format validity on single fields, should happen as close to the point of entry into your code as possible. In this case it should be as close to the UI as possible. One reason for this is that this allows you to assume proper values from that point on. Another is that this allows you to check before actually processing anything which brings functional benefits as well.

Validating stuff like, is this account already created is a whole different thing altogether and should reside in the business logic. To elaborate on your concerns here. Never ever use exceptions for logic! Exceptions are for exactly that, exceptions. Something unexpected went wrong so an exception occurs.
I personally am no fan of out parameters as well and would go for the response object. Also I would encourage you not to extrapolate functionality like this in a separate set of objects, where you can tailor your classes to closely mimic your functional needs instead of your data model.

HTH.

Title: Where should I place business logic validations?

Body:
We are having a heated discussion about this at work:
For sake of simplicity, I will use examples in the question.

Assume there is an application with an account request form, for which we have these requirements:

Dates and Email must match a regex

If the user already has an account request, he should not request for another

The problem is: where to verify the second requirement?

If we check on the controller, we would have to access the database from there and it is a business logic, so it doesn't seem right.

If we validate on the business layer, we would have to somehow return the validation information in case of a failed validation. Doing this would require either:

Each business method to have an "out" parameter;

We to encapsulate our return object into a "response" object with the validation information

The use of exceptions in case of failed validations (which, to me, falls in the anti-pattern of using exceptions for programm flow).

How should we design this?


答:
It may seem that I am going against the stream, but I have recently read the book Creativity, Inc. by Ed Catmull and there was a really nice paragraph tackling this situation:

Andrew Stanton spoke next. Andrew is fond of saying that people need to be wrong as fast as they can. In a battle, if you're faced with two hills and you're unsure which one to attack, he says, the right course of action is to hurry up and choose. If you find out it's the wrong hill, turn around and attack the other one. In that scenario, the only unacceptable course of action is running between the hills.

I am sure it can be applied for your situation as well. Maybe you can make the decision today by picking one and start working on it. If it works, then you'll have something ready in those two days and you'll say - "I picked this, and I can show you what we can do with it because I ran few tests...". If you notice in a day that the picked solution is totally not worth it, you can then choose a different one and work with that the next day. The worst case scenario is that you'll use both days to test two platforms, finding out that neither of them works - but that's ultimately the right answer, isn't it? Take out the weed, get rid of wrong possible choices, so any next decision will be much better than the previous one. The best case scenario is that you'll pick the right one right away and will have something ready to show after two days.

Obviously you won't master any platform in two days, but picking one ASAP will definitely give you a better perspective on how it works (much more than just reading about it) and will lead you to a better answer.