问:
Commenting strategies in C# & asp.net web api
I've been working on a ASP.NET Web Api 2 project as a learning exercise, and I was wondering what the norm regarding commenting is.

I use the Repository / Service Pattern, and everything is very much decoupled, which results in having a large number of classes whose purpose is pretty clear. I also name my variables in a way that they explain themselves.

This leaves me wondering what I should actually be commenting in this scenario.

Should I just stick to class-summaries ( even if the class itself is self-explanatory ) ?

What about self-explanatory methods ?

Do data / business entity classes need a summary ?

What about interfaces ?

To give a bit more context, here is one of my repository classes which provides CRUD functionality:

```<code>public class UserRepository : RepositoryBase<User, decimal>
{
    private readonly ShortStuffContext _context;

    public UserRepository(ShortStuffContext context)
    {
        _context = context;
    }

    public override IEnumerable<User> GetAll()
    {
        return _context.Users.BuildUser();
    }

    public override User GetById(decimal id)
    {
        return _context.Users.FirstOrDefault(u => u.Id == id).BuildUser();
    }

    public override CreateStatus<decimal> Create(User entity)
    {
        if (_context.Users.Any(u => u.Id == entity.Id))
        {
            return new CreateStatus<decimal> { status = CreateStatusEnum.Conflict };
        }

        var user = new Data.Entities.User();
        user.InjectFrom<SmartConventionInjection>(entity);
        _context.Users.Add(user);
        _context.SaveChanges();

        return new CreateStatus<decimal> { status = CreateStatusEnum.Created, Id = user.Id };
    }

    public override UpdateStatus Update(User entity)
    {
        var dbUser = _context.Users.FirstOrDefault(u => u.Id == entity.Id)
                             .InjectFrom<NotNullInjection>(entity);

        if (dbUser != null)
        {
            var changeTrackerUser = _context.ChangeTracker.Entries<Data.Entities.User>()
                            .FirstOrDefault(u => u.Entity.Id == entity.Id);

            changeTrackerUser.CurrentValues.SetValues(dbUser);
            if (_context.SaveChanges() == 0)
            {
                return UpdateStatus.NoChange;
            }
            return UpdateStatus.Updated;
        }
        return UpdateStatus.NotFound;
    }

    public override void Delete(decimal id)
    {
        var user = _context.Users.FirstOrDefault(u => u.Id == id);
        _context.Users.Remove(user);
        _context.SaveChanges();
    }
}
</code>```

So in a class like that, is it worthwhile to put a summary like "Provides CRUD functionality for the User Data Entity" ( and then repeat that summary for every other repository ), or not ? What about method comments, or inline comments?

Edit: My project is on Github. I know about adding comments to more complex methods, and I'm planning on adding comments to the Extensions and the ValueInjecter classes soon ( which hold by far the most complex code ). Apart from that, any advice regarding where to put comments is very much welcome.

答:
There is no definitive answer: some people will be inclined to add comments to every class and method; others will try to avoid commenting things which are already explicit enough.

If you follow StyleCop default rules, you have to comment every member, including private fields. You might want to suppress the warnings if the code is really repetitive. But if it is, you may ask yourself why is it not automatically generated (note: automatically generated code is marked specifically, and is not processed by StyleCop).

If you don't, feel free to comment as much or little as you feel appropriate. If I were maintaining the piece of code from your question, I would have added comments on every method, just to simplify my work later: I'd rather read a sentence in a tooltip in Visual Studio rather than try to guess right the meaning of the method. On the other hand, I would avoid commenting something like Title property of the class Product.

In all cases, try to bring something useful on those comments, not just repeat the name of the method or property. For example, if the class Product has a property Description, one way is to write:

```<code>/// <summary>
/// Gets the description of the product.
/// </summary>
</code>```

This comment doesn't bring anything useful. Another possibility is this one:

```<code>/// <summary>
/// Gets the piece of text which is displayed publicly and is usually written by the
/// managers. The description is localized for the current user.
/// </summary>
</code>```

Here, you bring three pieces of useful information:

The description is public. The web app may also have an internal summary field where managers can write text for themselves.

The description is usually written by managers. This helps understanding the business logic.

The description is a string translated in the language of the current user (probably CultureInfo.CurrentCulture).

Body:
There is no definitive answer: some people will be inclined to add comments to every class and method; others will try to avoid commenting things which are already explicit enough.

If you follow StyleCop default rules, you have to comment every member, including private fields. You might want to suppress the warnings if the code is really repetitive. But if it is, you may ask yourself why is it not automatically generated (note: automatically generated code is marked specifically, and is not processed by StyleCop).

If you don't, feel free to comment as much or little as you feel appropriate. If I were maintaining the piece of code from your question, I would have added comments on every method, just to simplify my work later: I'd rather read a sentence in a tooltip in Visual Studio rather than try to guess right the meaning of the method. On the other hand, I would avoid commenting something like Title property of the class Product.

In all cases, try to bring something useful on those comments, not just repeat the name of the method or property. For example, if the class Product has a property Description, one way is to write:

/// <summary>
/// Gets the description of the product.
/// </summary>

This comment doesn't bring anything useful. Another possibility is this one:

/// <summary>
/// Gets the piece of text which is displayed publicly and is usually written by the
/// managers. The description is localized for the current user.
/// </summary>

Here, you bring three pieces of useful information:

The description is public. The web app may also have an internal summary field where managers can write text for themselves.

The description is usually written by managers. This helps understanding the business logic.

The description is a string translated in the language of the current user (probably CultureInfo.CurrentCulture).


问:
what does it mean when a nested function isn't assigned to a var?
I'm referencing this link about closures:
https://stackoverflow.com/questions/111102/how-do-javascript-closures-work

This is specifically about javascript.
In the second answer with 956 votes, The author returns the nested function "sayAlert" after assigning it to the var keyword as shown below. (Example 3)

```<code>function say667() {
// Local variable that ends up within closure
var num = 666;
var sayAlert = function() { alert(num); }
num++;
return sayAlert;
}
var sayNumber = say667();
sayNumber(); // alerts 667
</code>```

However in the next example (Example 4), the author assigns the following functions, "gAlertNumber", "gIncreaseNumber", and "gSetNumber", without the var keyword. Then the author is able to call the nested functions as follows.

```<code>function setupSomeGlobals() {
// Local variable that ends up within closure
var num = 666;
// Store some references to functions as global variables
gAlertNumber = function() { alert(num); }
gIncreaseNumber = function() { num++; }
gSetNumber = function(x) { num = x; }
}

setupSomeGlobals();
gIncreaseNumber();
gAlertNumber(); // 667
gSetNumber(5);
gAlertNumber(); // 5

var oldAlert = gAlertNumber;

setupSomeGlobals();
gAlertNumber(); // 666

oldAlert() // 5
</code>```

I tried adding the keyword var to the begging of each nested function, but in my console it returns an error. So I'm assuming there's a difference between the two. But I don't know what this tactic is called and why it works...

答:
This is not just for functions - this is how JavaScript generally deals with assignments. When you use the var keyword, the variable is assigned at the current scope. When you don't use it, the variable is assigned at the global scope(the window object in browsers). That means that gSetNumber = ... is the same as window.gSetNumber = ...(assuming the code is ran in a browser) and gSetNumber(5); is the same as window.gSetNumber(5);. Since the window object is accessible from anywhere so is gSetNumber. sayAlert, on the other hand, was declared with the var keyword so it belongs to the local scope where it is declared and only accessible from there.

Note that while num is also a local variable declared with the var keyword, gAlertNumber, gIncreaseNumber and gSetNumber can be used to indirectly access it from anywhere since their closure closes over the local scope where num is declared but the function themselves are assigned to global variables.

ContentLicense: CC BY-SA 3.0


问:
Easily moving both direction of time during a rebase
After I have written some commits, I very often git rebase -i over them, in order to test them, if necessary split them, take parts form one commit and squash them to another, more appropriate one.

But there is a problem. Say, today I am hunting for a bug, that 5 recent commits are causing. I rebase interactively on the last known to work (bear with me, not using git bisect for a reason). The next commit introduces the bug, but is a big mess some unrelated code.

So I git reset HEAD~ and then form several internally logical commits.

Here is the problem. I do not know which is the first problematic commit. So I select edit for all commits when rebasing. After I am done with the problematic commit, I have a couple of commits in the past, that I would like to test further.

Currently, I do git rebase --continue many times, until the rebase is complete, and then rebase interactively again. This has a few problems:

It is tedious. At the very least, I would like a command that rebases to the top of the branch, skipping all edit declared commits.

Neverending merges. I need to merge often, and would prefer to first do the meaningful job of splitting the original commit, and only after that git commit --ammend the latter commits in order to be compatible with the edited hystory.

TL;DR;

How can I achieve this bi-directional traversal on a branch, while at the same time, creating, removing and amending commits? Or is this workflow conceptually wrong?

答:
This is my opinion, based on my experience.

Debugging is one process.  Rebasing is a different process.  If you try to combine the two of them you get a mess.

At the point that you start your rebase, you should have working code.  If you don't have working code, stop what you're doing and fix the code.  If this is code that someone else has submitted to you, this is their problem, not yours.  If your job is to integrate other people's code, it's perfectly reasonable to kick the problem back to them.  Otherwise you just make more work for yourself.

@Cupcake has already asked why you're not using git bisect.  Your answer tells me that you're working on too large a chunk of code.  "Large" is not defined by number of lines, but rather by functionality.  If someone is submitting code for you to integrate then they should be breaking it up into the right chunks, not you.  If a chunk of code deals with multiple unrelated features then it's too large.  (I'm using the word "chunk" to mean a logical changeset, which may include more than one commit.  There's nothing wrong with working on multiple commits as long as they're logically related.)

