问:
When there's no 1-1 mapping between subdomains and bounded contexts?
Reading this question and the accepted answer we see that although we would expect subdomains and bounded contexts to match that's not always the case. The person who wrote the accepted answer states that one possible cause is that there's already some legacy application on which there's more context for a single domain, or even just one context for everything.

That's fine, but there are any other ways in which we can fail to correspond exactly subdomains to bounded contexts? I mean, if I'm writing an application from scratch, without any legacy application in place, so basically I'm starting now, in that case would be anything stopping me from making one bounded context per subdomain?

答:
Disclaimer: I am "the person who wrote the accepted answer" to the other question. :o)

In practice there are quite a few situations where in the same subdomain there might be multiple Bounded Contexts.

Technology differences it might be a variation upon the legacy app mentioned above, but if we're developing a web and mobile version of the same application, we might end up with different BCs. They might be more or less diverging depending to the proximity of the development teams.

Purpose differences a recurring modelling pattern for BCs in the same subdomain is to have two separate models for Design and Execution. Usually the two models look like the same (they basically have the same data) but the purpose and behaviour is different. A Contract might be editable (details, discounts, etc) in Negotiation phase while it has to be basically read only in the Fulfilment phase. Sometimes the purposes (Negotiation and Fulfilment) can make two different subdomains, but some other times, they're just two phases of same stakeholders operation.

There are a some good links on this topic:

a presentation by Mathias Verraes: http://verraes.net/2014/11/modelling-heuristics/

a couple of posts from Cyrille Martraire: http://cyrille.martraire.com/2014/11/the-actual-vs-plan-dichotomy/ and http://cyrille.martraire.com/2014/11/make-money-vs-reduce-risks-dichotomy/

an old presentation of mine: https://skillsmatter.com/skillscasts/3403-why-do-all-my-ddd-applications-look-the-same (slides are available here: http://www.slideshare.net/ziobrando/why-do-all-my-ddd-apps-look-the-same-vienna-2014). The presentation has also been summarized by Cyrille here: http://cyrille.martraire.com/2012/09/collaborative-construction-by-alberto-brandolini/


问:
Does ORM promote database de-normalisation?
Doctrine and Propel both make use of single and concrete table inheritance to map object relationships. The former sees all possible fields in the class tree mapped to a single table - whereas the latter maps each class to a specific table, duplicating common fields in the inheritance hierarchy.

While this facilitates the ORM apparatus, it suggests bad database design to me. Are these bad design patterns to enforce on a database?

答:
I don't agree that ORM promotes de-normalisation or bad database design. In fact, the worst designed databases I've seen has been done without ORM's. By making it simple to have proper relations based on  row id instead of making a relation based on the value of a random field, it rather promotes good database design.

Possibly it doesn't promote normalization, but then again an ORM where it's easy to make tables/objects and relations could almost be seen to promote that as well. It's not much more work in an ORM to make a "location" table with addresses and link employees to the location instead of adding the address to the employee table. But without the ORM, separating out the location means that everytime you want to access the location as well, you need to make a join.

So my answer is: No, I don't think so. It's possibly in fact other other way around, a good ORMs encourages good database design, at least about those who have little experience.

ContentLicense: CC BY-SA 2.5


问:
Is a series of OR or a single IN SQL statement better?
I'm using MS SQL 2008 R2. I have been using a series of OR and have an issue where my app periodically give the following error:

```<code>Exception message: Timeout expired. The timeout period elapsed prior to obtaining
a connection from the pool. This may have occurred because all pooled connections
were in use and max pool size was reached.
</code>```

My SQL skills are fairly basic but I have a situation where I need to make selections from a database. Originally the selections were simple (either a single filter or select all)

```<code>Select column_names... From Table Where column = value
</code>```

Or

```<code>Select column_names... From Table
</code>```

Now I need to select where column could be one of a series of items. Which would be best to use

```<code>Select column_names... From Table Where column = value1 Or column = value2 Or column = ValueX...
</code>```

Or

```<code>Select column_names... From Table Where column In (value1, value2, valueX...)
</code>```

答:
SQL Server will typically optimize the IN to the same as the multiple OR statements.  Take this for example:

```<code>use AdventureWorks;
go

select BusinessEntityID
from HumanResources.Employee
where BusinessEntityID = 153
or BusinessEntityID = 25
or BusinessEntityID = 37;

select BusinessEntityID
from HumanResources.Employee
where BusinessEntityID in (153, 25, 37);
</code>```

Looking at the execution plan I can see that SQL Server treated them as like statements and used the same execution for them both:

Ultimately, though, you need to do the same exercise in your environment with your queries and your data (if you have differing plans for these different variations, feel free to post the post execution plans in your question and I can analyze).  And of course like all things relational data, you need to ensure that you have the proper querying and indexing in place in order to optimize the data retrieval.

The other side of that is readability/maintainability.  Consistency is king here for development teams, and if this is a solo code base then I'd tack on personal preference to that.  IN is a lot less verbose with characters, and the typical choice.

