答:
If you think that it would help the team's efforts, you should not hesitate to soften the "any developer can fix any bug" mentality which you see as creating issues.

The practice of Collective Code Ownership, sometimes also called Shared Code, is a fundamental principle in many flavors of Agile development, and it's probably what you're experiencing:

From extremeprogramming.org:

Collective Ownership encourages everyone to contribute new ideas to
  all segments of the project. Any developer can change any line of code
  to add functionality, fix bugs, improve designs or refactor. No one
  person becomes a bottle neck for changes.

From c2.com:

ExtremeProgramming considers code to belong to the project, not to an
  individual engineer. As engineers develop required functionality, they
  may browse into and modify any class. They are responsible for keeping
  all the UnitTests running (and writing new ones for new
  functionality). They take on the same integrity-preserving duties as
  the class owner in a CodeOwnership situation.

Working in this mode lets a responsible team move quickly to add new
  functionality while keeping responsibility in the right objects.
  CodeOwnership creates dependencies and bottlenecks when implementing
  UserStories. We avoid code ownership, because it conflicts with
  commitment from the PlanningGame. ("Code is nothing, stories are
  everything!")

There's some definite benefits to Collective Code Ownership. However, you are not the first person to note deficiencies in that approach. None other than Martin Fowler describes an approach that lies in-between the extremes of Strong Code Ownership (where individuals "own" their modules) and Collective Code Ownership. He describes this as Weak Code Ownership:

Weak code ownership is similar [to Strong Code Ownership] in that modules are assigned to owners,
  but different in that developers are allowed to change modules owned
  by other people. Module owners are expected to take responsibility for
  the modules they own and keep an eye on changes made by other people.
  If you want to make a substantial change to someone else's module it's
  polite to talk it over with the module owner first.

In the same article, he goes on to say:

The choice between weak and collective ownership has more to do with
  the social dynamics of the team. Both seem to work, and fail, equally
  well. Personally I prefer the dynamics of a collective code ownership
  team - particularly in the context of Extreme Programming.

The bottom line is that to truly adhere to Agile principles, the team should do what leads to good-quality, working code. If that means loosening the grip on Collective Code Ownership, then there's nothing wrong (or anti-Agile) about that.


问:
ORM: Keep entities coherent in a cache or retrieve entities each time?
We have a tricky question in a project using Java & Hibernate, with a model containing bi-directional relationships.

As it's a small project with few users, few entities, and few rows involved in relationships (not more than 100 in 1-n relationships), we don't really need a 2nd level cache.

Operations done with entities are simple: inserting, removing and performing some computations with entities involving relationships loading.

Let say we have two Java entities: Room and Furniture. An item of furniture is in one room and a room can have many items of furniture. So Furniture has a reference to Room, and Room has a list of Furniture.

For the Delete Furniture action, the easiest thing to do is to retrieve the right Furniture, and tell the EntityManager to remove the Furniture. But, to ensure the Java instances remain coherent, we should also remove the Furniture instance in the list of Furnitures in the associated Room. Unfortunately, if the Room instance is not loaded, a request will be done to the database for nothing if we don't have a cache.

So, what would be a better choice between:

A) Keeping it simple

In general, no preoccupation about bilateral relationships in java instances coherence, as we don't have 2nd level cache

Well document the fact that there is a cache per-action, so if specific computations must be done requering bilateral relationships coherence within an action, this action must take care of the coherence

No boilerplate code for bilateral relationships coherence management needed

No overhead of loading non-necessary entites

If a 2nd level cache must be added, then a big effort in refactoring has to be done

B) Keeping it coherent

Always maintain the bilateral relationship's coherence

Enable 2nd level cache

答:
Personally I'd do the simplest thing that could possibly work: Don't auto-fix the bilateral relations.

I've previously developed and maintained a system that (among many other things) did exactly this: ensure that the relations between business objects where always in sync with what the DB would look like (i.e. if you remove one item, the other is updated accordingly). It was quite a complex piece of code and it was pretty hard to keep all the corner cases in mind (it didn't help that this also supported nested transactions).

But if your business transactions are well defined and work pretty much independently from each other and each one is run in its own transaction, then all that complexity brings very little advantage.

ContentLicense: CC BY-SA 3.0


问:
JVM vs operating systems
Recently i was re-visiting the basic concepts of operating systems. Since I am a java developer, I have inherently started looking at everything from java point of view. I am also reading 'Inside the JVM fundamentals' from

http://www.artima.com/insidejvm/ed2/jvm.html

so when I see the basics of operating systems and JVM, I have begun to think that there are lot of similarities on an abstract level, i.e. both do the memory management, process scheduling, etc.

So I want to ask SO programmers whether I am correct in my learning or assumptions?

答: An Operating System is a Virtual Machine. A Virtual Machine is an Operating System. It's really more a matter of intent. The Squawk JVM, for example, is explicitly designed to run as an Operating System.</p>

Title: JVM vs operating systems


问:
Relative value of manual vs automated testing
The organisation I work for has recently employed a testing officer to run manual tests, but when I asked about being given time as a developer to write unit tests the response was that the manual testing would provide a bigger bang for the buck. That is something that feels wrong to me and I'm looking for a means to rate manual and automated testing against each other that is more scientific than a gut-feeling. I'm not saying there is no place for manual testing - but automated testing would seem, to me at least, to remove some of the more repetitive and boring tasks. We have a build server that runs some unit tests and some selenium tests - so its not like the idea of automated testing is a no-go, but just seen as a lower return on investment.

I can understand that having someone perform a full end to end test of a system tests the final product and ultimately that's all the user cares about, but it is slow going and very repetitive. Manual regression testing means repeating all the previous tests and confirming nothing has changed and if there's 4 paths through a process then that's 4 manual tests that could well take 5 minutes each.

So are there any verifiable facts and figures I can use to make the case for budgeting time for automated testing? For that matter what are the disadvantages to automated testing beyond those in the link?

答:
I'd be careful at all when thinking about "manual" testing vs "automated" testing in a return-on-investment (ROI) context. It's a form of fallacious thinking when discussing the value of automation (see the "Time Machine" section of that link).

The Time Machine fallacy summed up is this: the only way you can truly determine the ROI of a testing approach is by having a time machine where you can visit the future and see what happened. Since you (most likely) can't do this, ROI estimations should be seen as a heuristic at best, and not some hard rule. Use current information to make an informed decision about a given testing effort is useful to your team or not.

Instead, when it comes to testing, think about which areas of your product need the most attention, and where the largest risks may be. Perhaps it's been identified that end-to-end integration testing might find the most issues with your app. Even if unit testing brings benefits, those benefits may not be worth the associated costs (getting developer buy in, writing and running tests, etc). Likewise, try thinking about benefits/costs instead of advantages/disadvantages for testing.


答:
First, you should clearly differentiate unit tests and other automated tests. Those are two different things, with different aims.

Unit tests are tests to validate very small portions of your code. They are typically white box tests, written by a developer who knows the source code "under test". In TDD, they are written in a test-first manner, by a dev who is going to write the source code after he wrote the test. Those kind of tests cannot be transferred to a "test officer" by their nature, and if your organization is not completly misguided, you should not have to ask your boss if and when you are allowed to write them - just as you should not have to ask your boss if and when you are allowed to write comments into your source code.

Integration tests, acceptance tests and other black-box tests are a different thing. If you have a testing officer who is going to apply those tests just manually, and he has to repeat the same kind of tests over and over again, the need for automation should be requested by him, not by you (of course, you should make transparent to him what kind of tests you can automate, and which not). He should tell you for which kind of tests he thinks that automation will make sense, and for which one not. Perhaps he is going to do the automation himself, using some regression testing tool, or he will ask your help for creating some tools for him.

Of course, when you think if he is not experienced or smart enough to come to that conclusion by himself, you should talk to him (and if that does not help, perhaps to your boss). However, IMHO you should do this only when you get the impression that your testing officer is a bottleneck in your production because of some missing test automation.

Title: Relative value of manual vs automated testing

Body:
The organisation I work for has recently employed a testing officer to run manual tests, but when I asked about being given time as a developer to write unit tests the response was that the manual testing would provide a bigger bang for the buck. That is something that feels wrong to me and I'm looking for a means to rate manual and automated testing against each other that is more scientific than a gut-feeling. I'm not saying there is no place for manual testing - but automated testing would seem, to me at least, to remove some of the more repetitive and boring tasks. We have a build server that runs some unit tests and some selenium tests - so its not like the idea of automated testing is a no-go, but just seen as a lower return on investment.

I can understand that having someone perform a full end to end test of a system tests the final product and ultimately that's all the user cares about, but it is slow going and very repetitive. Manual regression testing means repeating all the previous tests and confirming nothing has changed and if there's 4 paths through a process then that's 4 manual tests that could well take 5 minutes each.

So are there any verifiable facts and figures I can use to make the case for budgeting time for automated testing? For that matter what are the disadvantages to automated testing beyond those in the link?


问:
Validating Objects With XSDs: Is Re-Serializing Redundant or Negligible?
Context:

I've got a web service that deals with request / response objects. There are strict, externally-defined schemas constraining both the structure and the content of both requests and responses. I need to validate all requests as they are received and all responses before they are sent back (on the web service end of the wire).

I don't want to replicate the validation rules in code, so I'll be validating serialized request / response objects (XML), probably using XmlReader as a starting point (for speed). It'll be 1-way object --> XML validation method that screams if validation fails, otherwise the original object will be used for the actual work.