I personally would not recommend your workflow.  I think you should be using
pull requests.  I use this at my day job.  Basically one person maintains a repository and other people submit requests to add commits to the repo.  If the maintainer approves the change, great.  If not, not.  Each request has to stand on its own, and each request should add a very well-defined piece of functionality.

The nice thing about pull requests (and forking a repository) is that it makes a very clear separation of who is responsible for doing what.  It sounds like that separation is missing from your current workflow.

If you're in the mood to dig in more deeply, I found Vincent Driessen's article on Gitflow to be very useful.

This is not what you asked, but you might also want to look into unit testing and continuous integration.  Those things will make it harder for bugs to hide and ultimately save you some time as well.

Good luck!  Git can be tricky to learn and it took me months to feel comfortable with it.


问:
Applying commits into another branch without merging
I have two git branches with almost the same code, but some minor changes in order to support different platforms.

I need to maintain these changes because I need them to run the software on different computers. So there is no master and development branch, both are equally important.

Nevertheless, I need to "synchronize" the core code base of the branches. So I would like to somehow apply the commits from one branch in a sort of patch fashion to the other branch and vice versa, without merging them, in order to maintain the different setups.

Is this possible with git?
If yes, how can I accomplish this?

Edit: can I merge only some files and leaves others out, but maintain the two branches?

答:
If the changes are very minor, like just different command-line arguments, this should be done with configuration files.

Otherwise, as @radium alluded to, you should make separate modules, include everything in source control, and have the build system determine which module is included.

Using Git to maintain two different branches is brittle and error-prone, because you have to always remember to make your changes in both branches.

You can use a .gitignore file to make sure that configuration files are ignored by git, store them somewhere in the repo, and have your build script copy the correct file into the designated location.

For example:

Repo contains:

meta/windows.properties
meta/mac.properties

.gitignore file says to ignore user.properties

Build script copies either meta/windows.properties or meta/mac.properties to user.properties.

Then you compile, build, run.


答:
If you feel that you can't add any useful information to the future reader of this classes in comments don't write it. In my opinion your code don't need comments, its pretty obvious, comments in this code are more noise than real information.

A programming language its of course a language, when you put a comment is because you can't express the things you want to express in this programming language and you use another language that gives you more freedom and tools for express (a human language like english). Sometimes you can justify this because programing language can have some obscure features or ways to do things that need an explanation, or perhaps you use some third party library with a very strange behavior than need an explantation. But IMMO the majority of the code don't need the use of a human language to express things, a lot of times the comments reflect a bad design, bad name choices, bad architecture etc,etc.

Every time when i think "i need a comment here for others to understand this" an alert its raised and i try to rethink my design, search for better names, do some refactors etc, etc, sometimes this helps me to find a better solution and i don't need the comment, sometimes i don't find a better solution an i put the comment, but i never put a comment before making a effort to try to express things more clearly in my programming language.

Title: Commenting strategies in C# & asp.net web api

Body:
I've been working on a ASP.NET Web Api 2 project as a learning exercise, and I was wondering what the norm regarding commenting is.

I use the Repository / Service Pattern, and everything is very much decoupled, which results in having a large number of classes whose purpose is pretty clear. I also name my variables in a way that they explain themselves.

This leaves me wondering what I should actually be commenting in this scenario.

Should I just stick to class-summaries ( even if the class itself is self-explanatory ) ?

What about self-explanatory methods ?

Do data / business entity classes need a summary ?

What about interfaces ?

To give a bit more context, here is one of my repository classes which provides CRUD functionality:

```<code>public class UserRepository : RepositoryBase<User, decimal>
{
    private readonly ShortStuffContext _context;

    public UserRepository(ShortStuffContext context)
    {
        _context = context;
    }

    public override IEnumerable<User> GetAll()
    {
        return _context.Users.BuildUser();
    }

    public override User GetById(decimal id)
    {
        return _context.Users.FirstOrDefault(u => u.Id == id).BuildUser();
    }

    public override CreateStatus<decimal> Create(User entity)
    {
        if (_context.Users.Any(u => u.Id == entity.Id))
        {
            return new CreateStatus<decimal> { status = CreateStatusEnum.Conflict };
        }

        var user = new Data.Entities.User();
        user.InjectFrom<SmartConventionInjection>(entity);
        _context.Users.Add(user);
        _context.SaveChanges();

        return new CreateStatus<decimal> { status = CreateStatusEnum.Created, Id = user.Id };
    }

    public override UpdateStatus Update(User entity)
    {
        var dbUser = _context.Users.FirstOrDefault(u => u.Id == entity.Id)
                             .InjectFrom<NotNullInjection>(entity);

        if (dbUser != null)
        {
            var changeTrackerUser = _context.ChangeTracker.Entries<Data.Entities.User>()
                            .FirstOrDefault(u => u.Entity.Id == entity.Id);

            changeTrackerUser.CurrentValues.SetValues(dbUser);
            if (_context.SaveChanges() == 0)
            {
                return UpdateStatus.NoChange;
            }
            return UpdateStatus.Updated;
        }
        return UpdateStatus.NotFound;
    }

    public override void Delete(decimal id)
    {
        var user = _context.Users.FirstOrDefault(u => u.Id == id);
        _context.Users.Remove(user);
        _context.SaveChanges();
    }
}
</code>```

So in a class like that, is it worthwhile to put a summary like "Provides CRUD functionality for the User Data Entity" ( and then repeat that summary for every other repository ), or not ? What about method comments, or inline comments?

Edit: My project is on Github. I know about adding comments to more complex methods, and I'm planning on adding comments to the Extensions and the ValueInjecter classes soon ( which hold by far the most complex code ). Apart from that, any advice regarding where to put comments is very much welcome.


答:
I have two git branches with almost the same code, but some minor changes in order to support different platforms.

Your are trying to use a version control system to solve a design problem.

I don't know the details of your systems but this "minor changes per platform" can be easily designed with a little abstraction and polymorphism if you use a OO language. In other paradigms, like structured or functional programming, there are other ways to achieve polymorphism, but its off course posible.

If you give more details on you systems you can get much better responses.

Title: Applying commits into another branch without merging

Body:
I have two git branches with almost the same code, but some minor changes in order to support different platforms.

I need to maintain these changes because I need them to run the software on different computers. So there is no master and development branch, both are equally important.

Nevertheless, I need to "synchronize" the core code base of the branches. So I would like to somehow apply the commits from one branch in a sort of patch fashion to the other branch and vice versa, without merging them, in order to maintain the different setups.

Is this possible with git?
If yes, how can I accomplish this?

Edit: can I merge only some files and leaves others out, but maintain the two branches?


问:
Scripts to run Java programs - e.g. Ant
My team currently use an Ant script to execute various Java programs.

Note that I am not asking about managing the build/deployment cycle for which we are already using Maven (quite happily).

For example, we use something like the following:

```<code><path id="lib">
  <fileset dir="path/to/lib" />
</path>

<path id="run" >
  <path refid="lib" />
</path>

<target name="aJavaProgram" >
  <java classname="path.to.AJavaProgam"
        classpathref="run" fork="yes" failonerror="false" append="true" />
</target>

<target name="anotherJavaProgram" depends="aJavaProgram" >
  <java classname="path.to.AnotherJavaProgam"
        classpathref="run" fork="yes" failonerror="false" append="true" />
</target>
</code>```

