问:
What is a real-world use case of using a Chomsky Type-I (context-sensitive) grammar
I have been having some fun lately exploring the development of language parsers in the context of how they fit into the Chomsky Hierarchy.

What is a good real-world (ie not theoretical) example of a context-sensitive grammar?

答:
Good question.  Although as mentioned in the comments very many programming languages are context-sensitive, that context-sensitivity is often not resolved in the parsing phase but in later phases -- that is, a superset of the language is parsed using a context-free grammar, and some of those parse trees are later filtered out.

However, that does not mean that those languages aren't context-sensitive, so here are some examples:

Haskell allows you to define functions that are used as operators, and to also define the the precedence and associativity of those operators.  In other words, you can't build the correct parse tree for an operator expression like:

```<code>a @@ b @@ c ## d ## e
</code>```

unless you've already parsed the precedence/associativity declarations for @@ and ##:

```<code>infixr 8 @@
infixr 6 ##
</code>```

A second example is Bencode, a data language that prefixes content with its length:

```<code><length>:<contents>
</code>```

The issue with this format is that it's pretty much impossible to parse without something context-sensitive, because the only way to figure out the "field" sizes is by ... parsing the string.

A third example is XML, assuming arbitrary tag names are allowed:  opening tag names must have matching close tags:

```<code><hi>
 <bye>
 the closing tag has to match bye
 </bye>
</hi> <!-- has to match "hi" -->
</code>```

Body:
Good question.  Although as mentioned in the comments very many programming languages are context-sensitive, that context-sensitivity is often not resolved in the parsing phase but in later phases -- that is, a superset of the language is parsed using a context-free grammar, and some of those parse trees are later filtered out.

However, that does not mean that those languages aren't context-sensitive, so here are some examples:

Haskell allows you to define functions that are used as operators, and to also define the the precedence and associativity of those operators.  In other words, you can't build the correct parse tree for an operator expression like:

a @@ b @@ c ## d ## e

unless you've already parsed the precedence/associativity declarations for @@ and ##:

infixr 8 @@
infixr 6 ##

A second example is Bencode, a data language that prefixes content with its length:

<length>:<contents>

The issue with this format is that it's pretty much impossible to parse without something context-sensitive, because the only way to figure out the "field" sizes is by ... parsing the string.

A third example is XML, assuming arbitrary tag names are allowed:  opening tag names must have matching close tags:

<hi>
 <bye>
 the closing tag has to match bye
 </bye>
</hi> <!-- has to match "hi" -->


问:
TDD Mock call verification - is it an anti-pattern?
I've been doing TDD for a while now, I feel pretty good about it, I love my test suites and all. However I've noticed that lately I've been doing a lot of mock call verification. For example I'd have a Service that will have a Repository injected - in my unit test I'd pass a mock of the Repository and verify that it was called within the method that I'm testing. I'd then check if the results returned are correct (in another test). This definitely "feels" wrong, since my unit tests are now tightly coupled to the implementation details. I've heard that you should test "behavior", however in a lot of the situations that's ... emm - not possible? If you have a void method for example, you usually test side-effects. I mean it's easy to go ahead and show some simple code-kata's where this can be demonstrated, but IMHO it doesn't reflect very well to the real world programs that we write. Is what I'm doing wrong? Is this type of testing sort of an anti-pattern? I'd appreciate your opinion on this.

答:
My thoughts re: 'aggregate services'.

Call verification will do this, but won't provide much value. You're just checking your wiring.

There are 3, non-exclusive, other ways to this:

Extend the tests you have for each individual service so that it checks the higher level behaviour. For instance, if your hitting an in-memory database in your unit tests of the service, take it up a level so you're testing the service against an actual db. The service layer is higher up the abstraction tree, and so should your test.

Use code generation to create the service directly from the aggregated services.

Use some sort of reflection or dynamic language to do the same thing. For example, in Java, it may be possible to use a groovy interface, which passes the call on directly.

There are probably other ways to do this, but just checking wiring has very low pay back, and will hard wire you in to this implementation.

ContentLicense: CC BY-SA 4.0

ContentLicense: CC BY-SA 3.0


问:
Using .exe of program with GNU General Public License version 2.0 for commercial
I have a question to somebody who is expert about "GNU General Public License version 2.0" license.

I am making program and my code is using another program ("HoboCopy") inside which have this one license. I downloaded just a .exe of this one program and I am wondering if its ok with license if my boss will sell program which I made without code of course, he wants to sell it like a normal program, just .exe to use.

I checked out for question like that, and no matches. Sorry I know that in a big licence documentary is probably wroten answer for my question, but forgive me, that I dont want to read it all, maybe somebody already know it and can tell me or eventually tell me the exactly piece of licence documentary where I can found answer for my question.

Thanks in advance.

EDIT:
After published my post I read this one: https://stackoverflow.com/questions/11057715/gnu-general-public-license-as-part-of-commercial-product?rq=1. Looks like I got answer that he can sell it. And I dont have to give my source, and HoboCopy source (even I dont have it).

Just maybe somebody can make me sure.

答:
You should read carefully terms 2 and 3 of the GPL v2 as they directly relate to your question. You should also consult with a lawyer (IANAL).

It is unclear in your question how your program relates to hobocopy.exe. There are three possibilities:

If your software does not include hobocopy.exe and the users must download/install it from somewhere to use your program, then your program does not need to be licenced as GPL and you do not have to distribute the sources of your program or those of hobocopy.exe.

If your software does include hobocopy.exe as a clearly separated component that your code uses as an external program (e.g. in Java, Runtime.getRuntime().exec(params)), then your program does not need to be licenced as GPL and you do not have to distribute the sources of your program, but you must distribute the sources of hobocopy.exe (if you distribute GPL software you must distribute the sources too).

If your software merges somehow with hobocopy.exe, even just creating a wrapper around it, in a way that the separation is not clear or they cannot "reasonably [be] considered independent and separate works in themselves", then your program can be considered a derived work and therefore must be licenced as GPL, and you must distribute the source code of your program and of HoboCopy. You can still charge for it, though, and "sell it like a normal program". The GPL does not prevent you from charging for the software, it only prevents you from distributing the binaries without the sources.


问:
Use my own GPL licensed code in a commercial product
I am developing a software project in Java/Swing licensed under GPL v3.
Later, I want to create a Android application which uses the algorithms of the Java/Swing application. This Android app will be a commercial product (sold on Google Play Store).

Is this a problem, when I use my OWN GPL code in a commercial SW developed by me?

答:
Other answers have already said that you can, as the copyright holder, change the license of your own code at any point. I will not insist on that.

I just wanted to add a detail that nobody else has mentioned: you can sell GPL code on Google Play in a commercial product. Nothing in the GPL prevents your Android GPL application from being a commercial product that you charge money for.

The only requirement for distributing GPL software is that you must distribute the source: distributing the binaries is optional, and charging is optional, but there is nothing wrong or illegal on distributing binaries and sources for a fee (i.e. selling GPL software).

OwnerDisplayName: Andreas Freitag


问:
Restart button in Python
I am having trouble with python. I am making a text-based adventure game, and I am trying to make a restart function when you die. I am trying to count deaths by doing deaths = deaths + 1 whenever you die, but the only way to restart is to re-run the entire script, which resets the death counter. Does anyone know how to restart a script without re-running the program?</p>

答:
You can call your script from another script, and when you "restart", use the reload built-in method.

```<code>reload(mymodule)
</code>```

This isn't truly ideal though for a game. What you're instead looking for is a level loader, with a main loop which handles state.

Does that make any sense? Its a fun challenge building your own level loader, and might be more effort than you want to put in.

Title: Restart button in Python

Body:
You can call your script from another script, and when you "restart", use the reload built-in method.

reload(mymodule)

This isn't truly ideal though for a game. What you're instead looking for is a level loader, with a main loop which handles state.

Does that make any sense? Its a fun challenge building your own level loader, and might be more effort than you want to put in.


问:
Form, Fit and Function changes in relation to software
I am looking at configuration management and the idea of form, fit and function change can determine whether a change is minor or major. I wondered how this definition could be applied when doing software development.

Is there a good guideline on whether a change to software is classed as a major or a minor change?

答: It depends on the organization, but often the best way to classify a change is from the user's perspective. Does it appear to be a major or minor change, from their perspective?</p>


问:
Average video frame size for video codec
In simple words, is it true that an average size of an encoded video frame would be FrameSize = BitRate/FrameRate? Because BitRate shows how much data we are transferring per time unit, and FrameRate shows how many frames does this time unit contain.

答:
Generally speaking, I suppose technically you're correct if you're looking for a general average. But I think we'd really have to hear the use case that you're looking for, as I can't imagine the resulting value being useful for very much at all (in fact, I mostly agree with John's answer). Each frame's size is going to vary wildly; random example. The 20th frame of a person looking at the camera is going to take up about 12 KB, whereas the jump-cut to a helicopter shot of Hong Kong's skyline is going to take up 700 KB.

Just a general tip for this site; often, giving more details about the exact problem you're trying to solve (ie, "My videos are streaming very slowly, and so I'm trying to....") may get you more helpful results than a very direct question.


问:
Should we mock entities and value objects when doing DDD?
After reading a few articles about Newable vs Injectable objects and how these concepts relate to DDD's services, entities and value objects, I was left with some doubts about using newables in my code especially in my unit tests.

Main candidates for newables were Entities and Value objects meaning that instead of injecting these dependencies into other objects one should just new an instance of these objects and use them directly in the code.

However, good DDD practices advocate assigning responsibilities to entities and value objects if they were deemed appropriate. So the entities and value objects will end having some serious business logic in them.