I'm using WCF, but with XMLSerializer as the schemas are complex and I need the additional XSD support.

Question:

1) Is there a way to avoid re-serializing the objects as they hit my end of the wire? Ideally I'd like to get at the XML before it's de-serialized on the way in, and after it's serialized, just before it goes, on the way out.

I'm aware of [OnSerializing] and [OnSerialized] annotations, but they won't work with XMLSerializer. I don't think I should be writing ReadXml() and WriteXml() using IXmlSerializable either - the schemas are complex and subject to change.

2) Given the XML documents are quite small (122kb seems to be the top end in the sample data set I have) am I right in asserting that the performance hit of re-serializing will be negligible?

3) Any better ideas?

答:
Have you thought about using the XSD code-gen tools? They can deserialize/serialize and validate via schema orders of magnitude faster than other techniques in C#. You can use partial classes or wrapper classes to add additional fields or object hierarchy for your domain business logic.

```<code>xsd.exe schema.xsd /classes
</code>```

Some code I lifted from here: http://snipplr.com/view/2660/serializing-and-deserializing-a-class-created-with-xsdexe-using-xml-strings/

```<code>public static string SerializeToXmlString(object targetInstance)
{
    string retVal = string.Empty;
    TextWriter writer = new StringWriter();
    XmlSerializer serializer = new XmlSerializer(targetInstance.GetType());
    serializer.Serialize(writer, targetInstance);
    retVal = writer.ToString();
    return retVal;
}

public static object DeserializeFromXmlString(string objectXml, Type targetType)
{
    object retVal = null;
    XmlSerializer serializer = new XmlSerializer(targetType);
    StringReader stringReader = new StringReader(objectXml);
    XmlTextReader xmlReader = new XmlTextReader(StringReader);
    retVal = serializer.Deserialize(xmlReader);
    return retVal;
}
</code>```

If you can't use XSD.exe (as you imply in your comments) then how about writing a few helper class functions that use XmlDocument.Validate right as you receive or send the messages? http://msdn.microsoft.com/en-us/library/ms162371.aspx You wouldn't really be duplicating validation code if it's a shared component.

From their nice example:

```<code>XmlReaderSettings settings = new XmlReaderSettings();
settings.Schemas.Add("http://www.contoso.com/books", "contosoBooks.xsd");
settings.ValidationType = ValidationType.Schema;

XmlReader reader = XmlReader.Create("contosoBooks.xml", settings);
XmlDocument document = new XmlDocument();
document.Load(reader);

ValidationEventHandler eventHandler = new ValidationEventHandler(ValidationEventHandler);

// the following call to Validate succeeds.
document.Validate(eventHandler);
</code>```

Body:
Have you thought about using the XSD code-gen tools? They can deserialize/serialize and validate via schema orders of magnitude faster than other techniques in C#. You can use partial classes or wrapper classes to add additional fields or object hierarchy for your domain business logic.

xsd.exe schema.xsd /classes

Some code I lifted from here: http://snipplr.com/view/2660/serializing-and-deserializing-a-class-created-with-xsdexe-using-xml-strings/

public static string SerializeToXmlString(object targetInstance)
{
    string retVal = string.Empty;
    TextWriter writer = new StringWriter();
    XmlSerializer serializer = new XmlSerializer(targetInstance.GetType());
    serializer.Serialize(writer, targetInstance);
    retVal = writer.ToString();
    return retVal;
}

public static object DeserializeFromXmlString(string objectXml, Type targetType)
{
    object retVal = null;
    XmlSerializer serializer = new XmlSerializer(targetType);
    StringReader stringReader = new StringReader(objectXml);
    XmlTextReader xmlReader = new XmlTextReader(StringReader);
    retVal = serializer.Deserialize(xmlReader);
    return retVal;
}

If you can't use XSD.exe (as you imply in your comments) then how about writing a few helper class functions that use XmlDocument.Validate right as you receive or send the messages? http://msdn.microsoft.com/en-us/library/ms162371.aspx You wouldn't really be duplicating validation code if it's a shared component.

From their nice example:

XmlReaderSettings settings = new XmlReaderSettings();
settings.Schemas.Add("http://www.contoso.com/books", "contosoBooks.xsd");
settings.ValidationType = ValidationType.Schema;

XmlReader reader = XmlReader.Create("contosoBooks.xml", settings);
XmlDocument document = new XmlDocument();
document.Load(reader);

ValidationEventHandler eventHandler = new ValidationEventHandler(ValidationEventHandler);

// the following call to Validate succeeds.
document.Validate(eventHandler);


答:
Everyone always wants external examples and studies, but these aren't very effective in convincing management.  If manual testing is truly a bottleneck at your company, then you will have all the internal examples you need:

A bug accidentally goes out the door.  You state that it used to work
  and request it get added to the regression tests.  Manual tester
  states it will make regression testing take too long.  You offer to
  make an automated test for it.  Manual tester welcomes the idea
  because he has been feeling overwhelmed and would like more time to
  focus on the more "interesting" test cases.  With the voices of angry
  customers still ringing in their ears, management starts to see your
  point about test automation.

If meetings like this aren't happening at your company, no amount of external studies will make your case.


问:
Is Safari Books Online still the best game in town?
I'm a Safari Books subscriber and have been for years.  I like having all the books available immediately.  I was wondering if there was a better competing service.  Does anyone know if there's another comparable service that maybe has a better search function (my frustration with which is what prompted me to ask this in the first place...)?</p>

答:
There's also Creative Edge creativeedge.com, but searching wouldn't be any different from Safari Books because Creative Edge is also an O'Reily site. The main differences are the subscription rates and content. Depending on what you're programming, Creative Edge might be a cheaper solution, since the unlimited option is closer to $20/mo. There aren't any download tokens and it's geared toward Creative work, as the name implies. A search for something like "comptia a+" or pmap ps wouldn't get you very far, but more general topics like C++ coding, HTML and django will get you a number of hits.

As for the searching, one thing you can try would be to use a third party search engine to do a site search, i.e., plug site:safaribooksonline.com pmap ps into Google. Other search engines like Yahoo, Bing! or Yandex will give you far fewer results than Google for the O'Reily sites, so it's probably a promotional deal with Google to generate page previews to potential subscribers.

Plugging the ISBN into Google Books and doing a search from the book preview can also be helpful.

World Cat is good for locating other editions of books when you can't find them on Safari, but it's not so great for the whole reading instantly thing.


问:
Is it reasonable to build applications (not games) using a component-entity-system architecture?
I know that when building applications (native or web) such as those in the Apple AppStore or Google Play app store that it's very common to use a Model-View-Controller architecture.

However, is it reasonable to also create applications using the Component-Entity-System architecture common in game engines?

答:
If the problem domain is well suited to it, certainly.

My current work involves an app that needs to support a variety of capabilities depending on a bunch of runtime factors. Using component based entities to decouple all of those capabilities and allow extensibility and testability in isolation has been idyllic for us.