We originally chose Ant for the following reasons (or rather I didn't choose Ant, it was that way when I joined, but I think these are good reasons for the choice):

it was an easy way of managing dependencies (although we now pick up these from Maven)

it allows us to easily build/maintain dependencies between particular jobs

we can deploy the Ant script, and the Java libraries, and easily run particular jobs - i.e.

we don't have to worry about classpaths (configured in the Ant script)

we don't have to worry about building jars with main classes specified in the manifest

we can use Ant to create / store / manage arguments passed to main() methods

we can plug these ant scripts into our IDEs and run the jobs from there.

Generally speaking, we have been very happy with this.

However, an increasing issue is the ant-java-shutdown hook issue - this means that if one of these Java programs fails but doesn't finish, terminating the Ant process from which it was started doesn't terminate the Java process - which then has to be done manually, and is a real bind.

Also, I'm conscious of two other (possible) factors:

this is using Ant in a slightly unusual way, which is perhaps not how Ant was intended to be used (or at least, so it seems to me...)?

I'm not really sure, but it seems that fewer and fewer developers/teams are using Ant these days, with preference for other technologies.

So, to clarify:

I want a flexible approach to execute various Java programs

the approach that we have been using was to do this via Ant scripts, but this had the following problems:

terminating the Ant task does not kill the Java program

this "feels" like Ant is not the right tool for the job

how might we meet the needs specified above?

if not Ant, the solution should not face the termination / shutdown hook issue

答:
Two options that I used in my last project:

maven assembly plugin: this plugin can generate for you a "package" that contains the libraries you need and a generated shell script to execute the program. Another option I like a lot is to generate a "fat jar" with all the libs merged in a big .jar. This simplifies a lot the distribution and executing of java programs and you can simple execute with java <class_name> -jar <ftr-jar.jar>

Use groovy: I like a lot this option because gives me a lot of freedom. You can have .groovy script that simply calls your classes. Inside this scripts you can use "grab" to declare your dependencies (more info in this link: http://groovy.codehaus.org/Grapes+and+grab()).

Title: Scripts to run Java programs - e.g. Ant


问:
What do you use string reversal for?
In PHP it's strrev(), in Rails it's .reverse, but most languages don't have any string reverse function. Some have array reverse functions that can be used on characters. I was thinking this must be a major oversight but then it occurred to me, what would you actually use string reverse for???

The only time I can think I've seen it is in demos and lessons to turn "Hello World!" into "!dlroW olleH".

My question is; Is there a use for reversing a string or is it completely pointless?

.

Addendum

There have been way more answers that I had anticipated and not all of them were entirely academic. I would have put money that no one could come up with a legitimate example. I also didn't think I would learn anything new but Mark Canlas' regex suggestion is just brilliant and I look forward to the opportunity for it to prove itself. Thanks to all.

答:
I dunno maybe someone has a burning need to check for palindrome's....

I don't think its completely useless, as there may well be situations where one needs to be able to reverse a string.

ContentLicense: CC BY-SA 2.5

Title: What do you use string reversal for?


答:
I write comments for two purposes

Class / Method XML comments. To provide context to what a method/class/snippet does and why it may be there. This can 'repeat' what the code clearly expresses, but only to the person who wrote it. If the comment can tell me what is occurring without understanding the code it is a benefit

To highlight edge cases. In the event where I need to handle a specific case I'll leave an inline comment.

To expand on my comment:

If I were looking for comments I'd note that I don't know what GetUserById returns if a user with a given id is not found (Null, default or throws an exception).

Simiarly I would leave a comment on create status saying that a Status of Conflict is returned when the entity's id matches an existing user id.

Comments may seem like they're regurgitating code, but this is only to those who read and understand it. Consider that you need not do this in order to use it.


问:
Is a degree needed for low-level/embedded programming jobs?
I know that it is possible to get into software development without a degree in computer science, but is it possible (or rather, common) to be able to get an embedded programming job without the computer science degree (or any engineering degree as well)?</p>

答:
As a hiring manager for various companies whose core products include embedded system, I can say that I would simply not hire anyone who did not have a degree in either CS or EE from an accredited institution. The degree shows that the person is committed to a deep understanding of their field and will not simply blunder through problems.

I have, on multiple occasions, taken over groups in which a mix of degreed and non-degreed engineers were on the team... My observation is that, by far, the non-degreed engineers were lightweights and were suitable only for certain grunt-work types of programming where they couldn't do any real damage. The architectures and real thinking had to be done by the guy with degrees.

It makes sense too, when you think about it... the original poster of this thread is essentially saying "I want bypass the learning curve and just jump to front of the line". I'm not saying it is impossible, but when you finally land that embedded job you've been seeking you might be surprised at all the things you find you don't know.


问:
Why the terms used in Scrum are so strange?
I'm not a native English speaker, currently I'm reading some articles about Scrum.

I was wondering if the English terms used in Scrum seem strange to you?
For example,

backlog instead of todo;

artifact instead of element;

retrospective instead of review;

even the name of Scrum, it make no sense to me as a process name.

Can anyone give some hint to me? For example, I don't see the relationship between a scrum in football and iteration process.

答:
Wiktionary has the the following etymology to offer about the origin and meaning of Scrum terminology:

Scrum - (rugby) An ordered formation of forwards in which each side aims to gain control of the ball; a scrum.

backlog - An accumulation or buildup, especially of unfilled orders or unfinished work

artifact - Something viewed as a product of human conception or agency rather than an inherent element. *)

product owner - One who owns (something).

product - Anything that is produced; a result.

sprint - A short race at top speed

burn down chart - To burn completely, so that nothing remains.

burn down chart - A systematic non-narrative presentation of data.

velocity - The rate of occurrence.

All said, the words are specific and very precisely express the intended meaning in general, and in plain English.

*) I like this one even better ;-) "artifact - An object made or shaped by some agent or intelligence, not necessarily of direct human origin." (emphasis by me)


答:
```<code>public bool IsPalindrome(string toCheck)
{
    return toCheck == toCheck.Reverse();
}
</code>```

Title: What do you use string reversal for?

Body:
In PHP it's strrev(), in Rails it's .reverse, but most languages don't have any string reverse function. Some have array reverse functions that can be used on characters. I was thinking this must be a major oversight but then it occurred to me, what would you actually use string reverse for???

The only time I can think I've seen it is in demos and lessons to turn "Hello World!" into "!dlroW olleH".

My question is; Is there a use for reversing a string or is it completely pointless?

.

Addendum

There have been way more answers that I had anticipated and not all of them were entirely academic. I would have put money that no one could come up with a legitimate example. I also didn't think I would learn anything new but Mark Canlas' regex suggestion is just brilliant and I look forward to the opportunity for it to prove itself. Thanks to all.


问:
How can we make a certain thing inbuilt in c language with our own header file?
I want to make the basic trigonometric functions in maths inbuilt functions using my own header file . so as the users can do trigonometry in c language compilers. </p>

答: You can't make new functions "built-in" to C without changing the compiler. However, you can write and extend libraries with new functions that your programs can then reuse wherever they want. For that, you need to compile a library with the functions, your program needs to include the library header file, and the linker has to include the object code for your functions. Please elaborate if you need more specific help.


问:
How does the "Fourth Dimension" work with arrays?
Abstract:

So, as I understand it (although I have a very limited understanding), there are three dimensions that we (usually) work with physically:

The 1st would be represented by a line.

The 2nd would be represented by a square.

The 3rd would be represented by a cube.

Simple enough until we get to the 4th -- It is kinda hard to draw in a 3D space, if you know what I mean...  Some people say that it has something to do with time.

The Question:

Now, though that doesn't all make much sense, that is all great with me.  My question isn't about this, or I'd be asking it on MathSO or PhysicsSO.  My question is: How does the computer handle this with arrays?

I know that you can create 4D, 5D, 6D, etc... arrays in many different programming languages, but I want to know how that works.

答:
Most of the aspects of this question have already been considered, but I think it will help if you consider the nature of a dimension. Not all dimensions are spatial. A dimension is a context for measurement. Here are some examples:

Frequency - colour or pitch

Mass

Valence

Colour (up quark, down quark, strange quark, charmed quark etc)

Spin direction

Angle

Loudness

Hotness (of chili)

The "fourth" dimension is only fourth because there are three spatial dimensions. Space and time loom large because, well, they loom large. Very much in-your-face. But any quantifiable, measurable quality can be a dimension if you measure it.

For example, brassieres have three dimensions: cup size, chest size and interstitial (I don't know what you girls call it but I mean the distance between cups).


问:
How could your company's learning/development department best serve you?
I'll preface my question with a disclaimer - I am not an engineer, I'm just someone who works with them full-time, in a learning and development capacity.

Given that, one of the comments I get regularly from the engineers I'm tasked with developing is that they feel that they're having solutions (both technical and non-technical) for development "pushed" at them vs. anyone from my field consulting with them to determine what they really need.

So my question is - if you could give your company a list of the top 3-5 things they could do - in a classroom, or elsewhere - to develop meaningful skills that would help you be a better engineer, a better employee, and one more likely to STAY with the company for the long haul, what would make the cut and why?

Thanks in advance for your responses.

答:
Here are my suggestions:

Help me understand myself.  This can be tricky as well as quite costly to some degree as this is rather personalized, but the key here is to help me know what are my strengths, what kinds of things do I like to do in a professional setting, how could the company better utilize me, etc.  Note that this can be quite psychological or spiritual so some sensitivity may be required.  For example, some people may believe in a higher power that has a reason for everything that exists while others may think the bible is a book of fairy tales, just to give the extremes with most people being somewhere between the two.  Another part here is finding one's passions and interests, which may not always be easy of course.  Other areas under here could include MBTI, Enneagram, Strengths Finder, or F-Score to name a few tests one could take to try to learn more about themselves.  The self-awareness part of emotional intelligence is also here as well for another idea of how to approach this.

Let me know my path choices in the company.  For example, if I am happy being a developer, could I be one for 25 years at the company?  Do I have to find some career progression and walk down that road?  This is partially about my knowing what the company wants and could use but also about my knowing what options do I have to explore.  Some people may want to choose from a list of options rather than create their own out of thin air.

Help me find the resources to advance myself.  This is what comes after I know who I am and where I could go.  Is there a mentorship program in the company?  Are there volunteer groups that may interest me and show me that the company cares about the community around me?  What is there to help me move from where I am to where I want to be.  Another way to look at this is the question of how much assistance is there in setting goals that could be provided.  I don't want to have to come up with all of the points on my own, but I also don't want this forced upon me either.  Is there a peer recognition group?  Are there athletic or artistic groups that I may want to join?  Another side here is that beyond knowing what is out there, encouragement and emotional support may also be key points here in my attempt at personal fulfillment.

Relationships and communication development.  In a way this is covering some other areas of emotional intelligence where the point here can be to help me see what kinds of relationships do I have, how engaged am I, how well am I communicating what I do, want, or need?  A tricky part here is that while this may come across as rather "girlie" the reality is that I'm pretty sure this wasn't covered in my Math or Computer Science classes even though part of the nature of my existence is to have bonds with other people and share stuff.

I'll admit to going down some of these myself in terms of what I'd like from the learning and development department.  I suppose asking for a change on that development part may be asking too much, right? :)


问:
How to get around the Circular Reference issue with JSON and Entity
I have been experimenting with creating a website that leverages MVC with JSON for my presentation layer and Entity framework for data model/database. My Issue comes into play with serializing my Model objects into JSON.

I am using the code first method to create my database.  When doing the code first method a one to many relationship (parent/child) requires the child to have a reference back to the parent. (Example code my be a typo but you get the picture)

```<code>class parent
{
   public List<child> Children{get;set;}
   public int Id{get;set;}

}
class child
{
    public int ParentId{get;set;}
    [ForeignKey("ParentId")]
    public parent MyParent{get;set;}
    public string name{get;set;}
 }
</code>```

When returning a "parent" object via a JsonResult a circular reference error is thrown because "child" has a property of class parent.

I have tried the ScriptIgnore attribute but I lose the ability to look at the child objects. I will need to display information in a parent child view at some point.