Now if a service operates on an entity or a value object should I mock the entity or value object and pass the mock to the service (mocking will require an interface for the value objects or entities which seems to be advocated against) ?

Or should I just new an entity/value object and pass a concrete implementation to the service and thus violating the unit testing principle of testing only one unit?

答:
I'm reading that you're of the opinion that unit tests, much like SOLID objects, must have "one reason to break". It's a noble goal, but I think you'll find that in many cases it is simply not feasible. One of those cases is here, where you have a "rich" domain object (DDD differentiates between Entities and Value Objects, which both comprise the "domain model") that is a dependency of the system under test.

In these situations, I have the philosophy that, given the domain object has its own comprehensive unit test coverage, trusting that the object will work as designed in a unit test for a different SUT does not necessarily violate the unit test. If this test were to break because of a breaking change to the domain, then I would expect the domain object's unit test to break as well, leading me toward something to investigate. If the domain object's unit test had been updated properly as a red test, then made green with the change, and this other test then failed, that's not necessarily a bad thing either; it means that the expectations of this other test conflict with the new expectations for the domain, and I need to make sure both of them agree with each other and the overarching acceptance criteria of the system.

As such, I would only mock a domain object if said domain object produced "side effects" that were undesirable from a unit-testing perspective (i.e. touching external resources like data stores), or if the logic of the domain object were sufficiently complex that placing it in the proper state for the test becomes a roadblock to defining and passing the test.

That then becomes the driving question; which is easier? To use the domain object for its intended purpose within the test, or to mock it? Do whichever is easier, until it's no longer the easier option, such as when a functional change breaks the test of the service in a complex way; if this happens, then rewrite the test to produce a mock that exposes the functional requirements depended on by the service, without the complexity that breaks it.

Understand that either way, there should be an integration test that uses the real domain object plugged into the real service that tests the interaction between these two at a higher level of abstraction (such as testing, for instance, not only the functionality behind a service endpoint, but a proxy across which the domain object is serialized and sent).


问:
Law of Demeter causing subclassing indecision and conflict with Single Responsibility
This is my situation:

I have a class called CueList, which is basically a wrapper around ArrayList. I have another class called TimeTicker that alerts all the Tickable (interface) in its list that a certain amount of time has passed. Since I need to tick all of the items in CueList, but I don't want to violate DRY by keeping a copy of all of the CueList items in the TimeTickable class as well (which would make a nightmare when I want to delete a Cue), my immediate instinct was to make CueList a Tickable and have it pass on the "tick" message to all of its items.

This seems to violate the Single Responsibility principle, which says that CueList should not worry about both keeping track of all the cues AND Ticking them.

So what I did was create a CueManager class that is itself Tickable and links everything up (and ticks all of the CueList elements).

But now, because of the law of demeter, I have a bunch of duplicate methods in the CueManager that just mirror the TimeTicker and CueList class.

Doesn't that mean that the CueManager class has multiple reasons to change? Doesn't that mean it violates the Single Responsibility principle.