edit:
My work involves providing connectivity to proprietary hardware (in C#). Depending on what form-factor the hardware is, what firmware is installed on it, what level of service the client has purchased, etc, etc. we need to provide different levels of functionality to the device. Even some features that have the same interface have different implementations depending on what version the device is.

Previous codebases here have had very wide interfaces with many not implemented. Some have had many thin interfaces that were then statically composed in one beasty class. Some simply used string -> string dictionaries to model it. (we have many departments who all think they can do it better)

These all have their deficiencies. Wide interfaces are a pain and a half to mock/test effectively. Adding new features means changing the public interface (and all existing implementations). Many thin interfaces led to very ugly consuming code, but since we ended up passing around a big fat object testing still suffered. Plus the thin interfaces didn't manage their dependencies well. String dictionaries have the usual parsing and existence issues and well as performance, readability and maintainability hellholes.

What we're using now is a very slim entity that has its components discovered and composed based on runtime info. Dependencies are done declaratively and auto-resolved by the core component framework. The components themselves can be tested in isolation since they work directly with their dependencies, and issues with missing dependencies are found early - and in one location rather than first use of the dependency. New (or test) components can be dropped in and no existing code is impacted by it. Consumers ask the entity for an interface to the component, so we're free to screw around with the various implementations (and how the implementations are mapped to runtime data) with relative freedom.

For a situation like this where the composition of the object and its interfaces can include some (highly varied) subset of common components, it works very well.


答:
The Component-Entity-System architecture for game engines works for games because of the nature of game software, and its unique characteristics and quality requirements. For example, entities provide a uniform means of addressing and working with things in the game, which may be drastically different in their purpose and use, but need to be rendered, updated, or serialized/deserialized by the system in a uniform fashion. By incorporating a component model into this architecture, you allow them to keep a simple core structure, while adding more features and functionality as needed, with low code coupling. There are a number of different software systems which could benefit from the characteristics of this design, such as CAD applications, A/V codecs, or other systems which are centered around producing a structured pipeline for diverse content which needs to interact in a complex manner with other types of objects, while still remaining easily modifiable by the development team.

TL;DR - Design patterns only work well when the problem domain is sufficiently suited to the features and drawbacks they impose on the design.

Title: Is it reasonable to build applications (not games) using a component-entity-system architecture?

Body:
I know that when building applications (native or web) such as those in the Apple AppStore or Google Play app store that it's very common to use a Model-View-Controller architecture.

However, is it reasonable to also create applications using the Component-Entity-System architecture common in game engines?


问:
When am I ready to start using Jquery for Javascript?
I was told not to use Jquery as a beginner because it would hamper my learning of Javascript.  Now I've read a couple books on Javascript, read loads of sites, and made a Javascript web app.  Am I ready for Jquery? If not, then how will I know when I'm ready?</p>

答:
If you understand the DOM API and the problems jQuery has historically solved (I highly recommend quirksmode.org if you don't yet), by all means start using jQuery. As you do, ask yourself how it works and then commit to learning what it's doing under the hood if you really want to upgrade your javascript skills.

What you see in that $ function looks awful at first but it actually does a lot to reduce jq object memory footprints and keep things reasonably performant and can teach a lot of valuable tricks for writing JS. Just keep in mind that jQuery has actually inspired (or included early versions of) a lot of new official-spec (W3C and ECMA) JavaScript methods that are now common or easily normalized for in most browsers. We have forEach and a number of similar callback-iteration methods now for arrays. We have query selection built-in in IE>=8 and post IE8 all of the bad old IE-proprietary DOM methods are no longer necessary. Method chaining is a really simple trick. With that under your belt you can pretty much write your own JQ that would cover 98% of use-cases.

Whether it's a must-have nowadays is certainly more of a dilemma than it used to be for starting a new app but I personally continue to find it helpful for reducing DOM API boilerplate/cruft and a convenient way to get a UI team on the same page quickly. It's also an ideal model for any tool/library in that it stays out of your way when you don't want or need it to help you.

I personally still like it for the way it implements generic events, the fact that it's selector API can still be faster than the querySelector methods in a lot of cases (they appear to plug into the right to left evaluating CSS engines for most browsers) and its implicit iteration of collections which reduces a ton of cruft for common DOM-handling. I could write my own much slimmer version but it's already there and minimized to the size of a medium-sized jpeg so I don't.

OwnerDisplayName: Cornucopia

LastEditorDisplayName: Cornucopia

ContentLicense: CC BY-SA 2.5


问:
In Agile development, who owns the software "features" and how to you manage the development?
Some development teams in my company are switching to Agile development practices and their developers' work seem to be diminishing to discuss and program minutia about trivial software features because of two week iteration cycles. And also because of "any developer can fix any bug" mentality. I have recently joined one of those team, transferring from another team in the same company...

I feel strongly that developers should own their software features from start (design) to finish (implementation and unit testing).  Agile seems to be going counter to this thinking. Is there any truth to my perception or am I just living a bad implementation of Agile?

During our two week iterations, people somewhat arbitrarily get assigned new little features and bug fixes, depending on their workload during that cycle. Nobody seems to be owning responsibility of major features of the software. We spend stupid amount of times on trivial things, like adding a single button to a dialog during a two week iteration, complete with a story, daily scrums, code review, etc.

So in Agile projects, how does one manage larger features? Who own the responsibility: individual developers or the whole team?  How does one extract him/herself from minutia and focus on longer term goals?  Any feedback would be valuable.

答:
The first problem I see is that the estimation process is going a bit wide. Yes, developers should have a say in how much work they should be expected to take on. No, that does not mean that adding a single button to a web form is now a two-developer-week story (however many points that equates to in your business's estimation process). If that's the current state of affairs, then you as the project manager should be doing some second-guessing.

Second, I hear "from start (design) to finish (implementation and unit testing)" and the first thought that comes to mind is "you're doing it wrong". Your unit tests are a part of your design work as a developer/development team, and should happen first; you take the basic requirements, distill them into a simple "checklist" of "If... When... Then..."-type sentences, and then convert those sentences into a series of basic tests that assert the program meets those assertions and therefore the requirements. That happens before you write a line of the production code that will meet the assertions of the tests. If your unit tests come last, after you've already implemented the software, you lose several key aspects of unit testing; in general, your developers can't "program to green", thus providing a minimalist definition of "done" that encourages lighter (yet maintainable) implementations that do what the client wants without wasting work doing more things that the client doesn't want yet (and may in the extreme be unwilling to pay T&M for, because it's not what he asked you to do).

As far as developers "owning" their features, there's a yes and no to it. First off, a pretty common shakeout from "self-organizing teams" is a tendency for developers to go off in pairs or threes and work on things they know best. Assuming you have a good all-around set of developer expertise such that the team can cover all of the work to be done in each iteration this way, you can simply let this happen; it's a good thing for velocity, as developers stay focused on and familiar with the areas of the codebase they've been working in from iteration to iteration.

However, one developer owning one feature for life is a dangerous mindset, because it lowers the "truck number" of your team (defined very frankly as "how many people could be hit by a truck before the team couldn't function, given the worst case scenario of specific people hit and resulting knowledge lost). If the one guy whom you have assigned the "File Import" feature of your software and has owned it for 2 years goes on vacation for three weeks, takes extended FMLA leave, changes jobs, or in the extreme, really does get hit by a truck and dies, now you don't have anyone else who knows that feature because that area of the codebase has been that one guy's exclusive purview for years. While someone else familiarizes themselves with this particular piece of the codebase, you are going to lose significant velocity, and you will also open yourself up to additional problems with defects, as the new guy who's just barely familiar with how the codebase works now may remain woefully ignorant of things he can and can't change within it.

Instead, you should look to cultivate a division of labor that keeps your truck number at least 2 or above, and in a larger team (a dozen or more) closer to 3 or 4. That way if one guy can't do the job, for any reason, there are several other people who can jump in. Sometimes, teams just naturally shake out this way, especially if you bring in a few XP techniques like pair or dojo-style programming (one guy writes in a new assertion based on requirements that the code doesn't meet; the next guy then codes to pass that test, then adds another requirement assertion that fails and passes it on). By definition in these situations, you have multiple eyes looking at the code, developing it, becoming familiar with it.

Overall, the idea of Agile is to promote "lightweight" development. Your team seems to be getting bogged down in minutiae of processes and documentation, when the primary focus, as per the Agile Manifesto, should be on the team members and their interactions, and of course on working, functional code. The processes inherent in Agile are a means to an end, and there isn't any one way to follow Agile; even the primary Agile frameworks like SCRUM are malleable based on your needs as a company, a team, and even from day to day (just make sure to keep the basic ideas of the values provided by these processes at heart when making such changes).


问:
Should my login logic be part of the controller or a service in MVC webapp
I'm using Shiro as my security manager for a Spring MVC web application.

The login basically happens in these lines:

```<code>Subject user = SecurityUtils.getSubject();
user.login(new UsernamePasswordToken(username, password));
</code>```

Where should I put this logic? login() can throw exceptions if the requested user doesn't exist or wrong password was provided, etc. Should I call the code from my controller and do the error handling there or should I call it from my service layer, catch exceptions and rethrow my own up to the controller?

答:
Either of the two options you present is valid.

Services (the Model layer) are allowed to call other services.  So having your service call the authentication service is acceptable.

Likewise, Controllers are allowed to call to services so that option is equally acceptable.

If Shiro is providing your only authentication mechanisms, then it's kind of a toss-up between either approach.  Calling from the Controller would seem a little faster to develop and potentially have less error handling code.

However, if you intend to add additional checks / wrappings around that authentication call, then you should have your Model make the call.  So if there is a likely additional call for authorization after the authentication check, then I would lean towards calling from the Model.

Quick note, loose definitions:

Authentication: "Am I who I say I am?"

Authorization: "Do I have the authority or permission to access this?"

OwnerDisplayName: Sotirios Delimanolis


问:
Why is the main memory for object allocation called the 'heap'?
Has anybody got an idea why the area of main memory where objects are allocated is referred to as the heap. I can understand the rationale for that of the stack LIFO but would like to know what the rationale is for the 'heap' name.</p>

答:
From the information found at StackOverflow - What is the origin of the term “heap” for the free store? and Why are two different concepts both called “heap”?

This information at least dates back to Knuth in 1975 referencing other (unnamed) authors:

Several authors began about 1975 to call the pool of available memory
  a "heap." But in the present series of books, we will use that word
  only in its more traditional sense related to priority queues.
  (The Art of Computer Programming - Fundamental Algorithms, 3rd ed., p. 435)

There is also mention of Wijngaarden discussion on Algol in the early 1970s referring to the available memory pool as a heap (heap is a reserved word in Algol which is defined in places as "allocate variable some free space from the global heap." - Algol68 dates from 1968).

Implementing the ALGOL 68 heap from 1970 may be of use in tracking down some aspects of word origin, though much if it is behind a paywall.


问:
How to make ASP .NET MVC website have a continuous process running?
This website is supposed to be a game where the players have some 'buildings' and these buildings produce resources. E.g. an iron mine may produce 30 pieces of iron ore per minute and automatically add it to the user's inventory. It doesn't matter whether the user is online or not, it should be running 24/7. So when the user does log in to their account, they will see their stack of iron ore has built up depending on how long it has been.

Some pointers in the right direction would be greatly appreciated :)

答:
```<code>Need to save some state
Put it in the database
Retrieve on next login
</code>```

Actually, when the user logs in again, what you'll need to do is figure out how many pieces of iron ore should have been mined while the user was gone, and update the database with that knowledge the next time the user logs in.

If other users interact with the "pieces of ore" information while the user is not logged in, you can update that information when it is requested by the other player.

The one thing that I don't think you want to do is create a "user agent" that runs in the background for every not logged-in person; I don't think you need that kind of complexity if you're interacting with players that are not even logged in, and if there are many players, it's not going to scale.

So update the information "just in time," when it is requested.

Body:
Need to save some state
Put it in the database
Retrieve on next login

Actually, when the user logs in again, what you'll need to do is figure out how many pieces of iron ore should have been mined while the user was gone, and update the database with that knowledge the next time the user logs in.

If other users interact with the "pieces of ore" information while the user is not logged in, you can update that information when it is requested by the other player.

The one thing that I don't think you want to do is create a "user agent" that runs in the background for every not logged-in person; I don't think you need that kind of complexity if you're interacting with players that are not even logged in, and if there are many players, it's not going to scale.

So update the information "just in time," when it is requested.


答:
Here are several approaches on top of my head:

Use a background process that runs continuously on the server, and checks the database of buildings every min/sec to see when a building last produced the items, and if it is time, do the production work.

Have buildings produce at certain times if the way above costs too much to run. Say every 15th min. of a hour. So your script will run 4 times in an hour, reducing the server workload.

Calculate the item values only when needed. You won't be running any continuos processes with this way.

Title: How to make ASP .NET MVC website have a continuous process running?

Body:
This website is supposed to be a game where the players have some 'buildings' and these buildings produce resources. E.g. an iron mine may produce 30 pieces of iron ore per minute and automatically add it to the user's inventory. It doesn't matter whether the user is online or not, it should be running 24/7. So when the user does log in to their account, they will see their stack of iron ore has built up depending on how long it has been.

Some pointers in the right direction would be greatly appreciated :)