I have tried to make base classes for both parent and child that do not have a circular reference. Unfortunately when I attempt to send the baseParent and baseChild these are read by the JSON Parser as their derived classes (I am pretty sure this concept is escaping me).

```<code>Base.baseParent basep = (Base.baseParent)parent;
return Json(basep, JsonRequestBehavior.AllowGet);
</code>```

The one solution I have come up with is to create "View" Models. I create simple versions of the database models that do not include the reference to the parent class. These view models each have method to return the Database Version and a constructor that takes the database model as a parameter (viewmodel.name = databasemodel.name).  This method seems forced although it works.

NOTE:I am posting here because I think this is more discussion worthy. I could leverage a different design pattern to over come this issue or it could be as simple as using a different attribute on my model.  In my searching I have not seen a good method to overcome this problem.

My end goal would be to have a nice MVC application that heavily leverages JSON for communicating with the server and displaying data.  While maintaining a consistant model across layers (or as best as I can come up with).

答:
The one solution I have come up with is to create "View" Models. I
  create simple versions of the database models that do not include the
  reference to the parent class. These view models each have method to
  return the Database Version and a constructor that takes the database
  model as a parameter (viewmodel.name = databasemodel.name). This
  method seems forced although it works.

Sending out the bare minimum of data is the only correct answer. When you send out data from the database, it usually doesn't make sense to send out every single column with all the associations. The consumers shouldn't need to deal with database associations and structures, that is for databases. Not only will this save bandwidth but it's also much easier to maintain, read and consume. Query the data and then model it for what you actually need to send out eq. the bare minimum.


问:
Repository Pattern: Doctrine2 vs Microsoft Entity Framework?
I have been using Symfony2 with Doctrine2 for some years. I have recently started using Microsoft's Entity Framework with MVC5. From my Symfony2 experience I understand that a repository's job is only to retrieve and return objects, no additional operations like Saving. Now every examples I have seen for EF has a method Save/Update as part of the repository.

For symfony I have been creating manager classes as follows:

```<code>interface IManager
{
    function getClassName() ;
    IRepository getRepository() ;
    function Save(object);
    function Update();
}
</code>```

So I pass around the manager, if I need to retrieve objects I call the repository directly. If I need to save I call the manager's save method.

Is a repository supposed to support save/update? What do you think of my IManager class, should I also use it for EF?

答:
Entity Framework is not the implementation of Repository Pattern. EF is the Object Relational Mapper. Yes, it looks and behaves like Repository Pattern with Save/Update functionality.

Your IManager makes sense, and with enough abstraction, the Manager doesn't have to be coupled to EF at all. That will give you an option of switching ORMs if needed.


答:
I've seen situations where a desktop application was talking with embedded devices and was switching byte-order endianness constantly, and data was moved around as strings. That's about it for me though.

I wouldn't have used strings for that application but thats just the way it was.....

Title: What do you use string reversal for?


问:
How do two applications communicate?
Say I had a PHP page with a calculator interface, but I want to transfer the sum to Windows Calculator.exe and then get a reply from the application back to my PHP page, how do you go about doing this?

I understand that the sum could easily be done in PHP and it would be pointless using another application, but I just wondered how it would be done and will be helpful to know for my next project. I couldn't find any relevent exisiting questions but the search criteria for this isn't easy!

Thanks

答:
Applications can communicate using an Application Programming Interface (API). When writing a program, the developer can choose to expose certain functions to allow other programs to interact with them. By only exposing certain functions, and in a certain way, the developer allows people to use his application in a safe way without accidentally (or intentionally) doing destructive things.

An API may be exposed in several ways, depending on the languages involved. In a .NET environment, for instance another .NET program could add a reference to an API dll created for this purpose. Another example is a web service API which can be communicated with using HTTP requests. If the API uses a common cross language technique such as JSON or XML to input and output data, a program in any language may be able to communicate with it.

Title: How do two applications communicate?


问:
Learning potentially unrelated materials on company's dime, is it acceptable?
I am facing a similar problem as the OP of this question where my environment is good, but I feel like my learning is stagnating and I don't have the ability/resources to change positions/quit my job at this time nor am I sure I would want to if I did have the ability to.

