答:
Is there a reason you are avoiding using an Enum for this?

That is:

```<code>    public enum NamedQueryEnum {
       LIST_CARRIAGE_DIRECTIONS("CarriageRouteEntity.listCarriageDirections"),
       LIST_DESTINATIONS("DestinationEntity.listDestinations");
       // additional query names get added here

       private String queryName;

       private NamedQueryEnum( String queryName) {
          this.queryName= queryName;
       }

      public Query getQuery(EntityManagager entitymanager) {
          return entityManager.createNamedQuery(entityManager.createNamedQuery(queryName));
      }
   }
</code>```

Then your call would be:

```<code>NamedQueryEnum.LIST_CARRIAGE_DIRECTIONS.getQuery(entityManager));
</code>```

Title: "Clean Code": How to organize named queries?

Body:
Few days ago I started to read Robert C. Martin "Clean Code" book and it encouraged me to look more detailed at my code. After I opened eclipse I saw this:

```<code>entityManager.createNamedQuery("CarriageRouteEntity.listCarriageDirections");
</code>```

and I decided to move string CarriageRouteEntity.listCarriageDirections to constant string. After quick fix I created something like this:

```<code>@NamedQueries({
        @NamedQuery(name = CarriageRouteEntity.LIST_CARRIAGE_DIRECTIONS, query = "just query ...") })
public class CarriageRouteEntity {
    public static final String LIST_CARRIAGE_DIRECTIONS = "CarriageRouteEntity.listDirections";
    // ...
}
</code>```

so now I call it like this:

```<code>entityManager.createNamedQuery(CarriageRouteEntity.LIST_CARRIAGE_DIRECTIONS);
</code>```

And here I started to wondering where should I put named queries constants. Is entity class good place for this? Maybe I should create new class with these constants like

```<code>public class CarriageRouteEntityNamedQuery {
        public static final String LIST_CARRIAGE_DIRECTIONS = "CarriageRouteEntity.listDirections";
}
</code>```

but if another programmer will try to create named query will he knew where to look at it? What are your opinions? How to organize these constants? Maybe instead of creating CarriageRouteEntityNamedQuery class I should create enum and add method to entity CarriageRouteEntity called getNamedQuery() which will tell another programmer in which enum he/she should look for constants?

Body:
Is there a reason you are avoiding using an Enum for this?

That is:

    public enum NamedQueryEnum {
       LIST_CARRIAGE_DIRECTIONS("CarriageRouteEntity.listCarriageDirections"),
       LIST_DESTINATIONS("DestinationEntity.listDestinations");
       // additional query names get added here

       private String queryName;

       private NamedQueryEnum( String queryName) {
          this.queryName= queryName;
       }

      public Query getQuery(EntityManagager entitymanager) {
          return entityManager.createNamedQuery(entityManager.createNamedQuery(queryName));
      }
   }

Then your call would be:

NamedQueryEnum.LIST_CARRIAGE_DIRECTIONS.getQuery(entityManager));


问:
Graph data structures and journal format for mini-IDE
Background:

I am writing a small/partial IDE. Code is internally converted/parsed into a graph data structure (for fast navigation, syntax-check etc). Functionality to undo/redo (also between sessions) and restoring from crash is implemented by writing to and reading from journal. The journal records modifications to the graph (not to the source).

Question:

I am hoping for advice on a  decision on data-structures and journal format.

For the graph I see two possible versions:

 g-a Graph edges are implemented in the way that one node stores references to other nodes via memory address

 g-b Every node has an ID. There is an ID-to-memory-address map. Graph uses IDs (instead of addresses) to connect nodes. Moving along an edge from one node to another each time requires lookup in ID-to-address map.

And also for the journal:

 j-a There is a current node (like current working directory in a shell + file-system setting). The journal contains entries like "create new node and connect to current", "connect first child of current node" (relative IDs)

 j-b Journal uses absolute IDs, e.g. "delete edge 7 -> 5", "delete node 5"

I could e.g. combine g-a with j-a or combine g-b with j-b. In principle also g-b and j-a should be possible.

[My first/original attempt was g-a and a version of j-b that uses addresses, but that turned out to cause severe restrictions: nodes cannot change their addresses (or journal would have to keep track of it), and using journal between two sessions is a mess (or even impossible)]

I wonder if variant a or variant b or a combination would be a good idea, what advantages and disadvantages they would have and especially if some variant might be causing troubles later.

答:
There are 2 common data structures to represent graph(s): Adjacency Lists and Adjacency Matrices. They are listed here with their time/space complexities. Choose the one that's most appropriate based on the (estimated) complexity/density of your graph and the operations you expect to do on it most.

In my experience, I've always preferred a directed adjacency matrix (2D array of bool or float storing the existence or weight of the edge).

It's dead simple to write/reason about.

I've never had the need to add/remove vertices after initial construction time.

The most common operation for my graphs is almost always querying, and that is O(1).

I haven't had graphs large enough to worry about space.

That said, they have the same interface, so they're swappable.

ContentLicense: CC BY-SA 3.0


问:
Design pattern for overlapping actions and animations?
Is there a design pattern for dealing with overlapping UI actions and animations? A few examples:

Let's say I have an interactive table row that expands to reveal an extra control when the user clicks on it, and vice versa if they click on it again. If the user clicks on the row while the expand animation is in progress, I want it to stop animating and shrink back to its original size from the place where it stopped.

I have a set of rows from example 1 inside a group. When the last row is deleted, I want the group to shrink and then remove itself in a callback. However, while the group is shrinking, the user could still add another row to it. If that happens, I want the group to stop shrinking, expand to the correct size, and add the row.

What if I have a sorting function for the UI in example 2? If the user clicks on the sort button, the rows shuffle and animate into their new positions. However, I still want the user to be able to click on table rows, delete rows, and do everything else that my UI allows. The UI should behave sensibly, with the shuffle animation taking precedence.

You could automatically fast-forward all animations for a UI element when a new action is performed on it, and/or block user input in all animating UI elements. But that seems inelegant to me. As a user, I really admire UIs that don't stutter or block me from doing what I want — UIs, in other words, that behave like real objects — and I'd like to do the same in my own applications.

It seems to me that you'd need to have constraints for each action/animation in order to make this a robust system. For example, you might need to ensure that any changes to your data/state/model happen only in the callback to your animation, not before. In example 2, you can't delete the group in your model as soon as the user clicks the button to delete the last row; it has to be done at the end of the animation, and at the end of the animation only. (Otherwise, if the user decides to add another row during the delete animation, reverting the group delete would be very difficult.) You might also need to design the animation system in such a way that if two animations from two different actions overlap, any mutually exclusive properties would continue animating as before. (In other words, if the user sorts the table while a row is expanding on click, the width expansion should not stop just because the row is moving to its new position.) And what about starting defaults for each animation? If a row fades out when deleted, and then another action implicitly cancels the delete, the fade out should stop and animate back in, even though the other action might not necessarily know about it.

There's also the higher-level issue of animations (visual property changes) vs. actions (sequences of events, with potential model changes, that include animations). In example 2, "delete last row" is clearly an action, since the end result is that a group gets removed. However, in most UI libraries, you'd add the callback to the animation, conflating the two. This is also an issue in games. If I need to trigger a grenade throw after my character's throw animation finishes, how do I represent that in my code? How do I place the grenade throw on my timeline without mixing model and view code, while still allowing the animation to slow down and speed up based on external factors?

The more I think about this, the more my head hurts, and the more I'm convinced that somebody has already thought this through a lot more carefully than me. Any ideas?

(At the moment, I'm mostly interested in this for web UI, but I'm also interested in a general approach for my future, non-web projects.)

答:
You do want to attach animations to table rows while keeping their interaction capabilities untouched. A decorator fits in here: it'll manage the animation, while forwarding user interaction events to the decorated object. Note that the animation by itself isn't important here, and it'd suffice for it to be a (mere) parameter of the decorator object (thus letting us to reuse the same decorator class with arbitrary animations). Also, this way you can have an arbitrary number of animations simultaneously active over the same row, just by nesting decorators; the visual result is another story :)

If we take a step back and look for the big picture, though, even from the point of view of the user interface animations are only details -if well more or less tricky to deal with, and definitely of great relevance in order to provide a good user experience. But they aren't the focus. A generic scheme could be like this:

The user asks the system for an action to be performed, by means of whatever predefined input event.

The system schedules the user's command. Immediate execution should not be assumed here, unless explicit requirement.

The system executes the user's command, and this takes an arbitrary amount of time and tasks (between whom animations can be counted) to be performed. Here, the system can (begin to) execute commands sequentially or concurrently, depending an the scheduler and the dependencies between the requested actions.


问:
Should I change the name of the WTFPL?
I'm using the WTFPL in my personal projects that I have published on GitHub.

Currently I'm using the license verbatim, but I have a suspicion that I shouldn't be leaving the third line:

```<code>Copyright (C) 2004 Sam Hocevar <sam@hocevar.net>
</code>```

in there, and instead should use my name instead of Sam's.

But the license is very confusing about this.

Half of the WTFPL site is about the WTFPL itself, so I thought that copyright statement might refer to a copyright on the license text itself, and not on the project that is using the license.

However, the site also says:

Everyone is permitted to copy and distribute verbatim or modified copies of this license document, and changing it is allowed as long as the name is changed.

So would I have to change the name from "WTFPL" to something like "WTFPL-Domenic"?

答:
I think Ishmaeel's answer put me on the right track, by citing the WTFPL FAQ page.

The correct form for a WTFPL v2 LICENSE.txt is