问:
Ria service security
I have a silverlight app that connects to a entity framework over WCF ria service.

These calls have to be secure. What can I do so only valid users can call the ria service, and to make the call secure?

The user has to log in to get to the silverlight app, so maybe that login in some way can be saved for authentication of the ria calls?

答:
There are two things you need to do:

As you have correctly identified you can use the fact that the user has logged in to authenticate the RIA Service calls. You can either do this on a call by call basis or arrange you code so that you can only make the RIA Service calls if the user is logged in.

You can use the ASP.NET membership database code to do this so you don't have to roll your own security code. You can limit the length of time the login is valid for, have some sort of idle checking to make sure you log out any inactive users etc.

Connect to the web site via a https connection. In and of itself this doesn't make the connection secure, but does give an extra layer of protection when you do log in.

Title: Ria service security


问:
Should the variable be named Id or ID?
This is a bit pedantic, but I've seen some people use Id as in:

private int userId;
public int getUserId();
```

<p>and others use:</p>

<pre class="lang-cs prettyprint-override"><code>private int userID;
public int getUserID();
</code>```

Is one of these a better name than the other? Why? I've seen this done very inconsistently in large projects. If I were to set a standard which would most people be familiar with? Which is the conventional standard?

答:
The most important rule to follow in these cases is consistency: Do as everyone else does.

For instance, look at your language's XML APIs to see how they do it.

Java names classes like SAXParser and DOMException, .NET names classes like XmlDocument.

Based on that, I'd say "ID" in Java, "Id" in C#.

However, I've seen that Java EE 6 has an annotation named @Id (see documentation), so it seems Java considers "Id" to be just a normal word.

Title: Should the variable be named Id or ID?


答:
It should be in a Service Layer.

```<code>public interface UserService {
    public User findByLogin(final String userName);
}
</code>```

And in a Service implementation :

```<code>public class UserServiceImpl implements UserService {

    @Inject
    private UserRepository userRepository;

    public User findByLogin(final String userName, final String password) {
        Preconditions.checkArgument(!Strings.isNullOrEmpty(userName), "Username is mandatory !");
        return Preconditions.checkNotNull(userRepository.findByLogin(userName), "User not found !");
    }
}
</code>```

And an Identity provider service :

```<code>public class InternalIdentityProviderImpl implements ... {

    @Inject
    private UserService userService;

    public void authenticate(final String login, final String password) throws BadCredentialsException, IdentityNotFoundException {
        try {
            Preconditions.checkArgument(!Strings.isNullOrEmpty(login), "Username is mandatory !");
            Preconditions.checkArgument(!Strings.isNullOrEmpty(password), "Username is mandatory !");
        catch(Exception e) {
            throw new BadCredentialsException(e);
        }

        // Check user
        try {
            User internal = Preconditions.checkNotNull(userService.findByLogin(username));
        } catch(Exception e) {
            // logs
            throw new IdentityNotFoundException(e);
        }

        // Shiro authentication
        Subject user = SecurityUtils.getSubject();
        user.login(new UsernamePasswordToken(username, password));
    }

}
</code>```

You should decorelate how the user is retrieved from the identity provider, and how it is validated by your identification system.

Currently I used RuntimeException thrown by Guava Preconditions, but you can use a specific handcrafted Exception.

ie:

IdentityNotFoundException : from your identity provider.

BadCredentialsException : from your identification system.

This service could be called from the controller, and handle the exception to display the right message.

Title: Should my login logic be part of the controller or a service in MVC webapp

Body:
I'm using Shiro as my security manager for a Spring MVC web application.

The login basically happens in these lines:

```<code>Subject user = SecurityUtils.getSubject();
user.login(new UsernamePasswordToken(username, password));
</code>```

Where should I put this logic? login() can throw exceptions if the requested user doesn't exist or wrong password was provided, etc. Should I call the code from my controller and do the error handling there or should I call it from my service layer, catch exceptions and rethrow my own up to the controller?

Body:
It should be in a Service Layer.

public interface UserService {
    public User findByLogin(final String userName);
}

And in a Service implementation :

public class UserServiceImpl implements UserService {

    @Inject
    private UserRepository userRepository;

    public User findByLogin(final String userName, final String password) {
        Preconditions.checkArgument(!Strings.isNullOrEmpty(userName), "Username is mandatory !");
        return Preconditions.checkNotNull(userRepository.findByLogin(userName), "User not found !");
    }
}

And an Identity provider service :

public class InternalIdentityProviderImpl implements ... {

    @Inject
    private UserService userService;

    public void authenticate(final String login, final String password) throws BadCredentialsException, IdentityNotFoundException {
        try {
            Preconditions.checkArgument(!Strings.isNullOrEmpty(login), "Username is mandatory !");
            Preconditions.checkArgument(!Strings.isNullOrEmpty(password), "Username is mandatory !");
        catch(Exception e) {
            throw new BadCredentialsException(e);
        }

        // Check user
        try {
            User internal = Preconditions.checkNotNull(userService.findByLogin(username));
        } catch(Exception e) {
            // logs
            throw new IdentityNotFoundException(e);
        }

        // Shiro authentication
        Subject user = SecurityUtils.getSubject();
        user.login(new UsernamePasswordToken(username, password));
    }

}

You should decorelate how the user is retrieved from the identity provider, and how it is validated by your identification system.

Currently I used RuntimeException thrown by Guava Preconditions, but you can use a specific handcrafted Exception.

ie:

IdentityNotFoundException : from your identity provider.

BadCredentialsException : from your identification system.

This service could be called from the controller, and handle the exception to display the right message.

ContentLicense: CC BY-SA 4.0


问:
Using double dot notation in URL link
I've recently been working on a project and I've been seeing two different forms of url's being used.

```<code>src="../MyLinkUrl"
</code>```

and

```<code>src="/MyLinkUrl"
</code>```

We are using MVC .NET and the times I have seen the .. usages have been in Javascript code files and not when it's been generated by the MVC URL helpers.  Typically the usages range from specifying a controller action to specifying images.

Both seem to work but I'm wondering which is the better practice or if it depends on the context.  Some questions I have are:

What benefits/pitfalls does one have over the other

Is one better practice than the other

Does it depend on context and if so what context?

答:
When you see /path/to/file that is an absolute path.  Starting from the server's root, it's followed down to the file.  With just /file that means that you're looking directly in the server's root.

Whenever you do not have a leading slash, the path is taken as relative.  This means that, starting from your current point in the file system, you follow the path. ../file would mean to look in the parent directory for file.  If you had just file it would look in the current directory.

Title: Using double dot notation in URL link


问:
What is the most egregious waste of money you have seen, and what did you do about it?
Often we as programmers see large organisations wasting huge sums of money on bloated and inefficient solutions to problems. This pains me greatly because I like organisations to benefit from best of breed solutions. However, my abilities as a programmer are limited when it comes to influencing the key decision makers and often my perspective on the matter is constrained to my own little technical world.

So, my question is this. After encountering an egregious waste of money on some software and/or hardware that really got your goat, what did you do about it to get it fixed or were you doomed to bite the bullet and mutter forever under your breath? I'm interested in hearing your overall experiences and especially what lessons you learned about how to tackle this sort of thing in the future. Let's not name names, the experience of how to tackle the problem is more important than the actual offending product.

答:
We were having a smallish amount of work and barely making bills and payroll in a small shop in which I worked.  The solution: hire an efficiency consultant and a personal secretary for the boss so he could go perform more "meat and potatoes" work.

Solve a budget shortfall by increasing spending...fail.

On the plus side - the efficiency expert supplied a dry erase board where we tracked our billable hours and paid hours...guess who had the least amount of billable hours.


问:
Level of detail in System Requirements
I've read in multiple places that the requirements must not be influenced by solution and must not contain solution. So in the below example , please can you help in letting me which is correct -

Application A is interacting with Application B to install a new service / change the service type and disconnect a service. There 3 different service types 1,2 and 3. Application B does not support changing service from 1 to 2 or 1 to 3. Hence 1 must be disconnected and then 2 and 3 must be added. However service can be changed from 2 to 3 or 3 to 2 directly.

In the above case , changing the service from 1 to 2 or 1 to 3 is a system level contraint. However from an end user's perspective this is a service change.

In the above case , should I have a single system requirement stating system shall allow service to be changed for all the service types supported or should I have 2 different system requirement - 1 stating which all services can be upgraded directly and the 2nd stating in which cases service needs to be disconnected and installed?

答:
Requirements are that and only that: what is the required outcome for the system in question?

In this case, the System Requirements appears to be:

Application A must be able to:

install a new service of type 1, 2, or 3

change the service type of an existing service of type 1, 2, or 3

disconnect a service of type 1, 2, or 3

in Application B

Requirements should be stated positively whenever possible, and phrased so as to be testable.

The specific implementation problems described are not part of the requirements. They are part of the design constraints.

Title: Level of detail in System Requirements


问:
User Stories - How should it be defined for complex changes involving multiple applications
This is one of the definitions that I asw for user stories -

When the time has come for creating user stories, one of the developers (or the product owner in Scrum) gets together with a customer representative. The customer is responsible for formulating the user stories. The developer may use a series of questions to get the customer going, such as asking if some particular functionality is desired, but must be careful not to dominate the idea creation process.

In a large organization there could be multiple lines of business. For a particular line of business , there could be multiple applications (more than 10) that may be involved in fulfilling a business requirement. The requirement to each of these application teams could be provided by a business analyst and the high level solution could be formulated by a solution designer.

In scenarios such as these , would a single user story be defined for a specific change request that impacts multiple applications or would different user stories be created for each application? If it is a single user story then would a separate SRS be defined for each impacted application would it need to be associated with the user story defined?

答:
The effect on contributing systems is irrelevant at the level of a user story. The user does not care how it works.

As a [user role], I want [something] so that [benefit]

Ex: As a [mobile phone customer], I want [buy a phone] so that [I can make phone calls].

Note the total absence of any mention for the need to build cell towers ;)