The day before yesterday, I was assigned to help fix a problem with an ASP.NET website (which I normally don't work with)  that the customer was having and I needed to look up how to implement something. It only took me a couple of minutes to fix the problem and after that I ended up spending about four hours reading more about ASP.NET and implementing some of the exercises from the book. Then I spent another hour reading about networking and configuring routers which may be used when we need to change something in our lab, however, it is highly unlikely I would be the one to do it since we have a person dedicated to that task.

Today I took off work just so I could learn more about configuring networks and to practice on my home network.

Should I be billing the company for the time learning more about ASP.NET even though it is not a common part of my job or should I be charging like 1/2 rate? Is there a certain number of hours that you feel is acceptable to charge the company for time learning something or self-improvement?

答:
Should I be billing the company for the time learning more about ASP.NET even though it is not a common part of my job or should I be charging like 1/2 rate?

Should a lawyer bill a client full-price for the time they spent reading legal volumes about relevant laws and prior court precedent?

The answer is undoubtedly 'YES'.

We have seen the computing world undergo enormous change in the past two decades, and you should expect more of the same for the foreseeable future.  A client should expect and want its programmers, be they full-time or contract, to be fully informed when writing code.


问:
Constructor parameter validation in C# - Best practices
What is the best practice for constructor parameter validation?

Suppose a simple bit of C#:

```<code>public class MyClass
{
    public MyClass(string text)
    {
        if (String.IsNullOrEmpty(text))
            throw new ArgumentException("Text cannot be empty");

        // continue with normal construction
    }
}
</code>```

Would it be acceptable to throw an exception?

The alternative I encountered was pre-validation, before instantiating:

```<code>public class CallingClass
{
    public MyClass MakeMyClass(string text)
    {
        if (String.IsNullOrEmpty(text))
        {
            MessageBox.Show("Text cannot be empty");
            return null;
        }
        else
        {
            return new MyClass(text);
        }
    }
}
</code>```

答:
A constructor shouldn't have any side-effects.

Anything more than private field initialization should be viewed as a side-effect.

A constructor with side-effects breaks the Single-Responsibilty-Principle (SRP) and runs contrary to the spirit of object-oriented-programming (OOP).

A constructor should be light and should never fail.

For instance, I always shudder when I see a try-catch block inside a constructor. A constructor should not throw exceptions or log errors.

One could reasonably question these guidelines and say, "But I don't follow these rules, and my code works fine!"
To that, I would reply, "Well that may be true, until it isn't."

Exceptions and errors inside of a constructor are very unexpected. Unless they are told to do so, future programmers will not be inclined to surround these constructor calls with defensive code.

If anything fails in production, the generated stack trace may be difficult to parse. The top of the stack trace may point to the constructor call, but many things happen in the constructor, and it may not point to the actual LOC that failed.

I've parsed many .NET stack traces where this was the case.


答:
In addition to what @razethestray said, applications can also talk to each other by means of so-called RPC interfaces, which stands for Remote Procedure Calls.

However, RPC itself is a broad term. Actually there are plenty of ways how an RPC could be implemented. For example, Microsoft's DCOM relies heavily on RPC. On the other hand, a SOAP (web) server call is considered an RPC as well. the one thing that they all have in common is, that a client calls a piece of code in a remote (server) process through a well-defined API to achive something.

As you can imagine, it is a good idea and highly recommended to use existing frameworks for such a task, simply to hide and manage the complexity that comes with the infrastructure needed for this. Those frameworks and in some cases built-in IDE support (e.g. for SOAP) make an RPC essentially look like a normal function/method call. In fact, behind the scenes there may be happen a lot, especially when the other process is on a remote machine.

PS: That's a quite sophisticated topic for starters.

Title: How do two applications communicate?

Body:
Say I had a PHP page with a calculator interface, but I want to transfer the sum to Windows Calculator.exe and then get a reply from the application back to my PHP page, how do you go about doing this?

I understand that the sum could easily be done in PHP and it would be pointless using another application, but I just wondered how it would be done and will be helpful to know for my next project. I couldn't find any relevent exisiting questions but the search criteria for this isn't easy!

Thanks


问:
Does over-reliance on tools imply that you are lazy?
I started programming in C++ at uni and loved it. In the next term we changed to VB6 and  I hated it.

I could not tell what was going on, you drag a button to a form and the ide writes the code for you.

While I hated the way VB functioned I cannot argue that it was faster and easier than doing the same thing in C++ so i can see why it is a popular language.

Now I am not calling VB developers lazy in just saying it easier than C++ and I have noticed that a lot of newer languages are following this trend such a C#.

This leads me to think that as more business want quick results more people will program like this and sooner or later there will be no such thing as what we call programming now. Future programmers will tell the computer what they want and the compiler will write the program for them like in star trek.

Is this just an under informed opinion of a junior programmer or are programmers getting lazier and less competent in general?

EDIT: A lot of answers say why re invent the wheel and I agree with this but when there are wheels available people are not bothering to learn how to make the wheel. I can google how to do pretty much anything in any language and half the languages do so much for you when it come to debugging they have no idea what there code does of how to fix the error.

That's how I cam up with the theory that programmers are becoming lazier and less competent as no one cares how stuff works just that it does until it does not.

答:
Does over-reliance on tools imply that you are lazy?

Generally speaking, 'No'; but there is one big caveat.

I started programming in C++ at uni and loved it. In the next term we changed to VB6 and I hated it.

I could not tell what was going on, you drag a button to a form and the ide writes the code for you.

Yes, indeed. Your experience at uni speaks to the very caveat that I mentioned.

If you don't know what problem your tool is solving, or you're incapable of troubleshooting things when your tool has problems of its own, then that's a huge red flag. This circumstance doesn't necessarily imply laziness, but it probably implies inexperience.


问:
How to make Classic ASP interesting if you are stuck with it?
I used to work on a really small outsourcing company (4 programmers and the boss), then when the stress and the frequent long shifts made the situation unbearable I made the switch to a better paid job with a more relaxed schedule that allows me some more free time.

The problem, however, is that for the most part, everything is coded in Classic ASP that interfaces with a custom made C++ queueing system that stores everything in AS400 systems. My boss used to be one of the developers that made the initial efforts towards this, and naturally won't ever approve a switch to another languages / technologies despite the increasing difficulty that represents developing today business needs with yesterday tools.

I'm pretty much stuck coding with Classic ASP in the foreseeable future, and I'm struggling to find ways to make it at least interesting, as I used to work with .NET and Java previously, and I feel like I'm going backwards... Any advice?

答:
How to make Classic ASP interesting if you are stuck with it?

First, take pride in your work (even though it's Classic ASP). Reason: A poorly developed (or patched) Classic ASP page will be an even BIGGER albatross around your neck. Your boss will naturally expect you to fix any bugs that arise, and it will feel yucky. Just load up some good music, put on your headphones, and get in and get out as quickly as you can (assuming that there is, in fact, light at the end of the tunnel, and that you'll soon be working on something more interesting).

Second, to the extent that you're able, do your best to make the pages look and feel nice. Work your magic with CSS. Use Bootstrap if you can. And use AJAX and other techniques to reduce load times and full screen refreshes.

Third, try your best to use jQuery, jQuery UI, and other client-side libraries to make the pages fast and fluid. Sometimes, you may be able to eliminate entire ASP pages with modals, wizards, or even SPAs! This will both reduce the amount of Classic ASP that you'll have to write and it will make the work far more interesting.


问:
Should I be paid for time spent learning a framework?
To give light to the situation: I am currently one of two programmers working in a small startup software company. Part of my job requires me to learn a Web development framework that I am not currently familiar with. I get paid by the hour.

So the question is: Is it wholly ethical to spend multiple hours of the day reading through documentation and tutorials and be paid for this time where I am not actively developing for our product? Or should the bulk of this learning be done at home, or otherwise off hours, to allow for more full-on development of our application during the work day?

答:
Should I be paid for time spent learning a framework?

Should a lawyer working on retainer be paid for time spent reading legal volumes?

The answer to both questions is 'YES'.

We have seen the computing world undergo enormous change in the past two decades, and you should expect more of the same for the foreseeable future.  An employer should expect and want its employees to keep abreast of these changes so that they retain their value to the company.

This is much like the relationship between a client and his/her lawyer that works on retainer. The client would undoubtedly want that lawyer to stay abreast of all changes occurring in the legal world, so that he/she can best represent the client in mediation and court room interactions.


问:
Charles Barkley syndrome
Charles Barkley was an excellent basketball player, a hall of fame, and a dream team member.  He played for the 76ers, Suns, and Rockets.  Yet he never won an NBA championship.  Some might argue this was because he was never surrounded by other players of his caliber, and in the NBA, you can't win on your own.

So what does this have to do with programming?

How many of you out there feel like Sir Charles?  Leading your team in every category, KLOCs, bugs fixed, systems configured...  Always the one pushing for improvements, upgrading systems, negotiating with customers...  Feeling like you are carrying the team.  Anger just under the surface.

Only to retire eventually, without "the ring"1.

1: Keep in mind, Charles never blamed his team.  He just performed at his best.

答: Teach, don't preach. It's always fun to make yourself sound smart and make other people feel dumb/inferior, but that won't help them. Some don't want to hear it, so don't waste your time on them. There will be at least one or two people willing to listen and learn. Pass on what others have passed on to you.</p>

Title: Charles Barkley syndrome


问:
How do I deal with classes that are only used once, say in only a single function?
I have a class that basically builds up a memory-efficient version of a structure to be used in a performance-critical section of code.

The resulting structure is ugly but extremely fast, so not using it isn't really an option, but I also can't use it as the only representation of my structure because it has parts not relevant to the analysis stripped. Did I mention it's also very ugly?

Let's call this class Fast. I also have the original, pretty representation, let's call it Pretty. I have a function called Process() which is supposed to take in an instance of Pretty, convert it to Fast and then do a few million calculations on it and spit out a result:

```<code>Pretty pretty;
// do stuff with pretty

// in another hpp:
double Process(const Pretty& pretty)
{
  Fast fast(pretty); // create my fast object

  // do some processing on fast

  return result; // at this point fast dies
}
</code>```

The instance of Fast is created and dies within Process, but unfortunately I can't declare a class within a function, so I have to declare it elsewhere.

What I would like to do is make the entire class accessible only to Process, and not even have it seen by anyone else (just like I would conversely declare a function private if the class were the only object that should have access to it). But I can't declare a class private!

Here's my current attempt:

```<code>class Process
{
public:
  static double DoProcess(Pretty pretty); // this is the process function

private:
  class Fast
  {
    // construct fast here (only Process can see this class!)
  };
};
</code>```

And then I just call Process::DoProcess(). This isn't really a critical issue so I didn't post it on SO, but it's a style question and I would really like to have a neat solution! I've never come across this issue before and was wondering how others have dealt with it, and if they came up with a nicer solution.

答:
I can see three viable options here, where from a design perspective I find the bottom one most attractive.

One is to indeed use your approach, perhaps with operator() to avoid redundancy.

Another option is to define the class inside the function itself (this is allowed now).

However, chances are you may need the class later, and honestly I doubt that your namespace is so littered that you can't offer the Fast class file scope.

In this scenario,  declare the Process method in your header and define it in a .cpp file, underneath the definition of your Fast class,  which you should wrap in an anonymous namespace.

Either way,  I would pull out the definition from the header.  Faster compilation is a nice gain,  but the biggest perk is keeping interface and implementation separate.


问:
REPL - Do You Find It Useful?
Recently I started learning Clojure and downloaded Clojure-Box for Windows which came with SLIME and have been fiddling around with Clojure using the REPL mode. Now, I have starting learning many languages that have REPL available (F#, Python, Haskell) but have never used it until I started with Clojure and I realized how much of a help it is.

I was wondering how many people use REPL for the languages that have them available. If you don't use them, what is your reasoning not to? If you do use them, do you use them for testing code or just for learning languages?

答:
Absolutely.  I've been using GHCi (the Glasgow Haskell Compiler's REPL) quite often.  Although I think the best way to learn how to design substantial programs is by typing them in a text editor (where you can write more than one line easily), a REPL provides some major advantages:

Makes testing one-liners easy, so you can learn language features quickly:

```<code>> (\xs -> zip xs (tail xs)) [1..10]
[(1,2),(2,3),(3,4),(4,5),(5,6),(6,7),(7,8),(8,9),(9,10)]
> (zip <*> tail) [1..10]
[(1,2),(2,3),(3,4),(4,5),(5,6),(6,7),(7,8),(8,9),(9,10)]
>
> sortBy (\a b -> compare (length a) (length b)) ["ab", "abc", "a"]
["a","ab","abc"]
> sortBy (compare `on` length) ["ab", "abc", "a"]
["a","ab","abc"]
</code>```

Provides in-console documentation:

```<code>> :i <*>
class (Functor f) => Applicative f where
  ...
  (<*>) :: f (a -> b) -> f a -> f b
  ...
    -- Defined in Control.Applicative
infixl 4 <*>
>
> :i on
on :: (b -> b -> c) -> (a -> b) -> a -> a -> c
      -- Defined in Data.Function
infixl 0 on
</code>```

Great for doing simple (and even not-so-simple) tasks when you'd rather not write a whole program:

```<code>> -- Find longest words that don't have repeated characters.
>
> readFile "/home/joey/twl06" >>= mapM_ putStrLn . take 10 . reverse . sortBy (compare `on` length) . filter ((==) <*> nub) . lines
UNCOPYRIGHTABLE
DERMATOGLYPHICS
TROUBLEMAKINGS
DERMATOGLYPHIC
AMBIDEXTROUSLY
UNPROBLEMATIC
UNPREDICTABLY
TROUBLEMAKING
SUBORDINATELY
MULTIBRANCHED
</code>```

Title: REPL - Do You Find It Useful?

Body:
Absolutely.  I've been using GHCi (the Glasgow Haskell Compiler's REPL) quite often.  Although I think the best way to learn how to design substantial programs is by typing them in a text editor (where you can write more than one line easily), a REPL provides some major advantages:

Makes testing one-liners easy, so you can learn language features quickly:

> (\xs -> zip xs (tail xs)) [1..10]
[(1,2),(2,3),(3,4),(4,5),(5,6),(6,7),(7,8),(8,9),(9,10)]
> (zip <*> tail) [1..10]
[(1,2),(2,3),(3,4),(4,5),(5,6),(6,7),(7,8),(8,9),(9,10)]
>
> sortBy (\a b -> compare (length a) (length b)) ["ab", "abc", "a"]
["a","ab","abc"]
> sortBy (compare `on` length) ["ab", "abc", "a"]
["a","ab","abc"]

Provides in-console documentation:

> :i <*>
class (Functor f) => Applicative f where
  ...
  (<*>) :: f (a -> b) -> f a -> f b
  ...
    -- Defined in Control.Applicative
infixl 4 <*>
>
> :i on
on :: (b -> b -> c) -> (a -> b) -> a -> a -> c
      -- Defined in Data.Function
infixl 0 on

Great for doing simple (and even not-so-simple) tasks when you'd rather not write a whole program:

> -- Find longest words that don't have repeated characters.
>
> readFile "/home/joey/twl06" >>= mapM_ putStrLn . take 10 . reverse . sortBy (compare `on` length) . filter ((==) <*> nub) . lines
UNCOPYRIGHTABLE
DERMATOGLYPHICS
TROUBLEMAKINGS
DERMATOGLYPHIC
AMBIDEXTROUSLY
UNPROBLEMATIC
UNPREDICTABLY
TROUBLEMAKING
SUBORDINATELY
MULTIBRANCHED