```<code>Copyright © 2014 Domenic Denicola <domenic@domenicdenicola.com>
This work is free. You can redistribute it and/or modify it under the
terms of the Do What The Fuck You Want To Public License, Version 2,
as published by Sam Hocevar:

        DO WHAT THE FUCK YOU WANT TO PUBLIC LICENSE
                    Version 2, December 2004

 Copyright (C) 2004 Sam Hocevar <sam@hocevar.net>

 Everyone is permitted to copy and distribute verbatim or modified
 copies of this license document, and changing it is allowed as long
 as the name is changed.

            DO WHAT THE FUCK YOU WANT TO PUBLIC LICENSE
   TERMS AND CONDITIONS FOR COPYING, DISTRIBUTION AND MODIFICATION

  0. You just DO WHAT THE FUCK YOU WANT TO.
</code>```

As explained in the FAQ, this includes a copyright block at the top for the work, which then references the full, unmodified, original text of the WTFPL, included directly below.

The WTFPL itself includes a copyright line for itself, which must not be modified, as doing so would imply claiming copyright for the text of the WTFPL.

You can also just leave the copyright block for the work out. Several WTFPL-using projects seem to do this, often by distributing a COPYING file that is simply the verbatim text of the WTFPL:

libcaca

lolengine

monkeysay

I still think this is rather confusing, because this kind of practice does not appear in any other LICENSE.txt's I've seen around the internet. All MIT or BSD-licensed projects only seem to include a copyright block for the work, and not for the MIT or BSD license itself. (Indeed, I see no indication of who wrote those licenses.) Examples: 1, 2, 3, 4.

One attempt to address this seems to have been the WTFPL v3. I appreciate the spirit of that, although the guidance there around separate COPYING.txt vs. LICENSE.txt files didn't exactly help clarify the situation.

Title: Should I change the name of the WTFPL?

Body:
I think Ishmaeel's answer put me on the right track, by citing the WTFPL FAQ page.

The correct form for a WTFPL v2 LICENSE.txt is

Copyright © 2014 Domenic Denicola <domenic@domenicdenicola.com>
This work is free. You can redistribute it and/or modify it under the
terms of the Do What The Fuck You Want To Public License, Version 2,
as published by Sam Hocevar:

        DO WHAT THE FUCK YOU WANT TO PUBLIC LICENSE
                    Version 2, December 2004

 Copyright (C) 2004 Sam Hocevar <sam@hocevar.net>

 Everyone is permitted to copy and distribute verbatim or modified
 copies of this license document, and changing it is allowed as long
 as the name is changed.

            DO WHAT THE FUCK YOU WANT TO PUBLIC LICENSE
   TERMS AND CONDITIONS FOR COPYING, DISTRIBUTION AND MODIFICATION

  0. You just DO WHAT THE FUCK YOU WANT TO.

As explained in the FAQ, this includes a copyright block at the top for the work, which then references the full, unmodified, original text of the WTFPL, included directly below.

The WTFPL itself includes a copyright line for itself, which must not be modified, as doing so would imply claiming copyright for the text of the WTFPL.

You can also just leave the copyright block for the work out. Several WTFPL-using projects seem to do this, often by distributing a COPYING file that is simply the verbatim text of the WTFPL:

libcaca

lolengine

monkeysay

I still think this is rather confusing, because this kind of practice does not appear in any other LICENSE.txt's I've seen around the internet. All MIT or BSD-licensed projects only seem to include a copyright block for the work, and not for the MIT or BSD license itself. (Indeed, I see no indication of who wrote those licenses.) Examples: 1, 2, 3, 4.

One attempt to address this seems to have been the WTFPL v3. I appreciate the spirit of that, although the guidance there around separate COPYING.txt vs. LICENSE.txt files didn't exactly help clarify the situation.

ContentLicense: CC BY-SA 4.0


问:
Custom class for monetary amount (money value) instead of BigDecimal
On StackOverflow I found multiple advices to stick with BigDecimal in Java instead of reinventing the wheel.

Despite that, I decided to create my custom class, and I would ask if that was a good idea and pros or cons about my design in comparsion to BigDecimal. The reasons to choose custom implementation and characteristic of my design are:

no double/float constructors like in BigDecimal (risk of mistake) - long internally with 8 decimal places - this restrics min/max to ~10 bilion but system is cryptocurrency-targeted so typical values are small.

no difference in "0.0" and "0.00" as BigDecimal have

simple SQL compatibility by BIGINT column

hard connection to currency object/code - cannot create amount wihtout currency and also cannot do arthimethic/comparsion of two values in different currencies

Control of creation possible values to not overflow long (-10 bilion to 10 bilion)

internal overflow protection on computations

Do you think that those reasons as good to choose custem implementation instead of BigDecimal?

To minimize risks I have cover very lot of situations by unit test and also use BigDecimal for initial conversion from string:

```<code>BigDecimal decimal = new BigDecimal(value);
... check MIN/MAX allowed values ...
BigDecimal multiplied = decimal.multiply(new BigDecimal(String.valueOf(DECIMAL_DIVIDER)));
long internalResult = multiplied.toBigInteger().longValue();
return new Amount(internalResult, cryptoCurrency.getInternalCode());
</code>```

答:
Your reasons for creating a custom class are perfectly valid. If your system was only working with a single currency, the argument for creating a custom class would be much weaker. But with multiple currencies, I think a custom class is almost a must.

Note that your custom class could use a BigDecimal internally to hold the amount, if it was a good match for what you actually need to do. If a long matches your model better, then go ahead with that.


问:
Trying to get a better understanding of object-oriented design's performance pitfalls
I'm currently in a high-performance computing class taught in C++. Usually, I do work in C#, meaning everything is taken care of for me, and optimization comes behind maintainability and higher-level features. It's like... a nice productivity furnace that keeps me nice and warm in the programming project winter at the expense of my CPU cycle/cache miss electricity bill. However, now that I'm in C++ and efficient algorithm land, that stuff takes a back seat to optimization.

Since most of my work has been in C#, object-oriented programming is sort of my style. However, I have been reading/hearing more and more about how object-oriented code is an enemy of performance. As my understanding of software architecture shifts from being exclusively about class structure and encapsulation to understanding how things are disposed of from L1 cache and pipelining, I'm trying to understand the real reasons why object-oriented design (especially as it applies to C++) causes waste of hardware resources. Can you guys give me a few basic reasons why it impacts computer performance? I know there are other debates about OOP, but I'd like to just keep it to performance on a hardware and algorithmic level.

答:
Many of the OOP's performance problems come from indirection caused by inheritance and virtual methods. The virtual methods are problematic because:

They take more time because of virtual table lookup

Cannot be properly optimized, eg. using inlining for example. Or at least it is too hard to do it.

In some languages, they are forced to be reference types, so when you have many of them, they are scattered in memory instead of continuous block, hurting cache.