Just a note, though, if these conditional checks get out of control (hundreds of hundreds of elements in the IN clause, I've seen it before way too often) you might need to step back at what you are really doing and refactor your logic.

Your actual error is because of a different cause though...

It is worth noting though that your actual error message is a connection timeout, not a command timeout.  It looks as though you've exhausted all pooled connections in your connection pool for the application.  Take a look at this blog post I wrote on connection pooling.  That should explain why you're getting that error and how to fix.  It is very possible that other sessions are running too long, and not closing or disposing of the connection to return it back to the pool.  You would most definitely need to take a spearheaded approach in troubleshooting your connection timeout issues due to exhausted connection pooling.

ContentLicense: CC BY-SA 3.0

Body:
SQL Server will typically optimize the IN to the same as the multiple OR statements.  Take this for example:

use AdventureWorks;
go

select BusinessEntityID
from HumanResources.Employee
where BusinessEntityID = 153
or BusinessEntityID = 25
or BusinessEntityID = 37;

select BusinessEntityID
from HumanResources.Employee
where BusinessEntityID in (153, 25, 37);

Looking at the execution plan I can see that SQL Server treated them as like statements and used the same execution for them both:

Ultimately, though, you need to do the same exercise in your environment with your queries and your data (if you have differing plans for these different variations, feel free to post the post execution plans in your question and I can analyze).  And of course like all things relational data, you need to ensure that you have the proper querying and indexing in place in order to optimize the data retrieval.

The other side of that is readability/maintainability.  Consistency is king here for development teams, and if this is a solo code base then I'd tack on personal preference to that.  IN is a lot less verbose with characters, and the typical choice.

Just a note, though, if these conditional checks get out of control (hundreds of hundreds of elements in the IN clause, I've seen it before way too often) you might need to step back at what you are really doing and refactor your logic.

Your actual error is because of a different cause though...

It is worth noting though that your actual error message is a connection timeout, not a command timeout.  It looks as though you've exhausted all pooled connections in your connection pool for the application.  Take a look at this blog post I wrote on connection pooling.  That should explain why you're getting that error and how to fix.  It is very possible that other sessions are running too long, and not closing or disposing of the connection to return it back to the pool.  You would most definitely need to take a spearheaded approach in troubleshooting your connection timeout issues due to exhausted connection pooling.

ContentLicense: CC BY-SA 4.0


问:
What is the most efficient / fastest way to keep a list in order?
I implemented Dijkstra's path finding algorithm in JavaScript and a big part of it involves storing the distances to nodes and fetching the smallest. The distances change often and the smallest is fetched a lot.

I'm currently using an Ordered Linked List, with items being put in order when added.

Is there a faster way?

Edits:

Ordered Linked List = lowest value first.

Here's the code: https://raw.githubusercontent.com/nojacko/dijkstras-js/master/Dijkstras.js

Update:

Implemented arnaud's suggestion of a Fibonacci Heap. It was 32 to 85 times faster with diminishing returns the larger the dataset.

I deviated from the true Fibonacci Heap by not running consolidate every time a value was removed. I found running it once every 50 shifts performed best.

Source Code is here: https://github.com/nojacko/dijkstras-js/blob/bda68d1274629c30b1f902ffb7f95f1e3c695973/Dijkstras.js

答:
If it is truly an ordered linked list, this should be a fairly bad choice because you have to traverse the list one by one until you find the right place to insert the item. In other words O(N). This is ok if the list is small but can get out of hand for big graphs.

Usually, what you will need for that kind of stuff is a heap:

http://en.wikipedia.org/wiki/Heap_%28data_structure%29

...where you can insert and pop in O(log(n)) ...it's also usually available out of the box in most programming languages.


问:
Is static going to make any difference in this code snippet
I have been to an interview and was asked this question - is there any difference adding or removing the static keyword in these classes?

I know what static means but my understanding of this point is weak.

```<code>class Program
{
    static void Main(string[] args)
    {
            aAsposeNew.MultipleInstancesProblem();
            Console.ReadLine();
    }
}

public static class aAsposeNew
{
    public static void MultipleInstancesProblem()
    {
            var task1 = Task.Run(() => CreateDocument("document1.pdf"));
            var task2 = Task.Run(() => CreateDocument("document2.pdf"));
            var task3 = Task.Run(() => CreateDocument("document3.pdf"));
    }

    public static void CreateDocument(string documentName)
    {
        var doc = new Document();
        doc.Pages.Add();

        var table = new Aspose.Pdf.Table();
        var row = table.Rows.Add();
        table.ColumnWidths = "600";
        var hf =
            new HtmlFragment(@"<ul>
                                 <li>Internal HR Meeting Outcome</li>
                                 <li>Internal HR Meeting Outcome January 2015</li>
                               </ul>");
        var cell = row.Cells.Add();
        cell.Paragraphs.Add(hf);
        doc.Pages[1].Paragraphs.Add(table);

        doc.Save(@"C:\Output\" + documentName);
    }
  }
</code>```

and without the static keyword:

```<code>class Program
{
    static void Main(string[] args)
    {
            aAsposeNew aAN = new aAsposeNew();
            aAN.MultipleInstancesProblem();
            Console.ReadLine();
    }
}

public class aAsposeNew
{
    public void MultipleInstancesProblem()
    {
            var task1 = Task.Run(() => CreateDocument("document1.pdf"));
            var task2 = Task.Run(() => CreateDocument("document2.pdf"));
            var task3 = Task.Run(() => CreateDocument("document3.pdf"));
    }

    public void CreateDocument(string documentName)
    {
        var doc = new Document();
        doc.Pages.Add();

        var table = new Aspose.Pdf.Table();
        var row = table.Rows.Add();
        table.ColumnWidths = "600";
        var hf =
            new HtmlFragment(@"<ul>
                                 <li>Internal HR Meeting Outcome</li>
                                 <li>Internal HR Meeting Outcome January 2015</li>
                               </ul>");
        var cell = row.Cells.Add();
        cell.Paragraphs.Add(hf);
        doc.Pages[1].Paragraphs.Add(table);

        doc.Save(@"C:\Output\" + documentName);
    }
  }
</code>```

答: There wont be a difference in the functions execution but the manner in which it is called will be slightly different. I would suggest making it static, as it does not need a class instance to run.</p>


问:
Is jQuery an example of "god object" antipattern?
I want to ask – I am slowly learning jQuery.

What I see is an exact example of a God Object anti-pattern. Basically, everything goes to the $ function, whatever it is.

Am I right and is jQuery really an example of this anti-pattern?

答:
Benjamin asked me to clarify my position, so I edited my previous post and added further thoughts.

Bob Martin is the author of a great book titled as Clean Code. In that book there is a chapter (Chapter 6.) called Objects and Data structures, which he discusses the most important differences between objects and data structures and claims that we have to choose between them, because mixing them is a very bad idea.

This confusion sometimes leads to unfortunate hybrid structures that are half object and half data structure. They have functions that do significant things, and they also have either public variables or public accessors and mutators that, for all intents and purposes, make the private variables public, tempting other external functions to use those variables the way a procedural program would use a data structure.4 Such hybrids make it hard to add new functions but also make it hard to add new data structures. They are the worst of both worlds. Avoid creating them. They are indicative of a muddled design whose authors are unsure of—or worse, ignorant of—whether they need protection from functions or types.

Clean Code - Chapter 6. - Hybrids

I think DOM is an example of these object and data structure hybrids. For example by DOM we write codes like this:

```<code>el.appendChild(node);
el.childNodes;
// bleeding internals

el.setAttribute(attr, val);
el.attributes;
// bleeding internals

el.style.color;
// at least this is okay

el = document.createElement(tag);
doc = document.implementation.createHTMLDocument();
// document is both a factory and a tree root
</code>```

DOM should be clearly a data structure instead of a hybrid.

```<code>el.childNodes.add(node);
// or el.childNodes[el.childNodes.length] = node;
el.childNodes;

el.attributes.put(attr, val);
// or el.attributes[attr] = val;
el.attributes;

el.style.get("color");
// or el.style.color;

factory = new HtmlNodeFactory();
el = factory.createElement(document, tag);
doc = factory.createDocument();
</code>```

The jQuery framework is a bunch of procedures, which can select and modify a collection of DOM nodes and do many other things. As Laurent pointed out in his post, jQuery is something like this under the hood:

```<code>html(select("#body"), "<p>hello</p>");
</code>```

The developers of jQuery merged all of these procedures into a single class, which is responsible for all of the features listed above. So it clearly violates the Single Responsibility Principle and so it is a god object. The only thing because it does not break anything, because it is a single standalone class which works on a single data structure (the collection of DOM nodes). If we would add jQuery subclasses or another data structure the project would collapse very fast. So I don't think we can talk about oo by jQuery it's rather procedural than oo despite the fact that it defines a class.

What Laurent claims is a complete nonsense:

So what does it all mean? That jQuery (like LINQ) is not the God object anti-pattern. It's instead a case of a very respected pattern called the Decorator.

Laurent's comment

The Decorator pattern is about adding new functionality by keeping the interface and not modifying existing classes. For example:

You can define 2 classes which implements the same interface, but with a completely different implementation:

```<code>/**
 * @interface
 */
var Something = function (){};
/**
 * @argument {string} arg1 The first argument.
 * @argument {string} arg2 The second argument.
 */
Something.prototype.doSomething = function (arg1, arg2){};

/**
 * @class
 * @implements {Something}
 */
var A = function (){
    // ...
};
/**
 * @argument {string} arg1 The first argument.
 * @argument {string} arg2 The second argument.
 */
A.prototype.doSomething = function (arg1, arg2){
    // doSomething implementation of A
};

/**
 * @class
 * @implements {Something}
 */
var B = function (){
    // ...
};
/**
 * @argument {string} arg1 The first argument.
 * @argument {string} arg2 The second argument.
 */
B.prototype.doSomething = function (arg1, arg2){
    // doSomething implementation of B
    // it is completely different from the implementation of A
    // that's why it cannot be a sub-class of A
};
</code>```

If you have methods which use the common interface only, then you can define one or more Decorator instead of copy-pasting the same code between A and B. You can use these decorators even in a nested structure.

```<code>/**
 * @class
 * @implements {Something}
 * @argument {Something} something The decorated object.
 */
var SomethingDecorator = function (something){
    this.something = something;
    // ...
};

/**
 * @argument {string} arg1 The first argument.
 * @argument {string} arg2 The second argument.
 */
SomethingDecorator.prototype.doSomething = function (arg1, arg2){
    return this.something.doSomething(arg1, arg2);
};

/**
 * A new method which can be common by A and B.
 *
 * @argument {function} done The callback.
 * @argument {string} arg1 The first argument.
 * @argument {string} arg2 The second argument.
 */
SomethingDecorator.prototype.doSomethingDelayed = function (done, arg1, arg2){
    var err, res;
    setTimeout(function (){
        try {
            res = this.doSomething(o.arg1, o.arg2);
        } catch (e) {
            err = e;
        }
        callback(err, res);
    }, 1000);
};
</code>```

So you can substitute the original instances with the decorator instances in higher abstraction level code.

```<code>function decorateWithManyFeatures(something){
    var d1 = new SomethingDecorator(something);
    var d2 = new AnotherSomethingDecorator(d1);
    // ...
    return dn;
}

var a = new A();
var b = new B();
var decoratedA = decorateWithManyFeatures(a);
var decoratedB = decorateWithManyFeatures(b);

decoratedA.doSomethingDelayed(...);
decoratedB.doSomethingDelayed(...);
</code>```

The conclusion that jQuery is not a Decorator of anything, because it does not implements the same interface as Array, NodeList or any other DOM object. It implements it's own interface. The modules are not used as Decorators as well, they simply override the original prototype. So the Decorator pattern is not used in the whole jQuery lib. The jQuery class is simply a huge adapter which let us use the same API by many different browsers. From oo perspective it is a complete mess, but that does not really matter, it works well, and we use it.

Body:
Benjamin asked me to clarify my position, so I edited my previous post and added further thoughts.

Bob Martin is the author of a great book titled as Clean Code. In that book there is a chapter (Chapter 6.) called Objects and Data structures, which he discusses the most important differences between objects and data structures and claims that we have to choose between them, because mixing them is a very bad idea.

This confusion sometimes leads to unfortunate hybrid structures that are half object and half data structure. They have functions that do significant things, and they also have either public variables or public accessors and mutators that, for all intents and purposes, make the private variables public, tempting other external functions to use those variables the way a procedural program would use a data structure.4 Such hybrids make it hard to add new functions but also make it hard to add new data structures. They are the worst of both worlds. Avoid creating them. They are indicative of a muddled design whose authors are unsure of—or worse, ignorant of—whether they need protection from functions or types.

Clean Code - Chapter 6. - Hybrids

I think DOM is an example of these object and data structure hybrids. For example by DOM we write codes like this:

el.appendChild(node);
el.childNodes;
// bleeding internals

el.setAttribute(attr, val);
el.attributes;
// bleeding internals

el.style.color;
// at least this is okay

el = document.createElement(tag);
doc = document.implementation.createHTMLDocument();
// document is both a factory and a tree root

DOM should be clearly a data structure instead of a hybrid.

el.childNodes.add(node);
// or el.childNodes[el.childNodes.length] = node;
el.childNodes;

el.attributes.put(attr, val);
// or el.attributes[attr] = val;
el.attributes;

el.style.get("color");
// or el.style.color;

factory = new HtmlNodeFactory();
el = factory.createElement(document, tag);
doc = factory.createDocument();

The jQuery framework is a bunch of procedures, which can select and modify a collection of DOM nodes and do many other things. As Laurent pointed out in his post, jQuery is something like this under the hood:

html(select("#body"), "<p>hello</p>");

The developers of jQuery merged all of these procedures into a single class, which is responsible for all of the features listed above. So it clearly violates the Single Responsibility Principle and so it is a god object. The only thing because it does not break anything, because it is a single standalone class which works on a single data structure (the collection of DOM nodes). If we would add jQuery subclasses or another data structure the project would collapse very fast. So I don't think we can talk about oo by jQuery it's rather procedural than oo despite the fact that it defines a class.

What Laurent claims is a complete nonsense:

So what does it all mean? That jQuery (like LINQ) is not the God object anti-pattern. It's instead a case of a very respected pattern called the Decorator.

Laurent's comment

The Decorator pattern is about adding new functionality by keeping the interface and not modifying existing classes. For example:

You can define 2 classes which implements the same interface, but with a completely different implementation:

/**
 * @interface
 */
var Something = function (){};
/**
 * @argument {string} arg1 The first argument.
 * @argument {string} arg2 The second argument.
 */
Something.prototype.doSomething = function (arg1, arg2){};

/**
 * @class
 * @implements {Something}
 */
var A = function (){
    // ...
};
/**
 * @argument {string} arg1 The first argument.
 * @argument {string} arg2 The second argument.
 */
A.prototype.doSomething = function (arg1, arg2){
    // doSomething implementation of A
};

/**
 * @class
 * @implements {Something}
 */
var B = function (){
    // ...
};
/**
 * @argument {string} arg1 The first argument.
 * @argument {string} arg2 The second argument.
 */
B.prototype.doSomething = function (arg1, arg2){
    // doSomething implementation of B
    // it is completely different from the implementation of A
    // that's why it cannot be a sub-class of A
};

If you have methods which use the common interface only, then you can define one or more Decorator instead of copy-pasting the same code between A and B. You can use these decorators even in a nested structure.

/**
 * @class
 * @implements {Something}
 * @argument {Something} something The decorated object.
 */
var SomethingDecorator = function (something){
    this.something = something;
    // ...
};

/**
 * @argument {string} arg1 The first argument.
 * @argument {string} arg2 The second argument.
 */
SomethingDecorator.prototype.doSomething = function (arg1, arg2){
    return this.something.doSomething(arg1, arg2);
};

/**
 * A new method which can be common by A and B.
 *
 * @argument {function} done The callback.
 * @argument {string} arg1 The first argument.
 * @argument {string} arg2 The second argument.
 */
SomethingDecorator.prototype.doSomethingDelayed = function (done, arg1, arg2){
    var err, res;
    setTimeout(function (){
        try {
            res = this.doSomething(o.arg1, o.arg2);
        } catch (e) {
            err = e;
        }
        callback(err, res);
    }, 1000);
};

So you can substitute the original instances with the decorator instances in higher abstraction level code.

function decorateWithManyFeatures(something){
    var d1 = new SomethingDecorator(something);
    var d2 = new AnotherSomethingDecorator(d1);
    // ...
    return dn;
}

var a = new A();
var b = new B();
var decoratedA = decorateWithManyFeatures(a);
var decoratedB = decorateWithManyFeatures(b);

decoratedA.doSomethingDelayed(...);
decoratedB.doSomethingDelayed(...);

The conclusion that jQuery is not a Decorator of anything, because it does not implements the same interface as Array, NodeList or any other DOM object. It implements it's own interface. The modules are not used as Decorators as well, they simply override the original prototype. So the Decorator pattern is not used in the whole jQuery lib. The jQuery class is simply a huge adapter which let us use the same API by many different browsers. From oo perspective it is a complete mess, but that does not really matter, it works well, and we use it.


问:
How to appropriately structure a script used in an AJAX call?
When I first learned AJAX, I was also teaching myself the languages of PHP, JavaScript, SQL, HTML, and CSS. I followed my coworkers existing web apps as examples of how to write my own web applications. Now that I have a better grasp on the languages and how they work, I have begun to question the existing script structure that my coworkers and I use. Basically, we have all of our calls to one PHP file, and send an event in the url.

It is structured something like this:

Url:wepappname_ajax.php?event=dosomething

PHP:

```<code>If ($event == dosomething) {
     //do something
} elseif ($event == dosomethingelse) {
     //do something else
}
</code>```

Is a giant if statement really the route we should be taking? Should we section everything off into functions instead, or should we be making seperate PHP files for every different event?

答:
I think in any language/framework/application it is good to try to have single responsibility of components, for your case it would mean to have each of the ajax "events" in separate files.

you could have files like:

```<code>/ajax/posts.php
/ajax/userInfo.php
...
</code>```

each file could then require some core/common functionality from one location

it makes it much more readable/easier to maintain this way

you could also try using a framework that enforces this kind of structure.

hope this helps :)

Body:
I think in any language/framework/application it is good to try to have single responsibility of components, for your case it would mean to have each of the ajax "events" in separate files.

you could have files like:

/ajax/posts.php
/ajax/userInfo.php
...

each file could then require some core/common functionality from one location

it makes it much more readable/easier to maintain this way

you could also try using a framework that enforces this kind of structure.

hope this helps :)