答:
You should use the separate compilation model of C++ to your advantage.

C++ allows you to define a class without using a header file, so you can just define Fast in the same source file as where you have the definition of Process.

To avoid name clashes with other units that might also have a (different) class Fast, you can wrap it in an anonymous namespace.

This way, although Fast exists for the entire program, only Process can access it, because that is the only part where the name of Fast is known.

This assumes that Process is defined within a .cpp file and not as an inline function in a header file. For functions of any complexity, this is good design anyway because it is unlikely that the compiler will inline them and it can speed up the compilation step significantly.

Title: How do I deal with classes that are only used once, say in only a single function?

Body:
I have a class that basically builds up a memory-efficient version of a structure to be used in a performance-critical section of code.

The resulting structure is ugly but extremely fast, so not using it isn't really an option, but I also can't use it as the only representation of my structure because it has parts not relevant to the analysis stripped. Did I mention it's also very ugly?

Let's call this class Fast. I also have the original, pretty representation, let's call it Pretty. I have a function called Process() which is supposed to take in an instance of Pretty, convert it to Fast and then do a few million calculations on it and spit out a result:

```<code>Pretty pretty;
// do stuff with pretty

// in another hpp:
double Process(const Pretty& pretty)
{
  Fast fast(pretty); // create my fast object

  // do some processing on fast

  return result; // at this point fast dies
}
</code>```

The instance of Fast is created and dies within Process, but unfortunately I can't declare a class within a function, so I have to declare it elsewhere.

What I would like to do is make the entire class accessible only to Process, and not even have it seen by anyone else (just like I would conversely declare a function private if the class were the only object that should have access to it). But I can't declare a class private!

Here's my current attempt:

```<code>class Process
{
public:
  static double DoProcess(Pretty pretty); // this is the process function

private:
  class Fast
  {
    // construct fast here (only Process can see this class!)
  };
};
</code>```

And then I just call Process::DoProcess(). This isn't really a critical issue so I didn't post it on SO, but it's a style question and I would really like to have a neat solution! I've never come across this issue before and was wondering how others have dealt with it, and if they came up with a nicer solution.


问:
Was .NET's IObserver<T> intended for subscribing to multiple IObservables?
There are IObservable and IObserver interfaces in .NET (also here and here).  Interestingly, the concrete implementation of the IObserver does not hold a direct reference to the IObservable.  It doesn't know who it's subscribed to.  It can only invoke the unsubscriber.  "Please pull the pin to unsubscribe."

edit: The unsubscriber implements the IDisposable. I think, this scheme was employed to prevent the lapsed listener problem.

Two things are not entirely clear to me, though.

Does the inner Unsubscriber class provide the subscribe-and-forget behavior?  Who (and when exactly) calls IDisposable.Dispose() on the Unsubscriber?  Garbage collector (GC) is not deterministic.