问:
Does Dart have any useful features for web programmers?
http://www.dartlang.org/

I've checked out the site very briefly, and got curious. Is there any advantages of using Dart? Is it just a replacement for JavaScript?

It looks like simpler Java. Writing quite a lot of C# at work, the language feels very much like what I'm used to, so learning the syntax looks like a breeze to learn. Has anybody any opinions or experiences with the language?

(Compared to CoffeeScript (= I'm not doing Ruby syntax) the syntax looks more familiar to me).

答: Java/C# approach is definitely biased in knocking JS since the beginning of web 2.0 That is because of an artificial (or very real & necessary) differentiation between client-side languages and server-side languages. I think this is so server-side language can remain in 'control' of the core problem domains of web apps and to demarcate less serious code (ui code) from business code (server-side). Also Java I think loves to remain a server-side kernel since it lost the GUI war with applets due largely to Flash and HTML 5.  Now you have RedTamarin a NodeJS-esque AS3 project alluding to a pluralistic blended future of unified front and backend paradigms.</p>


问:
How to convince my coworkers that doing things right will save them time
I recently started at a new company, with a handful of programmers. Its a medium sized company, with around 70 employees, but IT only has 9-10, and there are 3 "programmers" beside myself. However, these guys have very limited experience and are doing a lot of stuff really terribly. For example, one of our projects is a PHP website. The majority of the code is stored in a 20,000 line PHP controller, with ~6000 lines of JavaScript embedded in the PHP.

I keep making small suggestions here and there but nobody has been listening, everyone says they are too busy to implement my suggestions. The thing is, they shouldn't be that busy, and wouldn't be if things were done right. They spend most of their time fixing things that keep breaking. If each project was built correctly, I could do it all myself.

What approach should I take to convince these guys or the manager that things need to change, and that changing things will save a bunch of time? Should I skip trying to convince my coworkers and go straight to the manager, with a business-y proposal on how the company will save a bunch of money if they start doing things correct?

答:
I've found that the primary cause for sloppy work, outside of the programmer simply not caring, is a lack of knowledge.  Unfortunately in a lot of environments, lack of knowledge is looked down on rather than openly discussed.

Some techniques that I've used with success to foster discussion, growth, and general excitement about programming are:

Weekly brown bag tech sessions (Have them research a topic and present).

Daily or weekly one on one mentoring sessions between junior and senior members.

Code reviews (with an emphasis on learning, not pointing out mistakes).

Learning is contagious.  When you foster an environment that encourages learning you not only produce better developers, but show others on your team that they are part of something bigger than a way to get a paycheck.


问:
Is there a viable alternative to the agile development methodology?
The two predominant software-development methodologies are waterfall and agile.  When discussing these two, there is often much focus on the particular practices that distinguish them (pair programming, TDD, etc. vs. functional spec, big up-front design, etc.)

But the real differences are far deeper, in that these practices come from a philosophy.

Waterfall says:  Change is costly, so it should be minimized.

Agile says:  Change is inevitable, so make change cheap.

My question is, regardless of what you think of TDD or functional specs, is the waterfall development methodology really viable?

Does anyone really think that minimizing change in software is a viable option for those that desire to deliver valuable software?  Or is the question really about what sort of practices work best in our situations to manage the inevitable change?

答:
Of course waterfall is viable. It brought us to the moon!

And it's a agile coach talking here!

Unless you can clearly identify problems related to the way you manage your projects, there is no valid reason to change.

As an alternative of Agile and Waterfall methodologies, I will suggest YOUR methodology. Adapted to your specific business, your specific team, your products, you way of working, your company culture... It's why Scrum is called a simple framework instead of a methodology.

Wanting to implement a methodology because someone on a blog you like talked about it is as stupid as letting problems going without doing anything.


答:
Upon seeing that you were hired as the Sr. PHP dev and your job is to fix things, I suggest it's time you flex some muscle.

If I was in your place, I'd do a good survey of the code and see mistakes that are happening over and over again. Block off meeting time each week to go over these things with the team. Don't point fingers or name names, just show how to do that task properly.

Next, since you've already seen needs fixing, make a list. If it's quick and easy to do, do it. If it'll make your life easier to have it done....do it. Make a list of all the things that need to be done and make tickets for them and see when people have cycles to do them. If someone is fixing a bug in a problem area, walk them through how to fix it properly.

If it requires a large change, sit down with the team and the stake holders and discuss options.

Have an open door policy where you'll help people out. Be someone who educates and not intimidates. No, "you have to do it this way" and more "it would be better if it was done this way". Explain advantages to doing it the way you suggest and the disadvantages of the way it's been done. People will be more willing to do it the right way if they feel they have learned something instead of being told their way is wrong and to do it some other way b/c you say so.

Title: How to convince my coworkers that doing things right will save them time

Body:
I recently started at a new company, with a handful of programmers. Its a medium sized company, with around 70 employees, but IT only has 9-10, and there are 3 "programmers" beside myself. However, these guys have very limited experience and are doing a lot of stuff really terribly. For example, one of our projects is a PHP website. The majority of the code is stored in a 20,000 line PHP controller, with ~6000 lines of JavaScript embedded in the PHP.

I keep making small suggestions here and there but nobody has been listening, everyone says they are too busy to implement my suggestions. The thing is, they shouldn't be that busy, and wouldn't be if things were done right. They spend most of their time fixing things that keep breaking. If each project was built correctly, I could do it all myself.

What approach should I take to convince these guys or the manager that things need to change, and that changing things will save a bunch of time? Should I skip trying to convince my coworkers and go straight to the manager, with a business-y proposal on how the company will save a bunch of money if they start doing things correct?


答:
Yes, various software development techniques are all viable depending on your problem domain.  It's "Horses for Courses".

For example, you're writing software to control a Nuclear power plant or to drive the NASA space shuttle.  This sort of problem domain is probably better suited to a waterfall (or even stricter) approach, you want to sort out all of the issues up front if possible (or BOOM!).

Building the latest web 2.0/3.0/buzzy marketing term UI?  Agile is a much better way to go (yo need that quick feedback and change).

There are what I would call software craftsmanship principles that can still be applied no matter waht the methodology is e.g:

Source control

build and CI

pair programming

TDD

I give a ^%$$&

and more.

Whatever you do, don't listen to the zealots on either side of the equation, do what's right for you, your team and your problem domain.

Title: Is there a viable alternative to the agile development methodology?

Body:
The two predominant software-development methodologies are waterfall and agile.  When discussing these two, there is often much focus on the particular practices that distinguish them (pair programming, TDD, etc. vs. functional spec, big up-front design, etc.)

But the real differences are far deeper, in that these practices come from a philosophy.

Waterfall says:  Change is costly, so it should be minimized.

Agile says:  Change is inevitable, so make change cheap.

My question is, regardless of what you think of TDD or functional specs, is the waterfall development methodology really viable?

Does anyone really think that minimizing change in software is a viable option for those that desire to deliver valuable software?  Or is the question really about what sort of practices work best in our situations to manage the inevitable change?


问:
Good library for combining .net stack traces
I currently report my production exceptions to a mysql database, where they have been collecting dust for the most part. The problem I faced is grouping the stack traces. I would like to be able to see kind of an aggregate of the stack traces that are the same, so that I can work them into the workflow.

I know one issue I have is I get stack traces in different languages, which throws things off, otherwise I'd just do a group by sql command.

Does anyone know of any libraries that could assist me with this? As long as I have something where I can put in a collection of stack traces and get out the result, I'm fine. I don't need any direct sql interaction, or reporting or anything like that(but I'll take any suggestions you guys have)

Thanks

答:
Prepackaged library?  Likely not.  There exists some - but it doesn't appear to be at the size of where we are intrested in - STAT and a YouTube video on it.  Interesting, but designed for systems that are an entirely different scale than most people work on.

In previous searches for similar solutions, ultimately I ended up writing my own stack trace fingerprinting software.

You've got a stack trace from the system and have stuck it some where.  It looks roughly like:

```
com.foo.bar.UserNotFoundException: User not found
    at com.foo.bar.ErrorHandler.handle(errorHandler.lang:42)
    at com.foo.bar.StuffDoer.doStuffA(StuffDoer.lang:314)
    at com.foo.bar.StuffDoer.doStuffB(StuffDoer.lang:271)
    at com.not.yours.base.Base(Base.lang:2357)
```

This the general format of a stack trace - it has the exception handler at the top (which isn't too useful) and the base of the system at the bottom (which isn't that useful either).

As an application programmer, what you really want is the stuff in the middle.  This may be one method, or a dozen, but its what actually identifies this stack trace vs other ones.  The specifics of the stuff outside your call isn't always that useful.

As a systems programmer, the stuff at the bottom is likely the most interesting.

The first step is to parse through the stack trace line by line identifying the relevant information and further identifying if the given frame is of interest at all - if everything goes through ErrorHandler.handle() before the stack is reported, that frame is not useful in identifying or grouping the stack.

Next, I serialized the array of the interesting bits of information (method name, class name - line number in the case that I dealt with in the past was too variable between releases that it wasn't useful, but it may be for you) and stored the hashcode of that in a database.  Because of the different systems and languages working on the application to identify a stack trace, this was a simple text join and md5sum (if I had to do it again, I'd be tempted to make it into JSON and hash code that).

In the database, the hash code of the interesting part of the stack trace could then be computed quickly and was a fixed size (nice for database indexes and or keys - though not bad for directories either).

Stack traces longer than a certain minimum size were examined multiple times.  For example, if the minimum size for further examination was 3, and the stack trace was "a b c d e", the following stack traces would be stored:

a b c d e

a b c d

b c d e

a b c

b c d

c d e

Yes, sometimes everything was a subset of another set of analysis, but it let people look at smaller parts and identify patterns of misbehavior.

Body:
Prepackaged library?  Likely not.  There exists some - but it doesn't appear to be at the size of where we are intrested in - STAT and a YouTube video on it.  Interesting, but designed for systems that are an entirely different scale than most people work on.

In previous searches for similar solutions, ultimately I ended up writing my own stack trace fingerprinting software.

You've got a stack trace from the system and have stuck it some where.  It looks roughly like:

com.foo.bar.UserNotFoundException: User not found
    at com.foo.bar.ErrorHandler.handle(errorHandler.lang:42)
    at com.foo.bar.StuffDoer.doStuffA(StuffDoer.lang:314)
    at com.foo.bar.StuffDoer.doStuffB(StuffDoer.lang:271)
    at com.not.yours.base.Base(Base.lang:2357)

This the general format of a stack trace - it has the exception handler at the top (which isn't too useful) and the base of the system at the bottom (which isn't that useful either).

As an application programmer, what you really want is the stuff in the middle.  This may be one method, or a dozen, but its what actually identifies this stack trace vs other ones.  The specifics of the stuff outside your call isn't always that useful.

As a systems programmer, the stuff at the bottom is likely the most interesting.

The first step is to parse through the stack trace line by line identifying the relevant information and further identifying if the given frame is of interest at all - if everything goes through ErrorHandler.handle() before the stack is reported, that frame is not useful in identifying or grouping the stack.

Next, I serialized the array of the interesting bits of information (method name, class name - line number in the case that I dealt with in the past was too variable between releases that it wasn't useful, but it may be for you) and stored the hashcode of that in a database.  Because of the different systems and languages working on the application to identify a stack trace, this was a simple text join and md5sum (if I had to do it again, I'd be tempted to make it into JSON and hash code that).

In the database, the hash code of the interesting part of the stack trace could then be computed quickly and was a fixed size (nice for database indexes and or keys - though not bad for directories either).

Stack traces longer than a certain minimum size were examined multiple times.  For example, if the minimum size for further examination was 3, and the stack trace was "a b c d e", the following stack traces would be stored:

a b c d e

a b c d

b c d e

a b c

b c d

c d e

Yes, sometimes everything was a subset of another set of analysis, but it let people look at smaller parts and identify patterns of misbehavior.


问:
Is using '{}' within format strings considered Pythonic?
I just learned you can write

```<code>'{}{}'.format(string_a, string_b)
</code>```

instead of

```<code>'{0}{1}'.format(string_a, string_b)
</code>```

in Python, i.e. you can omit the numerals for the string format parameters when you want things to slot in one by one in order.

Is this considered Pythonic?

NOTE: "Pythonic" is a commonly used term among Python programmers to mean idiomatic Python code. Within Python culture, there tends to be clear consensus on style questions, especially for very specific ones like this one, given the language's explicit design philosophy of "There should be one -- and preferably only one -- obvious way to do it." This is quoted from "The Zen of Python," a set of aphorisms which goes a long way towards defining what is "Pythonic" and which is included with every distribution of Python (at any Python interpreter command line, enter import this to see it).

答:
The {} feature was introduced in Python 3.1 (and also backported to Python 2.7). The enhancement that prompted this addition was issue 5237. Guido has several comments on that issue, including:

Please go ahead and finish this. I'm glad this is going in!

A feature with that sort of endorsement from the BDFL would certainly be considered "Pythonic" by any measure.


问:
Using assembly to write to a file
I am working with a trading application (reading data from the exchange) which generates a bucket load of data on a per second basis. We have different "log-levels" but even the minimal log-level generates so much data ! This process of log creation is quite I/O intensive.

Since I can write assembly using __asm__ , I was wondering if the operation of writing to the files is coded in assembly, will there be a speedup ? The rest of the code is C++.

Also, what are the caveats of doing such a thing ?

答:
The performance overhead of writing lots of data to disk isn't the execution speed of your code, but rather the physical limitations of the actual hard drive. Doing it assembly won't give you a noticeable performance increase.

Your best bet is to either log less data (recommended, if you're logging that much stuff how useful can it be) or change the drives so they can write quicker! Consider higher RPM's, SSD's, RAID (zero I think for parallel writing) or at least a dedicated disk with a dedicated controller. But really, unless you really need all that logging data, you're wasting your time. Fix your log levels so that WARN and ERROR only log stuff when those things actually happen. (and if they are happening all the time... fix your code).

Title: Using assembly to write to a file


问:
Are there any tools for remote coding interview?
Firstly, I'm not exactly sure if this question is a better fit over here, or on workplace.SE. So forgive me if it is in the wrong place.

We are interviewing some candidates for a development position, and currently they are not in our city.

We would like to give them simple coding tests to see how they will perform on the typical issues that we face in our daily work.

Are there any specific tools geared towards this? Right now we are using Skype and I feel this tends to decrease the performance of a lot of developers since they tend to be shy, and often can't work when someone is directly staring at them.

The problem with sending them the test questions by email are as follows:

It is not possible to know what their thought process is, sine we just see the end result. There is no discussion, or clarification of the question, which is an Important step.

There is no guarantee that the problems were solved by the candidates themselves. They could send it to a smarter friend, and we wouldn't be able to know.

How are these problems usually solved?

答: Google uses a shared Google Docs document between the interviewer and candidate while talking over the phone. They share the document, which is preset to a fixed-width font, to the candidate in advance with the confirmation email. A Bluetooth headset or speakerphone is recommended for hands-free coding during the phone interview.</p>


答:
The problem stems from the complexity of software.  Waterfall works great for things like bridge building and road paving because physics just never changes.  Sure, at some point we'll develop a new asphalt but it won't revolutionize the way roads are built.  The steel in a bridge's suspension is either the right size, or it isn't.  You can't kludge or stub a real construction project like you can with software.

Software changes.  Software changes rapidly.  Moore's law states that number of transistors on a chip doubles every 18-24 months.  In corollary, the number of lines of code in a program also doubles.  Complexity in between those lines of code therefore increases with a bigO of something like 2^(2t).

Software changes rapidly, and complexity increases exponentially with it.

When controlling the cost of the software, you want to control exponential factors, not just multiplicative or additive.  Changing code increases the complexity (and gets exponentially more complex itself as the project moves on) in an exponential manner.

Change is inevitable.  The very nature of programming extends the language with classes and custom methods, thus changing the language itself.  You can't do that in any other kind of engineering discipline (like building roads.  You don't invent new pavement just to pave a road in kansas over california).

The agile method also gives you a platform for handling future releases and bug fixes.  You alredy have the management tools, processes, trained employees, for developing versioned software.  With a waterfall method, you would need to retrain your team to handle even minor bug-fixes.

anyway, my 2 cents.


问:
What would Business Intelligence (BI) developers look for in code reviews?
Let me preface this with saying I am not a Business Intelligence (BI) developer.  I'm a .NET developer, and I have only a vague notion of what BI is, and encompasses.

I've been an evangelist for a secure development lifecycle in our company, and recently convinced the rest of the development team that we should be doing peer reviews including...

Requirements Reviews

Code Reviews

Architecture/design reviews

Documentation Reviews

The .NET team does code reviews and we look for various things - general overview:

Maintainability (clear design, adequately documented, etc.)

Code clarity (standard .NET coding/naming guidelines)

Security (scanning for failures to sanitize input, prevent SQL injection, etc)

Functionality (does it do what it's supposed to)

Usability

Performance

At any rate, our Business Intelligence developers don't really do the same type of coding/development that we do for websites, windows apps, etc.  Our templates/checklists don't really apply to them.  Since I've been the one trying to evangelize and get everyone do start doing peer reviews, they asked me for advice on what types of things they should be looking for.

I could probably guide them and help them to develop their own checklists by asking questions about what can go wrong, what is important  to them, etc., but I thought I'd ask and see if anyone is aware of established guidelines for doing "code reviews" for BI developers.

I'll also take, from BI people "What would you look for in evaluating another BI developer's work?".

答:
I could comment on the ETL side of the BI application development life cycle. The parameters depend on the tool/Language being used, but could largely relate to your above listed ones.

Maintainability -Adhereence to the defined design could be evaluated

Code clarity -
Naming conventions are there in BI ETL development too for different objects used in the code.
*Security -
Not applicable at a code review point of view in BI applications. Security focus is more in the design phase (which users need to see which sub-section of the data) and inthe administration side (reporting tool user log-in configuration) etc.

Functionality checks-
I think this comes under the unit testing phase or other testing phases - less to do here at the code review time, except for checking if there are unit test plans and test results available as part of the review.

Usability - NA

Performance -
Could be evaluated if requirements demand certain measures ( defined time to process the data) and if general guidelines for tuning is followed (simplest example - defining join rank for tables)

Additional: We usually check for impact analysis on existing code and and extent of component re-use . (We work in a multi-member team where multiple BI applications are


问:
Copying (forking) an open source project to your own repository
I'm currently using an open source project called CodeFirstMembership for one of my projects.  There's a critical issue that I need to get past, and the more I use it, the more I find things I need to modify.  It's extremely useful, except it doesn't look like the developer has much time to update it (totally cool, we've all been there).  I'm wondering about the etiquette and legality and general "hey, you stole my code you jerk" responses I'd get if I copied the source, moved it to github and made my own fork.

On Github, we do this all the time, forking projects, but it FEELs less jerk-ish because there's a connection to the original.  Is there anything wrong with me doing this, whether legal or otherwise since there's no copyright notice or license associated with this library?

答:
From http://codefirstmembership.codeplex.com/license

Conditions and Limitations

(A) No Trademark License- This license does not grant you rights to use any contributors' name, logo, or trademarks.

(B) If you bring a patent claim against any contributor over patents that you claim are infringed by the software, your patent license from such contributor to the software ends automatically.

(C) If you distribute any portion of the software, you must retain all copyright, patent, trademark, and attribution notices that are present in the software.

(D) If you distribute any portion of the software in source code form, you may do so only under this license by including a complete copy of this license with your distribution. If you distribute any portion of the software in compiled or object code form, you may only do so under a license that complies with this license.

(E) The software is licensed "as-is." You bear the risk of using it. The contributors give no express warranties, guarantees or conditions. You may have additional consumer rights under your local laws which this license cannot change. To the extent permitted under your local laws, the contributors exclude the implied warranties of merchantability, fitness for a particular purpose and non-infringement.

For other open source projects, have a look at the following resources

http://www.smashingmagazine.com/2010/03/24/a-short-guide-to-open-source-and-similar-licenses/

http://opensource.org/faq

http://www.softwarefreedom.org/resources/2008/foss-primer.html


问:
Using akka actors with service spring beans
Do you think that using akka actors in front of transactional service beans, is a good idea ?

Actors are waked up by a facade used by a client application, and actor use a message to handle right service call.

Is it a good practice ?

This article (http://honeysoft.wordpress.com/2012/08/05/akka-actor-dependency-injection-using-spring/) is talking about using spring beans with akka actors.
But I could not see the gain to use actors in front of (singleton) spring beans.

答:
Since the Akka docs state that Actors should not block (on IO, sockets, ...) unless it's is really unavoidable, it sounds like there might be little value in having actors wrap transactional services, of which I'm assuming the majority will be backed by transactional databases.

There might be other reasons to using Actors of course (the remoting, durable inboxes, clustering, ...)

OwnerDisplayName: Zenithar


问:
Applying DRY to an inheritance hierarchy
I'm working on refactoring a legacy application where I implemented the State pattern successfully as shown in the following diagram:

As you see there is a common behavior between the 3 states, so I decided to extract the common method Refund() to a parent abstract class RefundableState where I implemented it:

Refactoring further I notice that the Ship() method is common between the 2 states Cancelled and NewOrder, so I go for another round of extracting the common behavior to another parent class ShippableState:

Now I need my Cancelled state to extend 2 classes and in the same time I can't group the Refund() and Ship() function together as not all state permit the 2 actions.

How can I fix this?

Notes:

This question is mainly about applying DRY and refactoring not about how to implement the state pattern.

I'm using PHP 5.3, but I'm open to answers in any other languages.

答:
In Java (don't know PHP), you could Create ShippableState, RefundableState (and CancellableState) as interfaces, create ShippableRefundableState class that implements ShippableState and RefundableState.
But what about CancellableState? Without multiple implementation inheritance itcannot be fitted there somewhere without repeating it.

So maybe don't use inheritance, use composition. So have StateShipper/Refunder/Canceller with XXXState(state) method and delegate to it in your states.

In language with multiple implementation inheritance (eg. C++) you could create classes instead of interfaces and inherit from them in states. As long as multiple implementations does not multiply implement same thing, it is nice, awfull things starts when its not clear (to human) from which ancestor something is.


答:
I can say only that "DRY" is not a silver bullet. You have to use the common sense when deciding if specific refactoring is needed.

In your example you can clearly see that there are problems when applying 100% DRY approach. I think that this particular refactoring in this scenario is not needed. Especially 2nd step.

But if you really want to do this then ...

I would advise you to drop Inheritance based design and start using Interface based design. This inheritance limit was created because developers where making "crazy" and unmanageable solutions. If you encounter multi inheritance problem you are clearly doing something wrong.

With interfaces you can use composition and dependency injection to store similar code in one place.

Title: Applying DRY to an inheritance hierarchy

Body:
I'm working on refactoring a legacy application where I implemented the State pattern successfully as shown in the following diagram:

As you see there is a common behavior between the 3 states, so I decided to extract the common method Refund() to a parent abstract class RefundableState where I implemented it:

Refactoring further I notice that the Ship() method is common between the 2 states Cancelled and NewOrder, so I go for another round of extracting the common behavior to another parent class ShippableState:

Now I need my Cancelled state to extend 2 classes and in the same time I can't group the Refund() and Ship() function together as not all state permit the 2 actions.

How can I fix this?

Notes:

This question is mainly about applying DRY and refactoring not about how to implement the state pattern.

I'm using PHP 5.3, but I'm open to answers in any other languages.


问:
Should Junior Programmers be involved as code reviewers in the projects of Senior Programmers?
One of my team members, a junior programmer, has impressive programming skills for his level of experience.

And during code reviews, I believe in emphasizing learning, not pointing out mistakes.

But should junior programmers be involved in code reviews for more senior programmers? Or should code reviews be attended only by programmers with corresponding experience?

答:
A code review is made for reviewing code, not for learning. If I were a junior programmer, I would be intimidated to review senior's code.

On the other hand, reading senior's code is a great way of learning, provided that the Senior is available for answering all questions.

Two alternatives could be:

let Juniors attend code review meetings and let every attendant be open to some teaching/learning discussions

practice pair programming


答:
Although DRY is a good principle, you can also overdo it.

Even if each of the states supports a refund method, that does not mean you are repeating yourself. That would only happen if the business rules state that the refund handling must be identical in two or more states.

But even if there is common behaviour among a group of states, I don't see an advantage in adding multiple intermediate classes. Ultimately, all state classes in the pattern have to inherit from the same parent, so the common behaviour for several operations could also be bundled into that base class (especially if that common behaviour is to indicate "operation not supported").


答:
Should junior programmers be involved as code reviewers in the projects of senior programmers?

Yes they should.  It is a good learning experience to read other peoples' code.  (And that applies both for good code and bad.  Though one would hope that a senior developer's code wouldn't be bad ...)

Obviously, it is unwise to only have juniors doing the code review.  And unwise to put too high expectations on the juniors in terms of what they can find.  However, you could also be surprised by the fresh insights that the junior  programmers can bring to the table.

Another Answer mentioned juniors being / feeling intimidated.  That is NOT what code reviewing should be about ... for either the reviewed or the reviewers.  If that is happening, your group needs to change the way it does its code reviews ... and maybe the intimidators need to be pulled into line.

Title: Should Junior Programmers be involved as code reviewers in the projects of Senior Programmers?

Body:
One of my team members, a junior programmer, has impressive programming skills for his level of experience.

And during code reviews, I believe in emphasizing learning, not pointing out mistakes.

But should junior programmers be involved in code reviews for more senior programmers? Or should code reviews be attended only by programmers with corresponding experience?


答:
My answer is: Sometimes. It's going to vary from programmer to programmer, and from task to task.

For:

If you want those juniors to learn how to do an effective code review, then the best way is for them to see how the seniors do it.

A junior programmer might have more experience than a senior one in a particular language/domain/etc.

By forcing juniors to evaluate seniors' code, they are inevitably going to learn things. Pair programming is going to be a more effective way of doing this though, since any questions the junior may have can get immediate answers.

Nobody's code is sacred, and nobody is so good that their code shouldn't get reviewed. If you don't do this, who is going to review your top guys' code?

Not all juniors are equal, and not all seniors are equal. Sometimes there might not be much of a gap, so don't get hung up on job titles.

Against:

There's a risk of the reviews getting bogged down with non-issues from juniors.

The level of knowledge/skill required might simply beyond the junior's capabilities. This is going to not only waste their time, but quite possibly demoralize them too.


问:
Whats the greatest most impressive programing feat you ever witnessed?
Everyone knows of the old adage that the best programmers can be orders of magnitude better than the average. I've personally seen good code and programmers, but never something so absurd. So the questions is, what is the most impressive feat of programming you ever witnessed or heard of?

You can define impressive by:

The scope of the task at hand e.g. John single handedly developed the framework for his company, a work comparable in scope to what the other 200 employed were doing combined.

Speed e.g. Stu programmed an entire real time multi-tasking app OS on an weekened including  its own C compiler and shell command line tools

Complexity e.g. Jane rearchitected our entire 10 millon LOC app to work in a cluster of servers. And she did it in an afternoon.

Quality e.g. Charles's code had a rate of defects per LOC 100 times lesser than the company average. Furthermore he code was clean and understandable by all.

Obviously, the more of these characteristics combined, and the more extreme each of them, the more impressive is the feat.

So, let me have it. What's the most absurd feat you can recount? Please provide as much detail as possible and try to avoid urban legends or exaggerations. Post only what you can actually vouch for.

Bonus questions:

Was the herculean task a one-of, or did the individual regularly amazed people?

How do you explain such impressive performance?

How was the programmer recognized for such awesome work?

答:
Maybe I'm just showing my age, but I think some of the truly impressive feats of programming are being ignored.

Steve Wozniak, Apple Disk II/RWTS

Steve designed the hardware and software together, using really cool tricks in the software to eliminate a lot of complexity (and cost) in the hardware. Normal floppy disk drives used an LED and photosensor near the hub of the disk to shine through a hole punched in the disk substrate. The output from the photosensor was connected to a processor interrupt so the processor would know when to start its timing routine to wait for the correct sector on a track to be under the read/write head (though a few used "hard-sectored disks" that had a hole to signal the start of each sector instead of just one for the start of the track).

Steve eliminated that hardware by designing the software to encode the data in a way that would let you start reading from an arbitrary spot on the disk, and not only decode the data itself, but figure out where (logically) in the track you were. The Disk II drive didn't have the LED/photsensor setup, and completely ignored the hole(s) in the floppy disk.

Gordon Letwin, HPFS

Gordon Letwin was an architect (and coder) on the OS/2 team. At least as I've heard the story, at one point he went on vacation to get away from things, and spend three weeks (or so) sailing around on his yacht (yes, early MS employees could afford things like that...) ...but to keep from getting too bored, he decided to take along his laptop.

When he returned, he had HPFS written, debugged, and working -- entirely in Intel 386 assembly language. The code he wrote was eventually sold as the "HPFS386" that was exclusive (at least at the time) to the LAN Manager Edition of OS/2. Another team then spent something like six months writing a version in C that became the "normal" HPFS included in the normal editions of OS/2 (and after IBM and MS broke up, IBM updated and re-compiled the C code to get their "HPFS386"). Although it's been modified and update since, if you were being fair about things, NTFS would probably be called "HPFS 2.0" (or maybe 3.0) -- there's no question that Microsoft's best current file system is still closely derived from what he designed.

Burroughs B220 tapes

These embodied (at least IMO) the real beginnings of object oriented programming. Where IBM tapes (for one example) had "labels" to tell about the format of data on the tape, Burroughs tapes developed a convention (I don't think anybody knows for sure who started it) of putting a small set of routines on the tape that would understand the data and how it was formatted, so you could manipulate the data correctly without knowing the details of how it was formatted. In other words, the first few "blocks" on the tape were basically a vtable in persisted form. You'd basically read the vtable into memory, then use the methods it defined to manipulate the data on the rest of the tape. All very neat and simple (if just slightly less than completely portable).


问:
What can I do to help users create self-service reports?
I work using Reporting Services 2008 and I'm constantly creating ad-hoc reports. We'd like to use PowerPivot on Sharepoint but we're stuck on Sharepoint 2007. Using easy reporting software like Tableau Server would be fantastic but we can't afford it SSRS Report Builder hasn't proved to be very helpful, unfortunately.

I've been trying to think of ways to leverage Excel / PowerPivot or any other (free or inexpensive) tool. We just need to be able to provide more data to users so they can analyze on their own. This is an area our IT team as a whole needs to improve.

We use SSRS 2008 and SQL Server 2008. We also don't have a data warehouse, it's in the works...

答:
http://www.sqlpower.ca/page/wabit - is an open source on-the-fly reporting tool.
Not sure whether you are looking for something similar, but please check the demo videos they have in the website.

More: The above tools enables to connect to multiple databases and write queries in a visual manner. The filters could be dragged and dropped and joins between tables could be visually edited. I think this will be a step in the direction of a solution in your above mentioned issue with too much ad-hoc reporting and more close to the dimensional model/ database level manipulations and querying ,than an excel alternative. Also more power to the end user at the expense of more technical exposure.


问:
Why do we use story points instead of man days when estimating user stories?
In agile methodologies (e.g. SCRUM), the complexity/effort needed for user stories are measured in Story points. Story points are used to calculate how many user stories a team can take in an iteration.

What is the advantage of introducing an abstract concept (story points), where we can just use a concrete measurement, like estimated man-days? We can also calculate velocity, estimate coverage of an iteration, etc. using estimated man-days.

In contrast, story points are harder to use (because the concept is abstract), and also harder to explain to stakeholders. What advantage does it offer?

答:
The story point estimation follows fibonacci series 1,2,3,5,8,13,21...

A human brain can easily map things based on sizes.  For example:  We have a post it card and assign it a story point 2 and three post it card's size would mean 2*3=6 story points.

Story Point 6 falls between fibonacci series number 5 and 8 with 5 being the closer number and hence the storypoint would be 5.


答:
The primary purpose of a code review is to find defects or potential problems. The required participants in the review should be the people who are best suited to identify these problems, regardless of their title or seniority.

As an example, if an application is being developed in Python and the junior engineer has more experience with the Python language than the senior engineer who wrote the code, then they might be a valuable asset in pointing out alternative methods of doing something, but they may also have less knowledge of the system as a whole.

Beyond the experience in the tools and technologies, also consider experience in the application domain. Someone with 20 years of experience but only 1 or 2 in the financial industry may be helped by having an overall less experienced developer with only 5 years of experience all in the financial industry review his work.

Inviting less experienced staff members to observe and participate as much as possible the code review process may also be beneficial to allow them to learn a code base, ask questions, and learn about what is expected of them in not only code reviews, but in the code that they produce. However, you probably don't want too many people involved (focusing instead on the people who can fully support the code review and its purpose) in the process.

This really applies to any kind of review - requirements, design, code...


答:
Collabedit is also a nice platform for online coding interviews. It offers real time view of what the candidate is coding, as well as a feature to chat. It can also do syntax highlighting.

an online code editor that lets people collaborate in real-time.

It works in your web browser so no installation is needed...

Features

text editor

chat

document history

syntax highlighting for programming languages...

Title: Are there any tools for remote coding interview?

Body:
Firstly, I'm not exactly sure if this question is a better fit over here, or on workplace.SE. So forgive me if it is in the wrong place.

We are interviewing some candidates for a development position, and currently they are not in our city.

We would like to give them simple coding tests to see how they will perform on the typical issues that we face in our daily work.

Are there any specific tools geared towards this? Right now we are using Skype and I feel this tends to decrease the performance of a lot of developers since they tend to be shy, and often can't work when someone is directly staring at them.

The problem with sending them the test questions by email are as follows:

It is not possible to know what their thought process is, sine we just see the end result. There is no discussion, or clarification of the question, which is an Important step.

There is no guarantee that the problems were solved by the candidates themselves. They could send it to a smarter friend, and we wouldn't be able to know.

How are these problems usually solved?


问:
how do I form a team which is remote?
I've got a bit of a challenge.  While I'm not "in charge" I'm certainly lead developer on a project and my team will be scattered to high heaven.

I've got someone who works on Fridays only, and probably 2 people who will be 3-4 hours away in another state. (One of the lovely side effects of partnering with multiple universities).

Anyway, how can I get them all on the same "team"?? I've read a bunch of Joel Spolsky's stuff, but I can't create the same kind of environment that he uses.  This is also the first project I'll be lead on, so it's kindof make-or-break.

Specifically I'm looking for managing styles (personality), process models, project management  (scrum?), video conferencing tools, and the like.  I just don't have any resources for this kind of thing, and I'm afraid I'm going to be stuck doing too much work.

Thanks,

答:
This one is a tough one!  Have a google on "distributed agile teams" when you get the chance, but in short:

Communication is vital.  Find out how each team member prefers to communicate and come up with a medium that everyone is happy with.

Make sure all decisions/conversations are open (not private), e.g. Archivable mailing list, commit log, IRC chat is OK if you save off the logs

You probably want to adopt some sort of agile methodology, at least in terms of getting small units of work delivered often, that way you can all help each other out, see what others are up to and not 'disappear for weeks on end'

See http://www.producingoss.org for some good tips (open source, but many of these can be applied).

Use canned hosting (issue tracking, mailing lists, source control, build tool, CI etc), make it as painless as possible for everyone to get each others work and get it ti interoperate.

Try to all meet at least once in person or over a video conference, we interact vastly differently with people we've met in the flesh.

Good luck!

Title: how do I form a team which is remote?


答: Teamviewer is a commercial solution, but free for private use, to share a desktop over the internet (disclaimer: I don't work for that company). Opposed to a solution like Google Docs, the candidate can use in his favorite IDE to demonstrate his coding skills.</p>