If you remove this, you will loose major point of using OOP, like modularity or extensibility,  but you will gain a performance. The major advantage of C++ (especially compared to Java and C#) is you can pick where you want this indirection and where you want non-OOP way of doing things. You could do this in C#, but it is not that nice and easy as in C++.


问:
Practical Use of Depency Injection (IoC) Container
I am creating a MVC-ish framework in PHP. I am trying to implement a DI Container to allow the creation of controller objects (among others).

My MVC framework is pretty typical. Each module (or component if you wish) has a controller responsible for executing requests. These module controllers typically extend a base Controller class. All controllers will accept Request and Response objects as arguments.

The confusion occurs because some controllers may need different arguments in order to function. For example: Many controllers will need a Database object; Controllers which send mail may need a Mailer object; while a controller which logs data may need a Log object. The DI Container will contain the recipes for creating all these controllers.

My front controller needs to be able create any of these controller objects, as specified by a request. Furthermore, each controller needs to be able to create any other controller.

How do I get my front controller and module controllers to access the DI Container in a way that doesn't result in a dependency on the DI Container by each controller?

I actually don't mind if the front controller is dependent on the container, I am more concerned about the module controllers.

Thanks,

答:
You're going to have to have that dependency on the DI container somewhere. If it's the front controller, fine, but make sure that the front controller is then the single point of origin for all other controllers. All controllers should be created here.

Your DI Container should be clever enough to resolve dependencies to an unlimited depth. Any dependency a controller might have will get resolved by the container and injected into the controller. If any of those objects also have dependencies they should also get resolved by the container.

In my opinion, this is a good approach for several reasons. It gives you a way of removing calls to service locators or factories. In any class that uses the framework, you'll just need to worry about what that class is doing, and you can safely assume that everything it need will be provided. The other benefit is that you can share stuff across components. Your controller and a different component can reuse the same instance of a db repository or something like that. And of course, there's the testability that DI brings.


问:
Correct alignment when outcommenting code
Suppose I have some code

```<code>void some_block(void)
{
    some_statement_1();
    some_statement_2();
    some_statement_3();
}
</code>```

Now I wish to out-comment statement #2, but here I never can find a way where it feels right. Usually I will do the following:

```<code>void some_block(void)
{
    some_statement_1();
//    some_statement_2();
    some_statement_3();
}
</code>```

But now we got what looks like extra indentation of statement #2, yet it is arguable whether the indentation is still "correct". Alternatively we could do:

```<code>void some_block(void)
{
    some_statement_1();
    //some_statement_2();
    some_statement_3();
}
</code>```

This looks a bit better, yet still somehow also wrong. However the following just looks misplaced:

```<code>void some_block(void)
{
    some_statement_1();
  //some_statement_2();
    some_statement_3();
}
</code>```

How do you outcomment code and keep "correct" indentation?

Update

It seems most people who have provided answers did not answer my question, but simply state that it is bad practice to leave dead code around. While I completely agree with that, that was not the point of the question.

Right now I am facing a case of example where I have 5 helper functions, that manage 5 similar but slightly different structs for me. I use these helper functions to make my code easier to read.

But, at the moment (and for the next month probably) one of the structs are not going to be used. And I cannot commit anything which causes compiler warnings, so I have to outcomment that part of the code and commit it like that.

Also I forgot this last variant, which I think just looks plain wrong:

```<code>void some_block(void)
{
    some_statement_1();
//  some_statement_2();
    some_statement_3();
}
</code>```

答:
I hit Ctrl-/ and whatever my IDE does, I do that. Color highlighting tells me to ignore that line anyway (or to pay attention, depending on my context).

Before then, I used to replace spaces with slashes, keeping alignment:

```<code>block {
    codeline1;
//  codeline2;
    codeline3;
}
</code>```

Obviously, just prepending slashes for flush-left code.

ContentLicense: CC BY-SA 2.5

Body:
I hit Ctrl-/ and whatever my IDE does, I do that. Color highlighting tells me to ignore that line anyway (or to pay attention, depending on my context).

Before then, I used to replace spaces with slashes, keeping alignment:

block {
    codeline1;
//  codeline2;
    codeline3;
}

Obviously, just prepending slashes for flush-left code.


问:
What is the historical reason why Python uses the double underscore for Class Private members
In python a module private function or variable is named _foo.
If it is private to a class it is names __foo,
The mechanics behind how these work are different, however that is of little relevance to the question.

Why, during the design of the Python language was the double underscore characters chosen for class private members?
Why not single underscore, like for module private?
Why not some other character that is more visible? (Differentiating between _ and __ is hard).

I'm sure there is some history here, but I'm having trouble finding it, because all I find are tutorials telling me what it means, rather than why it is that way.

答:
Python Enhancement Proposal (PEP) 8 explains the intended meaning behind single- and double-underscore names, among other conventions.  Like many of the early PEPs, it represents Guido van Rossum's preferences, and as Python's acknowledged Benevolent Dictator for Life, his preferences are generally followed by the Python community.

The use of double underscores to indicate "magic" words goes at least as far back as the C preprocessor, which used that convention starting in the 1970s (e.g., __FILE__, __LINE__).  It did so because there were no symbols that were off-limits to the preprocessor, so a rarely-used naming pattern (multiple underscores and upper case words) virtually ensured a lack of conflicts.


答:
When doing any kind of software design, it is important to be aware of "Premature Optimization". The first rule is to be correct. Only after you can be assured of correctness through a complete set of unit tests, should you consider performance.

Performance is achieved through testing. Test your algorithms once they are functional to determine if additional performance is required.

Title: Trying to get a better understanding of object-oriented design's performance pitfalls

Body:
I'm currently in a high-performance computing class taught in C++. Usually, I do work in C#, meaning everything is taken care of for me, and optimization comes behind maintainability and higher-level features. It's like... a nice productivity furnace that keeps me nice and warm in the programming project winter at the expense of my CPU cycle/cache miss electricity bill. However, now that I'm in C++ and efficient algorithm land, that stuff takes a back seat to optimization.

Since most of my work has been in C#, object-oriented programming is sort of my style. However, I have been reading/hearing more and more about how object-oriented code is an enemy of performance. As my understanding of software architecture shifts from being exclusively about class structure and encapsulation to understanding how things are disposed of from L1 cache and pipelining, I'm trying to understand the real reasons why object-oriented design (especially as it applies to C++) causes waste of hardware resources. Can you guys give me a few basic reasons why it impacts computer performance? I know there are other debates about OOP, but I'd like to just keep it to performance on a hardware and algorithmic level.


问:
JSON Library - Jackson or Play Framework?
Working on a Java and Scala code-base, there's a debate about whether to use Java's Jackson JSON or the Play Framework's JSON Library.

After reading the Play JSON Docs, as well as Chapter 9 (JSON) of Play for Scala, I also ran through an example from Mykong on Jackson.

Based on looking at a few simple examples, Play's JSON Library seems like the superior choice due to, overall, its Functional Programming Approach:

Providing compile-time safety when parsing JSON with Option/JsResult data types.

As a result of the above, higher order functions (map/flatMap) are available and provide power and succintness

As I understand, Jackson parses via the typical try/catch paradigm. Dealing with JSON errors at compile-time(Play) v. run-time(Jackson) is a no brainer

Bottom line - Play's JSON library uses a functional programming approach that results in code that is easier to reason about than the Jackson library.

Overall, the choice seems clear to me. Am I missing any pros/cons for either library?

答:
It's important to note, first of all, that the Play ScalaJSON library uses Jackson. In effect, it is a wrapper around the parsing/formatting engine provided by Jackson, so it's a really good alternative. It provides a nice API around a very fast engine.

Now, the library I'd pick today for any JSON work would be Argonaut. Argonaut is a true functional library from the ground up, and I like many of its decisions.

I don't really see any point in picking Jackson itself, unless you need the most speed you can get.


问:
Is my understanding of abstract datatypes correct?
After reading lots of pages on various sites, I came to the conclusion that abstract datatype helps to separate the use of datastructure from its implementation. We can easily map the data into a datastructure by using an already available abstraction. And this abstraction is called ADT. Please tell me if I have understood this correctly. Also if you can give a small example, it will be very helpful. If you prefer to give any code in your example, C or Python would be helpful for me.

Addition: They are a very special implementation of data abstraction. What separates them from other instances of abstractions is that ADTs are theoretical constructs. Theoretical constructs that help map or represent data in a desired data structure. They have attributes or operations associated with them. These operations may be applied on the data that has been mapped into the ADT. How the data is actually stored inside the ADT or how the operations work are kept hidden.

EDIT: I had previously said, "ADT is like the blueprint of a datastructure". A few of the answers have explained why it's not. I didn't have a clear comprehension of what a 'blueprint' is and that was the reason for using the term. So, I've now removed it from my original text.

答:
Unfortunately there is a lot of confusion about Abstract Data Types and Objects.

I think that the OP is using the phrase "abstract datatype" as if it meant "data abstraction" or just in the general sense of defining abstract data.

Abstract Data Types are a very specific implementation of Data Abstraction, and is best realized in the language ML. Objects are another form of Data Abstraction.

You can read more about it in my papers here:

http://www.cs.utexas.edu/~wcook/publications.htm#oo


问:
enum for Java reference types
I need a simple enum declaring the Java reference types, as:

```<code>public enum ReferenceType {
    STRONG, SOFT, WEAK, PHANTOM;
}
</code>```

Does such enum exist somewhere in the Java API or a general utility library such as Guava ? I have not been able to find it in either place, although I found third party projects that declare it (e.g. google-guice: RefrenceType).

I just try to avoid polluting my project with silly classes/enums that may exist somewhere else.

Since asking this question, I found that Guava in fact used to have this, but they dropped it: Issue 1662:  Feature request for enum of reference types

答:
Think in terms of code polution

10-liner

vs

project just included to use a 10-liner.

Title: enum for Java reference types


问:
Why develop free, open source programs?
Why would someone use his own time to develop an open-source project for free and without compensation?</p>

答:
Besides money, of course there is fame -- and then their is learning how something works by building it and constructing it yourself.  Gaining valuable and marketable experience outside your normal work life.  I think Ayende is a good example of this.

As an aside -- generally I've found some of the best, most intuitive projects and frameworks I've worked with to be open source -- I think that people who are truly passionate enough to spend their free time building a project up from scratch or simply maintaining it produce a better product then people who are just grouped together from 9-5.

Title: Why develop free, open source programs?


问:
When is it worthwhile to replace working mature code with frameworks+patterns
Intro/Question

I fear that frameworks in many cases have become a fashion or trend and are being abused. In many ways people are sacrificing speed just because they want to keep up with every single lib that comes out. I am for a more conservative approach that only makes use of new libraries and frameworks when it absolutely makes sense.

Related: When NOT to use a framework

Update/Disclaimer (May 18, 2017)

I've come to the conclusion that rapid application development, ease, and maintainability are the targets. So frameworks (new and old) should be used  provided they help in reaching a final product quicker. Only when special cases exist (actual measurable performance issues) should we switch to custom code... or when the project itself is legacy and the cost of completely rewriting are too high.

Case

We have a Tomcat6 Servlet production that has been ongoing development since 2008 and there are many hours of work behind it. The code is very mature but it does not use any frameworks.

A new team member loves using frameworks and patterns for everything. Except for the love of frameworks, they also love cutting edge new releases and even proposed migrating from Tomcat6 to somethiong newer (JBOSS,GLASSFISH, or TOMCAT8).

I would never move a core production service to a container/server/web-server that just came out.

Not against refactoring code to keep it clean though!

I am against adding frameworks and patterns that add delay to production code servicing thousands of requests per second.

Serialization to stream (JSON/XML) while maintaining backwards compatibility

When a request comes, we produce both XML and JSON documents containing data related to the request params.

Since we maintain backwards compatibility for older clients changes must not break older support. Since we also support both JSON and XML, we make use of the Jackson but also KXML libraries.

For both formats we have 2 different serialization methods that use the streaming API. Except for being faster, I also find it is MUCH more flexible for maintaining backwards compatibility.

I like to use a sysyem of Major and Minor version. All minor changes to the backend that cause changes to the serialized document I add with IF statements in the serialization method. Once quite a few changes have accomulated (over 1 year), we add a new serialization method. So, all requests specifying version=1.00 to 1.99 are sent to serializeJSON1. All requests using version 2 to 2.99 are sent to serializeJSON2.

I've heard the argument that we should use ANNOTATIONS and MAP to objects.
I find this very distastefull as I have read streaming is the fastest.

The streaming API allows you to make necessary changes on the fly while MAPPING would require to store multiple versions of the same data as different objects, or jump through other hoops.

```<code> output.startTag(null, TagTable.PRODUCT);

 output.startTag(null, TagTable.ID);
 output.text(ID);
 output.endTag(null, TagTable.ID);

 output.startTag(null, TagTable.DESCRIPTION);

 if (locale != null && Translations.containsKey(locale) && version >= 1)
     output.text(this.DescriptionURL + "/" + locale);
 else
     output.text(this.DescriptionURL);

 output.endTag(null, TagTable.LONGDESCRIPTION);

 if (version >= 1 && version < 1.5) {
     output.startTag(null, TagTable.POPULARITY);
     output.text(String.valueOf((int) this.pop));
     output.endTag(null, TagTable.POPULARITY);
 } else if (version >= 1.5) {
     output.startTag(null, TagTable.RATING);
     output.text(String.valueOf((int) this.rating));
     output.endTag(null, TagTable.RATING);
 }
</code>```

In the specific 3 cases above I really don't see the point to replace working mature code with frameworks/libs/patterns that may add additional overhead and cost additional development time.

So, when is it worthwhile to replace working mature code with frameworks+patterns??

Comments?

Update: Some benchmarks

For the first two examples posted previously, using REST and HASHMAPs does not make overly that big a difference in performance but does make the code more readable.

Now for the more interesting issue about serialization when used in a hotspot.
Since the actual servlet in question had too much other code I made a toy example to test streaming vs mapping. The code is available at: https://stackoverflow.com/questions/21781540/

By all means test it, change it, run it.

What is very interesting is that the Just in time optimizer in java ends up making the difference negligable over time. So, here is how the percentage between mapping and streaming changes the more iterations there are.

```<code>Iter    Stream  Mapping
0       36,71%  63,29%
20      44,75%  55,25%
40      45,65%  54,35%
60      45,95%  54,05%
80      46,24%  53,76%
100     47,09%  52,91%
120     47,09%  52,91%
140     47,37%  52,63%
160     47,64%  52,36%
180     47,92%  52,08%
200     47,64%  52,36%
220     47,92%  52,08%
240     47,92%  52,08%
260     47,92%  52,08%
280     48,19%  51,81%
300     48,45%  51,55%
320     48,45%  51,55%
340     48,45%  51,55%
360     48,45%  51,55%
380     48,45%  51,55%
400     48,45%  51,55%
1000    48,72%  51,28%
2000    49,24%  50,76%
3000    49,24%  50,76%
4000    49,49%  50,51%
5000    49,75%  50,25%
6000    49,75%  50,25%
7000    49,75%  50,25%
8000    49,75%  50,25%
9000    49,75%  50,25%
</code>```

I also re-ran one more time have first 20 iterations more detailed:

```<code>0   39,76%  60,24%
1   41,18%  58,82%
2   40,83%  59,17%
3   40,12%  59,88%
4   40,48%  59,52%
5   40,83%  59,17%
6   40,83%  59,17%
7   40,83%  59,17%
8   40,48%  59,52%
9   40,12%  59,88%
10  41,52%  58,48%
11  42,53%  57,47%
12  42,86%  57,14%
13  42,86%  57,14%
14  43,18%  56,82%
15  43,50%  56,50%
16  43,50%  56,50%
17  43,82%  56,18%
18  43,82%  56,18%
19  43,82%  56,18%
20  44,75%  55,25%
</code>```

After 10,000 iterations (or calling JSON generation code 1000 times) here is the screenshot from VisualVM profiling (visualVM snapshot NPS file):

So, if this optimization behavior holds up in Tomcat servlets as well, it means there really is no point NOT to use mapping (and many other convenience functions/libs since the JVN will optimize over time).

Conclusions

Based on the answers/comments, I think at the end of the day whether to rewrite working production code is affected by business requirement, and specific cost-benefit analysis for each project.

Based on the benchmarking, it turns out avoiding some libs/frameworks may make no difference in the long run due to JIT JVM optimizations.

Update: After leaving code running all night

After 275,137 iterations and approximately 30,000 MS:

```<code>Mapping -   19,80%
Streaming -  80,20%
</code>```

I really wonder what JIT optimizations happen here and whether the behavior holds for a servlet.

答:
Ugh. Some points:

"I have read it is fastest". Don't be a cultist. Think for yourself. Measure for yourself. Personally, if you're generating XML by hand, I would question your sanity.

who knows what bugs lurk It is foolish and shortsighted to fear what you do not know. This leads to "not invented here" syndrome and quickly being passed by programmers who had the courage to learn better tools.

frameworks hinder performance Runtime performance is very often cheap. Programmer time is not. The trade off here is that these frameworks may add a slight performance penalty in exchange for saving you a bunch of time writing and maintaining the code. In the XML example, if you had used annotations and a serialization framework, you wouldn't have to write and test your own XML formatter (read: cost your company all that money).

Look - code that is done and tested is good. And certainly, adopting a framework because "that's what you're supposed to do" is a good way to make bad software. But these examples strike me as simply you making excuses to avoid change. Yes, change is scary. Yes, change can lead to bugs. But change is necessary to eliminate inefficiency, and improve your ability to maintain and extend your code.


问:
Is Python suitable for a statistical modeling application looking over thousands of past events?
I'm currently working on a project with a partner where we analyze large datasets of past sporting events. There are approximately 30,000 events per year and we have historical data for five years. Thus, we're looking at analyzing 150,000 events.

I wrote our first version in Python with a heavy reliance on Pandas (great tool, by the way). However, each time I add a "factor" or calculation to the process it slows down by quite a bit. Simply put, it can read all the various data files and data queries we need at a rate of 25-events-per-second.

The problem is once I start working with the data, it drops fast. If I add a simple calculation, it drops to 24... and each calculation after that it drops again.

With just 10-12 "factors" calculated from the data (we're not talking complex loops or anything crazy), it's now down to 6-events-per-second. ... and we're barely scratching the surface. At this rate, it'll take this thing days to work through all 150k events!

I've optimized our data queries, flat file reads etc. Those really aren't the issue. I can live with doing 15-20 events per second. However, I can't live with such drastic slowdowns each time a new factor calculation is added.

I've read a lot where Python as an interpreted language is slow etc., but my question to the experts out there - what language should this project be done in?

EXAMPLE...

One of the key "DataFrames" I am using through Pandas is fairly large. 350 rows x 70 columns, as an example. Even when trying to simply multiply one column's value by another...

```<code> data['value'] = data['col1'] * data['col2']
</code>```

...I see what I could consider significant drop in performance. It's very puzzling, and very frustrating. I understand this is a large set of data, but I can't believe this is anything so crazy that Python would be slowing to a crawl.

If I just read the data files and do no calculations on them at all, it reads 67 events in 2.807 seconds. If I add one simple calculation where I execute code like the example above, it slows to 2.877 seconds. Based on our research, we're needed to add upwards of 100 calculations on the data.... so 7 seconds worth of slowdown? Seems too hard to believe.

答:
I work on a platform that uses Python for testing and executing market data.
For just the equity pricing there are roughly ~98,000 events for each equity
per year, so when dealing with an individual stock have a similar profile for
our data sets.

(The aforementioned platform is Quantopian, https://quantopian.com.)

We also use pandas for the majority of our data structures, and though it is tough to really compare without also comparing the machines used, the number of calculations done per event... we are able to process a few orders of magnitude more events
per second; so there may not be reasons to give up on pandas, yet.

(The backtester used by our site is opensourced, https://github.com/quantopian/zipline
if you'd like to see how we use pandas throughout; of course, we still have bottlenecks to hammer out, too!))

From what I can see with how you are using your data set, this tip may help.

If possible, avoid writing your calculations back into your dataset DataFrame.

A corollary to that is, if possible, avoid indexing in inner loops.

While powerful and expressive, the indexing of a DataFrame has a performance penalty; much like accessing into a Python dictionary will create a lookup penalty.

Writing the data into the DataFrame will be more expensive.
So if your program can just use the Series that is returned by multiplying those
two columns, you may see some benefit from assigning that Series to its own variable
instead of putting it back into the DataFrame.

To illustrate, below is some excerpts from an IPython notebook that step by step
gets the pandas DataFrame values closer and closer to using a raw np.ndarray.
This following is not intended to be a cookbook, but to show where both writing and indexing into the DataFrame can hurt performance.
Also, I wouldn't be surprised if there is something in the pandas API that I am unaware of, which makes assignment of the column much more performant, which would invalidate my advice.

```<code>In [1]:
# Create a DataFrame with 3 columns and 350 random values each.
data = pd.DataFrame(randn(350, 3), columns=['col1', 'col2', 'value'])

In [2]:
# Time original example
%timeit data['value'] = data['col1'] * data['col2']
10000 loops, best of 3: 170 µs per loop

In [3]:
# Time without writing the example back into the DataFrame
# The value variable will be a pd.Series
%timeit value = data['col1'] * data['col2']
10000 loops, best of 3: 43.9 µs per loop

# Extract the pd.Series before inner loop
col1 = data['col1']
col2 = data['col2']

In [25]:
# Time without writing the example back into the DataFrame
# The value variable will be a pd.Series
%timeit value = col1 * col2
10000 loops, best of 3: 32.3 µs per loop

In [4]:
# Time with using the underlying numpy arrays.
# The value variable will be a np.ndarray
%timeit value = data['col1'].values * data['col2'].values
100000 loops, best of 3: 15.9 µs per loop

In [5]:
# Extract the numpy arrays before inner loop
col1_v = data['col1'].values
col2_v = data['col2'].values

In [6]:
# Time just the multiplication of two np.ndarrays
%timeit col1_v * col2_v
1000000 loops, best of 3: 1.5 µs per loop
</code>```

Body:
I work on a platform that uses Python for testing and executing market data.
For just the equity pricing there are roughly ~98,000 events for each equity
per year, so when dealing with an individual stock have a similar profile for
our data sets.

(The aforementioned platform is Quantopian, https://quantopian.com.)

We also use pandas for the majority of our data structures, and though it is tough to really compare without also comparing the machines used, the number of calculations done per event... we are able to process a few orders of magnitude more events
per second; so there may not be reasons to give up on pandas, yet.

(The backtester used by our site is opensourced, https://github.com/quantopian/zipline
if you'd like to see how we use pandas throughout; of course, we still have bottlenecks to hammer out, too!))

From what I can see with how you are using your data set, this tip may help.

If possible, avoid writing your calculations back into your dataset DataFrame.

A corollary to that is, if possible, avoid indexing in inner loops.

While powerful and expressive, the indexing of a DataFrame has a performance penalty; much like accessing into a Python dictionary will create a lookup penalty.

Writing the data into the DataFrame will be more expensive.
So if your program can just use the Series that is returned by multiplying those
two columns, you may see some benefit from assigning that Series to its own variable
instead of putting it back into the DataFrame.

To illustrate, below is some excerpts from an IPython notebook that step by step
gets the pandas DataFrame values closer and closer to using a raw np.ndarray.
This following is not intended to be a cookbook, but to show where both writing and indexing into the DataFrame can hurt performance.
Also, I wouldn't be surprised if there is something in the pandas API that I am unaware of, which makes assignment of the column much more performant, which would invalidate my advice.

In [1]:
# Create a DataFrame with 3 columns and 350 random values each.
data = pd.DataFrame(randn(350, 3), columns=['col1', 'col2', 'value'])

In [2]:
# Time original example
%timeit data['value'] = data['col1'] * data['col2']
10000 loops, best of 3: 170 µs per loop

In [3]:
# Time without writing the example back into the DataFrame
# The value variable will be a pd.Series
%timeit value = data['col1'] * data['col2']
10000 loops, best of 3: 43.9 µs per loop

# Extract the pd.Series before inner loop
col1 = data['col1']
col2 = data['col2']

In [25]:
# Time without writing the example back into the DataFrame
# The value variable will be a pd.Series
%timeit value = col1 * col2
10000 loops, best of 3: 32.3 µs per loop

In [4]:
# Time with using the underlying numpy arrays.
# The value variable will be a np.ndarray
%timeit value = data['col1'].values * data['col2'].values
100000 loops, best of 3: 15.9 µs per loop

In [5]:
# Extract the numpy arrays before inner loop
col1_v = data['col1'].values
col2_v = data['col2'].values

In [6]:
# Time just the multiplication of two np.ndarrays
%timeit col1_v * col2_v
1000000 loops, best of 3: 1.5 µs per loop


答:
No it wont exist mostly because enums are itself available in their most simplified form in java.lang package and can be used as per the user's wishes. So even if there will be an API for enum, it won't be of much help

For further reading on enums go to
http://docs.oracle.com/javase/tutorial/java/javaOO/enum.html

Title: enum for Java reference types

Body:
I need a simple enum declaring the Java reference types, as:

```<code>public enum ReferenceType {
    STRONG, SOFT, WEAK, PHANTOM;
}
</code>```

Does such enum exist somewhere in the Java API or a general utility library such as Guava ? I have not been able to find it in either place, although I found third party projects that declare it (e.g. google-guice: RefrenceType).

I just try to avoid polluting my project with silly classes/enums that may exist somewhere else.

Since asking this question, I found that Guava in fact used to have this, but they dropped it: Issue 1662:  Feature request for enum of reference types


答:
Design Patterns

As Rucamzu mentions a decorator pattern seems to fit. A visitor pattern seems like it also might fit as the object that runs the animation visits the DOM element multiple times throughout the course of an animation to update a DOM elements properties/styling to create the visual change.

Post spelling out the differences between the patterns.

Implementation within a Web UI (assuming JS/CSS/HTML)

There are several libraries that feature concurrent/successive asynchronous operation queuing. What to typically look for(in whatever target client one is programming for) should include:

provide chaining functionality (helpful for move the player arm then throw the grenade)

firing events/callbacks on a very granular level and also on a group based level (to know when the arm finishes and when the grenade animation finishes and when the grenade lands so that one can run the damage calculations and then)

reverse their single actions or group actions (helpful for your open/close animations)

There's a couple of libraries that I could consider.

Greensock TweenMax/TimelineMax

Greensock has one of the most robust animation packages out there. It has options for being lightweight and paired back or full blown with its numerous plugins (and somewhere in between). TweenMax allows for single animations and TimelineMax allows for the more advanced chaining/sequences.

CreateJS

If there's crazy animation it might be best off being done using canvas. There's a library that has 2d tweening capabilities that can be backed by WebGL if a browser has it. Also supports sprite sheeting for more in-depth animations.

Implementation as jQuery Deferred objects/promises.

Deferred objects can take an arbitrary time to succeed. Most AJAX requests in jQuery implement the deferred objects for success and fail. Also these actions can be immediate as well. This helps for chaining multiple animations and function calls and asynchronous operations. I don't believe that Deferred's can reverse their operations nor can they be rerun again, new instances need to be created, but can be extremely powerful.

Selection will probably be based on how intense the animations need to be as well as the browsers and devices that need to be supported.

Web UI implementation recommendation

Even though you aren't probably building a flash project, they have been known for complicated animation in their day. The top two items above have roots from the flash world of things, so they've been around for more than a few years. I've implemented almost every flash project for a 6 year period with Greensock's library. His documentation is solid and there's plenty of examples too: Greensock JS getting started.

Title: Design pattern for overlapping actions and animations?

Body:
Is there a design pattern for dealing with overlapping UI actions and animations? A few examples:

Let's say I have an interactive table row that expands to reveal an extra control when the user clicks on it, and vice versa if they click on it again. If the user clicks on the row while the expand animation is in progress, I want it to stop animating and shrink back to its original size from the place where it stopped.

I have a set of rows from example 1 inside a group. When the last row is deleted, I want the group to shrink and then remove itself in a callback. However, while the group is shrinking, the user could still add another row to it. If that happens, I want the group to stop shrinking, expand to the correct size, and add the row.

What if I have a sorting function for the UI in example 2? If the user clicks on the sort button, the rows shuffle and animate into their new positions. However, I still want the user to be able to click on table rows, delete rows, and do everything else that my UI allows. The UI should behave sensibly, with the shuffle animation taking precedence.

You could automatically fast-forward all animations for a UI element when a new action is performed on it, and/or block user input in all animating UI elements. But that seems inelegant to me. As a user, I really admire UIs that don't stutter or block me from doing what I want — UIs, in other words, that behave like real objects — and I'd like to do the same in my own applications.

It seems to me that you'd need to have constraints for each action/animation in order to make this a robust system. For example, you might need to ensure that any changes to your data/state/model happen only in the callback to your animation, not before. In example 2, you can't delete the group in your model as soon as the user clicks the button to delete the last row; it has to be done at the end of the animation, and at the end of the animation only. (Otherwise, if the user decides to add another row during the delete animation, reverting the group delete would be very difficult.) You might also need to design the animation system in such a way that if two animations from two different actions overlap, any mutually exclusive properties would continue animating as before. (In other words, if the user sorts the table while a row is expanding on click, the width expansion should not stop just because the row is moving to its new position.) And what about starting defaults for each animation? If a row fades out when deleted, and then another action implicitly cancels the delete, the fade out should stop and animate back in, even though the other action might not necessarily know about it.

There's also the higher-level issue of animations (visual property changes) vs. actions (sequences of events, with potential model changes, that include animations). In example 2, "delete last row" is clearly an action, since the end result is that a group gets removed. However, in most UI libraries, you'd add the callback to the animation, conflating the two. This is also an issue in games. If I need to trigger a grenade throw after my character's throw animation finishes, how do I represent that in my code? How do I place the grenade throw on my timeline without mixing model and view code, while still allowing the animation to slow down and speed up based on external factors?

The more I think about this, the more my head hurts, and the more I'm convinced that somebody has already thought this through a lot more carefully than me. Any ideas?

(At the moment, I'm mostly interested in this for web UI, but I'm also interested in a general approach for my future, non-web projects.)


问:
Software Licence Agreement: Does our spec abide by the licence
Can you determine if this Open Source Winforms UI Library licence allows companies to use this code in a commercial software application?

The MIT License (MIT)

Copyright (c) 2011 Sven Walter, http://github.com/viperneo

Permission is hereby granted, free of charge, to any person obtaining
  a copy of this software and associated documentation files (the
  "Software"), to deal in the Software without restriction, including
  without limitation the rights to use, copy, modify, merge, publish,
  distribute, sublicense, and/or sell copies of the Software, and to
  permit persons to whom the Software is furnished to do so, subject to
  the following conditions:

The above copyright notice and this permission notice shall be
  included in all copies or substantial portions of the Software.

THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND,
  EXPRESS OR IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF
  MERCHANTABILITY, FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT.
  IN NO EVENT SHALL THE AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY
  CLAIM, DAMAGES OR OTHER LIABILITY, WHETHER IN AN ACTION OF CONTRACT,
  TORT OR OTHERWISE, ARISING FROM, OUT OF OR IN CONNECTION WITH THE
  SOFTWARE OR THE USE OR OTHER DEALINGS IN THE SOFTWARE.

Licence can be found here

I can see that it gives permission to use the code in commercial products but it is subject to conditions. We intend to use the UI (a Windows 8 looking interface) in a simple application that will convert Civil Engineering survey files from one format to another which maybe sold commercially in the future.

Those in the know, do our intentions fall within the lines of the license rules?

答:
The license you cited is a common open source license. It is one of the 'permissive' type licenses which allows using the code in propriety software.  In short, you're probably fine to use the code in your application.  </p>

<p>That said, this is the internet, I am not a lawyer, I am not your lawyer, this is not legal advice, blah, blah.  </p>

Body:
The license you cited is a common open source license. It is one of the 'permissive' type licenses which allows using the code in propriety software.  In short, you're probably fine to use the code in your application.

That said, this is the internet, I am not a lawyer, I am not your lawyer, this is not legal advice, blah, blah.


答:
You can find one in hibernate ReferenceType though it only contains STRONG, SOFT and WEAK but not PHANTOM.

There are few others ReferenceType in eclipse net4j and Link.Type in true commons. But I think you will be better without them in case you want some modification later.

Title: enum for Java reference types


问:
algorithm to extract "possibilities" from a tree
From a given tree, subsequent trees have to be generated. Nodes can be marked as "variant" in the given tree (the example uses an asterisk to mark the node). All possible combinations between the variants form the resulting trees.

From the following tree:

```<code>- Product
    - Packaging *
        - Small box
        - Heavy box *
            - Eco
            - Non-eco
    - Delivery *
        - Standard
        - Express
</code>```

The following 6 trees should be generated:

```<code>- Product
    - Packaging
        - Small box
    - Delivery
        - Standard

- Product
    - Packaging
        - Small box
    - Delivery
        - Express

- Product
    - Packaging
        - Heavy box
            - Eco
    - Delivery
        - Standard

- Product
    - Packaging
        - Heavy box
            - Eco
    - Delivery
        - Express

- Product
    - Packaging
        - Heavy box
            - Non-eco
    - Delivery
        - Standard

- Product
    - Packaging
        - Heavy box
            - Non-eco
    - Delivery
        - Express
</code>```

Is there an elegant algorithm for this (recursive solution)?

答:
Recursive solution as follows. Essentially you have to walk the tree in depth first order, returning lists of nodes, and finally building a new tree.

From a leaf node, return self.

From a variant node, return a list formed by concatenating the nodes returned by each child, with self inserted at the front.

At the top level, form a set of tuples that are the Cartesian product of all its child nodes. Then for each tuple create a tree that has self as the head and one tuple as each set of branches; return the list of trees.

It sounds complicated, but it's probably less than 50 lines of Ruby. I'm still not convinced that the question is well formed, but this algorithm will produce the given output.


问:
Does anyone have experience with a difficult customer?
We have a reoccurring conflict with one of our larger and strategically important customers.
The company (let's call them "C" for now) sells and distributes technical articles, everything from hardware components to hairdryers, and has more than 400000 products in their catalog.

The product owner, who is also the head of product documentation and internal software at "C", has at some point in the 90's taken a course in software testing, and is now writing "Requirement specifications" as user tests. These are often contradictory and error prone, but she maintains that what she writes is what she want's, until she writes something else (in same imperative but ambiguous and abstract format). Furthermore, she demands a final budget for the project, and is unwilling to work in smaller iterations of budgeting.

I'm looking for hints on how to control the development-process (and our own economy) and still provide the customer with a product that gives the company most value-for-money.
Normally, I'd start a project by identifying goals of the project and business use-cases of the organization - and then deriving scope from those goals, using User-stories. The details (specifications) of how user-stories should be implemented, is decided at specifications prior to the sprint including the respective user-stories. This has repeatedly proven to result in better products and greater ROI for the customers.

Does anyone have experience of knowledge of techniques that can be used to "Reverse engineer" imperative user-tests, or any other input on how to handle the situation?

Historically, she has been allowed to completely dominate the development process, which has blown our budgets and taught her that she is in control of our process. Our management has now asked me to control (and defend) the development process. They told "C" that there will be used no more hours than the agreed budget, regardless of how "done" she (the product owner) feels that we are, which of course will be my leverage. She will become defensive, even aggressive to get things her way - any sound arguments based on professional reference or experience would be of help.

Follow up:

I thought I'd follow up in case anyone stumbled across this post with similar problems:

We have turned the communication around, and are expecting to deliver the next project within budget and on time (I'll edit this post again if hell breaks loose later on).

Initially, I focused on creating trust between me and the Product Owner. That meant choosing the relevant battles, and presenting myself as her tool to get most value for her money. Requirements are still expressed in more or less the same way (although she is open for input about syntax, she is firm about the format: Word Documents and Emails), but we are slowly trading control with visibility regarding the development process.

I managed to persuade her to participate in weekly meetings for project status, backlog grooming and prioritization. Between each meeting, she gets the chance to test the newest revision, which makes her test-feedback what used to be an object for discussion, the most valuable feedback for the backlog grooming and prioritization. By having a head-to-head talk about the feedback from the tests, we're able to "weed out" misunderstandings, contradictions and scope creep before it leaks into development.

The trust between us enabled us to have a constructive talk about each others organizations and the processes and intentions of these, which opened my eyes to quite a big part of the problems being our lack of capacity (professionally, theoretically, and methodically).

The product owner has called management to personally compliment the progress we are making, so I'm calling success on these first steps - but constantly watching the scope and progress, as to not "rest on ones laurels"

答:
There are a lot of red flags jumping out here:

"...larger and strategically important customers"

"These are often contradictory and error prone, but she maintains that what she writes is what she want's"

"They told "C" that there will be used no more hours than the agreed budget, regardless of how "done""

If you have someone who is that unwilling to change AND they are so important a client, you only have a few options:

You could include a massive percentage on your estimates as a contingency (20%? 50%)

You could implement strict change requests where items not originally in the requirements are costed separately.

If these things don't or won't work, then I'm not entirely sure what else you can do.


答:
This sounds like your agile system of working with the stakeholder is almost-but-not-quite working.

Firstly, imperative user stories (you should give an example) are simply more detailed, so you can generate better tests from it. Taking this example shows that they do work, but are brittle in the face of changing customer requirements. If the customer has very hard requirements though, then they are more appropriate. You need to highlight this difference to the customer and decide upon which is the most appropriate for their circumstances.

Second, I guess the problem is the person who writes the requirements is the person who accepts the delivery. There doesn't seem to be a mediating stage to this if the original requirements changed during development (which it appears they do). Now in an agile environment changing requirements are the norm - hence agile! - but the customer needs to understand that you deliver what they asked for, and if they continually change their mind, the overall delivery will not contain much result, seeing as you've spent all your time re-working.

Final budget is obviously something that both sides want, so you need to budget in terms of time - you work for them as much as they want and you will bill them per day. When the budget runs out, that's it, you stop. To make this happen you need to get the customer and your management in a budget meeting to agree this. Its not an uncommon means of limiting budgets, but they need to understand the time limits involved, which in turn should focus their minds on actual delivery rather than the continual keep-working-until-I'm-happy.

Lastly, the big problem you have is really one of habit, people have become used to the statue quo and just need to be brought together to re-establish the boundaries of your collaboration. You must drop the attitude where she is the enemy, or is incompetent. You must work with her, and no doubt she is much more competent than you realise, possibly you've ended up in the state you are because of built-up failings on both sides of the process. So whatever you do, start with a clean slate and an open mind, and you should succeed in fixing this problem.

Title: Does anyone have experience with a difficult customer?

Body:
We have a reoccurring conflict with one of our larger and strategically important customers.
The company (let's call them "C" for now) sells and distributes technical articles, everything from hardware components to hairdryers, and has more than 400000 products in their catalog.

The product owner, who is also the head of product documentation and internal software at "C", has at some point in the 90's taken a course in software testing, and is now writing "Requirement specifications" as user tests. These are often contradictory and error prone, but she maintains that what she writes is what she want's, until she writes something else (in same imperative but ambiguous and abstract format). Furthermore, she demands a final budget for the project, and is unwilling to work in smaller iterations of budgeting.

I'm looking for hints on how to control the development-process (and our own economy) and still provide the customer with a product that gives the company most value-for-money.
Normally, I'd start a project by identifying goals of the project and business use-cases of the organization - and then deriving scope from those goals, using User-stories. The details (specifications) of how user-stories should be implemented, is decided at specifications prior to the sprint including the respective user-stories. This has repeatedly proven to result in better products and greater ROI for the customers.

Does anyone have experience of knowledge of techniques that can be used to "Reverse engineer" imperative user-tests, or any other input on how to handle the situation?

Historically, she has been allowed to completely dominate the development process, which has blown our budgets and taught her that she is in control of our process. Our management has now asked me to control (and defend) the development process. They told "C" that there will be used no more hours than the agreed budget, regardless of how "done" she (the product owner) feels that we are, which of course will be my leverage. She will become defensive, even aggressive to get things her way - any sound arguments based on professional reference or experience would be of help.

Follow up:

I thought I'd follow up in case anyone stumbled across this post with similar problems:

We have turned the communication around, and are expecting to deliver the next project within budget and on time (I'll edit this post again if hell breaks loose later on).

Initially, I focused on creating trust between me and the Product Owner. That meant choosing the relevant battles, and presenting myself as her tool to get most value for her money. Requirements are still expressed in more or less the same way (although she is open for input about syntax, she is firm about the format: Word Documents and Emails), but we are slowly trading control with visibility regarding the development process.

I managed to persuade her to participate in weekly meetings for project status, backlog grooming and prioritization. Between each meeting, she gets the chance to test the newest revision, which makes her test-feedback what used to be an object for discussion, the most valuable feedback for the backlog grooming and prioritization. By having a head-to-head talk about the feedback from the tests, we're able to "weed out" misunderstandings, contradictions and scope creep before it leaks into development.

The trust between us enabled us to have a constructive talk about each others organizations and the processes and intentions of these, which opened my eyes to quite a big part of the problems being our lack of capacity (professionally, theoretically, and methodically).

The product owner has called management to personally compliment the progress we are making, so I'm calling success on these first steps - but constantly watching the scope and progress, as to not "rest on ones laurels"


答:
Rather than thinking of this customer as 'difficult' which is negative, how about seeing that just they want to be really involved in the process? Perhaps their experience with working with other suppliers has benefited from a close working relationship?

Historically, she has been allowed to completely dominate the development process

Do you have internal processes/guidance for managing customer relationships? if so, are they being used? If this customer is managing to 'dominate' in any way, it strikes me they're either missing, not being used or are lacking somehow.

Also, are you the best person to do this? If you're in a predominantly technical role, it seems that your company may want to bring in someone who has a more people-focused role to help build the relationship while you build the product. This is not necessarily going to be another layer through which you need to work - it should be a double-act between you and them.

In my experience, keeping all customers involved and engaged to best manage their expectations is the way forward. There are a number of techniques and strategies you could employ here:

Clear and Open Communication

So the customer wants to change a requirement in some way - as they're paying, they're entitled to do this, but let's make sure that:

You/someone acknowledges their request in a timely manner and give them an ETA for the next update. i.e. "Thanks for your email, we're discussing the work required to implement this change this afternoon. I'll come back to you with the outcome after that/tomorrow AM". and make sure you get back to them when you said you would.

Be open and transparent about progress. If a feature is going to be late, tell them as soon as you know - don't wait until you've missed the delivery date.

When problems arise, get their input. If the requirements are ambiguous/vague/contradictory, schedule a conference call or meeting to clarify. Be sure to convey that work cannot continue until this is resolved.

Regular Updates

So the communication shouldn't all be event-driven, you should schedule frequent updates - whether this is a [video]conference call, on-site or in-house meeting. Being able to regularly review progress with you will fill them with confidence that you're being straight with them, i.e. not hiding anything. Over time, they'll relax as they see that your team delivers per the updates you give them and that their requests are heard, managed and integrated.

Over my (long) career, I have had many meetings where we just talk through project progress, they ask a couple of questions and we're done, in under 10 minutes.

I've also had to tell customers with high expectations that we've made no progress at all for a week as we'd had a break-in in the office and equipment was stolen. We expected anger but they sympathised and fully understood our setback. One customer even loaned us some equipment (128mb DRAM sticks in ~1993).

Lightweight Change Management process

So if one of the issues you're having is them changing their mind (which they are perfectly entitled to do, being the 'customer' who is paying your bills), it may be a good idea to use a lightweight change management process. The worst thing you can do here is get them to sign some legal-looking document as they'll feel threatened, but you could do the following:

When they request a change, first estimate/plan the impact of that change. Clearly communicate the effect on budget/schedule of this change. Be sure to point out if this effectively undoes work they've already paid for.

Agree a time by which the change will be either accepted or rejected.

Ask for the acceptance or rejection in writing. Email is fine, but make sure it is clear.

When to get help

So there are some occasions where all the best intentions in the world still don't seem to get through to the customer. These are the ones I've experienced:

Customer hounds you on instruction from their management, to the point where the hounding is preventing you getting anything done. This needs a [video]conference call with your manager and their management to discuss why they are using this 'crack the whip' strategy. It may required that your company employs a Customer Relationship Manager who can buffer the interaction between them and you.

Customer keeps changing their mind. In this case, you need to have the confidence to halt the project until they decide which is the most important thing that you should be working on/delivering. Be very clear in your communication that the project must halt and that it's your concerns about the changing priorities that have required it. Book a face-to-face meeting with your management, them and their management to discuss. Their management will likely be more cross with them for causing this than you for having to take the actions.


问:
How do you manage config with dependency injection?
I am a big fan of DI/IOC. It is great for handling/abstracting away hard dependencies, and makes life a little easier.

However I have a small gripe with it, which I am not sure how to solve.

The basic idea in DI/IOC is that when an object is instantiated, all of its dependencies are pre-filled within the constructor.

However IMHO there are several types of parameters for constructors (especially when your objects are immutable).

Dependencies (Objects required for your object to do work)

Configuration (information about the environment required to do work)

Parameters (Data that work is done on)

I find that IOC works well with dependencies. But I am still trying to work out the best way to deal with the other two. However, since the constructor is run meant to be run by the IOC container, it seems I need to place these items into the IOC container.

I'd like to know what strategies/patterns people employ and what advantages and disadvantages people have found.

NB. I am aware this is a highly subjective question, and have tried to make it a "good" subjective question as per SE guidelines.

答:
Configuration (information about the environment required to do work)

Create a configuration class (to be picky: an interface + an implementation) which purpose is to provide the information about the environment. This makes the configuration in no way different from other objects required for your object to do work (point 1).

Parameters (Data that work is done on)

In an object oriented environment, primitive data types can be encapsulated in objects, so this also leads to point 1. But you will probably find this SO question interesting, it deals exactly with the situation of primitive parameters in a constructor, when using a DI container. In the given example, the design could be improved, which avoided the need for primitive types in the constructor completely.


问:
Should functions be prepared for overlapping buffers?
So I have a function in C like this:

```<code>void crunch(const char *in, char *out, size_t inLen, size_t outLen)
{
    //...
}
</code>```

If the two buffers overlap, the function may mess up the input buffer as well, while generating output.

What's the general practice?

Should I always consider overlapping buffers when implementing functions like this?

Should I assume that the user won't pass overlapping buffers?

Should I always document whether the function works well or not with overlapping buffers?

答:
That depends entirely on the philosophy of your software component.

Especially in the C world, it is considered perfectly normal to produce undefined behaviour on violated preconditions, if this makes the implementation simpler. In other contexts, your users and fellow implementers might find this completely unacceptable and would demand that you behave robustly by verifying the specified boundaries and doing an internal copy if necessary.

The only thing that all practitioners should agree on is that you have to explicitly declare what happens when the inputs overlap - even if the effect is undefined.


答:
First, the method must declare a contract. A contract says: if you do X, I will do Y. See http://en.wikipedia.org/wiki/Design_by_contract.

It must either (a) require non-overlapping buffers as a pre-condition or (b) allow overlapping buffers.

In case (a), the contract should be enforced for at least some part of the development/testing lifecycle. That is, you should add code to the function that tests for non-overlapping buffers and asserts (fails) if it's not satisfied. Since this code probably has performance constraints, you probably want to be able to switch the test on for development and testing and off for production, but that's a choice you make.

in case (b), you add code to permit overlapping buffers. That might be a different, possibly slower, algorithm or whatever technique you choose.

What I describe is best practice. I have no way of knowing if it's
general practice.

You must consider overlapping buffers.

You should assume nothing beyond your contract.

The contract provides the documentation.

Title: Should functions be prepared for overlapping buffers?

Body:
So I have a function in C like this:

```<code>void crunch(const char *in, char *out, size_t inLen, size_t outLen)
{
    //...
}
</code>```

If the two buffers overlap, the function may mess up the input buffer as well, while generating output.

What's the general practice?

Should I always consider overlapping buffers when implementing functions like this?

Should I assume that the user won't pass overlapping buffers?

Should I always document whether the function works well or not with overlapping buffers?


问:
What advantages do continuous integration tools offer on a solo project?
If you're doing a solo project - would you use CI tools to build from a repository? I've used Hudson and Cruise Control in a team environment, where it's essential to build as soon as anyone checks anything in.

I think the value of version control is still obvious, but do I need to build after every commit, seeing as I would just have built on my local machine, and no-one else is committing?

答:
After a brief contemplation I would suggest that it might even be more important for a solo developer than for a team.

At the most basic level a CI server demonstrates that you can build your application from scratch from committed source - combined with a decent set of tests it should demonstrate that you can build and run from scratch.

Since one of the things I try to do is ensure that my build includes a deployable package you also know that you can go get something to deploy (clean and from a known state/version).

In fact now, when you do File|New Project you should probably include creating or adding to your repository and setting up your CI build script and deployment setup (even if that's only to zip a pile of stuff for xcopy deployment)

Addendum (2016) - nowadays my CI system will also be an integral part of my deployment process, so its value has increased and I absolutely won't run any deliverable project without it. Automated push button deployment takes a lot of stress out of the process and in some way, shape or form a build server is integral to that.


问:
What rationale is used when programming language designers decide what sign the result of modulo operation takes?
Going through Modulo operation (the avenue I entered while exploring the difference between rem and mod) I came across:

In mathematics the result of the modulo operation is the remainder of the Euclidean division. However, other conventions are possible. Computers and calculators have various ways of storing and representing numbers; thus their definition of the modulo operation depends on the programming language and/or the underlying hardware.

Questions:

Going through Euclidean division I found that remainnder of this operation is always positive (or 0). What limitation of the underlying computer hardware forces programming language designers to differ from mathematics?

Every programming language has it predefined, or undefined, rule according to which the result of the modulo operation gets it's sign. What rationale is adopted while making these rules? And if the underlying hardware is the concern then shouldn't rules change according to that, independent of programming language?

答:
The hardware of all modern computers is sufficiently powerful to implement mod operations of either sign with no (or trivial) performance impact. This is not the reason.

The common expectation of most computer languages is that (a div b) * b + (a mod b) = a. In other words, div and mod considered together divide a number into parts that can reliably be put back together again. This requirement is explicit in the C++ standard. The concept is closely related to indexing of multi-dimensional arrays. I have used it often.

From this it can be seen that div and mod will preserve the sign of a if b is positive (as it usually is).

Some languages provide a 'rem()' function that is related to mod and has some other mathematical justification. I have never needed to use this. See for example frem() in Gnu C. [edited]


问:
equals and hashcode methods autogenerated, is it always a good practice?
Preamble: Let's say I aim to cover all my classes with test coverage.

Despite the common opinion (expecially in Java community) to "not pay too much attention to Cyclomatic Complexity (CC) and code coverage", I really think that these information are extremely useful: When you have a very high CC, or an uncovered zone in your code, very likely you wrote a dead code, or either is a smell that you have problems in design. In my personal experience I can say that many time dead code is code smell.

This problem become a little tricky when you have to deal with auto-generated code, and that's the point, how can I easily deal with hashcode and equals autogenerated methods?
I came across this question in StackOverflow and I realized some very good point:

https://stackoverflow.com/questions/5764380/unit-testing-equals-and-hashcode-a-complexity-story

But this question is not a duplicate because I want to use a different approach:

The best options available in the answers of that question are, as far as I can see, EqualsBuilder of Apache Commons Lang or Guava. Both uses reflection (correct me if I'm wrong) and that could be a problem for performance in some situations.

But my actual question is: Since most of the times both equals and hashcode methods are not covered, is that a hint that this particular class does not need those 2 methods?
Since many Java developers a lot of time generate equals and hashcode even when not needed, what am I missing?
Shouldn't be a better solution to generate those methods only when you need, for instance, to sort objects of that class, to use that objects as an Hashtable key, and so on?

As I said, I think that goals of low complexity and high coverage are admirable, but the solution of using EqualsTester , seems to me like "Force to cover code that you don't actually need in your program".

答:
The story of equals() combines several unfortunate design decisions that are now impossible to change, and that every Java user just has to live with one way or another: it is deeply woven into the semantics of the standard container types, it is automatically inherited by every user-defined class but with a behaviour that is usually not what you want, and defining it without also defining hashCode() silently results in undefined behaviour (i.e. the language imposes certain requirements on you but has no way of warning you if they are unsatisfied.)

You can get along by simply never defining the method IF you never use such objects anywhere that would expose the unwanted behaviour. But since software development is a cooperative game, this requires an iron-clad, no-exceptions, disciplined rule of "Absolutely no Foo widgets in Sets, ever!!" that everyone involved with the code must know and follow 100%.

It can be worthwhile to impose such a rule in order to gain some performance, just as with other very fundamental principles of coding - e.g. "No null return values, ever!" is a common strategy to save a lot of checking for null. But this depends on how much you really profit from the small simplification for each class. The downside is that you have added another unspoken assumption that all users of your class must know and follow, or silently suffer from undefined behaviour.


问:
Some team members don't actively participate in Sprint planning
Some team members just wait until the stories they are most likely to work on will be discussed and only then they participate. Otherwise they just play with their phone and don't listen.

In some way I understand this position. Why listen to a discussion about a feature you are unlikely to help develop in the Sprint or ever?

What do you think we should do?

答:
Stop code ownership. Make it equally likely for anyone in a team to work on any given task.

There will almost certainly be some kick-back on that, because developers get comfortable with a specific area of code, and with other people not looking over their shoulders. Also, management will see a problem with work taking longer than it might normally, because there's always a learning curve.

But it really is in everyone's best interests. Being indispensable is a two-edged sword. It starts becoming more difficult to get time off, in the evening, at weekends or to take holidays. And code-ownership is bad for a company because, when someone leaves, it costs more time than you've ever saved on small bits of knowledge transfer.


答: Their disinterest is just a symptom. The problem is you're not distributing work evenly to all your team members. Ideally every team member should be picking up any new ticket not restricted to certain project areas.</p>

Title: Some team members don't actively participate in Sprint planning

Body:
Some team members just wait until the stories they are most likely to work on will be discussed and only then they participate. Otherwise they just play with their phone and don't listen.

In some way I understand this position. Why listen to a discussion about a feature you are unlikely to help develop in the Sprint or ever?

What do you think we should do?


问:
Should entities be accessible from all layers of an application?
I am googling this issue now for weeks, but cannot find a good discussion.
It boils down to this:
As POCO entities used in a dbContext are in fact a definition of the database, shouldn't they be constrained to the Data Access Layer and not be visible outside it?

On the other hand: it is convenient to hide some POCO entities in the ViewModels. so that changed properties can be passed back easily to the Data Access Layer.

I find many examples of Entities that make their way into the user interface, but also many examples of where AutoMapper is used to map the properties of a ViewModel to an Entity.

Can someone point me to some good working examples or discussions that could help me make a well informed choice?

答:
I am googling this issue now for weeks, but cannot find a good
  discussion. It boils down to this: As POCO entities used in a
  dbContext are in fact a definition of the database, shouldn't they be
  constrained to the Data Access Layer and not be visible outside it?

This is a complete misunderstanding of the purpose of object relational mappers and domain driven design. What you want is persistence ignorance. You shouldn't model a database definition but the objects of your problem-domain and how they relate to and interact with each other. You shouldn't worry about persistence at all when you design your problem domain, unless you're trying to fight performance problems e.g.

Entities are most definitely a cross cutting concern and it is perfetcly fine to use them in every layer of the application. However, if you want to limit the modification of an entity to a certain module, you can hide the entities within the module and only publish DTO objects that are readonly to consumers outside of the module. But within the module, every layer can be allowed to work with the entity.

On the other hand: it is convenient to hide some POCO entities in the
  ViewModels. so that changed properties can be passed back easily to
  the Data Access Layer.

Yes it is, and if you don't do it like that, you'll bloat the code unecessarily and end up with a lasagna antipattern in the worst case.


答:
Do you invite the right people to your meetings? If you've split the system into areas of responsibility for subteams, why invite all subteams to every meeting?

For example if you have a frontend team, and a backend team, keep the planning sessions for frontend work to members of the frontend team. Maybe invite someone from the backend team as a liaison in case a task crosses team boundaries (but if that happens frequently, you may wish to reevaluate the split of responsibilities between your teams).

Ideally everyone should work on everything, but in reality that's often not practical unless your system is really small and simple, resulting in everyone knowing every part of it thoroughly. In practice of course many systems are large enough that to expect every member of your organisation to have enough knowledge of a planned task to be able to give valid input during planning sessions (let alone be equally productive working on every part of the system) is just not realistic.


答:
To properly answer this you have to consider 2 aspects: the entities themselves and the DB connection.

Naturally the DB connection should only be accessible from the data access layer, so you have a reduced surface to interact with the DB.

The entities that come from there though... obviously if you're retrieving a read-only entity and passing around like a plain old data object, then there's no problem, so ahead and use them knowing that you're just bypassing the pain of creating a whole alternative layer of objects that exist to pass the entity data across tiers. I mean, you could create a new class to send data to the presentation tier, and the logic tier could take the data from the entity and populate this new class... but generally why bother when you can just pass the entity itself and save yourself a heap of trouble and performance problems copying data.

However, it gets more interesting when you need to pass data back. Here you either have persistent entities that need to be specially marshalled as special objects (ie that contain enough information to remind the DB what they are and where they came from). This starts to make things messy, and while its easy to just pass the entity about, update its fields and pass it back up the tiers to the DB, you might as well open up access to your DB to the client in that case! Here I would try to make updates occur via special methods on your logic tier that call up into the DB to modify these. This also stops the problem where you modify an entity down on the client and fail to persist it back to the DB - you can end up with a modified entity that you use, not realising that its been orphaned by other activity.

That last bit is the most important part to understand - if you use entities through your layers, you will have to pass them up and down the stack like a complex client-server model, or your data integrity can become compromised.

So all in all, I would prefer to keep the entities in the DB layer.

Title: Should entities be accessible from all layers of an application?

Body:
I am googling this issue now for weeks, but cannot find a good discussion.
It boils down to this:
As POCO entities used in a dbContext are in fact a definition of the database, shouldn't they be constrained to the Data Access Layer and not be visible outside it?

On the other hand: it is convenient to hide some POCO entities in the ViewModels. so that changed properties can be passed back easily to the Data Access Layer.

I find many examples of Entities that make their way into the user interface, but also many examples of where AutoMapper is used to map the properties of a ViewModel to an Entity.

Can someone point me to some good working examples or discussions that could help me make a well informed choice?


问:
Correct alignment when outcommenting code
Suppose I have some code

```<code>void some_block(void)
{
    some_statement_1();
    some_statement_2();
    some_statement_3();
}
</code>```

Now I wish to out-comment statement #2, but here I never can find a way where it feels right. Usually I will do the following:

```<code>void some_block(void)
{
    some_statement_1();
//    some_statement_2();
    some_statement_3();
}
</code>```

But now we got what looks like extra indentation of statement #2, yet it is arguable whether the indentation is still "correct". Alternatively we could do:

```<code>void some_block(void)
{
    some_statement_1();
    //some_statement_2();
    some_statement_3();
}
</code>```

This looks a bit better, yet still somehow also wrong. However the following just looks misplaced:

```<code>void some_block(void)
{
    some_statement_1();
  //some_statement_2();
    some_statement_3();
}
</code>```

How do you outcomment code and keep "correct" indentation?

Update

It seems most people who have provided answers did not answer my question, but simply state that it is bad practice to leave dead code around. While I completely agree with that, that was not the point of the question.

Right now I am facing a case of example where I have 5 helper functions, that manage 5 similar but slightly different structs for me. I use these helper functions to make my code easier to read.

But, at the moment (and for the next month probably) one of the structs are not going to be used. And I cannot commit anything which causes compiler warnings, so I have to outcomment that part of the code and commit it like that.

Also I forgot this last variant, which I think just looks plain wrong:

```<code>void some_block(void)
{
    some_statement_1();
//  some_statement_2();
    some_statement_3();
}
</code>```

答:
As said by Alex in the emacs I use comment-region and let the emacs handle it.
(Please no -ve votes from vi user for using emacs. :-) ). Once I am sure about my code then I delete it. The point is leave it to your favorite editor and get used to what editor does.  </p>