Also, since most of the methods in CueManager mirror TimeTicker and CueList, doesn't that really mean that it IS a TimeTicker and CueList. Therefor shouldn't it INHERIT from CueList and TimeTicker! (Obviously you can't do multiple inheritance in Java, but I feel like it sort of makes sense to Inherit from CueList, but then that would violate Single Responsibility)

So in summary:

Law of Demeter makes me make a bunch of methods that merror two other classes, but that makes me think that it really should just inherit from both of those classes, but that would mean that one class handles multiple responsibilities (even if it is through its superclass).

答:
CueList is an ArrayList (or at the very least can expose some similar interface such as Collection, List or Iterable). All items in that ArrayList are, ostensibly, Tickables. TimeTicker doesn't, and shouldn't, care that its items are in a CueList specifically, nor should it care that the items in the list it acts on are anything but Tickables. By the same token, CueList should have no knowledge of TimeTicker; it is of no bearing to CueList's basic functionality AFAICT. This is the essence of the Least Knowledge Principle.

So, make TimeTicker act on an injected ArrayList<Tickable> (or a Collection<Tickable> or a List<Tickable> or an Iterable<Tickable>, whatever interface exposes the methods you use to spin through this list) and pass in CueList as this dependency, via some class that already has to know about both the list and the ticker.


答:
It depends on the type of software.

For something like a library, a major change is one that does not guarantee backwards compatibility with previous major versions of the library.

For something like desktop software, a major change may simply coincide with a purchasable and/or yearly upgrade.

For something like embedded software, a major change might coincide with a form, fit, or function change to the system or product.

Title: Form, Fit and Function changes in relation to software

Body:
I am looking at configuration management and the idea of form, fit and function change can determine whether a change is minor or major. I wondered how this definition could be applied when doing software development.

Is there a good guideline on whether a change to software is classed as a major or a minor change?


问:
What is the value of using version control?
I'm new to version control (currently using SVN), but I don't understand how this helps developers. What does version control do that makes it useful in a development environment?</p>

答:
The most productive developer is alone. A solitary developer never has to worry about coordinating with anyone else. But as soon as the project goes plural, there is overhead. And for every developer added to the team, the overhead gets worse. It is the job of the VCS to help manage this overhead and minimize the effects.

http://www.ericsink.com/vcbe/html/dvcs_private_workspace.html


答:
I would use the Domain Events pattern (google it) to afford TimeTicker and CueList to collaborate.

When the time is right, TimeTicker could 'raise' to a register of handlers an event called Tick. The register of handlers then passes Tick event onto all registered implementations of

```<code>Handle<Tick>  { void Handle(Tick t); }
</code>```

Now you have options:

CueList could implement Handle and tick its members.

each Cue could implement Handle for itself

or a general TickHandler class can get the CueList and update the cues

Title: Law of Demeter causing subclassing indecision and conflict with Single Responsibility

Body:
This is my situation:

I have a class called CueList, which is basically a wrapper around ArrayList. I have another class called TimeTicker that alerts all the Tickable (interface) in its list that a certain amount of time has passed. Since I need to tick all of the items in CueList, but I don't want to violate DRY by keeping a copy of all of the CueList items in the TimeTickable class as well (which would make a nightmare when I want to delete a Cue), my immediate instinct was to make CueList a Tickable and have it pass on the "tick" message to all of its items.

This seems to violate the Single Responsibility principle, which says that CueList should not worry about both keeping track of all the cues AND Ticking them.

So what I did was create a CueManager class that is itself Tickable and links everything up (and ticks all of the CueList elements).

But now, because of the law of demeter, I have a bunch of duplicate methods in the CueManager that just mirror the TimeTicker and CueList class.

Doesn't that mean that the CueManager class has multiple reasons to change? Doesn't that mean it violates the Single Responsibility principle.

Also, since most of the methods in CueManager mirror TimeTicker and CueList, doesn't that really mean that it IS a TimeTicker and CueList. Therefor shouldn't it INHERIT from CueList and TimeTicker! (Obviously you can't do multiple inheritance in Java, but I feel like it sort of makes sense to Inherit from CueList, but then that would violate Single Responsibility)

So in summary:

Law of Demeter makes me make a bunch of methods that merror two other classes, but that makes me think that it really should just inherit from both of those classes, but that would mean that one class handles multiple responsibilities (even if it is through its superclass).

Body:
I would use the Domain Events pattern (google it) to afford TimeTicker and CueList to collaborate.

When the time is right, TimeTicker could 'raise' to a register of handlers an event called Tick. The register of handlers then passes Tick event onto all registered implementations of

Handle<Tick>  { void Handle(Tick t); }

Now you have options:

CueList could implement Handle and tick its members.

each Cue could implement Handle for itself

or a general TickHandler class can get the CueList and update the cues


问:
Why does Java exit with success after an uncaught exception?
Any time a Perl, Python, C++ or Tcl program halts with an unhandled exception, those language runtimes take care to register a non-zero exit code for the process. Even Eclipse-based programs return 1 if they fail during startup. Programs run by the standard java.exe, however, happily return zero no matter how abruptly they end, unless the program calls System.exit() with an exit value. Even AssertionFailedError or UnsatisfiedLinkError are reported back to the calling program as successful exits.

Of course not all systems have program return codes, but Unix and Windows were important enough to warrant java.lang.Process.exitValue() for child processes; don't they also warrant honouring conventions for parent processes?

Is this a flaw in the language design or just in the implementation? Is there an argument that it's a good idea?

答:
If the Java Language Specification does not explicitly define what exit value to expect, then it is undefined and you should not rely on it.

You need to catch Throwable in your main method, and call System.exit(1) yourself.

ContentLicense: CC BY-SA 2.5


问:
What should be an optimal team (in terms of roles) to write a big enterprise nice-quality framework?
I have a set of questions that bothering me, hopefully someone will be able to answer them here:

What should be an optimal team (in terms of roles) to write a big enterprise nice-quality framework?

What big frameworks could act as a good references in terms of documentation, architecture, quality of implementation etc?

What is your assumptions about size of teams that developed this frameworks?

Looking forward for answers. Thanks!

答:
DO NOT BEGIN A PROJECT BY WRITING A FRAMEWORK

Useful frameworks are seldom or never written from scratch.  Useful frameworks are factored out of working applications and refined by attempts to use them in new applications.  Rinse and repeat a half-dozen times and you may have something worthwhile.


答:
Sounds like the Observer pattern where it is normal that the subject (TimeTicker) keeps a list of its observers (Tickables) so it can update them on an event.  Your Tickable interface can define an UnRegister() method which you can call when it is removed from any list.

```<code>class TickableItem
{
    TimeTicker Subject;

    void UnRegister()
    {
        this.Subject.UnRegister(this);
    }

    void Register(TimeTicker subject) { ... }

    void OnTick() { ... }
}
</code>```

The benefit of this approach is that your CueList doesn't need to know who the TimeTicker is. It's tickable items know who their TimeTicker's are (they can be registered with different ones).

Body:
Sounds like the Observer pattern where it is normal that the subject (TimeTicker) keeps a list of its observers (Tickables) so it can update them on an event.  Your Tickable interface can define an UnRegister() method which you can call when it is removed from any list.

class TickableItem
{
    TimeTicker Subject;

    void UnRegister()
    {
        this.Subject.UnRegister(this);
    }

    void Register(TimeTicker subject) { ... }

    void OnTick() { ... }
}

The benefit of this approach is that your CueList doesn't need to know who the TimeTicker is. It's tickable items know who their TimeTicker's are (they can be registered with different ones).


问:
Encapsulate downcasting when returning from a method
In chapter 24 of Code Complete the author says, in reference to encapsulate downcasting when returning from a method, "If a routine returns an object, it normally should return the most specific type of object it knows about. This is particurlarly applicable to routines that return iterators, collections, elements of collections, and so on."

Now, being a C# programmer, I typically always return ICollection instead of, say, IList or even List. By using an interface from higher up in the hierarchy I am free to switch collection type in the method without breaking the method interface. This seems like a good thing. What am I missing?

答:
This a question of weighing the benefits to yourself, the library author, and the benefits to others, the application programmers.

Publishing a general type leaves you free to change your mind later without violating the contract, but at the same time, it devalues the contract itself. If you return a generic collection, your user can't do anything with it except enumerate it. If that's all that is needed, fine. But if the user actually needs a well-defined ordering of the returned elements, a Collection is not sufficient. In a perfect world, every application programmer would recognize this and refrain from depending on the order in which the elements are returned. However (you know where this is going...), in the real world, what will likely happen is that you declare your results as a Collection, but implement them via some kind of List, and your users observe a predictable order of elements and come to depend on it. Then when you change the implementation, their programs break and they curse you. If you had committed to generating a List in the first place, this can't happen.

This is why it's a good idea to commit at least to some level of specific data structure in public interfaces. It is actually quite rare that you change your mind about whether a data structure will allow duplicates, or whether it allows null, or whether it has to be ordered or not, so decisions such as choosing List over Set aren't that hard to make, and they give your users more assurances to work with (rather than falsely assuming things that are true now but might change without notice).


问:
Are algorithm questions good interview questions?
I've had an argument recently with a fellow programmer. He was interviewing for a new position and was asked this question:

Give a sequence of numbers starting at
  X and ending in Y but with one element
  missing so N is Y-X-1, find the
  missing element in O(N) or better.

Now, the answer is irrelevant here (but interesting). This started a discussion on whether this was even a good question to ask during an interview.

One side: Algorithms are an inherit part of programming and a candidates ability to answer this question supports that this candidate will be a good programmer and be able to solve larger problems and can handle most programming tasks which are ultimately easy to understand and answer.

Other side: Writing algorithms from scratch is rarely used in modern programming and therefore is irrelevant in the bigger question of whether the person will be a good programmer. A person could successfully answer this question yet still not be able to do more common programmings tasks.

Your thoughts? Good interview question or not?

答:
I have to admit here, that I am one of those who like to ask algorithm questions in interviews, but I have to stress, that the actual answer to the question is absolutely irrelevant. I do not care the slightest if the interviewee knows the answer or not. Instead, for me, this question targets different aspects, like the following - in order of importance:

Requirements

Such questions are deliberately under-specified. In your example, there are no further details given about the sequence. If you have an interviewee who asks you whether these numbers are actually sorted, then that's a good sign. He has the correct mindset to ask customers on further details, that will help coming to a better solution in a shorter time. The candidate may also toy with the idea of using O(n) space to store an array of N numbers, but he should not do that without asking about more details on X and Y. Let's say that X and Y are between 1 and 1000, then sure, go ahead and fire up an array-based solution. But if I tell you the interval is 1 and 1 billion, then the problem becomes a totally different one. Let me stress again, that I don't care about the solution. I want to see if the candidate can find the distinction between these problems, which are immensely different.

Standard Techniques

I do not want to hire a programmer who doesn't even know what O(n) means. That's an absolute must-know if you had any decent education in that area. But it's also important to not just know what it means, but to actually apply that knowledge. In your example, I want a candidate to realize that he is not allowed to sort the data (without asking further questions targeting the option of a bucket sort or other O(n) sort approaches) due to sorting required O(n log n) in general.

Similarly, other algorithm questions target standard techniques like tree- or graph-traversal, or recursion. A candidate may slip at one of these techniques, which does not make a good impression. In such cases, however, I like to dig deeper to find out whether the candidate has any CS background at all. Of course, it depends on what the target position is, but usually a developer who doesn't know about runtime complexities, nor typical data structures and their traversals, is not going to be any help.

Problem-Dealing Mindset

After asking the question, you monitor the candidate closely. How does s/he react? You get the best results here from candidates who have absolutely no clue on how to solve the problem at first. In that respect, the question checks what might happen if a similar situation occurs at the workplace later. You may happen across such a problem during your development, and it is good to know how your candidate deals with these problems, even if s/he is not able to solve it all by themselves.

Example: You do not want your candidate to go into silent mode for the next half hour! Check if he can come up with intelligent questions (see Requirements), check if he starts thinking out of the box once he realizes he cannot do it. Even a "fun" counter-question like a "May I use the phone-a-co-worker option?" is a good sign.

How to answer

In general, the best answers you can give for these kind of questions are counter-questions! Telling an answer right-away basically fails the whole thing, and is in fact not a good answer at all, because all of these question hint at trade-offs, which your answer implies, without you having the required information yet to intelligently make that trade-off. Of course, the quality of the counter-questions varies between candidates.

As a general note on interview questions: Counter-questions are seldomly a bad thing. In one of my own interviews I was for example asked something like the following: "If you would have to implement X, would you choose C++ or Java for that, and why?" - I simply countered with "Am I limited to these two?". Guess for yourself, what kind of reaction you get from an interviewer for such a counter-question - and how easy it makes it for you to actually show the interviewer what you're capable of.


问:
Why do we not prefix Enums, Abstract classes and Structs?
The C# community has so ubiquitously used the "I" prefix to denote an interface that even the most inexperienced programmers know to use it.

Why is it then that we do not prefix enums, abstract classes or structs (possibly with "E", "A" and "S" respectively)?

For example, if we did mark all abstract classes with an "A", it would provide valuable information about that type which, while it could be inferred, is not immediately obvious.

Please note that I am not advocating for this change, I am merely trying to understand why we do not do things this way.

This thread answers why we do use the "I" prefix but doesn't answer why we don't use other prefixes.

答:
I think it isn't used much because:

most of the time it doesn't mater much if it is an enum, or an abstract class or a struct

if it does mater I can probably see it from usage and otherwise find out pretty quickly

if I change it being an enum, abstract class or struct , I also have to rename it

for people who don't know the convention it is pure noise.

people might just dismiss the entire idea because they have been taught not to use Hungarian notation. There have been and still are people who say you should not use Hungarion notation, without making the distinction between Apps Hungarian and Systems Hungarian. A nice discussion can be found in this SO question. Not just the first answer is interesting but there are great answers and comments. From that same question comes this article by Joel Spolsky (scroll to paragraph "I’m Hungary" )

in short : In general the added value doesn't add up to the cost.

From that last bullet point and some interpretation you could conclude. Systems Hungarian (prefix type) is bad and should not be used. Apps Hungarian (prefix kind) has it uses.

Taking that back yo your question I think your proposed notation is a form of Apps Hungarian and if you feel that the added value adds up to the costs and you implement it consistently in your code base it is just fine. But since you have to consider it on a per project basis it should not be a general rule.

I guess people noticed that it did mater for interfaces more often and that is why it has become a general rule for interfaces.


问:
Static methods or static functions?
I was just reading https://stackoverflow.com/questions/155609/what-is-the-difference-between-a-method-and-a-function and all of a sudden, the thing came to my mind was the static methods. </p>

<p>As static methods are no way associated with an object how can it be called as static methods (almost all developers do)? Is my understanding about the methods/functions is correct? </p>

答:
As static methods are no way
  associated with an object how can it
  be called as static methods (almost
  all developers do)? Is my
  understanding about the
  methods/functions is correct?

That's an abuse of language. In C++ :

a member function is a function associated with a type or instances of a type. It can be:

static : associated with the type itself, not with instances

non-static : associated with an instance of the type. They can be :

virtual : can be redefined by a child class of the type

non-virtual : cannot be redefined by a child class (but can be "hidden", often trigerring a compilation warning)

a method is a virtual member function that cannot be static by definition

The problem is that some post-C++ languages like Java, a all (non-static) member functions are virtual. So people started to say those are methods. As they didn't needed non-virtual member-functions, they only used the word method for any function that is member of a class.
Now, in those languages, types are also objects, are one instance, so you can say that their static members are in fact methods of the unique object represeting the type. (I'm not sure that's correct for any dynamic language)

Anyway, from your perspective, static member functions(or method if you prefer) should always be perceived as independant of the objects of the type they are member of, but implicitely associated with the type itself (whatever the implementation of that meaning is - whatever the language).

Title: Static methods or static functions?


答:
The point of the naming convention for interfaces is to provide a quick, no-brain decision about what to call the interface that your class implements. If you have a Frobnicator, but have to declare an interface for decoupling or whatever reason, then the decision to call it IFrobnicator requires no conscious thought, and this is good.

The same problem doesn't apply to the other constructs you name. Enums and structs are useful, but it's not necessary to find a second, short, transparent, obviously related name in addition to the name itself. Therefore, there is no pressure to slap an 'E' on to the name of an enum or struct.

(Abstract classes are somewhat similar to interfaces, since you do have to provide a second, concrete class to get anything done, so they might have acquired a convention of starting with 'A', but for whatever reason, they didn't. If I'm allowed to speculate, I think that 'I' being a particularly narrow letter might have had something to do with that.)

Title: Why do we not prefix Enums, Abstract classes and Structs?

Body:
The C# community has so ubiquitously used the "I" prefix to denote an interface that even the most inexperienced programmers know to use it.

Why is it then that we do not prefix enums, abstract classes or structs (possibly with "E", "A" and "S" respectively)?

For example, if we did mark all abstract classes with an "A", it would provide valuable information about that type which, while it could be inferred, is not immediately obvious.

Please note that I am not advocating for this change, I am merely trying to understand why we do not do things this way.

This thread answers why we do use the "I" prefix but doesn't answer why we don't use other prefixes.


问:
Should the search engine return a dictionary or strongly typed objects?
I'm building a search engine using Lucene.NET / Solr.NET, and I'm wondering should search hits be returned as a dictionary or strongly typed object.

```<code>public class SearchResult
{
    public string SearchTerm { get; set; }
    public List<Dictionary<string, object>> SearchHits { get; set; }
    ...
}

// where search hit looks like this
Dictionary<string, object> searchHit = new Dictionary<string, object>
{
    { "Name", "John Doe" },
    { "Address", "Some street" },
};
</code>```

vs

```<code>public class SearchResult
{
    public string SearchTerm { get; set; }
    public List<Foo> SearchHits { get; set; }
    ...
}

// where search hit looks like this
var searchHit = new SearchHit
{
    Name = "John Doe",
    Address = "Some address"
};
</code>```

I will be indexing different types of objects (People, Web pages, Files, etc.).
Each object has a different set of properties (people have name and address, while web pages have URLs and titles), and search hits don't have the same set of properties as original objects (WebPage class has the MainContent property, but after indexing, the search hit that represents this object will have the PreviewText property (the first 300 characters of MainContent property with stripped HTML tags).

I don't want to duplicate the code all over the place and have: IPeopleSearchService, IWebPagesSearchService, IFilesSearchService, etc. and corresponding search results: PeopleSearchResult, FileSearchResult, etc.

```<code>interface IFooService
{
    FooSearchResult Search(string text);
    void Index(Foo foo);
    ...
}

interface IBarService
{
    BarSearchResult Search(string text);
    void Index(Bar bar);
    ...
}
...
</code>```

I would like to have a more generic solution, but I don't like over-complexity. It should be readable and easily understandable by junior developer.

```<code>interface ISearchService<TEntity, TSearchHit>
{
    SearchResult<TSearchHit> Search(string text);
    void Index(TEntity entity);
}
</code>```

How would you design such a system? Any help would be greatly appreciated!

答:
Basically, what you're asking is: should I make the search results statically typed? I think the answer depends on what you're going to do with them and how much do you like static typing.

Regarding what you're going to do: if you're just going to display the results to the user, or something like that that treats all the fields in the search result equally, then using a Dictionary (which is basically the same as dynamic typing) makes sense. On the other hand, if you're often going to write things like searchHist.Address (or searchHit["Address"]), then that points more to static typing.

Regarding how much you like static typing: to me, as a proponent of static typing, using dynamic typing gives you small short term advantage (e.g. you don't have to write those dozen lines declaring each TSearchHit) for significant long term disadvantages (no compiler checking for typos, no IntelliSense). This means that I think static typing is almost always worth the up-front cost. Proponents of dynamic typing would tell you otherwise, but C# is mostly statically typed language, and presumably you're using that for a reason.


问:
What's a good way to manage long piece of code in files?
I am a web developer and at the moment am finding it hard to cope with long un-documented code written by previous developers in an organisation I work for. With the deadline gun always pointed at my forehead, it's doing my head in. I use aptana studio's search feature for some quick wins but it is becoming overwhelming to a point that I do not want to work with them anymore.

Is there any quick/proven approach that I can take to help me with a scenario like this?

答:
To answer your question from an experience point of view there is unfortunately no 'good' or 'easy' or 'quick' way to manage long sections of code.

In our projects we dealt with such legacy code by breaking the larger chunks of code into smaller functions. But this is obviously a time based solution.

We initially applied the basic 'Pirate Rules' of a function should do only one thing and should preferably not have  more than two parameters. Now we are adding that the new functions must also be Unit tested.


问:
How often to release in Scrum sprint
How often to you release during a sprint. Only at the end of the sprint or every time a feature is ready. And how to you handle bugfix releases?</p>

答:
Answering a question that is almost 2 years old may be a bit redundant, but to hopefully add value for others who come to this question i would like to add a 2cent or so. :)

To answer the question: You should preferably release what was committed to in the sprint, at the end of that sprint. Doing so ties in with all the other parts/processes/guidelines of scrum which is geared to getting the best business value out at the right time.

BUT emergencies, bugs, unexpected events etc may force your hand, which is where the concept if "Release Planning" could come in handy. With "Release Planning" I do not mean waterfall-type-planning but rather planning of expectations which could help manage the product backlog and priority of stories in sprints ect.

But perhaps David's comment on the question is something to best consider. Scrum is not always the right answer.

Title: How often to release in Scrum sprint


问:
Where should UI errors be generated and printed from? Log errors?
Function A() calls B() calls C(), which encounters an error. Which function writes to the log and which function reports to the user?

My first inclination is that all functions should write to the log, and that the inner-most UI-facing function should be responsible for outputting the error to the user. However, the fix needs to be done in C(), so perhaps instead of having an super-long log file which will take a while to parse, I should simply have the function which encountered the error log the error and the parameters used to call it.

Likewise, I'm not too convinced that the inner-most UI-facing function should output the error (consider CLI apps, as opposed to web or GUI apps). That was more of a gut-feeling decision, so any insight into actually engineering a solution would be appreciated.

答:
Logging

Let me start with the logging.  Well as I'm sure you're aware, there are various logging levels which most libraries support:  Debug, Info, Warning, and Error.

My approach is that Debug output should show all information that I, the programmer, would want to see.  The user using your program isn't likely going to want to see that you entered a specific method in the GUI, but I would in the case of a crash.  If you have no way of retrieving the stack trace of the crash, then the next best thing is to print out to the log the entry and exit of every method in your program with log level debug.

In your example, that means a log with the following output:

```<code>DEBUG <timestamp>:  ClassA::A() : Entering A
DEBUG <timestamp>:  ClassB::B() : Entering B
DEBUG <timestamp>:  ClassC::C() : Entering C
DEBUG <timestamp>:  ClassC::C() : Exiting C   // These don't show
DEBUG <timestamp>:  ClassB::B() : Exiting B   // in the case of
DEBUG <timestamp>:  ClassA::A() : Exiting A   // an error in C.
</code>```

Log level Info is information that I would consider to be relevant to functionality of the program.  Suppose for the purposes of this example that the objective of A is to perform an operation using a selected database, B is a means to view existing database connections and to create new database connections, and C is the specific information pertaining to a new database and a way of testing said connection.

Relevant Info level log messages for me would be:

```<code>INFO <timestamp>:  ClassC::C() : Saved database connection "localhost".
INFO <timestamp>:  ClassA::A() : Performing transaction using database connection "localhost".
INFO <timestamp>:  ClassA::A() : Transaction complete using database connection "localhost".
</code>```

Notice that these are messages you would also likely want to show to the user throughout the program (albeit a little verbose).  For me that is the difference between Debug and Info:  whether or not the user may also want to see this information.  Obviously logging levels warning and error should also be both logged and shown to the user.

```<code>WARNING <timestamp>:  ClassC::C() : Connection test for "localhost" failed.
</code>```

What I typically do in my programs is take an optional parameter which determines at what logging level I should present messages to the user with a default value of Info.  If the user does not want a verbose interface, he or she can set it to Warning instead and see only warnings and errors, and I can use it in order to output debugging information, for example.  In that case, just be sure to provide an alternative indicator that a particular task is finished (execute button becomes disabled during elaboration then afterwards becomes again enabled, for instance).

Exceptions

That said, how do I approach exceptions?  It depends on the context of the error.  If ClassC handles creation of new database connections and upon testing the connection, throws an exception, I would want to handle that sql exception inside ClassC since I am expecting potential problems.  Notice that I would only handle a sql exception.  If the problem were another that I wasn't expecting, it would slip through Class C and consequently move to ClassB.  ClassB may decide to catch exceptions related to missing drivers, since that is not entirely unexpected, and I wouldn't want such problems to be caught at lower levels.

However, assuming it is not either, we hit ClassA who's only role in calling ClassB was to allow the user the possibility to create new database connections.  If an exception hits ClassA, something serious has happened.  In such instances, what I typically do is to catch any exception, write the error and its stacktrace (if possible) to the log, show an unexpected error message to the user, then rethrow the exception.  In my personal opinion, it is irresponsible to catch all exceptions without being prepared to rethrow it, since it is correct that unexpected errors are still thrown.

The important point to note here is the level of responsibility.  The exceptions that I'm expecting are handled locally while unexpected exceptions in the context of my class are allowed to move up the chain.  In the absolute worst case, be sure to try to log the error and show an error message to the user.  Combine this with precision logging, and you're sure to be able to trace your steps to the place of error in most cases.

Body:
Logging

Let me start with the logging.  Well as I'm sure you're aware, there are various logging levels which most libraries support:  Debug, Info, Warning, and Error.

My approach is that Debug output should show all information that I, the programmer, would want to see.  The user using your program isn't likely going to want to see that you entered a specific method in the GUI, but I would in the case of a crash.  If you have no way of retrieving the stack trace of the crash, then the next best thing is to print out to the log the entry and exit of every method in your program with log level debug.

In your example, that means a log with the following output:

DEBUG <timestamp>:  ClassA::A() : Entering A
DEBUG <timestamp>:  ClassB::B() : Entering B
DEBUG <timestamp>:  ClassC::C() : Entering C
DEBUG <timestamp>:  ClassC::C() : Exiting C   // These don't show
DEBUG <timestamp>:  ClassB::B() : Exiting B   // in the case of
DEBUG <timestamp>:  ClassA::A() : Exiting A   // an error in C.

Log level Info is information that I would consider to be relevant to functionality of the program.  Suppose for the purposes of this example that the objective of A is to perform an operation using a selected database, B is a means to view existing database connections and to create new database connections, and C is the specific information pertaining to a new database and a way of testing said connection.

Relevant Info level log messages for me would be:

INFO <timestamp>:  ClassC::C() : Saved database connection "localhost".
INFO <timestamp>:  ClassA::A() : Performing transaction using database connection "localhost".
INFO <timestamp>:  ClassA::A() : Transaction complete using database connection "localhost".

Notice that these are messages you would also likely want to show to the user throughout the program (albeit a little verbose).  For me that is the difference between Debug and Info:  whether or not the user may also want to see this information.  Obviously logging levels warning and error should also be both logged and shown to the user.

WARNING <timestamp>:  ClassC::C() : Connection test for "localhost" failed.

What I typically do in my programs is take an optional parameter which determines at what logging level I should present messages to the user with a default value of Info.  If the user does not want a verbose interface, he or she can set it to Warning instead and see only warnings and errors, and I can use it in order to output debugging information, for example.  In that case, just be sure to provide an alternative indicator that a particular task is finished (execute button becomes disabled during elaboration then afterwards becomes again enabled, for instance).

Exceptions

That said, how do I approach exceptions?  It depends on the context of the error.  If ClassC handles creation of new database connections and upon testing the connection, throws an exception, I would want to handle that sql exception inside ClassC since I am expecting potential problems.  Notice that I would only handle a sql exception.  If the problem were another that I wasn't expecting, it would slip through Class C and consequently move to ClassB.  ClassB may decide to catch exceptions related to missing drivers, since that is not entirely unexpected, and I wouldn't want such problems to be caught at lower levels.

However, assuming it is not either, we hit ClassA who's only role in calling ClassB was to allow the user the possibility to create new database connections.  If an exception hits ClassA, something serious has happened.  In such instances, what I typically do is to catch any exception, write the error and its stacktrace (if possible) to the log, show an unexpected error message to the user, then rethrow the exception.  In my personal opinion, it is irresponsible to catch all exceptions without being prepared to rethrow it, since it is correct that unexpected errors are still thrown.

The important point to note here is the level of responsibility.  The exceptions that I'm expecting are handled locally while unexpected exceptions in the context of my class are allowed to move up the chain.  In the absolute worst case, be sure to try to log the error and show an error message to the user.  Combine this with precision logging, and you're sure to be able to trace your steps to the place of error in most cases.


问:
What should I do if I don't have any formal spec?
I recently was assigned to a task, but it says only a couple of words, like, do it as it made there, with no actual spec attached. What is the best thing to do in that circumstances?</p>

答: Get the specifications!  If that is not possible, reject the task!  It is your responsibility as a programmer to force the person asking you to do this job to provide you with sufficient information.  This is not only in your best interest but also in the best interest of said person.  Otherwise you risk that your client will be unhappy of the results, and as a consequence, that will make you downright miserable.


答:
As there are two distinct audiences for the error report, with completely different information needs, it makes sense to have the error reporting at multiple levels.

On the one hand, there are the developers who need to know exactly where the error was detected and all the nitty gritty details of the error itself. As the developers are also the ones who analyse the log files, it makes most sense to produce a log for an error as soon as it is detected, where most of the relevant information for the developers is still at hand and can be incorporated in the log.

On the other hand, the end-users of the application don't really care about what went wrong. They just want to know if the function they requested succeeded and if not, what they can do to make it succeed the next time.
This information is at a higher level of abstraction than the usual error-detection code and usually not even known at the level where the error is first detected.

For example, if there is an error when saving a file, the code responsible for writing the data to disk can't know if the save action was triggered automatically or by explicit request from the user, but that is important information when deciding how to inform the end-user of the problem.

In summary, error reports should be generated at the level where the information is at the right abstraction level to provide a meaningful and helpful report to the intended audience of the report.

Additionally, human readable texts meant for end-users should be generated in the UI components of the application to ensure that only the UI is affected if you need to support additional languages for the end users.

Title: Where should UI errors be generated and printed from? Log errors?

Body:
Function A() calls B() calls C(), which encounters an error. Which function writes to the log and which function reports to the user?

My first inclination is that all functions should write to the log, and that the inner-most UI-facing function should be responsible for outputting the error to the user. However, the fix needs to be done in C(), so perhaps instead of having an super-long log file which will take a while to parse, I should simply have the function which encountered the error log the error and the parameters used to call it.

Likewise, I'm not too convinced that the inner-most UI-facing function should output the error (consider CLI apps, as opposed to web or GUI apps). That was more of a gut-feeling decision, so any insight into actually engineering a solution would be appreciated.


答:
It depends on how much your process is flexible.

If your process is agile, you can start prototyping it and get various aspects either approved or clarified along the way. It is what agile process was created for. But it requires that somebody (customer delegate, product manager or such) is available to approve it and that you won't be blamed for delays caused by them changing their mind over and over.

If your process is not agile, responsible person to approve the realization is not readily available or you risk being blamed for delays, you have to insist on getting the specification clarified before you accept the task.

Title: What should I do if I don't have any formal spec?

Body: I recently was assigned to a task, but it says only a couple of words, like, do it as it made there, with no actual spec attached. What is the best thing to do in that circumstances?</p>


问:
Strategy for keeping secret info such as API keys out of source control?
I'm working on a website that will allow users to log in using OAuth credentials from the likes of Twitter, Google, etc.  To do this, I have to register with these various providers and get a super-secret API key that I have to protect with pledges against various body parts.  If my key gets ganked, the part gets yanked.

The API key has to travel with my source, as it is used at runtime to perform authentication requests.  In my case, the key must exist within the application in a configuration file or within the code itself.  That isn't a problem when I build and publish from a single machine.  However, when we throw source control into the mix, things get more complicated.

As I'm a cheap bastard, I'd much prefer to use free source control services such as TFS in the cloud or GitHub.  This leaves me with a slight conundrum:

How can I keep my body intact when my API keys are in my code, and my code is available in a public repository?

I can think of a number of ways to handle this, but none of them are that satisfying.

I could remove all private info from code, and edit it back in after deployment.  This would be a severe pain to implement (I won't detail the many ways), and isn't an option.

I could encrypt it.  But as I have to decrypt it, anyone with the source could figure out how to do so.  Pointless.

I could pay for private source control.  LOL j/k spend money?  Please.

I could use language features to segregate sensitive info from the rest of my source and therefore keep it from source control.  This is what I'm doing now, but it could easily be screwed up by mistakenly checking in the secret file.

I'm really looking for a guaranteed way to ensure I don't share my privates with the world (except on snapchat) that will work smoothly through development, debugging and deployment and be foolproof as well.  This is completely unrealistic.  So what realistically can I do?

Technical details:  VS2012, C# 4.5, source control is either going to be TF service or GitHub.  Currently using a partial class to split the sensitive keys off in a separate .cs file that won't be added to source control.  I think GitHub may have the advantage as .gitignore could be used to ensure that partial class file isn't checked in, but I've screwed that up before.  Am hoping for a "oh, common issue, this is how you do it" but I may have to settle for "that doesn't suck as much as it could have", :/

答:
Use encryption, but provide a master key at startup, as a password at the console, in a file only the process's user can read, or from a system-provided key store like Mac OS keychain or Windows key store.

For continuous delivery, you'll want various keys recorded somewhere. Configuration should be demarcated from code, but it makes a lot of sense to keep it under revision control.


答:
Your situation is quite common and when I was developing things for non-technical clients it happened to me all the time.

When those people hire you they most often don't know what they really want. They just know they want "something like that" or "something that can help me with this".

Part of a job of a competent software developer is to help those people make up their mind. That means that maybe you should think about the project and come with some specs yourself. Then you can finalize them with the other side. The specs are essential because with them you can clearly say if you completed the task or not.


问:
Why does DirectX use a left-handed coordinate system?
I considered posting on Stack Overflow, but the question strikes me as being far too subjective since I can't think of a reasonable technical explanation for Microsoft's choice in this matter. But this question has bugged me for so long and the issue keeps coming up in one of my projects, and I have never actually seen an attempt at explaining this:

OpenGL uses a right-handed coordinate system, where the +Z part of the world coordinate system extends toward the viewer.

DirectX uses a left-handed system where the +Z part of the world coordinate extends into the screen, away from the viewer.

I never used the Glide API, so I don't know how it worked, but from what I can gather, it uses a left-handed system as well.

Is there a technical reason for this? And if not, is there some conceptual advantage to a particular handedness of a coordinate system? Why would one choose one over the other?

答:
The lead developer of DirectX (and Direct3D) Alex St. John recently commented on that. In an article on the history of Direct3D he wrote:

I [...] was asked to choose a handedness for the Direct3D API.  I chose a left handed coordinate system, in part out of personal preference.  [...] it was an arbitrary choice.

Source:
http://www.alexstjohn.com/WP/2013/07/22/the-evolution-of-direct3d/


问:
TDD / one test representing the whole scenario ? or should I split it?
While practicing TDD, I came across this specification:

A user should be created with its password hashed, be persisted and an activation token should be returned.

Should my first unit test, (aiming to begin to test this scenario) should encompass the whole needs? :

```<code>shouldPersistTheNewlyCreatedUserWithAHasedPasswordAndReturnACorrespondingActivationToken
</code>```

Or rather, splitting its main parts into several smaller tests, and testing incrementally:

```<code>shouldCreateAUser
shouldReturnAUserActivationToken
shouldReturnAnActivationTokenBasedOnNewlyCreatedUserEmail
shouldPersistTheNewlyCreatedUser
shouldHashTheUserPersistBeforePersistingIt
</code>```

To put in a nutshell, should I rework the same test until a whole scenario passes? Or should I proceed incrementally by specifying additional features in other small tests.

IMHO, the benefit of the first solution is that the spec is defining in one place, no need to gather some chuncks of features to figure out the whole.
On the other hand, the number of assertions and expectations might be huge, therefore the test code would be less readable.

答:
tl;dr: Second option. You should split into several smaller tests, as that is what you're supposed to do with TDD (Red-Green-Refactor).

You start writing the simplest tests first to start out with the simplest implementation and build your way up towards a full scenario. The semantics with unit tests is totally different with scenario/functional/acceptance testing. Developers tend to confuse them all as the same but they're semantically different and fill different purposes.

TDD is built on the concept where a test has the granularity of a unit. Usually this unit is down to a method in a class. The whole point with TDD is to design code to be testable. If you start with a whole scenario as a unit and not the actual methods themselves you'll end up with code that may be doing too much.

There are different ways to go about with your scenario. I would roughly start by trying the following:

First write a UserService that can create a new user with a single test createUserShouldReturnUser.

Then write a IActivationTokenFactory interface that creates activation tokens. On UserService I'd continue with a test that uses the token factory as a mock object. The test is createUserShouldRequestActivationToken that requests any activation token from the mock object and puts it on the user object that is returned.

I proceed to write a concrete ActivationTokenFactory that implements IActivationTokenFactory. The test is to make sure it produces "legit" tokens.

and so on... I can imagine some kind of HashFactory object and some kind of persistance layer would be created as well.

Rinse, repeat until I have a full scenario and refactor along the way. I'd write the scenario test by now that exercises all the code, and make sure I have some unhappy paths to test as well (with failed persistance exceptions and whatnot).

It's easier to implement something if you divide and conquer... which is what you're supposed to do with TDD. Once you hit a snag, it's good to have these tiny unit tests for regressions if you decide to refactor something.


问:
What is the (craziest, stupidest, silliest) thing a client/boss asked you to do?
See title, but I am asking from a technical perspective, not

Take my 40 year old virgin niece on a date or you're fired.

答:
The stupidest thing I've been asked to do is probably a ground up rewrite of a very large project. It was about 350k lines, all C (with a little perl mixed in for 'helper' scripts) and worked well no matter what clients did to it.

Almost a year later, we had:

Lots of functions that basically did the same thing as the old functions

No real improvements in speed or functionality

A slightly smaller memory footprint

A much larger executable

Annoyed clients

Basically, we accomplished nothing that sensible refactoring could not have accomplished. But my boss was happy, we got rid of the helper scripts.

I consider it to be the most egregious waste of time and existing code that I've ever seen.


问:
What popular "best practices" are not always best, and why?
"Best practices" are everywhere in our industry.  A Google search on "coding best practices" turns up nearly 1.5 million results.  The idea seems to bring comfort to many; just follow the instructions, and everything will turn out fine.

When I read about a best practice - for example, I just read through several in Clean Code recently - I get nervous.  Does this mean that I should always use this practice?  Are there conditions attached?  Are there situations where it might not be a good practice?  How can I know for sure until I've learned more about the problem?

Several of the practices mentioned in Clean Code did not sit right with me, but I'm honestly not sure if that's because they're potentially bad, or if that's just my personal bias talking.  I do know that many prominent people in the tech industry seem to think that there are no best practices, so at least my nagging doubts place me in good company.

The number of best practices I've read about are simply too numerous to list here or ask individual questions about, so I would like to phrase this as a general question:

Which coding practices that are popularly labeled as "best practices" can be sub-optimal or even harmful under certain circumstances?  What are those circumstances and why do they make the practice a poor one?

I would prefer to hear about specific examples and experiences.

答:
Only one I can think of is formatting Java if statements like this:

```<code>if (condition) ...
</code>```

instead of

```<code>if(condition) ...
</code>```

For the most part, I've found best practices to be best, and any initial reservations I have with them tend to be misplaced, or overridden by more significant concerns.

Body:
Only one I can think of is formatting Java if statements like this:

if (condition) ...

instead of

if(condition) ...

For the most part, I've found best practices to be best, and any initial reservations I have with them tend to be misplaced, or overridden by more significant concerns.


问:
The best possible way to implement Business Rules in PHP
I'm planning to write an e-commerce app using PHP & MySQL with lots & lots of custom rules. Say for example, I want to have a rule like "Give Customer X, a 10% a discount  for Product Y if he bundles it with Product Z"

I've heard about Business rules engine(in Java and others). I intend to implement a flexible business rules functionality without hard-coding anything into PHP and with a good, solid architecture with the goal of maintainability and re-usability with the help of PHP OOPS.

Please advice me on the following aspects:

Does decision table fit my intended purpose?

How can I change rule/business logic of the PHP application without redeploying/re-writing?

答:
No matter whether you write the rules in PHP, JavaScript or some other, possibly domain-specific language. If the requirements are sufficiently complex (yours seem to be), they will require something with expressiveness of programming language and will require programming skill to update. Forget business people updating them, they don't have the necessary skill.

Now if programmer has to be around to update the rules, they are best written in existing language for which you can easily get somebody who understands it. For example PHP.

Now to the point of hard coding. PHP is not a compiled language. It is not even precompiled. The interpreter actually reparses it on each request. So when you change the file with business rules definition, it will immediately take effect. You want to version that file separately from the core of the application or you may even store it in the database, but PHP is probably simplest to implement, quite simple to maintain and also fastest as any rule interpreter written in PHP is going to add noticeable overhead.

You may want to use some sandbox (quick google reveals at least two implementations for PHP) to ensure that the business rules file can't touch anything outside the transaction object. This can be added anytime later, you can start without bothering about it. You may also later add some graphical language that will generate PHP into the database or something, but it's been repeatedly shown in practice that it takes a programmer to edit nevertheless, so it's effort with questionable return (though it might be a selling point).

(Edit) As I looked at decision tables, they don't seem to be very flexible. They need a column for every possible criterion, so as the rules grow in complexity, the table will need more and more columns and it won't be easy to understand any more anyway.

Also don't forget that an e-commerce package does not live in void, but needs to be integrated with various other systems. Most shops will probably already have a accounting system where they need to export data about finished transactions and store management system where they need to export data about goods to ship or in case of software shops accounts to create and licenses to assign, they will be using different payment processor to which you have to redirect and receive payment confirmation, etc. For these the logic will be different, so simple rules won't cut it. You absolutely need to support writing this in PHP, independent from the main core just like the business rules you mentioned.


问:
What should a proper Ready for Sprint definition contain?
Teams in our company deal with Product Owners who are in such a position that they cannot spend as much time with us, as we would like, to do proper Backlog Grooming.

Thus in order to alleviate some of the time constraints we have begun implementing the art of getting stories "Ready for Sprint" or in other words getting them into a state where we know/understand enough to take them into a sprint.

Unfortunately we are still new to what would be a proper definition of 'Ready For Sprint' and so the question of what would be good to keep in mind when getting a story in the backlog Ready for Sprint?

[EDIT]

In response to answers and comments by Ryathal and Donal Fellows i would like to try explain that we do not intend to actually build the stories. We would like to apply the practice of getting existing stories "Ready for Sprint" as explained by this Blog Post. Product owners should probably be adding to this but as mentioned we are not in a prime position with our product owners (as yet).

We have read that you can make definitions such as a story is in Ready state if its effort points are 5 or less, or the story must have Minimum Acceptance Criteria defined, or it must have a Balsamiq Mockup etc.

My question is geared towards finding what others have used in their definitions and what has worked for them. :)

答:
A story is "ready for sprint" when:

it contains verifiable requirements and

you believe it matches what the client wants.

You should also try working with your owner to increase the time they can devote to working with you, and find ways that they can do some backlog grooming on their own if they can't already. The best way to get more involvement is going to be delivering quality with your current level of interaction and explain that further involvement can further improve results.


问:
Is PHP "list()" language construct a bad convention?
PHP supports the list() language construct which, in short, allows you to return multiple values from a function and then attach them to different variable, eg:

```<code>function myBigReturn(){
    return array("foo", "bar");
}
list($fooer, $barer) = myBigReturn();
echo $fooer; // echoes "foo"
echo $barer; // echoes "bar"
</code>```

I have failed to find much info about such a language construct and I am curious - is usage of PHP list() construct considered a bad coding convention? Are there any serious articles/literature on this subject?

答:
I dare say it is almost pythonic. There is a similar construct in Python and very useful for automatically splitting out the return values.

The place I have seen it the most is when a function returns a point, which has an x/y, latitude/longitude, or azimuth and range value. At times a function can return a object with defined fields, but sometimes the automatic splitting is just what is needed.

As Rath points out there is no real speed difference.

It is generally not used when the number of items in the array is more than a handful, or if there is not a fixed number of items being returned.


答:
Well, your question seems a little bit vague to me because you really didn't mention what you need to know and what you get from the client, however, I always try to be realistic and think like the client in these situations.

Let say you have money and you want to order a sport car, or a big house or the nicest leather jacket in the planet or whatever else you think it's nice to buy. The question is, when you're ordering something that you're not expert in that field, can you specify the materials, specifications, etc. or not? For example, if you have to choose the gate for your big house, will you specify where they have to place the lock and the keyhole size or you just simply leave it up to them and you will choose the shape of the gate and its color? Again, if you're not an engineer, can you specify all the characteristics and specifications of the car you're gonna order or not?

Simply you can't specify them because you don't have any idea what they are and how they should be. As a client/buyer, you just need to draw the outlines of the final product and it's their job to make it work in a way that fits your needs.

Imagine if you feel your client needs some level of extra security for their web application, or if they mention that clearly, then it is your job to offer them to use SSL. You don't need to make them understand what is SSL, how it works and why it's necessary for them. You have to tell them what is the added benefit of using that thing (in this case SSL), the extra effort needed to implement it and its price, and then it will take up 30 seconds for them to make up their mind and decide whether they want it or not.

However, I agree that in some working situations you might probably receive vague tasks, mostly from your supervisor or the project manager. The only thing I can recommend in these situations is:

First, make them clearly understand that they didn't provide sufficient information (make it official, send them email so you can referrer to that in the future).

Second, ask for the information you need in a nice way, let them knows that you will work better if they give you the proper information or at least as much as they have/know (make it clear that it's for their benefit, not because you are lazy or unexperienced).

If the information is not provided or it's not sufficient in the end, try to do it as normal and as usual as possible. Try to understand them and their needs. If you didn't specify your preferences on the light colors for your new house, you probably want warm or pure white (something usual) not anything red-ish/blue-ish.


答:
If your employer/supervisor/client didn't give you a specification, you will have to write one yourself and get them to sign off on it.

For every project, there are three things you need to know:

What is the problem you are trying to solve?

What are the deliverables?

How will you know when you are finished?

Until and unless you have the answers to these three questions, WRITTEN DOWN AND SIGNED OFF, you are not ready to start doing ANYTHING but getting the answers to these three questions, written down and signed off.

The answers to these three questions form the core of your spec and your statement-of-work.


问:
How to tackle a 'branched' arrow head anti-pattern?
I recently read this question that features, the arrow anti-pattern.

I have something similar in code I'm trying to refactor except that it branches. It looks a little something like this:

```<code>if(fooSuccess==true&&barSuccess!=true){
    if(mooSuccess==true){
           .....
    }else if (mooSuccess!=true){
           .....
    }
}else if(fooSuccess!=true&&barSuccess==true){
    if(mooSuccess==true){
           .....
    }else if (mooSuccess!=true){
        if(cowSuccess==true){
                    .....
        }else if (cowSuccess!=true){
                    .....
        }
    }
}
......
</code>```

In short it looks like this

```<code>if
   if
     if
       if
         do something
       endif
    else if
     if
       if
         do something
        endif
    endif
    else if
     if
       if
         do something
        endif
    endif
 endif
</code>```

Outline borrowed from Coding Horror article on the subject

And the code goes on through different permutations of true and false for various flags. These flags are set somewhere 'up' in the code elsewhere, either by user input or by the result of some method.

How can I make this kind of code more readable? My intention is that eventually I will have a Bean-type object that contains all the choices the previous programmer tried to capture with this branching anti-pattern. For instance, if in the outline of the code above we really do only have three, I have an enum set inside that bean:

```<code>enum ProgramRouteEnum{
    OPTION_ONE,OPTION_TWO,OPTION_THREE;

    boolean choice;
    void setChoice(boolean myChoice){
        choice = myChoice;
    }
    boolean getChoice(){
        return choice;
    }
}
</code>```

Is this an acceptable cure? Or is there a better one?

答:
I'm not sure your example is a particularly good one for this question, but it's possible to condense it to be much simpler and still preserve the same logic:

```<code>if(fooSuccess && !barSuccess)
{
    if(mooSuccess)
    {
        // .....
    }
    else
    {
        // .....
    }
}
else if (!fooSuccess && barSuccess)
{
    if(mooSuccess)
    {
        // .....
    }
    else if(cowSuccess)
    {
        // .....
    }
    else
    {
        // .....
    }
}
</code>```

Notice how there's no more than one level deep of ifs.  To clean this up, I took the following steps:

Never check whether a boolean value is == true, != true, or != false.  Occasionally I've found it worth checking whether it == false to make it more apparent that that's the expected case, but even that should be exceptional.

If your else block consists of nothing but an if/else block, then you can merge it with the parent else.

If your if statement only has one input/variable, you don't need to check the inverse for the else.

Body:
I'm not sure your example is a particularly good one for this question, but it's possible to condense it to be much simpler and still preserve the same logic:

if(fooSuccess && !barSuccess)
{
    if(mooSuccess)
    {
        // .....
    }
    else
    {
        // .....
    }
}
else if (!fooSuccess && barSuccess)
{
    if(mooSuccess)
    {
        // .....
    }
    else if(cowSuccess)
    {
        // .....
    }
    else
    {
        // .....
    }
}

Notice how there's no more than one level deep of ifs.  To clean this up, I took the following steps:

Never check whether a boolean value is == true, != true, or != false.  Occasionally I've found it worth checking whether it == false to make it more apparent that that's the expected case, but even that should be exceptional.

If your else block consists of nothing but an if/else block, then you can merge it with the parent else.

If your if statement only has one input/variable, you don't need to check the inverse for the else.


答:
The code can be simplified like this:

```<code>boolean condA = ( fooSuccess  && !barSuccess &&  mooSuccess )
boolean condB = ( fooSuccess  && !barSuccess && !mooSuccess )
boolean condC = (!fooSuccess  &&  barSuccess &&  mooSuccess )
boolean condD = (!fooSuccess  &&  barSuccess && !mooSuccess &&  cowSuccess)
boolean condE = (!fooSuccess  &&  barSuccess && !mooSuccess && !cowSuccess)

if (condA) {
    ....
    return;
}
if (condB) {
    ....
    return;
}

... and so son

if (condE) {
    ....
    return;
}
</code>```

In essence:

Evaluate complex conditions into a single boolean

Since conditions are exclusive (as it's typically the case in nested arrow heads) you don't have to nest the ifs, just add a return so that no other block is run.

This reduces the cyclomatic complexity enormously and makes the code trivial.

Having what exactly gets run in every case, you can even do a Karnaugh table to identify and remove redundant condition combinations, just as they do in logic circuits design. But you didn't provide that in the example.

Be sure to extract all this logic into its own method so the return statements don't interfere with blocks that have to be run anymay.

Descriptive names should be chosen for conA..condF.

Title: How to tackle a 'branched' arrow head anti-pattern?

Body:
I recently read this question that features, the arrow anti-pattern.

I have something similar in code I'm trying to refactor except that it branches. It looks a little something like this:

```<code>if(fooSuccess==true&&barSuccess!=true){
    if(mooSuccess==true){
           .....
    }else if (mooSuccess!=true){
           .....
    }
}else if(fooSuccess!=true&&barSuccess==true){
    if(mooSuccess==true){
           .....
    }else if (mooSuccess!=true){
        if(cowSuccess==true){
                    .....
        }else if (cowSuccess!=true){
                    .....
        }
    }
}
......
</code>```

In short it looks like this

```<code>if
   if
     if
       if
         do something
       endif
    else if
     if
       if
         do something
        endif
    endif
    else if
     if
       if
         do something
        endif
    endif
 endif
</code>```

Outline borrowed from Coding Horror article on the subject

And the code goes on through different permutations of true and false for various flags. These flags are set somewhere 'up' in the code elsewhere, either by user input or by the result of some method.

How can I make this kind of code more readable? My intention is that eventually I will have a Bean-type object that contains all the choices the previous programmer tried to capture with this branching anti-pattern. For instance, if in the outline of the code above we really do only have three, I have an enum set inside that bean:

```<code>enum ProgramRouteEnum{
    OPTION_ONE,OPTION_TWO,OPTION_THREE;

    boolean choice;
    void setChoice(boolean myChoice){
        choice = myChoice;
    }
    boolean getChoice(){
        return choice;
    }
}
</code>```

Is this an acceptable cure? Or is there a better one?

Body:
The code can be simplified like this:

boolean condA = ( fooSuccess  && !barSuccess &&  mooSuccess )
boolean condB = ( fooSuccess  && !barSuccess && !mooSuccess )
boolean condC = (!fooSuccess  &&  barSuccess &&  mooSuccess )
boolean condD = (!fooSuccess  &&  barSuccess && !mooSuccess &&  cowSuccess)
boolean condE = (!fooSuccess  &&  barSuccess && !mooSuccess && !cowSuccess)

if (condA) {
    ....
    return;
}
if (condB) {
    ....
    return;
}

... and so son

if (condE) {
    ....
    return;
}

In essence:

Evaluate complex conditions into a single boolean

Since conditions are exclusive (as it's typically the case in nested arrow heads) you don't have to nest the ifs, just add a return so that no other block is run.

This reduces the cyclomatic complexity enormously and makes the code trivial.

Having what exactly gets run in every case, you can even do a Karnaugh table to identify and remove redundant condition combinations, just as they do in logic circuits design. But you didn't provide that in the example.

Be sure to extract all this logic into its own method so the return statements don't interfere with blocks that have to be run anymay.

Descriptive names should be chosen for conA..condF.


问:
Where is it appropriate to do input validation in Erlang?
I'm writing a module that runs a finite state machine* based on the contents of an array of records passed in at initialization.  Each record describes a state and includes instructions on how to act on inputs (i.e., when in state S1, input I triggers a transition to state S2).  For the FSM to work correctly, the transitioned-to states need to exist.

My quandary is where to validate those transitions.

The defensive programmer in me says to do it once as early as possible, such as when the FSM is initialized.  This means I can raise an error when I'm first handed bogus data and avoid handing back a process that may fail later as a result.  The rest of the implementation won't have to be as defensive because the table is known to be good and any errors that Erlang decides to raise will be a result of implementation rather than having being fed bad data.  It will also make debugging easier for those using the module since they'll get a badarg or something else back immediately instead of having to paw through my sources later to figure out that it was their mistake and not mine.

The Erlang philosophy seems to be that things should be left to run as long as possible, failing only when they have to and letting a supervisor take care of picking up the pieces.  On one hand, this makes sense because a given FSM could run forever without encountering the inputs it would take for a bad transition.  On the other, failing late puts the onus on the callers to write repetitive  tests for something that's easy for me implement once.

I know that most rules in this business aren't hard and fast, but is one approach more "Erlangy" than the other?  Would a fail-early implementation appear out of place if released for others to use?

*I am aware of the gen_fsm behaviour and that what I'm doing has some comparative shortcomings.  This is a learning exercise for some other things, and a FSM happens to be something that incorporates them.

答:
The reason it seems less "Erlangy" to do onerous type checking is because the language is dynamically typed.

If you really need to ensure that data of a certain type is used, you can use the is_TYPE/1 functions to verify your input as guard expressions. You should do this as early as you are able.

http://learnyousomeerlang.com/types-or-lack-thereof


问:
Is a "start", "run" or "execute" method a good practice?
I'm currently working on a code base that has many classes that implement a Start method.
This seems like two-phase construction to me, which I had always considered a bad practice.  I can't tell the difference between this and a constructor.

When is it appropriate to use a start method instead of normal object construction?

When should I prefer to use the constructor?

Edit:
I don't think it is that relevant but the programming language is C#, it could equally apply to Java or C++

答:
A Start() method (like Run(), Execute() or anything similar) is appropriate when the cost of constructing the object is low, but the cost of using it is high.  For example: A class which encapsulates a best-path-optimization algorithm.  It's trivial to set it up with a set of parameters (X squares by Y squares, with suchandsuch evaluation method), but it may take a while to execute.  If you want to create 20 of these objects, you may want to delay execution until all of them have been created - this lets you parallelize them easier, for example.

Alternatively, it could be useful when you don't know when the object is going to be needed to start - perhaps because it's based on user input, or logic which selects from a list of possibilities.

This assumes, of course, that Start() is the useful method on the object, and not an equivalent to an Initialize() method.  If it is just an extra way to set more parameters, it shouldn't exist.


问:
Defining a standard
How would you go about defining a standard? I am defining a protocol for a sort of thing that does not exist yet and I would like to create an RFC for it, and use a well-known port number provided by IANA. How do I start?</p>

答:
If all you need is the port number you can contact the IANA using the form provided on http://www.iana.org/form/ports-services to request a port being assigned to you.

You probably should do that early to prevent having to change the port later on.

For actually writing an RFC see Tom Morgan's answer.

Title: Defining a standard


答:
Code Complete (and many other software engineering resources) emphasizes matching your classes to real world objects. I believe the fundamental reason for this is that it makes it more likely that you have a true grasp of what it is that you're implementing, rather than hacking away at an intangible idea.

If you're a subscriber to this theory, I don't see anything wrong with adding a Start() method to any class that should, were it a real object, also have a resting state. If it doesn't make any sense for your object to exist while not running (or doesn't make any sense for your object to be running at all), then I would say it is bad practice.

Title: Is a "start", "run" or "execute" method a good practice?

Body:
I'm currently working on a code base that has many classes that implement a Start method.
This seems like two-phase construction to me, which I had always considered a bad practice.  I can't tell the difference between this and a constructor.

When is it appropriate to use a start method instead of normal object construction?

When should I prefer to use the constructor?

Edit:
I don't think it is that relevant but the programming language is C#, it could equally apply to Java or C++


答:
You may use lazy initialization.

In computer programming, lazy initialization is the tactic of delaying
  the creation of an object, the calculation of a value, or some other
  expensive process until the first time it is needed.

That way you avoid temporal-coupling, meaning the consumer of your class has to call certain methods in certain order. Having to call start() first is a way of having to know how the class works internally, which is bad because you may change that in the future.

Delay the expensive initialization until it's first needed..

Example:

```<code>public class FooClass{

    private ExpensiveResource resource;
    private CheapResource cheap;

    public  FooClass(String someParameter){
        // constructor: initialize CheapResource cheap
            // but NOT ExpensiveResource resource
    }

    public ExpensiveResource getExpensiveResource(){
        if (resource == null) {
            this.initializeExpensiveResource();
        }
        return this.resource
    }

    public String getExpensiveResourceName(){
        if (resource == null) {
            this.initializeExpensiveResource();
        }
        return this.resource.getName();
    }

    public CheapResource getCheapResource(){
        return this.cheap;
    }

    private initializeExpensiveResource(){
        // do expensive initialization of field "resource"
    }

}
</code>```

```<code>public class Test{
    public static void main (String args[]){

        FooClass foo = new FooClass("some string");
        CheapResource cr = foo.getCheapResource();
        String s = foo.getExpensiveResourceName();
          // just now is the expensive resource initialized

    }
}
</code>```

Body:
You may use lazy initialization.

In computer programming, lazy initialization is the tactic of delaying
  the creation of an object, the calculation of a value, or some other
  expensive process until the first time it is needed.

That way you avoid temporal-coupling, meaning the consumer of your class has to call certain methods in certain order. Having to call start() first is a way of having to know how the class works internally, which is bad because you may change that in the future.

Delay the expensive initialization until it's first needed..

Example:

public class FooClass{

    private ExpensiveResource resource;
    private CheapResource cheap;

    public  FooClass(String someParameter){
        // constructor: initialize CheapResource cheap
            // but NOT ExpensiveResource resource
    }

    public ExpensiveResource getExpensiveResource(){
        if (resource == null) {
            this.initializeExpensiveResource();
        }
        return this.resource
    }

    public String getExpensiveResourceName(){
        if (resource == null) {
            this.initializeExpensiveResource();
        }
        return this.resource.getName();
    }

    public CheapResource getCheapResource(){
        return this.cheap;
    }

    private initializeExpensiveResource(){
        // do expensive initialization of field "resource"
    }

}

public class Test{
    public static void main (String args[]){

        FooClass foo = new FooClass("some string");
        CheapResource cr = foo.getCheapResource();
        String s = foo.getExpensiveResourceName();
          // just now is the expensive resource initialized

    }
}


答:
It should contain enough information that, at the end of the sprint, acceptance is not going to be a problem.

Sometimes a single sentence is good enough.

Quite often, some team members will want more information/requirements written down to make sure nobody changes their mind and remembers all that was agreed on.

Anything written down should be as objective/verifiable as possible. I like the 'given/when/then' and 'as ... i ... so that ...' formats quite a lot, as they convey a lot of information and verifiable requirements in a compact form.

I have seen a couple of attempts at defining 'rules' or gates for the different stages in a story lifecycle (ready for sprint, accepted...) - and in my experience rules alone don't work well. It's very easy to end up having an overly exhaustive list of things a story must contain to be considered (use case, tests plan, mock ups, acceptance criteria, documentation, etc). It's very hard to ensure that those items are 'good'. And in many cases (simple stories with a lot of shared context or unsurprising content), mocks, tests plans and details are a waste of time.

An recent example: encouraging 'as X I want to Y', I ended up with 'As an admin, I expect data confidentiality and integrity to be maintained in the platform.' It meets the guidelines, but is completely useless at telling dev what they need to deliver/test/document.

I don't think you can get away from having good communication between PO and dev, and a good feeling about what each side is going to think is good enough.

Title: What should a proper Ready for Sprint definition contain?

Body:
Teams in our company deal with Product Owners who are in such a position that they cannot spend as much time with us, as we would like, to do proper Backlog Grooming.

Thus in order to alleviate some of the time constraints we have begun implementing the art of getting stories "Ready for Sprint" or in other words getting them into a state where we know/understand enough to take them into a sprint.

Unfortunately we are still new to what would be a proper definition of 'Ready For Sprint' and so the question of what would be good to keep in mind when getting a story in the backlog Ready for Sprint?

[EDIT]

In response to answers and comments by Ryathal and Donal Fellows i would like to try explain that we do not intend to actually build the stories. We would like to apply the practice of getting existing stories "Ready for Sprint" as explained by this Blog Post. Product owners should probably be adding to this but as mentioned we are not in a prime position with our product owners (as yet).

We have read that you can make definitions such as a story is in Ready state if its effort points are 5 or less, or the story must have Minimum Acceptance Criteria defined, or it must have a Balsamiq Mockup etc.

My question is geared towards finding what others have used in their definitions and what has worked for them. :)