问:
How does non-interruptive autosave work?
Many apps save state and progress automatically in the background. Mobile apps save what page you're on even after the apps are cleared out of RAM. OneNote and Word for iOS save documents automatically. Elementary OS apps are supposed to open where the user left off last time. But if non-interruptive saving is possible, why does auto-save in desktop word processors require the user to wait for saving to finish?

This process doesn't seem to be instantaneous, for some reason. Scrolling position in Safari Reader Mode is a bit off after you press the home button while scrolling.

How does non-interruptive autosave work?

答:
Auto-save always makes you wait, because you don't want the user to be changing data while the save is taking place.  It appears to be instantaneous when it is instantaneous (more or less).

The reason why e.g. Microsoft Word takes more time to save data is because its XML format is incredibly complex. Desktop applications in general can have twenty years of cruft they have to support, and also generally support more complex formatting and structure than mobile applications need to support with their ten or fewer years of existence and much simpler requirements.

If you want to see for yourself, try opening a nontrivial Word or Excel document on your phone compared to a simpler format such as the ones LibreOffice uses or a simple Notepad application. I have done this and anecdotally I can say those complex formats take far more time to load and save.


问:
Why should a HashMap be used(in functions) to determine which value to return(for a key) when an if else construct can do the job in better time?
While I was recently working at a big company, I noticed that the programmers there followed this coding style:

Suppose I have a function that returns 12 if the input is A, 21 if the input is B, and 45 if the input is C.

So I can write the function signature as:

```<code>int foo(String s){
    if(s.equals("A"))      return 12;
    else if(s.equals("B")) return 21;
    else if(s.equals("C")) return 45;
    else throw new RuntimeException("Invalid input to function foo");
}
</code>```

But on code review I was asked to change the function to the following:

```<code>int foo(String s){
    HashMap<String, Integer> map = new HashMap<String, Integer>();
    map.put("A", 12);
    map.put("B", 21);
    map.put("C", 45);
    return map.get(s);
}
</code>```

I can't convince myself on why the second code is better than the first. The second code would definitely take more time to run.

The only reason to use the second code can be that it offers better readability. But if the function is getting called many times then wouldn't the second function slow down the running time of the utility calling it?

What do you think about this?

答:
The point is to move the creation of the hashmap outside the function and do it once (or just less times than otherwise).

```<code>private static final Map<String, Integer> map;
static{
    Map<String, Integer> temp = new HashMap<String, Integer>();
    temp.put("A", 12);
    temp.put("B", 21);
    temp.put("C", 45);
    map = Collections.unmodifiableMap(temp);//make immutable
}

int foo(String s){
    if(!map.containsKey(s))
        throw new RuntimeException("Invalid input to function foo");

    return map.get(s);
}
</code>```

However java has since java7 been able to have (final) strings in switches:

```<code>int foo(String s){
    switch(s){
    case "A":
        return 12;
    case "B":
        return 21;
    case "C":
        return 45;
    default: throw new RuntimeException("Invalid input to function foo");
}
</code>```

Body:
The point is to move the creation of the hashmap outside the function and do it once (or just less times than otherwise).

private static final Map<String, Integer> map;
static{
    Map<String, Integer> temp = new HashMap<String, Integer>();
    temp.put("A", 12);
    temp.put("B", 21);
    temp.put("C", 45);
    map = Collections.unmodifiableMap(temp);//make immutable
}

int foo(String s){
    if(!map.containsKey(s))
        throw new RuntimeException("Invalid input to function foo");

    return map.get(s);
}

However java has since java7 been able to have (final) strings in switches:

int foo(String s){
    switch(s){
    case "A":
        return 12;
    case "B":
        return 21;
    case "C":
        return 45;
    default: throw new RuntimeException("Invalid input to function foo");
}


答:
In your second example, the Map should be a private static member to avoid redundant initialization overhead.

For large amounts of values, the map will perform better. Using a hashtable, one can look up the answer in constant time. The multiple-if construct has to compare the input to each of the possibilities until it finds the right answer.

In other words, the map lookup is O(1) while the ifs are O(n) where n is the number of possible inputs.

Map creation is O(n), but is only done once if it is static constant state. For a lookup performed frequently the map will outperform the if statements in the long run, at the cost of slightly more time when the program is starting up (or the class is loaded, depending on language).

That being said, the map is not always the right tool for this job. It is nice when there are a lot of values, or the values must be configurable through a text file, user input, or database (in which case the map acts as a cache).

Title: Why should a HashMap be used(in functions) to determine which value to return(for a key) when an if else construct can do the job in better time?

Body:
While I was recently working at a big company, I noticed that the programmers there followed this coding style:

Suppose I have a function that returns 12 if the input is A, 21 if the input is B, and 45 if the input is C.

So I can write the function signature as:

```<code>int foo(String s){
    if(s.equals("A"))      return 12;
    else if(s.equals("B")) return 21;
    else if(s.equals("C")) return 45;
    else throw new RuntimeException("Invalid input to function foo");
}
</code>```

But on code review I was asked to change the function to the following:

```<code>int foo(String s){
    HashMap<String, Integer> map = new HashMap<String, Integer>();
    map.put("A", 12);
    map.put("B", 21);
    map.put("C", 45);
    return map.get(s);
}
</code>```

I can't convince myself on why the second code is better than the first. The second code would definitely take more time to run.

The only reason to use the second code can be that it offers better readability. But if the function is getting called many times then wouldn't the second function slow down the running time of the utility calling it?

What do you think about this?


问:
Why are cases in a switch statement not isolated?
As far as I can tell in all C-like languages something like this:

```<code>switch(variable) {
    case 'a':
        printf("Hello ");
    case 'b':
        printf("World!");
    case 'c':
        printf("\n");
}
</code>```

Will print "Hello World!" if variable == 'a'. I'm curious about the reasoning behind this behaviour as it seems to me automatically inserting breaks at the end of every case would make its behaviour a lot more consistent with expectations and a lot less error-prone.

For example: "In case your die rolls a 6, draw another card" is an action that has to be done in a single case, which to me the case keyword implies.

答:
That is because you can't assume that logic and program flow should stop after a single match.  It is a good design for a multiple-match type of conditional test.

Take this for example:

```<code>switch (shape)
{
    case Square:
        printf("I am a square\r\n");
    case Rectangle:
        printf("I am a rectangle\r\n");
        break;
    case Circle:
        printf("I am a circle\r\n");
        break;
}
</code>```

If we didn't have the fall through behavior here, we'd have to be redundant with printf("I am a rectangle\r\n"); in order to have that code execute for both a square and a rectangle.

Body:
That is because you can't assume that logic and program flow should stop after a single match.  It is a good design for a multiple-match type of conditional test.

Take this for example:

switch (shape)
{
    case Square:
        printf("I am a square\r\n");
    case Rectangle:
        printf("I am a rectangle\r\n");
        break;
    case Circle:
        printf("I am a circle\r\n");
        break;
}

If we didn't have the fall through behavior here, we'd have to be redundant with printf("I am a rectangle\r\n"); in order to have that code execute for both a square and a rectangle.


答:
To write the equivalent of a switch statement in assembly you'd need to add jumps at the end of each branch to prevent execution from continuing to the next branch. C was designed to have a fairly straightforward mapping to machine code, and the pattern would've been familiar to assembly programmers at the time.

Its descendants likely kept it out of historical inertia, which should not be underestimated. For example, the designers of C# clearly felt accidental fall-through is a major source of bugs and is the uncommon case, so you need to explicitly fall through if you want it, but they still kept the syntax of adding a break at the end!

Title: Why are cases in a switch statement not isolated?

Body:
As far as I can tell in all C-like languages something like this:

```<code>switch(variable) {
    case 'a':
        printf("Hello ");
    case 'b':
        printf("World!");
    case 'c':
        printf("\n");
}
</code>```

Will print "Hello World!" if variable == 'a'. I'm curious about the reasoning behind this behaviour as it seems to me automatically inserting breaks at the end of every case would make its behaviour a lot more consistent with expectations and a lot less error-prone.

For example: "In case your die rolls a 6, draw another card" is an action that has to be done in a single case, which to me the case keyword implies.


答:
See Stack Overflow.

A summation of the popular arguments presented there is that:

A switch statement can provide fallthrough while still allowing you to have a choice about it with the break statment.

It was a mistake in the design of C that ended up becoming the standard for case statments.


答:
Case statement fall through is rarely needed, but it does sometimes happen. (I have heard that C was originally meant to program telephone switchboards, in which this need arises often, but I was unable to confirm it.)  But the truth is that even in modern software, the need for a case statement fall through does arise every once in a rare while.

If the C language did not allow case statement fall-through, then workarounds would be necessary, but the line of thinking back in 1972 was to avoid wasting clock cycles. By allowing case statement fall-through, programmers could have it both ways: you could either fall through or break, whichever was pertinent to your needs, on a case per case basis.

The primary focus of the C language originally was to be nice to the machine, not nice to the programmers. The original C was lean, mean, and very unforgiving.

The idea behind preventing case statement fall through is a very modern concept, and it is all about protecting programmers from themselves. Very few people were thinking along such lines in AT&T Bell Labs back in 1972, when C was invented.


问:
Browser game played in an iframe - security concerns
I'm not sure if this counts as an Information Security or Webmasters question rather than Programmers, however I'll see how we go.

I've been prototyping a help website for a particular browser game, and I've made the layout of the help website compact and concise with the idea that the rest of the page space can be filled with an iframe that will contain the game itself so players can also play while being on my website.

This way, players of the game can play the browser game and have access to all of the tools and information on my help website at the top of the page. The help website doesn't interact with the game inside the iframe of course, and its purpose is to provide useful references and calculators relating to the game.

I've done some research into the security of iframes, and how the website hosting the iframe can't interfere with the iframe due to the Same Origin Policy. The only security flaw I can think of for players is players not being sure that the real official browser game is running in the iframe and not a fake phishing copy.

What other security concerns should I be aware of and how can these be overcome either by me, the developer, or checked by users to ensure their security on my help website when playing the game via my help website? My main concern is players not feeling safe playing the game through an iframe on my website.

答:
There are many well documented vulnerabilities and attacks that use frames.

OWASP has a good list of them here with examples:

https://www.owasp.org/index.php/Cross_Frame_Scripting

Generally, users should always be wary of any frame content especially Cross-Origin frames. Frames, including iframe, have undoubtedly been one of the largest vulnerabilities in the past and new vulnerabilities are found quite often.

A browser extension would be my ideal form of a "helper" that would integrate into the existing page, Chrome has a great engine and community for this.

That said, it is ultimately up to the user whether they trust you or not no matter how you handle it.


问:
How can I implement scrum if management won't commit resources?
I want to try to apply scrum to a project.  For the purposes of my question, let's assume that there are no other problems I'm trying to solve; I just want to practice scrum.

Over the summer we're hoping to have 3 full-time developers (two working half-time on the project) and 1 or 2 interns.

Unfortunately, management insists that they must be able to pull resources at a moment's notice whenever they deem it necessary, and they refuse to commit personnel for even a 2-week sprint.  I think at most they will pull two people from the project, leaving at least one senior engineer and two interns on the project.  I still want to try scrum, but how can I work around this?  Do I just convince the other team members to try it with me, and do it without management's blessing?

I know the foundation of scrum is that team members must be permitted to work uninterrupted for the duration of a sprint, but is there a way to work around this if management will not guarantee the resources?  Certainly in the real world people must get sick or leave the team in the middle of the sprint once in a while.  How does the scrum team deal with this and track its acceleration in a meaningful way?

My idea at this point is to do the following:

Implement scrum with 2-week sprints but only allocate resources that are less likely to be pulled. Others may work on the project, but not necessarily as part of the scrum team's development crew.  (Maybe they focus on testing or documentation, or pull work items from the project backlog instead of the TODO list.)

If we are interrupted after a sprint has started, make a note, reallocate resources and tasks, and restart the sprint with the remaining resources.

If the team was rarely interrupted, or if the sprint was usually interrupted only a day or two from the beginning or end of the sprint, try to use that data to convince management that scrum would not be that disruptive to the other projects.  (This is assuming we can demonstrate that scrum worked at all for the duration of the summer.)

Is it likely this will work, or is it not really worth the effort to try to implement scrum if we cannot guarantee that the team won't be interrupted?  Are there any other practical solutions to this problem?

答:
Scrum doesn't know nor care anything about management issues. It's a way to organize  your work, and to make problems visible so they can be fixed. Scrum can't fix your problem, but it at least can make it visible.

Start doing scrum, making any assumptions you want about resource availability. Plan according to that. Follow the scrum practices. When a resource gets yanked from the project, note that as a distraction and carry on -- this is really no different than if someone got sick, quit, or is just having a bad day. The rest of the team has to carry on and try to finish (but not by working extra  hours!)

At the end of a sprint, you now have evidence of how much you've been able to accomplish. Hopefully you'll start to see a pattern emerge: you cannot effectively plan with a constantly changing team. You'll (hopefully!) also see that when you can go two weeks without losing anyone, you are able to complete a predictable amount of work.

In short: do scrum, and let it do what it does best, which is to expose impediments early, and give you a framework for dealing with the impediments.


问:
Should I prefer Python generators to lists?
Python iterators can be very memory efficient. Should I always prefer to use generators instead of just lists? In what situations should I prefer a plain array?

For example instead of this:

```<code>emails = [user.email for user in users]
</code>```

should I prefer this?:

```<code>emails = (user.email for user in users)
</code>```

Note: I do mean 'generators' not 'iterators'.

答:
You've got iterators confused with generators.

Your first example is a list iterator expression while the second is a generator expression. The key difference is that the generator creates each member of the given collection lazily (as needed) rather than eagerly (at once, whether needed or not). You can define your own generators by using yield rather than return.

As far as usage goes, you want an iterator when you need the list (or dictionary or whatever) for something in and of itself. You'd use a generator when the collection is incidental to the final product. For example, you might use a generator to get a list of numbers that satisfy some criteria from some other criteria. You don't care about the original list, only the members which fit the criteria. Thus, you use a generator to only get those numbers.

A more concrete example would be finding the angles of triangles whose sides are a given length. We don't want all the poor, deformed failed triangles, only the strong, healthy successful triangles. Thus we'd use a generator.

This Stack Overflow post goes into more detail.


问:
How To Avoid Dependencies between Modules
We have two modules, lets call them U and F.

Module U has entities like that:

```<code>class Upload {
    Long id;
    User uploadedBy;
    Date uploadedAt;
}
</code>```

Module F has entities like that:

```<code>class Field {
    Long id;
    String displayName;
    Type type;
}
</code>```

And both have the typical manager beans with create, edit, delete and some GUI depending on them.

So now what one customer wants to have is for us to add to the entites of module U so they will look like that:

```<code>class Upload {
    // fields as above
    List<Field> fields;
}
</code>```

I don't think that's the best idea, because it would create a dependency between F and U that is not necessary for most customers. So now we are trying to find a good architecture that allows us to model what the customer wants without creating dependencies.

One thing that came to mind was to create a Module E with entities like that:

```<code>class ExtendedUpload1 {
    Upload upload;
    List<Field> fields;
}
// or...
class ExtendedUpload2 extends Upload {
    List<Field> fields;
}
</code>```

So only that module will have dependencies to both F and U, and both F and U can live separately. But we have an API in between GUI and server, meaning separate values classes and interfaces both sides work with. And while we can inject additional functionality to both GUI and server, dynamically extending the API is the actual problem. We would need to copy all the API classes to work with the new values.

What architectural patterns apply to that use case? How could we solve the problem elegantly?

答:
If the language you use supports generics, what about something like the following:

```<code>    class Upload<ExtendedData> {
      Long id;
      User uploadedBy;
      Date uploadedAt;
      List<ExtendedData> data;
    }
</code>```

This way, Upload and Field can live in different namespaces / modules, but can be combined in the client-specific case where the user wants to Upload Field instances.

Body:
If the language you use supports generics, what about something like the following:

    class Upload<ExtendedData> {
      Long id;
      User uploadedBy;
      Date uploadedAt;
      List<ExtendedData> data;
    }

This way, Upload and Field can live in different namespaces / modules, but can be combined in the client-specific case where the user wants to Upload Field instances.


问:
Object caching in this code too expensive?
I'm having some trouble with a game developed in Java which is kinda slow. I benchmarked it a little bit and found the problem: most of the time, the JVM is in the Object.<init>() since there are a lot of objects which gets created and destroyed every tick.

This class which gets created this often is a really small class, just 3 integers, nothing more. But this was a problem I tried to solve. So I started a few tests on how I could increase the speed. What I found is unexpected. First off, code I tested with is as follwos:

```<code>public class NewVsCloneTest implements Cloneable {
    int a = 0;
    int b = 0;
    int c = 0;

    public static void main(String... args) throws Exception {
        Stack h = new Stack();
        System.out.println("Benchmarking Copy vs Clone...");
        long time = 0;
        long n = 0, c = 0, s = 0;
        NewVsCloneTest obj = null;
        for(int num = 0; num < 50; num++){
            time = System.currentTimeMillis();
            for(int i = 0; i < 10000000; i++){
                obj = new NewVsCloneTest();
            }
            n += (System.currentTimeMillis() - time);
            System.out.println("New took " + (System.currentTimeMillis() - time) + " MilliSeconds");
            time = System.currentTimeMillis();
            for(int i = 0; i < 10000000; i++){
                obj = (NewVsCloneTest) obj.clone();
            }
            c += (System.currentTimeMillis() - time);
            System.out.println("Clo took " + (System.currentTimeMillis() - time) + " MilliSeconds");
            time = System.currentTimeMillis();
            for(int i = 0; i < 10000000; i++){
                obj = h.getOne();
                h.pushOne(obj);
            }
            s += (System.currentTimeMillis() - time);
            System.out.println("Sta took " + (System.currentTimeMillis() - time) + " MilliSeconds");
        }

        System.out.println("After 50 runs, new took " + n + ", clone took " + c + " and stack took " + s);
        System.out.println("On average, new took " + n / 50.0 + ", clone took " + c / 50.0 + " and stack took " + s / 50.0 + " per 10 mio runs.");
    }

    public static class Stack {
        private NewVsCloneTest[] vars = new NewVsCloneTest[10];
        {
            for(int i = 0; i < 10; i++)
                vars[i] = new NewVsCloneTest();
        }
        int pos = 9;
        public NewVsCloneTest getOne(){
            return vars[pos--];
        }

        public void pushOne(NewVsCloneTest var){
            vars[++pos] = var;
        }

    }

}
</code>```

The results I get:

```<code>After 50 runs, new took 3462, clone took 5784 and stack took 4132
On average, new took 69.24, clone took 115.68 and stack took 82.64 per 10 mio runs.
</code>```

So, this was really unexpected for me, that new is faster than the small stack-implementation. I mean, the stack already can do nothing but get and put one. No rangechecks, no size-change, just nothing. I even gave "NewVsCloneTests" a few more ints, a few longs, a few objects (just nullptr's) and a few chars, but got the same outcome.

So the thing is, I've seen a lot of source code where one cached instances of classes which will get needed very often but just for a short time, so I thought it would make a difference. But my results show me that even worse.

How can I handle this particular problem?

The class which gets instantiated this often is just a dataholder for coordinates (x, y, z), and it gets instantiated this often (copy-constructed if you will) because I can't hand out my originals.

答: Pass the x, y, z around as primitives (i.e. int or long or whatever).   Since they are primitives, they are passed by value.    Hence there is no need to copy an object when passing them to another piece of code, they're copied as part of the pass-by-value operation.</p>


问:
Is it actually possible to have a 'useful' programming language that isn't Turing complete?
Where it is accepted that a language has to be Turing complete to be any good, is it actually possible to have a 'useful' programming language that isn't Turing complete?

I should clarify that this is quite specifically about 'programming' languages in the traditional sense, and not markup or query languages.

答:
The C preprocessor is not Turing-complete (by design), yet it can still implement an interpreter for a language that is Turing complete (Order-the-language, as described in the documentation, is basically just a run-of-the-mill purely functional ML/Scheme type thing, and would be relatively unremarkable - probably quite nice to use - if it weren't for the unusual implementation).

The trick behind it is similar to the arguments above about implementing any Turing machine in a finite physical universe: the C preprocessor can't provide an infinite number of steps, or data cells, to the language, but it can:

provide an unreasonably large dynamic number (2^64 or so by default), large enough for solving most realistic problems using an exponential expansion process (mumble mumble lifetime of the universe mumble).

use an arbitrary static cap for the above number, i.e. while the number of steps must be some finite number, you can change what the specific cap is at "compile"-time by changing the static settings of the interpreter engine. Since there is no (theoretical) limit on the actual value of this cap, it can (theoretically) be extended to fit the space requirement for any terminating program.

Not to argue that Order is necessarily "useful" in itself, or that any CPP-implemented engine would be, but it's an interesting proof of concept. It's also supposedly dynamically typed, which is unusual for this area.


答:
The main drawback of generators is they can only be traversed in one direction.  There's no going back to a previous value.  You also can't share them.  There are many cases where that can easily be accounted for, or even where it is preferable, but there are also many cases where it isn't.  Sorting, for example.

That's why a lot of times you'll see generators used for the initial processing stages of a large amount of data, then once it's filtered into a subset and mapped into a nice format, it gets put into a long-lasting concrete data structure for further use.  That way you don't spend the memory allocation, cache misses, and garbage collection costs for large intermediate arrays you'll immediately throw away.

Title: Should I prefer Python generators to lists?

Body:
Python iterators can be very memory efficient. Should I always prefer to use generators instead of just lists? In what situations should I prefer a plain array?

For example instead of this:

```<code>emails = [user.email for user in users]
</code>```

should I prefer this?:

```<code>emails = (user.email for user in users)
</code>```

Note: I do mean 'generators' not 'iterators'.


问:
Is it a good idea to require passwords in offline applications?
I am developing an application which can install extension modules (plugins, if you will) from APT-style repositories hosted elsewhere. The plugins need not be signed (although the downloads are verified), and can be downloaded over basic insecure HTTP. Is it a good idea to require the user's password (in a similar way to sudo) to download packages, or just to install them? Should I require a login at all?

To be more specific: should I verify that the user installing the packages is authorised to do so client-side?

答:
I think this really depends on the nature of your application. Is it for an individual or something that could be run by many on a server environment? Is it for a technical user or somebody less technical.

Take Eclipse, for example. You can connect to any repo and download plugins without needing to log in. The users that are going to be doing that, though, are technical in nature and are operating (hopefully) on their own machine where not much could get screwed up.

I think you should implement some sort of preventative guard (such as a sign in) in the following cases:

The target user is a non-technical individual and this is an application that could be used in a business

Locking it down would allow the people who know what they are doing to modify and/or install the plugins. It also allows for uniformity in the environment so that if there are any issues the internal IT can make easier work of it.

The application is going to be on a server

If the application is going to be hosted on a server, it is a good idea to password protect it so that not everybody who has access to the server would be able to modify the program at will.

Any other time, I wouldn't think that it is really necessary to put the safe guard in place since it would be a non-secure setting for an individual.


答:
While there are multiple approaches here, the best approach and the key to security on the desktop is to assume that any userland software running is already compromised. In other words, place your trust in the operating system, not the programs. If the operating system is compromised... it is time to replace the computer.

You mentioned sudo as a way to authenticate to install (not download) system packages. This is because the package manager is locked down and requires root (group or user) access. In other words, apt-get does not enforce security itself, it simply does things that require root access. On my system it is r-x for the root group, of which I am a user. So I can execute it, but it cannot do anything useful unless it runs as root because the things it attempts to do require root access.

In the same vein, a userland program should not care too much about security. Instead, it should rely on the credentials of the logged-in user to allow it to access system resources that are secured by the operating system. If the user needs elevated privileges, then run as root, use sudo, or right-click and "run as administrator" in Windows.

In theory, any application-level security can be broken in a matter of time by anyone with access to the system.

Even server software such as SQL Server follows this model by preferring to rely on system groups and privileges. If you try to use SQL Server authentication and turn off the group-based security it will warn you this is not secure -- because it is not.

Remember, the OS is in a special, privileged execution environment that gives it unfettered access to all system resources. Applications in modern operating systems do what the operating system allow them to do. Leverage that built-in security and do not reinvent the wheel.

To address your question more directly, it can be acceptable to authenticate in the program itself if you are installing plugins to the user's profile, localizing any damage to the user's account. However, that is rather pointless as you do not require any different privileges to finish the action. I would still recommend not authenticating, and relying on the built-in security to let the action succeed or fail (in this case, most likely succeed).

The only time it truly makes sense to enter a password without elevating privileges is for encrypting or decrypting data: but that should not be a user account password anyway.

Title: Is it a good idea to require passwords in offline applications?

Body:
I am developing an application which can install extension modules (plugins, if you will) from APT-style repositories hosted elsewhere. The plugins need not be signed (although the downloads are verified), and can be downloaded over basic insecure HTTP. Is it a good idea to require the user's password (in a similar way to sudo) to download packages, or just to install them? Should I require a login at all?

To be more specific: should I verify that the user installing the packages is authorised to do so client-side?


问:
First stab at python classes... when do I need 'self'?
Could someone look over this and let me know if i've butchered anything.  It's just a simple class definition in python, but I don't have any local devs to make sure I'm using the language right.  Using 'self' so much feels awkward and I don't know if it is needed.</p>

```<code>import time
import pexpect
from datetime import datetime
import deviceModelconfigs
from kafka import KafkaClient, KeyedProducer, HashedPartitioner, RoundRobinPartitioner

class Device():
    def __init__(self, roomName, ip, model):
        self.model = model
        self.ip = ip
        self.roomName = roomName
        self.codes = deviceModelconfigs.setCodes(self.model)
        self.powerStatus = 'na'
        self.signalStatus = 'na'
        self.networkStatus = 'na'

    def connect(self):
        self.child = pexpect.spawn('telnet '+ self.ip + ' 2001')

    def sendMessage(self):
        print ("devices", self.roomName, str("{\"timestamp\":\"" +  str(datetime.utcnow().isoformat()) +
                "\",\"roomName\":\""+ self.roomName +
                    "\",\"powerStatus\":\""+ self.powerStatus +
                    "\",\"signalStatus\"\""+ self.signalStatus +
                    "\",\"networkStatus\":\""+ self.networkStatus +
                "\",\"deviceModel\":\""+ self.model +
                "\",\"deviceType\":\""+ self.codes['deviceType'] + "\"}"))

    def testPower(self):
        try:
            self.child.sendline(self.codes['pwrStCmd'])
            self.child.expect(self.codes['pwrStOnRe'], timeout=5)
            status = 'on'
        except:
            try:
                self.child.sendline(self.codes['pwrStCmd'])
                self.child.expect(self.codes['pwrStOffRe'], timeout=5)
                status = 'off'
            except:
                status = 'na'
        return status

    def testAll(self):
        self.powerStatus = Device.testPower(self)
        Device.sendMessage(self)
        self.child.terminate(True)

jeff = Device('FM1-200','10.1.174.12','WD510U')
jeff.connect()
jeff.testAll()
</code>```

答:
You need self when you want to refer to the instance of a class within the class itself.

For example, an instance method can call other instance methods or properties or use instance fields.

If you have used other object oriented languages, you may have a habit of using this. Python's self is similar (while not identical) to this in other languages.

The usage of self in your sample code looks correct.

Note that:

You may consider replacing strings like "{\"timestamp\":\"" by the more readable '{"timestamp":"'.

Consider using string formatting. Two most popular ways to format strings in Python is % and .format. If you are unsure which one should you use, this answer on Stack Overflow may help.

You use strings to describe statuses. While this is an acceptable approach, you may also be interested in Python's enums.

You import four types from kafka. Have you considered using just import kafka? This answer on Programmers.SE explains the difference between import and from ... import.

In testPower, you have code duplication. Consider extracting lines containing sendline and expect statements in a separate method.


问:
Use of NOLOCK on Microsoft SQL Server
The (NOLOCK) optimizer hint is well known by most SQL developers for setting the isolation level so that tables with rows or escalated page locks can be read. I've always known about the bad and ugly; dirty reads, errors, dup rows that can occur. My specific question is why is it so overused in every organization I tend to consult with? I've seen it used for every select statement on every table in the last 3 clients I've been at. These are OLTP systems and not replicated data that is read only. What are the possible reasons for this? Is the memory/hardware insufficient to get transactions processed? Is data consistency less important than it used to be? What is the general consensus and best practice on using NOLOCK? </p>

答:
Because many teams are clueless about benefits and drawbacks of the different features of Microsoft SQL Server.

Imagine a slow app. Management has a choice: either throw more hardware (which translates into immediate and substantial cost), or blame developers for not doing their job correctly and expect them to make it faster (which translates into substantial cost spread over weeks or months). What, in your opinion, is the management's choice in most companies?

Now, the team searches for the ways to optimize their app and a programmer learns that NOLOCK makes everything magically faster. Great—he tells to himself—I can tell that to my team and our product will be faster. If the team has a skillful DBA, they have a chance to avoid the mistake. If they don't (and in too many cases, they don't), they may end up with NOLOCKs everywhere.

Unfortunately, consequences of the lack of data consistency are not immediate. In some cases, the application may function for months without issues. Then, when an inconsistency happens, nobody knows the origin of the problem. Programmers blame system administrators. System administrators blame programmers. The system may end up being patched to avoid inconsistencies in the specific location by adding dubious tests at application level which make everything slow as hell, and function for months before encountering an inconsistency somewhere else.

This being said, there are valid circumstances where data consistency doesn't matter. The feature is there for a purpose; if the number of transactions is high and obtaining inconsistent data is perfectly acceptable, there is nothing wrong in using NOLOCK. For instance, would it really matter to get a comment on a forum while a rollback happened to remove it? Probably not. On the other hand, if you see it being used in a banking application inside a method which transfers money from an account to another, this is more problematic.

Title: Use of NOLOCK on Microsoft SQL Server


问:
RSpec vs Test::Unit in Rails
I've never been really convinced of the advantages that you get by switching over to RSpec from Test::Unit in Ruby on Rails (despite reading from time to time about RSpec).

What is it about RSpec that most Rails project seems to be using it?

(some code examples clearly indicating advantages of one over the other would be much appreciated)

答:
Lately it seems that Cucumber has been getting more support in the Rails community.  Here's the nutshell argument I heard from an interview with RSpec's lead (from an old Ruby on Rails Podcast).

In the agile community (at the time) there was a big push for Test Driven Development with the emphasis on testing first to prove you had to change something.  There was something philisophically wrong with that.  In essence, testing is a way to verify that your implementation is correct, so how do you think differently about the driving design?  RSpec's lead surmised that you specify first, and wouldn't it be great if the specification also checked the results of your implementation?

The simple renaming assert to should helps to focus the mind in the correct way to write specifications, and think about design.  However, that's only part of the equation.

More importantly, since many TDD beleivers were claiming that the tests documented the design, most documentation was poor at best.  Tests are fairly opaque to non-developers unfamiliar with the language.  Even then, the design isn't immediately apparent from reading most tests.

So as a secondary goal, RSpec devised a way to generate written documentation from the specifications.  It's this written specification that gives RSpec an edge over simple Test::Unit for driving the design of an application.  Why write something more than once when you can document and verify design consistency at the same time?

My understanding is that Cucumber, which had the benefit of coming later and learning lessons from RSpec, does a better job of this secondary goal without losing the primary goal (ability to test the implementation from the specification).  Cucumber does this with a fairly English like API that non-programmers can reasonably grok.  They might need some help from programmers to fill in some definitions of new verification methods, but it's designed to be extensible.

Bottom line is that RSpec/Cucumber shouldn't replace unit testing altogether.  They may be better suited to documenting and verifying your design--but there are several implementation tests that still need to be done, particularly with subtle bugs that derive from the implementation and not the design of the application.  It does reduce the number of tests you have to write though.

Title: RSpec vs Test::Unit in Rails


答:
You seem to already know what the table hint NOLOCK does, but you question "why" do people use it so frequently.  In people's experience, or people that have shared experience with them, they have alleviated concurrency problems before by using the read uncommitted table hint.

Despite what the hint does (the lack of issuing a shared lock on data to prevent from blocking or being blocked), they still use it.  Why?  Because it is "easy" to sacrifice important things (consistent and clean data, security, etc.) with common "fixes".

Why leave it up to chance that your query will block?  Just specify WITH (NOLOCK).  13 characters that wipe clean any thought of being blocked or blocking.

Of course this is bad practice, and could lead to reading data that is dirty and inconsistent, but it is easy.  Typically this is done by SQL developers that don't want to trouble themselves with troubleshooting blocking and other concurrency situations, and they'd rather take the easy way out.

My specific question is why is it so overused in every organization I tend to consult with? I've seen it used for every select statement on every tables in the last 3 clients I've been at. What are the possible reasons for this?

Because those that use and abuse it tend to not understand relational database management systems or concurrency models, and it errs on the side of generosity in lieu of data cleanliness.

Is the memory/hardware insufficient to get transactions processed?

No, that's typically not the driving factor.

Is data consistency less important than it used to be?

Data consistency should be a timeless goal.  99% of the time it's out of laziness or ignorance that developers use it.

What is the general consensus and best practice on using NOLOCK?

The best practice is don't use it unless you've absolutely proven without a doubt that you need it and it is ok.  Simple as that.

Title: Use of NOLOCK on Microsoft SQL Server

Body: The (NOLOCK) optimizer hint is well known by most SQL developers for setting the isolation level so that tables with rows or escalated page locks can be read. I've always known about the bad and ugly; dirty reads, errors, dup rows that can occur. My specific question is why is it so overused in every organization I tend to consult with? I've seen it used for every select statement on every table in the last 3 clients I've been at. These are OLTP systems and not replicated data that is read only. What are the possible reasons for this? Is the memory/hardware insufficient to get transactions processed? Is data consistency less important than it used to be? What is the general consensus and best practice on using NOLOCK? </p>


问:
How much physical memory is consumed by the stack of a .NET thread?
In Stephen Cleary's article in MSDN magazine "Introduction to Async/Await on ASP.NET" he says that "every thread pool thread on a modern OS has a 1MB stack."  (modern OS == Windows 7/8 for this discussion)  But I thought that this was 1MB of virtual memory, and that physical memory was allocated dynamically as the stack grew.  Based on my dated C++ threading knowledge on other OSs, I believe that actual stack sizes rarely exceed 64k, especially in languages that make heavy use of the heap like .NET.

Does Windows allocate 1MB of physical memory, or does the stack dynamically allocate more memory as needed?  Maybe it is cheaper to allocate it all up front now and rely on swapping it out as needed?  I was going to test this using the profiler but I don't see how to get the stack size from it.

答: The link Robert Harvey added as a comment does explain this more explicitly, but, by default, Windows allocates 1MB of virtual memory which is committed as physical memory as needed (as you described).


问:
Optional dependencies in npm?
I have a similar question to this, but not quite the same.

I would like for the user of my app to install it with whatever dependencies are needed for the way he would want to use it. So, for example, if they want to persist to MongoDB, then only Mongo-related libraries will be installed, but if they want to persist to Redis, then only Redis-related libraries will be installed. I don't want to make them download and install libraries they won't be using.

I know I can do that for development purposes with devDependencies, but this goes farther than that. As the answer in the question above says, this is more closely related to Python's setuptools extras_require and Clojure's leiningen profiles. Anything like that in npm? I really feel like devDependencies should be a dev profile of a more versatile way of specifying dependencies.

答:
The codependency module may be what you're looking for, or anything that does something similar to:

declare optional dependencies in package.json that aren't automatically installed by npm install, say optionalPeerDependencies

a custom require-style function that knows about optionalPeerDependencies and does the right thing, including throwing/warning when nothing is found that fulfills a required class of modules (e.g. neither redis, nor mongo, nor mysql, etc. are installed).

document the expectation that consumers of this module install at least 1 of the optional peer modules

One variation would be if the module's core functionality works without any optional dependencies (e.g. plugin pattern), no error/warning when nothing is found that fulfills a peer dependency.

Another variation is doing the list above while accounting for production versus development dependencies, i.e. an analog for dependencies and devDependencies.

Perhaps combined with an on-demand require such that optional modules are required lazily, e.g.:

```<code>exports = {
    Core : require('./core'),
    get redis(){ return require('./redis'); },
    get mongo(){ return require('./mongo'); }
}
</code>```

Title: Optional dependencies in npm?

Body:
The codependency module may be what you're looking for, or anything that does something similar to:

declare optional dependencies in package.json that aren't automatically installed by npm install, say optionalPeerDependencies

a custom require-style function that knows about optionalPeerDependencies and does the right thing, including throwing/warning when nothing is found that fulfills a required class of modules (e.g. neither redis, nor mongo, nor mysql, etc. are installed).

document the expectation that consumers of this module install at least 1 of the optional peer modules

One variation would be if the module's core functionality works without any optional dependencies (e.g. plugin pattern), no error/warning when nothing is found that fulfills a peer dependency.

Another variation is doing the list above while accounting for production versus development dependencies, i.e. an analog for dependencies and devDependencies.

Perhaps combined with an on-demand require such that optional modules are required lazily, e.g.:

exports = {
    Core : require('./core'),
    get redis(){ return require('./redis'); },
    get mongo(){ return require('./mongo'); }
}


问:
Web API: avoiding name conflicts in URL query parameters
I am implementing a REST-like API and have just faced an interesting problem. There is a need to provide a resource with an open list of query parameters to filter the results.
For example:

```<code>GET /api/items?field1=value1&field2=value2
</code>```

Field names are configurable, so I don't have the complete list of possible names.

There are also parameters with special meaning, e.g. orderBy=field5

The problem is when there is a field with the same name as one of the pre-defined parameters. The API has to somehow distinguish between them.

Many command-line programs use two hyphens ("--") to mark the end of options and start of arguments. I think of something analogous in URLs.

Is there any good practice in this subject?

答:
You can also mix the special fields with the field names. e.g.

```<code>/api/items?field1.orderByDesc=value1&field2=value2&field3.orderByAsc=value3
</code>```

With this approach, you keep the field-specific filters close to the field without having to scan a separate parameter's value. Of course if you have some non-field related special params, such as pagination requests, then the "filters" special param is your best bet. You can make it less prone to conflicts by prefixing an improbable character sequence like

```<code>/api/items?field1.orderByDesc=value1&field2=value2&field3.orderByAsc=value3&z9x8y7rowStart=100&z9x8y7count=50
</code>```

The z9x8y7 approach is similar to how PHP prefixes a $ before variable names.

On a different note, you may want to add a version number in the API itself, something like

```<code>/api/v1/items?........
</code>```

This will allow you to keep multiple versions of your API alive, thus giving your consumers time to convert to a new version of your API when you release a new API. Some examples : http://www.lexicalscope.com/blog/2012/03/12/how-are-rest-apis-versioned/

Body:
You can also mix the special fields with the field names. e.g.

/api/items?field1.orderByDesc=value1&field2=value2&field3.orderByAsc=value3

With this approach, you keep the field-specific filters close to the field without having to scan a separate parameter's value. Of course if you have some non-field related special params, such as pagination requests, then the "filters" special param is your best bet. You can make it less prone to conflicts by prefixing an improbable character sequence like

/api/items?field1.orderByDesc=value1&field2=value2&field3.orderByAsc=value3&z9x8y7rowStart=100&z9x8y7count=50

The z9x8y7 approach is similar to how PHP prefixes a $ before variable names.

On a different note, you may want to add a version number in the API itself, something like

/api/v1/items?........

This will allow you to keep multiple versions of your API alive, thus giving your consumers time to convert to a new version of your API when you release a new API. Some examples : http://www.lexicalscope.com/blog/2012/03/12/how-are-rest-apis-versioned/


问:
Is a makefile really needed
I have been programming in c/c++ for a while now, and I have never once used a makefile. I know that it is supposed to be useful when you are dealing with a large project, but I have always been able to compile, build and execute my program using only

```<code>gcc main.c -o run
</code>```

and if I am working with an external library (gtk+, for example) I make a simple bash script that looks like:

```<code>#!/bin/bash
echo compiling....
gcc main.c `pkg-config --cflags --libs gtk+-3.0` -o run
</code>```

So what I'm asking is do I need to learn how to make a makefile?

答:
First, a Makefile for make is really useful when you build a program from several translation units (i.e. several *.c or *.cc files which are #include-ing some other header files) which are linked together (it is not very useful for a single source file tiny program). It organizes the various compilation steps of the translation units (and avoid running useless compilations again). See also this answer to a related question.

During the debugging phase, compile with all warnings and debug info (e.g. gcc -Wall -Wextra -g for C code compiled by GCC...) and learn how to use your debugger, e.g. GDB and memory leak detectors like valgrind.... Be scared of undefined behavior. With a recent GCC 5 compiler (at end of 2015), you may also want to use (occasionally) various -fsanitize= debugging options. Have some good testing procedures. For production and benchmarking, ask for compiler optimizations (e.g. add -march=native -O2 to your GCC compiler flags). For C++11 code, replace gcc with g++ -std=c++11; in your GNU Makefile, use CC & CFLAGS variables for C and CXX & CXXFLAGS for C++.

As soon as you are writing some not-tiny program in C or C++ (e.g. more than ten thousand lines of source code), you'll want to organize it in several translation units (at least to avoiding very long build times while working on it, and preferably to group together related code or features). Notice that with C++ the usual included header files are themselves quite big, so having tiny translation units slows the overall build process.

The size, organization, name, and purpose of a translation unit (i.e. of a foo.c or bar.cc file) is a matter of habits and conventional. Some people prefer having many tiny files (of a few dozen lines). I like having source files of several thousand lines. The recent version of GCC compiler, and the recent Linux kernel have dozens of human-written C or C++ source files bigger than ten thousand lines. Both are quite large software (many millions of source lines)

Then, you could build such a program using some other builder (like omake or scons, or ninja etc...), or even using a shell script (BTW, the GNU make distribution contains a shell script to build it on systems without any make yet!).

But yes, I believe you should learn GNU make (and you may even want to take advantage of recent GNU make features, e.g. Guile scriptability). Here is an example of Makefile, and another one.

Notice that for historical reasons the tab character is significant for make, so you need a specific mode in your editor.

In many cases, e.g. for configuration reasons, the Makefile is generated (e.g. with autoconf or cmake).

In several cases some *.c files or some header *.h included by them are generated by other programs (like SWIG, GNU bison, etc...)

You should look into the source code of several free software programs (e.g. GNU make itself! See also sourceforge, github, etc... to find some) and try building them. That would teach you a lot.

So you don't need make (or some other builder) yet, just because your programs are very tiny. As soon as they will grow, you'll need some building process. Notice that large programs (a web browser, an optimizing compiler, an OS kernel) have often many millions lines of source code organized in at least hundreds of translation units, and often have some generated C/C++ code (by some script in awk, python, guile, etc..., or a specialized program itself coded in C++, or an external generator like ANTLR or gperf) for application-specific metaprogramming or aspect-oriented programming purposes.

PS. Some other programming languages (Ocaml, Haskell, Go, SML, ...) know about modules and have very different builders.

Title: Is a makefile really needed


答:
Program to an interface is usually used for decoupling. It doesn't really matter how the interface is implemented. The modules F and U can have their own implementations.
If you need complete decoupling, move the interface in a new module I, where you can define the API. In this way, F and U are consumers for the I module and they are still independent of each other.

Title: How To Avoid Dependencies between Modules

Body:
We have two modules, lets call them U and F.

Module U has entities like that:

```<code>class Upload {
    Long id;
    User uploadedBy;
    Date uploadedAt;
}
</code>```

Module F has entities like that:

```<code>class Field {
    Long id;
    String displayName;
    Type type;
}
</code>```

And both have the typical manager beans with create, edit, delete and some GUI depending on them.

So now what one customer wants to have is for us to add to the entites of module U so they will look like that:

```<code>class Upload {
    // fields as above
    List<Field> fields;
}
</code>```

I don't think that's the best idea, because it would create a dependency between F and U that is not necessary for most customers. So now we are trying to find a good architecture that allows us to model what the customer wants without creating dependencies.

One thing that came to mind was to create a Module E with entities like that:

```<code>class ExtendedUpload1 {
    Upload upload;
    List<Field> fields;
}
// or...
class ExtendedUpload2 extends Upload {
    List<Field> fields;
}
</code>```

So only that module will have dependencies to both F and U, and both F and U can live separately. But we have an API in between GUI and server, meaning separate values classes and interfaces both sides work with. And while we can inject additional functionality to both GUI and server, dynamically extending the API is the actual problem. We would need to copy all the API classes to work with the new values.

What architectural patterns apply to that use case? How could we solve the problem elegantly?


问:
What is the purpose of planning poker in a sprint?
Our business analyst and project leads tell us the client's requirement as Stories. Every Sprint planning, we (developers) are asked to play planning poker.

They asked all of us to consider the 'Complexity' rather than 'Effort'. We are really confused and we are wasting time on our meetings. One developer raised a question, 'What should we really want to consider? Is it about the code/DDL change that we have to do in this requirement (time estimation) or is it about whether or not we have understood the requirement?'

But what do they (business analyst & project leads) really mean by 'understand the requirement' and 'raise a card'?

Plus, we have slicing meetings for individual scrum teams, where each developer gives an estimation of time for given task for each scrum team. So, what kind of thing are they really talking about in Planning Poker?

Can anyone explain this using an example? Try to differentiate what they are really talking about when they say 'Complexity' & 'Effort'.

答:
Consider the Project Manager's point of view

By asking for complexity they want a number that they can compare with your next sprint to find your velocity as a team. They may also be trying to use it to add together your result with the estimates from other teams to provide an over all estimate on when all the stories will be done.

The project manager is looking for an estimate of when the project will be finished, or if they are flexible on other sides of the time-function-cost triangle, what other leavers can be pulled to make it fit in to the time left. This is not unreasonable. Business decisions will need to be made based on this estimate. The problem is that it is really hard to estimate this for software. Planning poker is one of the ways to help with this problem. Rather than seeing it as simply adding together the number of story points, rather think of it as a more complex function of estimating as well as you can, doing the work, measuring how long it did take, iterating, and then extrapolating.

The discussion is more important than a number

I find the most important part of story pointing meetings are the discussions that come up. If anyone in the team is not confident suggesting a number, then they probably don't fully understand the story and there needs to be more discussion. From the Agile Manifesto "Customer collaboration over contract negotiation". Rather than just specifying a contract written as a user story and saying the team failed if they don't do exactly what you want, it is always better to talk about what the customer really wants until you understand it.

Complexity Vs Effort

To address your specific question about complexity vs effort, everyone seems to have a different opinion on this. Mountain Goat, who are the people who make the planning poker cards that have goats on the back of them and whose owner Mike Cohn is big in the Agile / Scrum world, say that it should be effort and not complexity.

It is normally not seen to be a measure of time (see example below for a counter example) as people are bad at estimating time, with other factors affecting what number they give: e.g. pressure to keep the number low so you can fit more features in, pressure to give a higher number to give yourself some room if you run in to a problem. Building software is hard. When you build your 100th house you can estimate how long it will take you as you have built 99 houses before that. If the software you are building is the same as previous programs you have built then you can copy and paste, any worth while software project is different and so will have problems that you didn't foresee at the beginning.

As with time estimates containing hidden pressures, so a measure of effort also has issues. If a junior developer estimates a high complexity they may feel they are leaving themselves open to attack as not being good enough from others who would give it a lower estimate. This is not only detrimental to your estimates but to the people on the team.

The planning poker numbers are not 'number of days' or some other measure of time, they are a relative measure to be able to compare two user stories. The first thing you need to do in a new team is to establish a baseline. Pick one user story that is in the middle of the complexity range and agree as a team a number in the middle of the range that you want to assign it. Now all other user stories can be numbered relative to this one. I have found this makes it much easier.

Reasons you can't give an estimate

When project managers ask you for when a project will be done they need to understand the complexity of the question they are asking. Programmers are not factory workers, where their productivity can be measured by multiplying how fast they type by how long they work. They are figuring out answers to problems and that is hard. By playing planning poker you first identify who in the team feels they can't answer the question of which number to assign and then you dig in to why they can't answer that question. I think there are at least four reasons:

The story is too big. Break it down into smaller, more specific user stories. Remember each user story should be providing one piece of value to the user; input - process - output = value.

They don't understand the problem domain well enough to be able to say how long it will take them or even ask all the questions properly. Go talk to people who do know more about the stakeholders domain / programming that kind of application, whatever it is you haven't seen before. If that is not possible or doesn't get you all the way there then you can use a design spike. Go and prototype a solution but only for a limited and specified amount of time. Define how long the prototyping phase will go on for, not too long, and then meet back up again to share your new understanding.

Your stakeholders are not being specific enough. "Build me a cloud" is not an acceptable user story. "Build me a system where I can spin up VMs on demand" is better as it is broken down further but is still not at the level where you can give an accurate estimate on how long it will take you as there will be a hundred hidden assumptions in that statement that your stakeholder has that you won't find out until you show them something.

Finally, even if you can give an estimate it will probably be wrong the first time. Estimating is a hard problem and the best way I know of to solve hard problems is to use the scientific method. Collect data on what numbers each team member estimates, then collect data on how long it really took them, or how 'complex' it really was, although that is harder, and then compare these over time. Eventually you will get a feel for who overestimates and who underestimates and then you should share this with the team. People can help each other become better at estimating. These numbers can also be fed back into your tracking tool to help better predict how long stories will take.

Conclusion

I believe the point really should be the discussion, but if you really need to give someone a number then just try to make it one that is independent of which team member works on it and in what order the stories are worked on. The point is to get to a back log that is both prioritised, so you are working on them in the right order, and sized, so that the Project Manager can see roughly how many more you can fit in before your deadline. You should be able to stop at the end of any iteration and ship with all the features completed that had been started.

Warning

You can estimate time to complete tasks within your team as much as you want as long as you keep the numbers to yourself. Once you allow any number to escape the team and be seen by other people they will do things with that number that you did not intend. They will try to use it as a number of days to complete the tasks. They will try to hold you to the relative complexity rating and ask why it took you longer to complete one user story than another with the same number of points. They will add your numbers together and compare them to other team's numbers and ask you why the other team is 'doing more work' as they complete more story points within a time period. You can't stop this but you can keep open lines of communication with all your stakeholders and try to set their expectations as close to your understanding of reality as possible.

Aside

The planning poker set of numbers are normally distributed such that the gaps between the numbers keeps getting bigger. I believe this is meant to discourage people from arguing over whether a user story is a 16 or a 17, if it's bigger than a 13 then just make it a 20.

Example

I know of at least one team that only uses the numbers 1, 2, 3, and 4 for planning poker. They, against convention and contrary to the discussion above, define these as programming days (actually pair programming days, that is how many days it would take two programmers working together at the same machine to complete the user story). If the team thinks it would take more than 4 days to complete a user story then it is left not story pointed and the product owner is asked to work with the team to break the story down further or to specify it more exactly so that it can be brought within this range for a future planning meeting. But this is advanced agile and probably should only be used by people who are already experienced in using the other techniques.