[Disclaimer:  overall, I've spent more time with C and C++ than with C# .]

What should happen if I want to subscribe an observer K to an observable L1 and the observer is already subscribed to some other observable L2?

```<code>K.Subscribe(L1);
K.Subscribe(L2);
K.Unsubscribe();
L1.PublishObservation(1003);
L2.PublishObservation(1004);
</code>```

When I ran this test code against MSDN's example, the observer remained subscribed to L1.  This would be peculiar in real development.  Potentially, there are 3 avenues to improve this:

If the observer already has an unsubscriber instance (i.e. it’s already subscribed), then it quietly unsubscribes from the original provider before subscribing to a new one.  This approach hides the fact that it’s no longer subscribed to the original provider, which may become a surprise later.

If the observer already has an unsubscriber instance, then is throws an exception.  A well-behaved calling code has to unsubscribe the observer explicitly.

Observer subscribes to multiple providers.  This is the most intriguing option, but can this be implemented with IObservable and IObserver?  Let’s see.  It is possible for the observer to keep a list of unsubscriber objects: one for each source.  Unfortunately, IObserver.OnComplete() does not provide a reference back to the provider who have sent it.  So, the IObserver implementation with multiple providers would not be able to determine which one to unsubscribe from.

Was .NET's IObserver intended for subscribing to multiple IObservables?

Does the textbook definition of the observer pattern require that one observer has to be able to subscribe to multiple providers? Or is it optional and implementation-dependent?

答:
The two interfaces are actually part of Reactive Extensions (Rx for short), you should use that library pretty much whenever you want to use them.

The interfaces are technically in mscrolib, not in any of the Rx assemblies. I think this is to ease interoperability: this way, libraries like TPL Dataflow can provide members that work with those interfaces, without actually referencing Rx.

If you use Rx's Subject as your implementation of IObservable, Subscribe will return an IDisposable that can be used for unsubscribing:

var observable = new Subject<int>();

var unsubscriber =
    observable.Subscribe(Observer.Create<int>(i => Console.WriteLine("1: {0}", i)));
observable.Subscribe(Observer.Create<int>(i => Console.WriteLine("2: {0}", i)));

unsubscriber.Dispose();

observable.OnNext(1003);
observable.OnNext(1004);
```


答:
As a (seemingly) leader in your team, you should NEVER mention to your team (or your bosses) that you don't feel like you're getting the credit you deserve. If you really want to get the credit you feel you deserve I have a semi-wild suggestion for you -

Help out your team. Help them fix bugs, help them configure systems. When time comes, and someone says "Hey, great job on getting all those bugs fixed Joe" - let him take the credit. The people around you will know what truly happened and will respect you more for not playing the "I/Me" game.

Sometimes you're better off staying in the background and letting the team take credit for the work that was accomplished. If you're carrying the load you SHOULD NOT say as much. TEAMS succeed or fail, NOT people.

Title: Charles Barkley syndrome

Body:
Charles Barkley was an excellent basketball player, a hall of fame, and a dream team member.  He played for the 76ers, Suns, and Rockets.  Yet he never won an NBA championship.  Some might argue this was because he was never surrounded by other players of his caliber, and in the NBA, you can't win on your own.

So what does this have to do with programming?

How many of you out there feel like Sir Charles?  Leading your team in every category, KLOCs, bugs fixed, systems configured...  Always the one pushing for improvements, upgrading systems, negotiating with customers...  Feeling like you are carrying the team.  Anger just under the surface.

Only to retire eventually, without "the ring"1.

1: Keep in mind, Charles never blamed his team.  He just performed at his best.


答:
The name "Scrum" symbolises a team working together to move a ball up the field of play. It's a team of equals working together on a single, focused goal.

It could be said that the phrasing used in Scrum is deliberately different. It acts as a constant reminder that what we do, and how we do it, has changed.

Title: Why the terms used in Scrum are so strange?

Body:
I'm not a native English speaker, currently I'm reading some articles about Scrum.

I was wondering if the English terms used in Scrum seem strange to you?
For example,

backlog instead of todo;

artifact instead of element;

retrospective instead of review;

even the name of Scrum, it make no sense to me as a process name.

Can anyone give some hint to me? For example, I don't see the relationship between a scrum in football and iteration process.


问:
IOS app updates that don't require App Store submission
Some apps, I've noticed that developers are able to update their software without submitting them to the App Store.

For example, Game of War will occasionally tell you that an update is available and to restart your device.  You can then watch the progress bar carefully and see that updates are being pushed to the app.

I'm assuming they are using XML to change certain attributes and their location on the server.  That's a guess but I don't know.  They are able to make significant feature changes to the game, like adding hyperlinks to map locations,  push sales promotions, add certain events etc. These methods don't require compilation, as that would obviously require resubmitting the app.

What technologies allow this? Are they all server side changes with XML objects being updated on the client? What is apple's policy in the developer terms?

答:
From the iOS guidelines, any app which downloads code in any form is (or at least should be) automatically rejected for the App Store. Most likely is that your app is downloading something which would be covered under the concept of 'content.' Depending on the particular app, this could be new images, sound effects/music, new structural descriptions (ie a file describing a new zone in your game, specifying how the game constructs it from existing resources, or resources included as part of the update), or any number of similar items. Basically, the AppStore component of the program will contain the logic used to construct and control the app, while the data being downloaded controls the specific content being shown at any given point in time.

From your example (Game of War), being an online multi-player game, it would likely contain code in the AppStore component which controls the interaction between the server and your device, how to send and receive chat messages, player actions, etc. I haven't played this particular game myself, but it appears to be using the standard gridded map model - each building (including it's phases of construction), and each unit on the map could be generated by the AppStore component based on downloaded image files and animation descriptions. Your game can incorporate updates including new unit types, or new buildings without having to change any code on the device, simply by downloading the components necessary to display them.

The structure is similar to how many MMO's (like World of Warcraft, etc) work on the PC, although the fact that interpreted code is still a fairly grey area in regards its legality in iOS apps (see this question) means that the apps are less likely to be downloading interpreted components which can change the fundamental interactions with the app (ie the actions you are able to perform in a game, or including a chat feature into an existing game, unless it was designed for and just not 'activated' in the initial release) and more just including new items which match one of the existing patterns of understood elements.

You will probably find this type of interaction more in games, where the coded logic makes up only a small fraction of the total size of the game and the majority of the size is the images, sounds, 3D models, structural descriptions, etc which the game uses to construct its internal environment, than in business apps. Essentially though, the inbuilt Maps and Music apps follow a similar concept:

your audio tracks would be the equivalent of a downloaded 'update' in Music

the idea of downloading purchased content to a new device through iTunes
operates on the same principal

while I believe Maps on the iOS downloads the map images directly
from a server, similar software in portable GPS devices use an
internal store of map images and road descriptions which can be
updated in this fashion to provide up-to-date information on new
roads without having to change any compiled code

even the AppStore itself works under the same underlying theory, if you
consider that the other installed applications are essentially it's 'content'
(the AppStore can download an 'update' to another installed app without having
to change any of its own code)


问:
Is it safe to rely on static analysis to "reproduce" concurrency bugs reliably?
I've inherited some Java code which I suspect harbours some concurrency bugs when synchronizing between a thread that queries data and an IO event that updates the same data. I'm trialling a static analysis tool called ThreadSafe which indeed detects various concurrency issues (i.e. field accessed from asynchronously invoked method without synchronization and Inconsistent synchronization of accesses to a collection).

After discovering how difficult it is to reproduce data races reliably by writing unit tests, I wondered if it's advisable to depend on ThreadSafe to "reproduce" the bugs reliably?
What I'm asking is, is it safe to depend on the static analysis tool to tell me when I've fixed the bugs? (Of course, to fix the bugs I will need to understand each one in context).

答:
Producing a useful static analysis tool involves balancing a number of conflicting concerns, including at least the following:

False positive (false alarm) rate

False negative (uncaught bug) rate

Run time and scalability

False positives are a critical concern with bug detection tools since they waste developer time. It's possible to eliminate false negatives, but for many types of bugs, including concurrency bugs, this would involve an unacceptable increase in the false positive rate. The rate of both false positives and false negatives can be decreased at the cost of increased run time, but the most accurate analysis techniques don't scale beyond small applications, and anyway they can't both be decreased to zero.

Dynamic analysis tools often claim a false positive rate of 0%, but that's because they only find bugs once they actually happen. For a race condition or deadlock that only happens once in a blue moon, that's not so useful.

For these reasons, ThreadSafe doesn't promise to find all concurrency bugs - it aims to find the most important ones, with a low false positive rate. Some users have tried ThreadSafe on code with a known concurrency bug that they spent days to find, and discover that it finds that bug - and often other genuine bugs that they didn't know about - with no false positives, within minutes.

A good place to start for information about ThreadSafe is this InfoQ article. For more, see the ThreadSafe website where you can sign up for a free trial.

(Disclosure: ThreadSafe is a commercial tool, and I'm co-founder of Contemplate, the company that produces it.)


问:
What is a UNiversal IT Test (UNITT) and how do I prepare for one?
I will be taking an advanced PHP UNiversal IT Test (UNITT) for a position I am applying for.

However, I am unfamiliar with the term 'unitt test'.

What is a unitt test and how would a company execute one?

If anyone is familiar with this, please let me know the best way to prepare

答:
It sounds like the company is getting you to take the online tests administered by Fourth Valley Concierge (see here), specifically selecting PHP for the programming language component. You would need to speak to the company in question to see whether this is the only component you will be taking, or if they are requiring you to do the full UNITT test.

As for the test itself, the only information I have located indicates it is composed of a series of multiple-choice questions, and (for the programming component) practical programming skill questions performed through an online testing structure. From their 2012 tests:

Round 1: an examination of logical thinking, technical knowledge and business knowledge. The subject of technical knowledge includes questions from four categories: algorithms, database, security, and network. The test time is 60 minutes, and the examination includes multi-choice questions.

Round 2: an examination measuring your programming skills. You may choose one programming language among Java, PHP and C++. The examination consists of knowledge-based multi-choice questions and practical programming skill questions. The test time is 35 minutes.

As for preparation, a basic knowledge and familiarity with PHP (since this is apparently the language required for this company), as well as a firm grasp of the basic skills (covering the four main test categories of algorithms, database, security and network) would probably be useful, particularly how to implement standard algorithms, access and manipulate databases, maintain security and interface with the network in the given language. You might also want to speak to the company who is asking you to take the test - explaining that while you are familiar with PHP (which I hope you are given this is what they are testing you for), that you are not familiar with the specific test they have indicated and ask them whether they have more information on it they could give you.

OwnerDisplayName: Willow


问:
How to organize the dependencies of a project
I have a project built with Gradle, which contains libraries which can be used freely outside the main project, like this:

The folders with a square at the bottom right are project modules.

I want to opensource this project (I mainly use Git and GitHub for tasks like this), but I have no idea how to organize it. Should I create separate repositories for each library (and if so, how can I link them to the main repository?), or should I put it all in one repo (I guess that's bad practice)?

The main criteria is that when git clone repo_url is run, it should recreate project structure one-to-one, so it can still be built with ./gradlew build.

答:
You can create separate Git repositories for each library, publish them, then use Git submodules to link them to the main repository.

```<code>git submodule add submodule1_url directory1
git submodule add submodule2_url directory2
git commit -m "add submodules"
</code>```

Working with submodules is a little more complex. After cloning the repo, you need to clone the submodules as well:

```<code>git clone repo_url
cd repo
git submodule init
git submodule update
./gradlew build
</code>```

And voilà - you have a project with independent submodules.

You might also want to look at gradle: Chapter 50. Dependency Management. I haven't read that myself, but handling the dependencies outside of the SCM is often preferred, and as gnat was saying, you should take a look at the different options and decide for yourself.

Body:
You can create separate Git repositories for each library, publish them, then use Git submodules to link them to the main repository.

git submodule add submodule1_url directory1
git submodule add submodule2_url directory2
git commit -m "add submodules"

Working with submodules is a little more complex. After cloning the repo, you need to clone the submodules as well:

git clone repo_url
cd repo
git submodule init
git submodule update
./gradlew build

And voilà - you have a project with independent submodules.

You might also want to look at gradle: Chapter 50. Dependency Management. I haven't read that myself, but handling the dependencies outside of the SCM is often preferred, and as gnat was saying, you should take a look at the different options and decide for yourself.


问:
Who invented Haskell's type classes?
Haskell's type classes are a very powerful tool and give Haskell a great expressive ability, compared to functional languages that don't have them. When were they invented, and who invented them?</p>

答:
The paper which introduced type classes was "How to make ad-hoc polymorphism less ad-hoc" by Wadler and Blott in 1988. In the paper, they mention that type classes were discovered during the standardization work on Haskell, however the wording doesn't make it clear who discovered them. (One would assume it was the authors, but that isn't said explicitly.)

They mention some prior art by Stefan Kaes.

The Acknowledgement section says:

The important idea that overloading might be reflected in the type of a function was suggested (in a rather different form) by Joe Fasel. For discussion and comments, we are also grateful to: Luca Cardelli, Bob Harper, Paul Hudak, John Hughes, Stefan Kaes, John Launchbury, John Mitchell, Kevin Mitchell, Nick Rothwell, Mads Tofte, David Watt, the members of the Haskell committee, and the members of IFIP 2.8.

Title: Who invented Haskell's type classes?


问:
What is the advantage of currying?
I just learned about currying, and while I think I understand the concept, I'm not seeing any big advantage in using it.

As a trivial example I use a function that adds two values (written in ML). The version without currying would be

```<code>fun add(x, y) = x + y
</code>```

and would be called as

```<code>add(3, 5)
</code>```

while the curried version is

```<code>fun add x y = x + y
(* short for val add = fn x => fn y=> x + y *)
</code>```

and would be called as

```<code>add 3 5
</code>```

It seems to me to be just syntactic sugar that removes one set of parentheses from defining and calling the function. I've seen currying listed as one of the important features of a functional languages, and I'm a bit underwhelmed by it at the moment. The concept of creating a chain of functions that consume each a single parameter, instead of a function that takes a tuple seems rather complicated to use for a simple change of syntax.

Is the slightly simpler syntax the only motivation for currying, or am I missing some other advantages that are not obvious in my very simple example? Is currying just syntactic sugar?

答:
Currying depends crucially (definitively even) on the ability to return a function.

Consider this (contrived) pseudo code.

var f = (m, x, b) => ... return something ...

Let's stipulate that calling f with less than three arguments returns a function.

var g = f(0, 1); // this returns a function bound to 0 and 1 (m and x) that accepts one more argument (b).

var y = g(42); // invoke g with the missing third argument, using 0 and 1 for m and x

That you can partially apply arguments and get back a re-usable function (bound to those arguments that you did supply) is quite useful (and DRY).

Title: What is the advantage of currying?


问:
How to structure a program into classes
So after a while of working in programming field I still haven't figured it out how exactly should programs be structured, in a large set I mean. Which I think it's also because of working in an enterprise development.

Say that I want to write a program, a messenger for a LAN network. How do I really know what classes to make for this program? How to divide the program into smaller pieces and classes in the best and most efficient way? This is just an example. I don't mean specifically for this problem set, it's the general approach that I am wondering about.

EDIT: I have asked this question here because it exactly says in the help center:

What topics can I ask about here?

Programmers Stack Exchange is a Q&A site for professionals and
students in software development and related fields who are interested
in getting expert answers on conceptual questions about software
development.

If you have a question about...

software requirements

software architecture and design

algorithm and data structure concepts

My question, according to my understanding, refers to the to the software architecture and design. It's not a specific coding question otherwise it would have been asked on Stackoverflow. It is a conceptual question which should be fit here. The comments and answers are referring to that there are a lot of books covering this topic. I'd accept even a book name for an answer if the book answers my question. If the answer does not fit into this form of Q&A, at least I could be pointed to the right direction. After all we're all here to learn something.

答:
By some definitions, a class is a type (or a structure) that provides implementation and interface (assuming it's not an abstract class) for some specific sub-set of a problem.

With that in mind we can say that most sensible way of organizing and naming class would be to divide them logically.

In your given example the classes could be:

```<code>Message
Session
Atendee
Status
Connection
... and so on
</code>```

This is all strictly related to OOP: Object Oriented Programming - http://en.wikipedia.org/wiki/Object-oriented_programming#Additional_features - if you take a look at the Encapsulation enforces modularity you could see that

Encapsulation refers to the creation of self-contained modules that bind processing functions to the data. These user-defined data types are called "classes," and one instance of a class is an "object." For example, in a payroll system, a class could be Manager, and Pat and Jan could be two instances (two objects) of the Manager class. Encapsulation ensures good code modularity, which keeps routines separate and less prone to conflict with each other.

... which is more or less what I was trying to convey.

Title: How to structure a program into classes

Body:
By some definitions, a class is a type (or a structure) that provides implementation and interface (assuming it's not an abstract class) for some specific sub-set of a problem.

With that in mind we can say that most sensible way of organizing and naming class would be to divide them logically.

In your given example the classes could be:

Message
Session
Atendee
Status
Connection
... and so on

This is all strictly related to OOP: Object Oriented Programming - http://en.wikipedia.org/wiki/Object-oriented_programming#Additional_features - if you take a look at the Encapsulation enforces modularity you could see that

Encapsulation refers to the creation of self-contained modules that bind processing functions to the data. These user-defined data types are called "classes," and one instance of a class is an "object." For example, in a payroll system, a class could be Manager, and Pat and Jan could be two instances (two objects) of the Manager class. Encapsulation ensures good code modularity, which keeps routines separate and less prone to conflict with each other.

... which is more or less what I was trying to convey.


答: Once I discovered LINQPad, my IDE usage for scratch projects and learning went way down. Although not traditional REPL, it is a scratch-pad-type interface for .NET languages and is excellent for learning and testing.  There are so many times that I just want to try something out quickly without the full-blown heavyweight development environment and REPL is perfect for that.</p>

Title: REPL - Do You Find It Useful?

Body:
Recently I started learning Clojure and downloaded Clojure-Box for Windows which came with SLIME and have been fiddling around with Clojure using the REPL mode. Now, I have starting learning many languages that have REPL available (F#, Python, Haskell) but have never used it until I started with Clojure and I realized how much of a help it is.

I was wondering how many people use REPL for the languages that have them available. If you don't use them, what is your reasoning not to? If you do use them, do you use them for testing code or just for learning languages?


问:
Automatically create or update object in database
I have a database class with the following interface:

```<code>public Database {
    //returns false if p (its ID) is already available
    //otherwise adds p the the list and returns true
    public boolean create(Person p);

    //returns false if p (its ID) was not found in the list
    //replaces the available Person q (q.ID == p.ID) with p and returns true
    public boolean update(Person p);

    //returns false if p (its ID) was not found in the list
    //marks the available Person q (q.ID == p.ID) as inactive returns true
    public boolean remove(Person p);
}
</code>```

The Person is immutable and can be identified by a unique id. I have a EditDialog which looks like this:

I wanted to reuse my code and so the EditDialog is used for create a Person or update it. So this dialog is initialized either by a available Person instance (Edit-Operation) or by a new one (Create-Operation).

Because I learned that there is always an evil user I wanted to avoid the following scenario:

Click "Create Person" button

New Person is created in Database

EditDialog for new Person is displayed

Click "Chancel" button

Person has to be removed (= marked inactive) from Database

EditDialog is disposed

repeat

Which would lead to many inactive Persons in the Database. So I decided to only create the Person in the Database, if the user clicks the "Save" button. Which leads to two possible scenarios for the Listener of the "Save" button:

New Person should be created in Database

Person should be updaated in Database

So the code of the Listener looks like the following:

```<code>if(!database.create(p) {
    database.update(p);
}
</code>```

Which is not so pretty in my opinion. The Long and the short of it is, should the Database automatically

update a Person if it's availabe at invokation of create(Person)?

create a Person if it's not yet available at invokation of update(Person)?

Or is there another solution/practice I didn't think about?

答:
Your UI should tell the database layer what operation to perform. In the UI, you will obviously have two buttons, one which says "Create new Person" and the other saying, "Edit this Person". So you already know what action needs to be performed.

When you invoke the UI Dialog, pass in this state (Add or Edit) to the dialog. Then, based on the value of this variable, the dialog can call either Database.create() or Database.update() when you click Save.


问:
Testing gap between unit and integration: Integration in the Small, Component, Unit Integration Tests
Over the past few weeks I've been mulling and researching how to fill a gap in our testing methodology.  In simplified terms unit tests are too small and traditional integration tests are too big.

A frequent scenario comes up where A and B both use component C.  However A and B have slightly different requirements for, and make slightly different assumptions about C.  If I'm the developer of A how and where do I test my assumptions about C?

Obviously unit testing A with mocked assumptions about C is fine for testing A in isolation, but it doesn't test the assumptions themselves.

Another possibility is to add unit tests for C.  However this isn't ideal because, while A is in development, altering the tests for C with evolving assumptions from A will excessively be clumsy. Indeed As developer might not even have adequate access to the unit tests of C (e.g an external library).

To frame this with a more concrete example: Assume that this is a node application.  A, and B depend on C to read a file (among other things) and store the file contents in object passed to C.  At first all files that C handles are small and can be read synchronously without significant blocking. However the developer of B realizes that his files are getting huge and needs to switch C to a async read.  This results in a sporadic synchronization bug in A, which is still assuming C is reading files synchronously.

This is the type of bug that is notoriously difficult to track down from full integration tests, and may not be caught in integration tests at all.  It is also not caught by As unit tests because the As assumptions are mocked.  However it could easily be caught by a "mini" integration test that exercises just A and C.

I've only found a few references to this type of testing. Integration in the Small, Component Integration Testing, Unit Integration Testing.  It also relates somewhat to BDD testing direction rather than formal TDD unit testing.

How do I fill this testing gap?  Specifically -- where do I put such tests?  How do I mock the inputs of A and C for "mini" integration tests? And how much effort should be put into separating testing concerns between these tests and unit tests? Or is there a better way to fill the testing gap?

答:
It appears to me that you have a fundamental problem with your components.

C should do what C needs to do, and be tested, documented and designed to do just that. When you have a situation where C is designed to "do what B wants" you have an abusive relationship, one that becomes very clear when A arrives and wants C to do something slightly different.

What you should not be doing is unit testing C in the context of A, and especially not A in the context of C - you test A independently, and you provide the results of a mocked C to A. If the real-world version of C does not provide those same results, then you have a bug or design flaw in C that will be caught when you perform your big integration tests. Unit testing has always been this way - you cannot test one unit by testing another unit at the same time. Unit testing just isn't designed to do that.

Integration tests do not have to be "the entire program", though they frequently as set up that way. They can be a test rig that runs A and C together without running the rest of the program (or as little of it as you can get away with). At this point I can't advise further as it depends what these components do  and how they interact with the rest of your program but its usually the case that you can write a test rig that provides test coverage of both components. Whether it is worth the effort to do that, or whether it is more efficient to integration test the whole program as one (even if you run a subset of the integration tests) is something only you can answer. Most integration tests are comprised of many sections so hopefully you should be able to run just those relevant to these 2 components (and if not, get your integration test suite so it does work in many pieces).


问:
Can a version of Python's shelve module that knows when its entries have been modified be written in any programming language?
shelve is a Python module that makes it easy to persist a Python dictionary to disk (under the right conditions).

The documentation for shelve gives this example to demonstrate one of the pitfalls of using a shelf:

```<code>import shelve

d = shelve.open(filename)

# ...snip...

# as d was opened WITHOUT writeback=True, beware:
d['xx'] = range(4)  # this works as expected, but...
d['xx'].append(5)   # *this doesn't!* -- d['xx'] is STILL range(4)!
</code>```

The documentation explains:

Because of Python semantics, a shelf cannot know when a mutable persistent-dictionary entry is modified. By default modified objects are written only when assigned to the shelf (see Example).

To say that shelves behave this way "because of Python semantics" seems to me to be measuring Python via a high bar! It would be hard to for shelve to know whether any object contained in a shelf has a reference to something which has been mutated (or a reference to something that has a reference to something that has been mutated). Can this be done in any programming language?

答:
No, this is not just a Python problem.

Resolving the question of "has this object been modified since X happened?" (in this case, the object being added to the dictionary) would require one of two things.  Either you use immutable objects, in which case the answer is always "no" and the question is rather meaningless, or you have some way to note when an object is changed in any way.

As far as I know, no language does this automatically.  The .NET framework has a concept of "observable properties" that raise an event when the property is modified, but they have to be implemented manually, and they will only work for properties on the object itself.  (If the object has a sub-object that gets modified, this would change the parent object's serialized representation too.)  So no; this may be an issue "because of Python semantics" but it's because of object-oriented semantics in general.


问:
Forcing ExtJS application updates after deployment
I work on an ExtJS application with a Django backend, and we keep running into issues when we push new code. Our users seldom refresh their browsers, so after a code push we end up with users using the same (now outdated) version of our ExtJS application for days at a time instead of the new, updated version.

How do other people deal with this issue? (I haven't found anything online about this, so I probably haven't found the right keywords yet.)

答:
It seems like you are running into issues with the browser caching older versions of your application and resource files.  This is a common problem as web browsers are "greedy" cache-ers and will go through great lengths not to use updated versions.

You have a few options.  ExtJS itself supports a "no-cache" option that can be configured via an application load configuration. disable caching configuration.  This will cause your browser to fetch each file anew on every load.  This can have some negative effects if you application changes rarely (every 3 months or so), but you are forcing users to download MBs of application files for every load.  This however is very good when you are in development and code changes regularly.

For the rarely changing app, I use a custom application name ("aka, b3.0-myapp") and include all the app files in the b3.0-myapp directory.  When upgrade time happens, I rename the app b3.1-myapp, and move the app directory.  You can then do some load failure handlers (aka, their code still tries to load 3.0), and present a message gracefully at that point.