答:
System acceptance should be against the customer's requirements. You are correct that analysis and derivation is performed against the customer's initial set of requirements. Often, customer requirements aren't enough to design and implement against, so it's necessary to elaborate on the needs of the customer, refine their requirements, and produce technical system requirements that is suitable for engineers to work against. In some cases, it may even be necessary to add requirements due to regulations or to meet business objectives. All of these refinements and derivations should be validated with the customer to ensure that everyone understands what must be done and what the end products will be or do.

The derived requirements should be traceable to some higher level requirement, either a customer requirement, a regulation, or a business objective. This will ensure that your design and implementation fulfills known requirements. Ensuring that each customer requirement is identified at a system/technical requirements level also helps to avoid missing requirements in design and implementation activities.

Title: Tender vs. Requirements vs. Solution Design

Body:
Conventionally, which of the above documents is deemed to hold the most weight when it comes to system acceptance?

I recently had a conversation along these lines:

It was argued that the initial requirements / tender documentation should be used to determine system acceptance. It was said that the solution design only serves to describe the way in which the system will solve the problem, not the problem it will solve. Furthermore, it was argued that if requirements are missed during solution design, the requirements should be referenced during system acceptance and that if any requirements were missed then the original tender should be referenced.

Conversely, I suggested that - while requirements may be based on the original tender - they supersede it once agreed with the stakeholders. Furthermore, during solution design, analysis is performed to address and refine these initial requirements, translating them into a system capable of meeting the actual requirements. Once signed off by the relevant users, this solution design should absolutely represent the requirements (by virtue of the fact that it's designed upon them) but actually supersedes them as the basis for system acceptance.

Is one of the above arguments more valid than the other?

EDIT: Apologies for the ambiguous terms. In this situation, tender is the document the customer took to market when shopping for a provider - it includes details of all the high-level features they're looking for. Solution design is not a technical document, it's the functional specification.


问:
Found a better solution to a problem at work - should I deter from posting the code snippet online?
I think most of us, programmers, used Stack Overflow to solve every day problems: looked for an efficient algorithm to do something.

Now imagine a situation: you have a problem to solve. Googled a bit, found a StackOverflow question but you are not really satisfied with the answers so far. So you have to do your own research: you need to do it because you want it in the company's app.

Eventually after some hours you have found the better solution. You're happy, you added it to the company's code base, then you want to submit your answer with a code snippet (just several lines) to the question you've found before to help others too.

But wait: the company's software is closed source, and you worked on it on the clock.

So does this mean I shouldn't post the answer neither at work nor at home to that question in the rest of my life, because I solved it at work, and the company owns that piece of code?

答:
I've posted code snippets online but I always edit the code so as to remove any references to the company, any customer data and often I rename fields/variables too. I basically end up re-writing the code so it can't be traced back to an employer. It takes a bit of extra effort but I think it's worth it.

Aside from the legal aspect you also have to think that you've been trusted with your employers property. If you freely post bits of it online then it looks like you lack discretion and can't be trusted. Even if you had permission a future employer finding your snippet from a search engine may not know this.

This is why I would tend to err on the side of caution.

ContentLicense: CC BY-SA 3.0


问:
Requirement refinement between two levels of specification
I am currently working on the definition of the documentation architecture of a system, from customers needs to software/hardware requirements.
I encounter a big problem with the level of refinement of requirements.

The classic architecture is : PTS --> SSS --> SSDD --> SRS/HRS
with PTS : Purshaser Technical Specification
SSS : Supplier System Specification
SSDD : System Segment Design Description
SRS / HRS : Software / Hardware Requirement Specification.

Requirements from PTS are reworked in SSS, this document only expressed the needs (no design requirements are defined at this level). Then, the system design is described in SSDD : we allocate requirements from the SSS to functions from the design and functions are then allocated to component (Software or hardware) (we are still at the SSDD level). Finally, for each component, we write one SRS or one HRS. Requirements in SRS or HRS are refinement of requirements from SSS (and traceability matrix are made between these two levels).

My problem is the following one :

Our system is a complex one, and some of the requirements in the SSS needs to be refined twice to be at the right level in the SRS (means that software people can understand the requirement to make their coding). But, with this document architecture, I can only refine once the requirements from the SSS. The second problem is that only a part of the requirements from the SSS needs to be refined twice. The other part only need one refinement.

On the picture below, the green boxes are requirements at the right level for SRS or HRS. And purple boxes are intermediate requirements which can not be included in SSS since they are design requirements. Where can I put these purple requirements ??

Is there someone who has already encountered this problem ? Should I write two documents at SRS level ? Should I include intermediate requirements in SSDD ? Should I includes the two refinement levels (purple and green) in the same SRS document (not sure that's possible since a SRS is only for one component) ???

Thanks for your help and expertise ;-)

答:
Since the question is vague I'll answer 2 ways.

1) Assuming that your system only has 1 configuration item, which is why that document appears to be missing in your above description then you are merely mapping SSS Requirements to Hardware and Software Documents. In which case, there are no "Purple" requirements. The people writing the SRS/HRS are responsible for turning the SSS Requirement (possibly using the SSDD and any DIDs as a reference, which might be where your "purple" requirements come from) and turning those SSS and derived requirements into the appropriate SRS/HRS requirement.

2) If your system has multiple Configuration Items then the SSS Requirements are mapped to the "Configuration Item" Performance Specification Document. This document is where your "Purple" Requirements would go along with module specific reinterpretations of the SSS Requirements mapped to it (again possibly using the SSDD/DIDs as reference). Then that document is used to map down to the hardware and software which are then used to create a separate SRS/HRS.  I suspect this is what you are trying to do.


问:
Using MS-PL licensed library for internal company use
I want to use a MS-PL licensed library in a proprietary software, but it'll run inside my company, with no external distribution.

Does the license allows this kind of usage or it constitutes a violation of the license?

答:
From MS-PL:

Definitions

The terms "reproduce," "reproduction," "derivative works," and "distribution" have the same meaning here as under U.S. copyright law.

This then directly goes to the copyright law.  From bitlaw:

The distribution right grants to the copyright holder the exclusive right to make a work available to the public by sale, rental, lease, or lending.

Or the more wordy text Title 17 USC § 106 (3)

Subject to sections 107 through 122, the owner of copyright under this title has the exclusive rights to do and to authorize any of the following:

...

(3) to distribute copies or phono records of the copyrighted work to the public by sale or other transfer of ownership, or by rental, lease, or lending;

Again, note the 'to the public' in there.

As described in the original poster's question:

but it'll run inside my company, with no external distribution.

This is not to the public and does not constitute distribution of the work.

That said, I am not a lawyer, and thus if you have specific issue with this you had best contact your company lawyer to get an authoritative answer.


问:
Is it considered bad practice to access a returned array by a key straight away?
I couldn't think of a good way to word the title, sorry. But what I mean is, is it considered bad practice to do:

```<code>print get_array()[2]
</code>```

over:

```<code>output=get_array()
print output[2]
</code>```

(where get_array() is a function that returns an array, if that wasn't clear). Which method is better? Why?

答:
From a design point of view, there seems to be a problem here - you're accessing a function that returns a set of values, take one specific value from it, and discard the rest.

Doesn't this feel like a waste, retrieving values you have no use for? Wouldn't it make more sense to replace get_array()[2] with a specific call, get_item(2)?


问:
Design Patterns - Why the need for interfaces?
OK. I am learning design patterns. Every time I see someone code an example of a design pattern they use interfaces. Here is an example:

http://visualstudiomagazine.com/Articles/2013/06/18/the-facade-pattern-in-net.aspx?Page=1

Can someone explain to me why was the interfaces needed in this example to demonstrate the facade pattern? The program work if you pass in the classes to the facade instead of the interface. If I don't have interfaces does that mean

答:
You can think of the main purpose of interfaces as allowing code to be abstract as opposed to specific.  In a language with strong type safety, it allows you to treat multiple classes with similarities the same without needing to know which specific one of these types is being used.

For example, you could have an interface for People in which several child classes extend.  You could then have a method that deals in people, accepting any or all types of classes that implement People without any concern for what they are beyond that.  This is also provided by other forms of inheritance, but interfaces have the special restriction that they themselves can't have an implementation.


问:
Practices for domain models in Javascript (with frameworks)
This is a question I've to-and-fro'd with for a while, and searched for and found nothing on: what're the accepted practices surrounding duplicating domain models in Javascript for a web application, when using a framework like Backbone or Knockout?

Given a web application of a non-trivial size with a set of domain models on the server side, should we duplicate these models in the web application (see the example at the bottom)? Or should we use the dynamic nature to load these models from the server?

To my mind, the arguments for duplicating the models are in easing validation of fields, ensuring that fields that expected to be present are in fact present etc. My approach is to treat the client-side code like an almost separate application, doing trivial things itself and only relying on the server for data and complex operations (which require data the client-side doesn't have). I think treating the client-side code like this is akin to separation between entities from an ORM and the models used with the view in the UI layer: they may have the same fields and relate to the same domain concept, but they're distinct things.

On the other hand, it seems to me that duplicating these models on the server side is a clear violation of DRY and likely to lead to differing results on the client- and server-side (where one piece gets updated but the other doesn't). To avoid this violation of DRY we can simply use Javascripts dynamism to get the field names and data from the server as and when they're neeed.

So: are there any accepted guidelines around when (and when not) to repeat yourself in these situations? Or this a purely subjective thing, based on the project and developer(s)?

Example

Server-side model

```<code>class M
{
    int A
    DateTime B
    int C
    int D = (A*C)
    double SomeComplexCalculation = ServiceLayer.Call();
}
</code>```

Client-side model

```<code>function M(){
    this.A = ko.observable();
    this.B = ko.observable();
    this.C = ko.observable();
    this.D = function() { return A() * C(); }
    this.SomeComplexCalculation = ko.observalbe();
    return this;
}l
M.GetComplexValue = function(){
    this.SomeComplexCalculation(Ajax.CallBackToServer());
};
</code>```

I realise this question is quite similar to this one, but I think this is more about almost wholly untying the web application from the server, where that question is about doing this only in the case of complex calculation.

答:
I think good design patterns and a framework like Breeze can help you out. Don't repeat the domain model on the client again, leave it on the server but use Breeze to pull the model to the client.

Here is a great example of using breezejs with the repository and unit of work patterns.

https://github.com/yagopv/DurandalAuth

The domain model is kept on the server and breeze reads the metadata and creates the entities locally from the server.  I think this is a great solution to your problem.  You get local entity framework type access locally via JS and you can keep your model on the server.  I think it strikes a good balance of the issues you brought up in your question.


问:
How to factor out data layer in nopCommerce and replace MS SQL with RavenDB?
I am new to nopCommerce and ecommerce in general but I am involved in an ecommerce project. Now from my past experiences with RavenDB (which mostly were absolutely pleasant) and based on the needs of the business (fast changes with awkward business workflows) It seemed to be an appealing option to have RavenDB handling all sort of things related to the database.

I do not understand design and architecture of nopCommerce fully so I did not reach to a conclusion on how to factor data parts, since it seems the services layer actually does not abstract data-layer concepts away; like bringing in EF working model to other layers.

I have found another project which used NuDB as it's database as a nopCommerce fork. But it did not help because NuDB still has the feeling of a RDBMS and is not as different as RavenDB.

Now first how can I learn about the internals of nopCommerce (other than investigating the code)? It's workflows? It's conventions?

Second has anyone tried something similar before with a NoSQL database (say like MongoDB or RavenDB)? Is it possible to achieve this in a 1 (~2) month time frame?

Thanks in advance;

答:
Whoa, slow down, you never just swap out a database. That is extremely risky especially if the database is already in production. And converting from relational to nosql can be time consuming as things won't match up exactly. Your reason seems to be that you prefer the one you are used to which is a horribly invalid reason for the amount of risk you are taking by converting the database.

Nor is this a question for strangers on the Internet, if you propose to do such a thing, your business leaders need to know in advance and with much discussion as to the time and the risk and the benefits. It is NOT your call, it is a management decision.

But further, you will need to determine if you need to convert existing data and look for any existing other things which might use the database backend besides your application such as reporting applications or data imports. It might even be set up specifically to follow rules which are required by auditors or credit card processors and which may preclude teh use of nosql.

I wouldn't even want to take on converting an Oracle database to SQl server or vice versa without at least a year in the project plan let alone convert from relational to nonrelational.

However, consider that new functionality could use the nosql approach if it is approved in advance, for things that cannot easily be defined in advance.  There is no rule that a project can't use both nosql when appropriate and relational when appropriate.


问:
Side effect-free interface on top of a stateful library
In an interview with John Hughes where he talks about Erlang and Haskell, he has the following to say about using stateful libraries in Erlang:

If I want to use a stateful library, I usually build a side
  effect-free interface on top of it so that I can then use it safely in
  the rest of my code.

What does he mean by this? I am trying to think of an example of how this would look, but my imagination and/or knowledge is failing me.

答:
A key concept here is that of external mutable state. A library that has no external mutable state, is one that is free of side-effects. Every function in such a library only depends on the arguments passed into it.

If your function accesses any resource that wasn't created by it, given to it (ie. as a parameter), then it depends on external state.

If your function creates something that it doesn't pass back to the caller (and doesn't destroy it) then your function is creating external state.

When the external state from above can have different values at different times, then it is mutable.

Handy litmus tests that I use:

if function A needs to be run before function B then A creates external state that B depends on.

if a function I'm writing cannot be memoized, then it depends on external mutable state. (The memoization might not be a good idea because of memory pressure, but it should still be possible)


问:
When there's no TCO, when to worry about blowing the stack?
Every single time there's a discussion about a new programming language targetting the JVM, there are inevitably people saying things like:

"The JVM doesn't support tail-call optimization, so I predict lots of exploding stacks"

There are thousands of variations on that theme.

Now I know that some language, like Clojure for example, have a special recur construct that you can use.

What I don't understand is: how serious is the lack of tail-call optimization? When should I worry about it?

My main source of confusion probably comes from the fact that Java is one of the most succesful languages ever and quite a few of the JVM languages seems to be doing fairly well.  How is that possible if the lack of TCO is really of any concern?

答:
Consider this, let's say we got rid of all loops in Java (the compiler writers are on strike or something). Now we want to write factorial, so we might right something like this

```<code>int factorial(int i){ return factorial(i, 1);}
int factorial(int i, int accum){
  if(i == 0) return accum;
  return factorial(i-1, accum * i);
}
</code>```

Now we're feeling pretty clever, we've managed to write our factorial even without loops! But when we test, we notice that with any reasonably sized number, we're getting stackoverflow errors since there's no TCO.

In real Java this isn't a problem. If we ever have a tail recursive algorithm, we can transform it into a loop and be just fine. However, what about languages with no loops? Then you're just hosed. That's why clojure has this recur form, without it, it's not even turing complete (No way to do infinite loops).

The class of functional languages that target the JVM, Frege, Kawa (Scheme), Clojure are always trying to deal with the lack of tail calls, because in these languages, TC is the idiomatic way of doing loops! If translated to Scheme, that factorial above would be a good factorial. It'd be awfully inconvenient if looping 5000 times made your program crash. This can be worked around though, with recur special forms, annotations hinting at optimizing self calls, trampolining, whatever. But they all force either performance hits or unnecessary work on the programmer.

Now Java doesn't get off free either, since there's more to TCO then just recursion, what about mutually recursive functions? They can't be straightforwardly translated to loops, but are still unoptimized by the JVM. This makes it spectacularly unpleasant to try to write algorithms using mutual recursion using Java since if you want decent performance/range you have to do dark magic to get it to fit into loops.

So, in summary, this isn't a huge deal for many cases. Most tail calls either only proceed one stackframe deep, with things like

```<code>return foo(bar, baz); // foo is just a simple method
</code>```

or are recursion. However, for the class of TC that don't fit into this, every JVM language feels the pain.

However, there is a decent reason why we don't yet have TCO. The JVM gives us stack traces. With TCO we systematically eliminate stackframes that we know are "doomed", but the JVM might actually want these later for a stacktrace! Say we implement a FSM like this, where each state tail-calls the next. We'd erase all record of previous states so a traceback would show us what state, but not anything about how we got there.

Additionally, and more pressingly, much of bytecode verification is stack based, eliminating the thing that lets us verify bytecode is not pleasant prospect. Between this and the fact that Java has loops, TCO looks like a bit more trouble than it's worth to the JVM engineers.

Body:
Consider this, let's say we got rid of all loops in Java (the compiler writers are on strike or something). Now we want to write factorial, so we might right something like this

int factorial(int i){ return factorial(i, 1);}
int factorial(int i, int accum){
  if(i == 0) return accum;
  return factorial(i-1, accum * i);
}

Now we're feeling pretty clever, we've managed to write our factorial even without loops! But when we test, we notice that with any reasonably sized number, we're getting stackoverflow errors since there's no TCO.

In real Java this isn't a problem. If we ever have a tail recursive algorithm, we can transform it into a loop and be just fine. However, what about languages with no loops? Then you're just hosed. That's why clojure has this recur form, without it, it's not even turing complete (No way to do infinite loops).

The class of functional languages that target the JVM, Frege, Kawa (Scheme), Clojure are always trying to deal with the lack of tail calls, because in these languages, TC is the idiomatic way of doing loops! If translated to Scheme, that factorial above would be a good factorial. It'd be awfully inconvenient if looping 5000 times made your program crash. This can be worked around though, with recur special forms, annotations hinting at optimizing self calls, trampolining, whatever. But they all force either performance hits or unnecessary work on the programmer.

Now Java doesn't get off free either, since there's more to TCO then just recursion, what about mutually recursive functions? They can't be straightforwardly translated to loops, but are still unoptimized by the JVM. This makes it spectacularly unpleasant to try to write algorithms using mutual recursion using Java since if you want decent performance/range you have to do dark magic to get it to fit into loops.

So, in summary, this isn't a huge deal for many cases. Most tail calls either only proceed one stackframe deep, with things like

return foo(bar, baz); // foo is just a simple method

or are recursion. However, for the class of TC that don't fit into this, every JVM language feels the pain.

However, there is a decent reason why we don't yet have TCO. The JVM gives us stack traces. With TCO we systematically eliminate stackframes that we know are "doomed", but the JVM might actually want these later for a stacktrace! Say we implement a FSM like this, where each state tail-calls the next. We'd erase all record of previous states so a traceback would show us what state, but not anything about how we got there.

Additionally, and more pressingly, much of bytecode verification is stack based, eliminating the thing that lets us verify bytecode is not pleasant prospect. Between this and the fact that Java has loops, TCO looks like a bit more trouble than it's worth to the JVM engineers.


问:
Styling the HTML tag in a web document
is it good Coding Practice to add style to the  tag of a web document?

why should you not style the  tag of a web document?

I ask this because of this answer on a StackOverflow question.

Personally I don't think this is good coding practice.

is there a WC3 standard that says this is good/bad?

答:
There's the matter of cross-browser inconsistencies between the  tag and the
 tag, with the
 having more consistent behavior. The w3c recommends that you style the  tag rather than the  tag. Much of this again has to do with modern browser behavior:

Many web developers do not understand the difference between applying
  style to the body element versus the html element. Most of the time
  these authors will apply style only to the body element; when that's
  not sufficient, they'll spam all sorts of styles on both html and body
  until the page happens to look correct.

The confusion is understandable. In the beginning, both were treated
  similarly, with (now-deprecated) attributes like bgcolor being applied
  to the body tag, affecting the whole page.

This article attempts to enlighten you, Web Developer, to fully grok
  how these two elements are used in modern web browsers.

Title: Styling the HTML tag in a web document

Body:
There's the matter of cross-browser inconsistencies between the <html> tag and the <div> tag, with the <div> having more consistent behavior. The w3c recommends that you style the <body> tag rather than the <html> tag. Much of this again has to do with modern browser behavior:

Many web developers do not understand the difference between applying
  style to the body element versus the html element. Most of the time
  these authors will apply style only to the body element; when that's
  not sufficient, they'll spam all sorts of styles on both html and body
  until the page happens to look correct.

The confusion is understandable. In the beginning, both were treated
  similarly, with (now-deprecated) attributes like bgcolor being applied
  to the body tag, affecting the whole page.

This article attempts to enlighten you, Web Developer, to fully grok
  how these two elements are used in modern web browsers.


问:
Simple website with a GPL V3 Framework
I write web-based software and simple website ("Home", "Who we are", "Contact").

For a simple website I'm using a covered GPL v3 framework. The user surf the website, send an email, take info, etc. I repeat: simple website, not a Joomla or Wordpress.

1) Will the website be covered with the GPL? I don't modify the framework. I'm using his classes in other classes... (OOP).

2) For the point 1, if yes, do I need to add (e.g. in the footer) name of framework and his link?

3) I must permit download of entire website to study code (nothing that a programmer has interest in)? E.g. placing it in Github?

4) If 2 is NO, how you can "understand" that we use that framework? In effect no php lines are exposed to the browser... You cannot understand that when you push "Send email" the site is calling $this->send($email). If you write me an email "Are you using XXX framework"? I can answer NO.

答:
You are not distributing the framework or any of its code, you're distributing a website of your own creative design (unless ofcourse you didn't actually designed it). As such you do not need a license, let alone conform to anything it has to say.

The GPL accompanying your framework of choice does not cover the contents of your website, nor the design.

As for being required to "state" that you're using a certain framework, I do NOT believe there is any legal basis for this, atleast not as far as a GPL license would be concerned. The GPL only cares about forced reproduction when being modified (or linked to, ew ugh nasty, use BSD license instead).

Disclaimer: I AM NOT A LAWYER. I DISLIKE GPL.

Title: Simple website with a GPL V3 Framework


答:
I try to explain it in terms of the article you linked to: the use of interfaces makes it possible to create unit tests for the VehicleFacade, to test that class in isolation. This can be accomplished by providing mock implementations of IEngineController, ITransmissionController, and so on, instead of using the real EngineController, TransmissionController etc.

Of course, those interfaces also allow to create different vehicles from different engine controllers, different transmission controller etc. and combine them freely. In real world scenarios, however, I expect the first use case (tests) to occur much more often then the second.

Title: Design Patterns - Why the need for interfaces?

Body:
OK. I am learning design patterns. Every time I see someone code an example of a design pattern they use interfaces. Here is an example:

http://visualstudiomagazine.com/Articles/2013/06/18/the-facade-pattern-in-net.aspx?Page=1

Can someone explain to me why was the interfaces needed in this example to demonstrate the facade pattern? The program work if you pass in the classes to the facade instead of the interface. If I don't have interfaces does that mean


答:
Tail calls optimizations is mainly important because of tail recursion. However, there is an argument why it is actually good that the JVM does not optimize tail calls: As TCO reuses a part of the stack, a stack trace from an exception will be incomplete, thus making debugging a bit harder.

There are ways to work around the limitations of the JVM:

Simple tail recursion can be optimized to a loop by the compiler.

If the program is in continuation-passing style, then it is trivial to use “trampolining”. Here, a function does not return the end result, but a continuation which is then executed on the outside. This technique allows a compiler writer to model arbitrarily complex control flow.

This may need a larger example. Consider a language with closures (e.g. JavaScript or similar). We can write the factorial as

```<code>def fac(n, acc = 1) = if (n <= 1) acc else n * fac(n-1, acc*n)

print fac(x)
</code>```

Now we can have it return a callback instead:

```<code>def fac(n, acc = 1) =
  if (n <= 1) acc
  else        (() => fac(n-1, acc*n))  // this isn't full CPS, but you get the idea…

var continuation = (() => fac(x))
while (continuation instanceof function) {
  continuation = continuation()
}
var result = continuation
print result
</code>```

This now works in constant stack space, which is kind of silly because it's tail-recursive anyway. However, this technique is able to flatten all tail calls into constant stack space. And if the program is in CPS, then this means that the callstack is constant overall (in CPS, every call is a tail call).

A major disadvantage of this technique is that it's much harder to debug, a bit harder to implement, and less performant – see all the closures and indirection I'm using.

For these reasons it would be vastly preferable to have the VM implement a tail call op – languages like Java that have good reasons not to support tail calls would not have to use it.

Title: When there's no TCO, when to worry about blowing the stack?

Body:
Every single time there's a discussion about a new programming language targetting the JVM, there are inevitably people saying things like:

"The JVM doesn't support tail-call optimization, so I predict lots of exploding stacks"

There are thousands of variations on that theme.

Now I know that some language, like Clojure for example, have a special recur construct that you can use.

What I don't understand is: how serious is the lack of tail-call optimization? When should I worry about it?

My main source of confusion probably comes from the fact that Java is one of the most succesful languages ever and quite a few of the JVM languages seems to be doing fairly well.  How is that possible if the lack of TCO is really of any concern?

Body:
Tail calls optimizations is mainly important because of tail recursion. However, there is an argument why it is actually good that the JVM does not optimize tail calls: As TCO reuses a part of the stack, a stack trace from an exception will be incomplete, thus making debugging a bit harder.

There are ways to work around the limitations of the JVM:

Simple tail recursion can be optimized to a loop by the compiler.

If the program is in continuation-passing style, then it is trivial to use “trampolining”. Here, a function does not return the end result, but a continuation which is then executed on the outside. This technique allows a compiler writer to model arbitrarily complex control flow.

This may need a larger example. Consider a language with closures (e.g. JavaScript or similar). We can write the factorial as

def fac(n, acc = 1) = if (n <= 1) acc else n * fac(n-1, acc*n)

print fac(x)

Now we can have it return a callback instead:

def fac(n, acc = 1) =
  if (n <= 1) acc
  else        (() => fac(n-1, acc*n))  // this isn't full CPS, but you get the idea…

var continuation = (() => fac(x))
while (continuation instanceof function) {
  continuation = continuation()
}
var result = continuation
print result

This now works in constant stack space, which is kind of silly because it's tail-recursive anyway. However, this technique is able to flatten all tail calls into constant stack space. And if the program is in CPS, then this means that the callstack is constant overall (in CPS, every call is a tail call).

A major disadvantage of this technique is that it's much harder to debug, a bit harder to implement, and less performant – see all the closures and indirection I'm using.

For these reasons it would be vastly preferable to have the VM implement a tail call op – languages like Java that have good reasons not to support tail calls would not have to use it.


问:
How to support a product built with agile development?
Two of the functions our company provides our customers are:

Our Development team of ~10 employees creates software products for businesses in a particular industry. The software is used on hundreds of our customers' computers. Although the product is, for most customers, off-the-shell, larger customers drive its development, so it's somewhere between shrinkwrap software and custom software.

Our Support team of ~25 employees provides technical support for both our own software and a few other software products for which we are the vendor.

Our Development team recently switched to Scrum for their development methodology, and while I support this change, I worry that our Support team is going to have more trouble in the future.  With a quicker release cycle, our customers will have features and products in production which Support isn't even aware of until the customer calls. We've never been particularly good at getting documentation and information from Development to Support, but I fear Scrum will just exacerbate the problem.

What are good references on how companies reconcile Development's desire to release frequently with Support's desire to have full documentation and support information before customers see the product?  How should a company structure their release and change management when using agile methods?

EDIT: What I'm interested are specifics on how companies structure themselves to deal with these issues. Does the scrum team push releases to customers? Does the software have to go through a release/change management team who will not deploy until Support has been given documentation and brought up to speed?  How do you get releases to customers quickly yet still keep everyone informed of changes and new features?

答: Involve Support team representative in weekly client calls (i.e when giving a walk through to your client ) by that even your support team rep will get to know the product better before releasing to client </p>

ContentLicense: CC BY-SA 2.5


问:
What are `Developmental Milestones` for programming skills?
I studied in the field of Computer Science for 6 years,  bachelor's degree and master's degree. I have studied all the basic programming like C, Java, VB, C#, Python, and etc. When I have free times, I will learn new programming languages and follow new programming trends by myself , such as PHP, HTML5, CSS5, LESS, Bootstrap, Symfony2, and GitHub. So, if someone wants me to write some instructions using these languages, I'm certain that I can do it, not so good but I can get a job done. However, I don't have any favorite programming language. Moreover, I also have studied about algorithms, database, and etc.

Everything I just wrote so far seems that I know a lot in this field. In fact, I feel I am very stupid. I cannot answer 80% of the questions on SO. In spite of those languages, I have studied. Perhaps it is because I have never worked before.

As there is the Developmental Milestones for children, which refers to how a child becomes able to do more complex things as they get older, I would like to evaluate the same thing but for programming skills. What are the set of functional skills or age-specific tasks that most programmers can do at a certain age range?

In order to evaluate myself, I would like to ask your opinions that all of the skills I mentioned above, are they enough for programmers to know when they are 25 years old?

What are your suggestions in order to improve the skills in this field?

答:
I have studied all the basic programming like C, Java, VB, C#, Python, and etc.

This tells me you've not quite understood what Computer Science is at it's core.. All it is, is 0's and 1's... slinging bits around.  Just because you've studied something for X years doesn't mean you understand the underpinnings of a technology..

Focus on things at the core.  What would get you a job at the top computer firms in the world? Google, Apple, etc...

Algorithms

Data Structures

Big O analysis

You've mentioned very little of these things, yet they are the core of computer science.

Again, stop comparing yourself on an age scale, and just have fun with computer science.  I cannot answer 90% of the things on Stack Overflow.. but I am calm because that's not my (or your) job.. focus on what you want to accomplish with computers, and science, and relax..


问:
Randomly and uniquely iterating over a range
Say you have a range of values (or anything else) and you want to iterate over the range and stop at some indeterminate point.

Because the stopping value could be anywhere in the range, iterating sequentially is no good because it causes the early values to be accessed more often than later values (which is bad for things that wear out), and also because it reduces performance since it must traverse extra values.

Randomly iterating is better because it will (on average) increase the hit-rate so that fewer values have to be accessed before finding the right one, and also distribute the accesses more evenly (again, on average).

The problem is that the standard method of randomly jumping around will result in values being accessed multiple times, and has no automatic way of determining when each value has been checked and thus the whole range has been exhausted.

One simplified and contrived solution could be to make a list of each value, pick one at random, then remove it. Each time through the loop, you pick one fromt he set of remaining items. Unfortunately this only works for small lists. As a (forced) example, say you are creating a game where the program tries to guess what number you picked and shows how many guess it took. The range is between 0-255 and instead of asking Is it 0? Is it 1? Is it 2?…, you have it guess randomly. You could create a list of 255 numbers, pick randomly and remove it. But what if the range was between 0-232? You can’t really create a 4-billion item list.

I’ve seen a couple of implementations RNGs that are supposed to provide a uniform distribution, but none that area also supposed to be unique, i.e., no repeated values.

So is there a practical way to randomly, and uniquely iterate over a range?

答:
linear congruential generator (the x'=(a*x+c) mod m one) with some random seed

if you have m equal to the size of the array you will not get a repeat value until you cycle through all of them

the quality of their randomness isn't the greatest but if you just want to load balance it's fine

edit: one thing to keep in mind is that repeats are not likely on uniform distribution with a good RNG and a large range to generate from, so only excluding the last few is an option

so you can keep the last N numbers you took and exclude them from the available pool (just generate another number when it's a repeat),


问:
Best place to learn Component Object Model
I need to learn COM for my current project. I am a noob and I haven't been able to find good starting points for COM. I have been looking into MSDN and googling... I did find some interesting articles on codeproject.com, but I am not satisfied. Why do we use COM ? Why does it exist ? In what places does it exist ? ..... and so on .. So, will you please tell me where can I find answers to these questions ?</p>

答:
The followings could be useful COM overviewM:

http://www.youtube.com/watch?v=-uodiz25YNE

http://progtutorials.tripod.com/COM.htm

The first video talks about the general idea of creating Binary Components to reuse codes written in different languages (language-independent) and are in different machines (processes) (location independent/transparent). This technology is used in some Software Companies to integrate with other software (companies) instead of buying their software and embed them into their own or writing the codes from scratch in their systems.

This technology has three different versions (implementtaions):

OLE/COM/DCOM/ActiveX for C++ developers (ATL is used to make programmer's job easier)

JavaBeans/RMI/EJB for Java developers

CORBA/IIOP

Just think of it as a technology that comes handy when you have your software written in Java and you want to add a functionality to it that is already exist in a package but it is written in C++ and even perhaps is located in different machine not in your local machine. How do you call "new" , how do you make objects and call methods from them?

The following books that I have seen people who do COM coding have either of them in their bookshelves:

Developer's Workshop to COM and ATL 3.0

Inside Com

Essential COM


答:
Interfaces are unrelated to Design Patterns. They are about Object-Orientation. In OO, the type of an object is defined by its behavior, i.e. by the protocol it speaks (its methods).

Classes in languages like Java and C#, however, also define representation (fields) in addition to behavior (methods). One of the basic tenets of OO is that objects cannot know the representation of other objects even of the same type. However, if you use classes as types, other objects of the same class can know the representation of other objects, even private fields. Therefore, using classes as types breaks OO. (Unfortunately, in both Java and C#, classes are types.)

The only way to do object-oriented programming in Java or C# is to use classes only as factories (i.e. only directly after new) and never as types (i.e. never as the type of a field, return type or parameter type of a method or type argument to a generic type, never cast to a class, never use it with instanceof). And as types, use only interfaces, not classes (and certainly not primitives in Java).

That's what interfaces do: they enable object-oriented programming in Java and C#, without them, OOP would simply be impossible in those languages.


答:
A significant portion of calls in a program are tail calls. Every subroutine has a last call, so every subroutine has at least one tail call. Tail calls have the performance characteristics of GOTO but the safety of a subroutine call.

Having Proper Tail Calls enables you to write programs that you cannot otherwise write. Take, for example, a state machine. A state machine can be very directly implemented by having each state be a subroutine and each state transition be a subroutine call. In that case, you transition from state to state to state, by making call after call after call, and you actually never return! Without Proper Tail Calls, you would immediately blow the stack.

Without PTC, you have to use GOTO or Trampolines or exceptions as control flow or something like that. It's much uglier, and not so much a direct 1:1 representation of the state machine.

(Note how I cleverly avoided using the boring "loop" example. This is an example where PTCs are useful even in a language with loops.)

I deliberately used the term "Proper Tail Calls" here instead of TCO. TCO is a compiler optimization. PTC is a language feature that requires every compiler to perform TCO.


答:
Think of an interface like a Contract.  It's a way to say, "These classes should follow these set of rules."

Let's use an example and call it IAnimal.  We could say that the interface defines two methods Run and Walk. It's a way to say, "I MUST be able to call Run, Walk, etc. on classes which implement IAnimal."

Why is this useful?  You may want to build a function which relies on the fact that you must be able to call Run and Walk, for example, on the object.  You could have the following:

```<code>public void RunThenWalk(Monkey m) {
    m.Run();
    m.Walk();
}

public void RunThenWalk(Dog d) {
    d.Run();
    d.Walk();
}
</code>```

... and repeat that for all objects which you know can run and walk.  However, with your IAnimal interface, you can define the function once as follows:

```<code>public void RunThenWalk(IAnimal a) {
    a.Run();
    a.Walk();
}
</code>```

By programming against the interface, you are essentially trusting the classes to implement the intent of the interface.  So in our example, the thought is "I don't care how they Run and Walk, so long as they Run and Walk.  My RunThenWalk will be valid as long as they fulfill that agreement.  It functions perfectly well without knowing anything else about the class."

Body:
Think of an interface like a Contract.  It's a way to say, "These classes should follow these set of rules."

Let's use an example and call it IAnimal.  We could say that the interface defines two methods Run and Walk. It's a way to say, "I MUST be able to call Run, Walk, etc. on classes which implement IAnimal."

Why is this useful?  You may want to build a function which relies on the fact that you must be able to call Run and Walk, for example, on the object.  You could have the following:

public void RunThenWalk(Monkey m) {
    m.Run();
    m.Walk();
}

public void RunThenWalk(Dog d) {
    d.Run();
    d.Walk();
}

... and repeat that for all objects which you know can run and walk.  However, with your IAnimal interface, you can define the function once as follows:

public void RunThenWalk(IAnimal a) {
    a.Run();
    a.Walk();
}

By programming against the interface, you are essentially trusting the classes to implement the intent of the interface.  So in our example, the thought is "I don't care how they Run and Walk, so long as they Run and Walk.  My RunThenWalk will be valid as long as they fulfill that agreement.  It functions perfectly well without knowing anything else about the class."


问:
In retrospect, has it been a good idea to use three-valued logic for SQL NULL comparisons?
In SQL, NULL means "unknown value". Thus, every comparison with NULL yields NULL (unknown) rather than TRUE or FALSE.

From a conceptional point of view, this three-valued logic makes sense. From a practical point of view, every learner of SQL has, one time or another, made the classic WHERE myField = NULL mistake or learned the hard way that NOT IN does not do what one would expect when NULL values are present.

It is my impression (please correct me if I am wrong) that the cases where this three-valued logic helps (e.g. WHERE myField IS NOT NULL AND myField <> 2 can be shortened to WHERE myField <> 2) are rare and, in those cases, people tend to use the longer version anyway for clarity, just like you would add a comment when using a clever, non-obvious hack.

Is there some obvious advantage that I am missing? Or is there a general consensus among the development community that this has been a mistake?

答:
This seems to be a duplicate question...
https://stackoverflow.com/questions/7078837/why-doesnt-sql-support-null-instead-of-is-null

I don't think it's a mistake - this behavior is described in the ANSI standard.

Most databases allow you to change behavior of the equality operator.

```<code>set ansi_nulls on
if null = null
   print 'this will not print'
set ansi_nulls off
if null = null
   print 'this should print'
</code>```

Also, you can note that many programming languages expect similar semantics when comparing objects against null.

Body:
This seems to be a duplicate question...
https://stackoverflow.com/questions/7078837/why-doesnt-sql-support-null-instead-of-is-null

I don't think it's a mistake - this behavior is described in the ANSI standard.

Most databases allow you to change behavior of the equality operator.

set ansi_nulls on
if null = null
   print 'this will not print'
set ansi_nulls off
if null = null
   print 'this should print'

Also, you can note that many programming languages expect similar semantics when comparing objects against null.


问:
Can anyone explain to me what problem Core Data solves?
Core Data seems to add a needless layer of complexity.  If you want to save data created natively by the user in an app why not just use an object and then write the data all to SQLite or back to a server using a RESTful script if necessary.

Android doesn't have Core Data (though if it has something similar I haven't seen it.).   What the heck is the point of buggy CD except useless needless overhead for people who can't write SQL or CGI scripts?

答:
You absolutely could write SQL queries and store whatever data you need in a SQLite database or just write raw data to a file. In fact you are free to do so right now in an iOS app. Why then might we want a different abstraction?

Immediately you're going to notice that your application is working with objects and you need to translate them into some form you can write to your data store. You might just write a bunch of raw bytes from memory to disk but that will be very hard to reconstruct back into an object of the appropriate type and as soon as you change an object's structure your data will be even more difficult to recover. Instead you'll probably decide to serialize the object into some more reasonable form. That works well if you just want to write to a file but then it is hard to selectively reconstruct objects. No problem, you store data in sqlite in a form you can query on and now you can quickly search for and load specific objects. Of course its inconvenient to have every class in your app handle a bunch of database reads and writes, you probably want some service which can automate mapping classes to tables and objects to rows in those tables. Now you've build your own object-relational mapping library.

Mapping objects to rows in tables is a good start but some of your objects contain other child objects so you end up needing to save and load entire graphs of objects at a time. That's ok with a little work you can handle that too.

Oh and it would be nice if you could double check that your data is valid before you actually save it so you might add some rules to prevent saving invalid objects to the database.

Your ORM library works great but as you keep working on the app you discover that you need to change some of your objects. That means you need to change how they are represented in the database too. Now you need to define some process for migrating an old database schema to a new one.

As your app grows it becomes infeasible to store all of the results of some of your queries in memory. You solve that with a clever scheme for just loading a few objects at a time as they are needed.

Then you discover that users sometimes want to undo their changes. You could store each change as a row in a table but after doing that a couple of times you realize that your data storage service could automatically keep track of changes for you.

Now you have a pretty powerful tool for managing persisted objects in your application. Its so handy it would be nice if you could use it in other situations too, like for objects you just want to keep in memory and not write to a database. Of course then it would be even better if you could choose to move some of those objects over into the database later.

You have now reinvented most of CoreData. An attempt to build a fairly general purpose tool for persisting objects and managing common operations around their persistence. You don't use it for everything but it's awfully handy to pull into your apps as soon as they have some non-trivial requirements around how they manage data.


答: TRUE and FALSE make statements about the content of a value. NULL indicates the complete absence of any value at all. If NULL behaved the same way as FALSE, then you would be unable to account correctly for the absence of data in a query, something that is very important in a database. I think that alone makes NULL different enough from TRUE/FALSE that it merits being handled specially.</p>

Title: In retrospect, has it been a good idea to use three-valued logic for SQL NULL comparisons?

Body:
In SQL, NULL means "unknown value". Thus, every comparison with NULL yields NULL (unknown) rather than TRUE or FALSE.

From a conceptional point of view, this three-valued logic makes sense. From a practical point of view, every learner of SQL has, one time or another, made the classic WHERE myField = NULL mistake or learned the hard way that NOT IN does not do what one would expect when NULL values are present.

It is my impression (please correct me if I am wrong) that the cases where this three-valued logic helps (e.g. WHERE myField IS NOT NULL AND myField <> 2 can be shortened to WHERE myField <> 2) are rare and, in those cases, people tend to use the longer version anyway for clarity, just like you would add a comment when using a clever, non-obvious hack.

Is there some obvious advantage that I am missing? Or is there a general consensus among the development community that this has been a mistake?


答:
I think the crux of the problem is that as well as "UNKNOWN" it is also used to mean "NOT APPLICABLE" or "ABSENT" e.g. You have a PERSONS table with a SPOUSE_ID. What do you put in their for a single person? In most cases a designer will make this field NULLable to be filled with the partners ID when available and left blank for sad singles and happy bachelors.

In my experience this is actually the most common use for NULLs. So while a comparison of two UNKNOWN values should result in another UNKNOWN; a comparison between two ABSENT values should result in equality -- but SQL does not allow for this.

It would have been trivial to add another extra operator (say "==") to the mass of SQL keywords and operators which would indicate you want 2 nulls to be considered equal.

While I think the relational model is sound and has a long future ahead, I think the mess that is SQL is due for a total rethink. It would be nice if we could start again from the very beginning and have an API based on Codd's original relational algebra.


问:
What is the right level of site blocking for you as a developer?
Almost all developers who work for a large corporation find themselves on the wrong side of site blocking software. It can be both frustrating ("Just let me read that damn blog!") and helpful ("Woah! Dodged a bullet with that site").

In your opinion, what is the right level of blocking to apply to developers and why?

答:
The only valid reason for blocking is as a security precaution and aside from a standard phishing filter at a browser level blocking is the wrong solution to that problem.

Let developers see everything on the condition that:

They run a firewall and up to date anti-virus

They have an anti-phishing filter on

They're willing to be held responsible for any malware they introduce to the company if they don't take reasonable basic precautions *.

Beyond that you're more likely to impact productivity than increase it by blocking sites.

* This comes from my experiences with the iloveyou virus where a smart developer I was working with happily clicked on an unknown file with a visible .vbs extension.  If you want to be treated like an adult then you do need to act like one and developers don't (or shouldn't) have the excuse of ignorance.


问:
Planning Poker and wordy developers
My team is composed of 4 developers; all seasoned and skilled. One of them is a wordy, well intended chap who insists on defining the technical solution to our stories before we put down our estimates with Planning Poker. He refuses to estimate if he doesn't have a rough idea of the agreed technical solution (which sounds reasonable, right?).

The problem is that our estimating sessions are taking forever to finish!! In your experience, how do you deal with this kind of personality when playing the planning poker?

答:
For the teams I work with, at the start of every planning session I set a 3 minute sand timer on the table. I let the whole team know that if at any point they feel the conversation is becoming a deep dive, or irrelevant, or in any other way is going beyond what they feel is needed to estimate the story in story points, then anyone on the team can flip the timer over. Once the sand runs out, then the team immediately estimates.

This method empowers every individual on the team to limit the conversation, when they feel the conversation is no longer useful to estimate the story being discussed. At the same time, it does not immediately cut off the conversation, but does give everyone a visual indication that they conversation needs to wrap up in the next few minutes, because we are then going to vote.

Another tool which I use to help keep the planning sessions focused, is to make certain that everyone on the team has reviewed the stories at the top of the backlog at least a couple days prior to planning. The idea is that if you have a list of questions immediatly upon reading the stories, you can let the product owner know about the potential questions several days prior, so that they can clarify the story or the acceptance critiera to hopefully limit the later discussion. This also allows folks to start thinking about the potential design of the story, prior to being in planning (and trying to design during planning).

Title: Planning Poker and wordy developers


答: The problem here is that NULL isn't a value--it's a nebulous set of values, and you don't know which one it is. Setting equality here is meaningless, because then the values wouldn't be NULL. It enforces the mathematical underpinnings of relational databases. In many ways, it's like asking why infinity = infinity isn't valid.</p>


答:
I think Larsenal has given the best answer so far, but I'd like to expand on it to give a concrete example from working enterprise-level code (not in C#, but another ECMAScript-based language). In my code, I can treat Classes that are fundamentally different things as if they were the same from the viewpoint of the client code.

In my application, I have an IPaging Interface that defines functions like nextPage(), previousPage(), etc. This Interface is implemented by View Classes, but also by Controller Classes. What this allows me to do is bootstrap the application with a View that directly implements IPaging that gets passed to the Application's currentPaging variable. This View is already up and running while the Controllers are loaded with the data they need to proceed. This gets something interactive in front of users right away.

Once they're past that View, the Application's currentPaging variable is then given an instance of a Controller that implements IPaging. That Controller might then implement IPaging by calling those same functions on an IPaging View (that might again have IPaging Views inside it that allow nested, hierarchical navigation), or it might implement IPaging a different way, by swapping out pages of data to a View that has nothing to do with IPaging. The choices are literally limitless, and I can use the same Application framework with Views or Controllers that are customized to be slightly or very different based on the requirements we get. And our clients, like most clients, are nuts--so we have to be as flexible as possible.

I have never regretted using an Interface when perhaps there are only one or two implementations, but I have dearly regretted not using an Interface when I need an implementation that doesn't inherit from the same base Class and I didn't use an Interface. And once you have references to a specific Class spread all through your codebase and referenced from multiple projects, it's tough to put the genie back into the bottle.

One advantage of Interfaces that I get in the language I use (that I suspect you could also have in C#) is that I have the choice to load in implementations of the Interfaces I use at runtime from an external source. The loading Application doesn't need to compile in the Class definitions of the loaded implementations--it only needs the definition of the Interface to be able to cast to that Interface. Interfaces, by definition, have virtually no code in them.


答:
There are three variations of the GPL v3 license that can have different effects towards your website: the regular GPL, LGPL and Affero GPL.

The Affero GPL license gives the clearest situation here: As your website provides the public the possibility to execute the code of the website (by accessing it), you must also provide public access to the code of your website under terms compatible with the Affero GPL license.

Under both the GPL and LGPL, the mere fact that others can execute the code residing on your server does not mean that you are distributing that code. So, if you just host the website without giving a download link for the code (or putting it in a publicly accessible repository), you are not distributing the code and any requirements that a framework or library has on redistribution are moot.

If you do provide public access to your code, then the use of a GPL licensed framework most likely means that your code must also be released under the GPL license. The only exception is if the framework uses the LGPL license and is linked into your code as a replaceable library.

With regards to naming the framework used in your website, unless it is a requirement in their copyright license, you have no obligation to name the framework, but it can be seen as a gesture of goodwill if you do mention the framework and provide a link to it. Preferably, the link should point at the homepage of the framework.

Title: Simple website with a GPL V3 Framework

Body:
I write web-based software and simple website ("Home", "Who we are", "Contact").

For a simple website I'm using a covered GPL v3 framework. The user surf the website, send an email, take info, etc. I repeat: simple website, not a Joomla or Wordpress.

1) Will the website be covered with the GPL? I don't modify the framework. I'm using his classes in other classes... (OOP).

2) For the point 1, if yes, do I need to add (e.g. in the footer) name of framework and his link?

3) I must permit download of entire website to study code (nothing that a programmer has interest in)? E.g. placing it in Github?

4) If 2 is NO, how you can "understand" that we use that framework? In effect no php lines are exposed to the browser... You cannot understand that when you push "Send email" the site is calling $this->send($email). If you write me an email "Are you using XXX framework"? I can answer NO.


问:
MVC + 3 tier; where ViewModels come into play?
I'm designing a 3-tiered application using ASP.NET MVC 4. I used the following resources as a reference.

CodeProject: MVC + N-tier + Entity Framework

Separating data access in ASP.NET MVC

I have the following desingn so far.

Presentation Layer (PL) (main MVC project, where M of MVC was moved to Data Access Layer):

```<code>MyProjectName.Main
    Views/
    Controllers/
    ...
</code>```

Business Logic Layer (BLL):

```<code>MyProjectName.BLL
    ViewModels/
    ProjectServices/
    ...
</code>```

Data Access Layer (DAL):

```<code>MyProjectName.DAL
    Models/
    Repositories.EF/
    Repositories.Dapper/
    ...
</code>```

Now, PL references BLL and BLL references DAL. This way lower layer does not depend on the one above it.

In this design PL invokes a service of the BLL. PL can pass a View Model to BLL and BLL can pass a View Model back to PL.

Also, BLL invokes  DAL layer and DAL layer can return a Model back to BLL. BLL can in turn build a View Model and return it to PL.

Up to now this pattern was working for me. However, I've ran into a problem where some of my ViewModels require joins on several entities. In the plain MVC approach, in the controller I used a LINQ query to do joins and then select new MyViewModel(){ ... }. But now, in the DAL I do not have access to where ViewModels are defined (in the BLL).

This means I cannot do joins in DAL and return it to BLL. It seems I have to do separate queries in DAL (instead of joins in one query) and BLL would then use the result of these to build a ViewModel. This is very inconvenient, but I don't think I should be exposing DAL to ViewModels.

Any ideas how I can solve this dilemma? Thanks.

答:
main MVC project, where M of MVC was moved to Data Access Layer

Common misconception. The M of MVC has nothing to do with data, despite the many examples and tutorials that claim so.

M  is your ViewModel and should reside in your MVC project. The ViewModels you have in your BLL are actually to be named DataContracts or BusinessModels.

In your controller you have something comparable to this:

```<code>Get(id):
    dataContract = _service.Get(id);
    viewModel = Map(dataContract);
    return viewModel
</code>```

In your service, something like this:

```<code>Get(id):
    dataModel = _dataAccess.Get(id);
    dataContract = Map(dataModel);
    return dataContract;
</code>```

And in the DataAccess, you perform the proper joins according to the object requested. You are however of course free to add custom methods to your DataAccess when required, so your service can call those methods:

```<code>GetWithBars():
    dataModels = _repository.Query("select from foos join bars");
    return dataModels;
</code>```

Body:
main MVC project, where M of MVC was moved to Data Access Layer

Common misconception. The M of MVC has nothing to do with data, despite the many examples and tutorials that claim so.

M  is your ViewModel and should reside in your MVC project. The ViewModels you have in your BLL are actually to be named DataContracts or BusinessModels.

In your controller you have something comparable to this:

Get(id):
    dataContract = _service.Get(id);
    viewModel = Map(dataContract);
    return viewModel

In your service, something like this:

Get(id):
    dataModel = _dataAccess.Get(id);
    dataContract = Map(dataModel);
    return dataContract;

And in the DataAccess, you perform the proper joins according to the object requested. You are however of course free to add custom methods to your DataAccess when required, so your service can call those methods:

GetWithBars():
    dataModels = _repository.Query("select from foos join bars");
    return dataModels;


问:
Pro/con of using Angular directives for complex form validation/ GUI manipulation
I am building a new SPA front end to replace an existing enterprise's legacy hodgepodge of systems that are outdated and in need of updating. I am new to angular, and wanted to see if the community could give me some perspective. I'll state my problem, and then ask my question.

I have to generate several series of check boxes based on data from a .js include, with data like this:

```<code>$scope.fieldMappings.investmentObjectiveMap = [
  {'id':"CAPITAL PRESERVATION", 'name':"Capital Preservation"},
  {'id':"STABLE", 'name':"Moderate"},
  {'id':"BALANCED", 'name':"Moderate Growth"},
   // etc
  {'id':"NONE", 'name':"None"}
];
</code>```

The checkboxes are created using an ng-repeat, like this:

```<code><div ng-repeat="investmentObjective in fieldMappings.investmentObjectiveMap">
 ...
</div>
</code>```

However, I needed the values represented by the checkboxes to map to a different model (not just 2-way-bound to the fieldmappings object).

To accomplish this, I created a directive, which accepts a destination array destarray which is eventually mapped to the model. I also know I need to handle some very specific gui controls, such as unchecking "None" if anything else gets checked, or checking "None" if everything else gets unchecked.

Also, "None" won't be an option in every group of checkboxes, so the directive needs to be generic enough to accept a validation function that can fiddle with the checked state of the checkbox group's inputs based on what's already clicked, but smart enough not to break if there is no option called "NONE".

I started to do that by adding an ng-click which invoked a function in the controller, but in looking around Stack Overflow, I read people saying that its bad to put DOM manipulation code inside your controller - it should go in directives. So do I need another directive?

So far: (html):

```<code><input my-checkbox-group
          type="checkbox"
          fieldobj="investmentObjective"
          ng-click="validationfunc()"
          validationfunc="clearOnNone()"
          destarray="investor.investmentObjective" />
</code>```

Directive code:

```<code>.directive("myCheckboxGroup", function () {
  return {
    restrict: "A",
    scope: {
      destarray:      "=",  // the source of all the checkbox values
      fieldobj:       "=",  // the array the values came from
      validationfunc: "&"   // the function to be called for validation (optional)
    },
    link: function (scope, elem, attrs) {
      if (scope.destarray.indexOf(scope.fieldobj.id) !== -1) {
        elem[0].checked = true;
      }
      elem.bind('click', function () {
        var index = scope.destarray.indexOf(scope.fieldobj.id);
        if (elem[0].checked) {
          if (index === -1) {
            scope.destarray.push(scope.fieldobj.id);
          }
        }
        else {
          if (index !== -1) {
            scope.destarray.splice(index, 1);
          }
        }
      });
    }
  };
})
</code>```

.js controller snippet:

```<code>.controller( 'SuitabilityCtrl', ['$scope', function ( $scope ) {
  $scope.clearOnNone = function() {
    // naughty jQuery DOM manipulation code that
    // looks at checkboxes and checks/unchecks as needed
  };
</code>```

The above code is done and works fine, except the naughty jquery code in clearOnNone(), which is why I wrote this question.

And here is my question: after ALL this, I think to myself - I could be done already if I just manually handled all this GUI logic and validation junk with jQuery written in my controller. At what point does it become foolish to write these complicated directives that future developers will have to puzzle over more than if I had just written jQuery code that 99% of us would understand with a glance? How do other developers draw the line?

I see this all over Stack Overflow. For example, this question seems like it could be answered with a dozen lines of straightforward jQuery, yet he has opted to do it the angular way, with a directive and a partial... it seems like a lot of work for a simple problem.

Specifically, I suppose I would like to know: how SHOULD I be writing the code that checks whether "None" has been selected (if it exists as an option in this group of checkboxes), and then check/uncheck the other boxes accordingly? A more complex directive? I can't believe I'm the only developer that is having to implement code that is more complex than needed just to satisfy an opinionated framework.

答:
Your problem seems to be easily solveable with 2-way databinding and some model handler functions in a controller, but you write that you need more than the binding to the fieldmappings object?

Do you actually make use of the fieldmappings object model? If not, you could clone its contents to a model of your own on controller initialization.

After that just set the checkbox models to false instead of your jQuery DOM manipulation and Angular will uncheck the boxes for you.


问:
Why do we use to talk about addresses and memory of variable in C?
Why do we use to talk about addresses and memory of variable in C, where in other languages (like in Java, .Net etc) we do not talk about variable address and memory in a program, we will directly use the variables.

But in C Language we are listening the word address and memory.

How to explain this?

I hope C is high level language designed over the assembly language. So C is a thin layer over assembly language (in assembly language we will use memory locations to store a variable and track a variable). But in other languages these addresses and memory related things are wrapped in that specific language, so that we will not listen these words.

答:
But in C Language we are listening the word address and memory.

How to explain this?

Because computers use addresses and memory. The C language is designed to be used on computers - where the formal definition of a computer is something with a CPU, some memory and some I/O. In other words, not necessarily a desktop PC. And thus to become a half-decent C programmer, you must know what a computer is and how it works.

Higher level languages have hidden away this, to enable programming for people who don't know anything about computers, so that they can focus on writing applications and algorithms, without knowing what goes on between the lines.

Many high level languages run on top of a virtual machine, which is essentially another program written in a lower level language, with the purpose to execute the scripts or byte code generated by the high level language. But in the end, all executed programs ultimately use addresses and reside in memory.


问:
How to estimate tasks in scrum?
Let's say we have a backlog of User Stories, each with an estimated number of Story Points, and now we're doing the Sprint Planning.

Now, the Stories should be broken down into tasks and many Scrum resources suggest that each task should be estimated in person-hours. Since all questions have been discussed by the team at this point, estimating a task should not take longer than a minute. However, since a task should not be longer than a day, assuming a three week sprint with 8 developers means 120 tasks, and taking two hours only for estimations seems to be a bit much to me.

I know that experienced teams can skip or short-cut task estimations, but let's say we're not at that stage yet.

In your experience, how many tasks are there in a sprint and how long should it take to estimate all of them? (Estimating only half of them doesn't make much sense, does it?)

Clarifications:

I know the answer depends on sprint length and team size, so let's assume 8 developers and three weeks.

The numbers mentioned might be rules of thumb, but even if they are off (eg, more tasks, less time needed to estimate each) we will end up with about 2 hours for the estimation. So maybe the question should be "What percentage of the planning meeting should be reserved for pure task estimation, and don't we have better things to do?"

答:
Frankly, I think that if you're asking this question, you're indeed not entirely convinced of the use of sprint planning.

The point of sprint planning is to get the team into a state where they feel comfortable committing to a given set of user stories, where they feel they know enough to get started. Wether that takes one hour, or 2 of 4 or the whole day is completely beside the point; it will be done when it will be done.

Say you want to shorten it and limit it to 2 hours. The fact that they need information will not change, so you will inevitably wind up with portions of what used to be sprint planning, smeared out over the rest of your sprint.

In the end, all that matters is that the team can commit to some work and actually deliver that work to the satisfaction of both themselves and the other stakeholders. All the rest doesn't matter. Focus on what actually delivers value, don't focus on vanity metrics.

P.S.: no matter how much literature indicates you should estimate tasks in hours, I still find it to be a horribly useless and counter-productive idea and I know I'm not alone in this.

Title: How to estimate tasks in scrum?


问:
Business Logic Layer in MVC Application
In my ASP MVC application I decided to add another Business Layer and made the model only to have properties.

All other functionality like save to db, get from db is done on this new Business layer. So now the controller will be calling this business layer and model for various operations. Is it a good approach to design like this?

I decided not to use model for this purpose because I would need a number of models for different actions. (for eg, one for edit and other for create)

答:
If by model you mean domain model, then that is the place where business logic should reside. If you strip it from any business logic you get what's commonly referred to as a "anaemic domain model" (see www.martinfowler.com/bliki/AnemicDomainModel.html)

The gist is: your company has its own perception of a particular business domain. It has certain terms for entities, it prescribes certain behaviours to entities and interactions between them. The best way to model something like that is to actually create domain entity classes that have both state and (business) behaviour. Not by creating all sorts of services that suck up the behaviours that ordinarily are part of a domain entity.

Title: Business Logic Layer in MVC Application


问:
How to deal with the "programming blowhard"?
So I'm sure everyone has run into this person at one point or another, someone catches wind of your project or idea and initially shows some interest. You get to talking about some of your methods and usually around this time they interject stating how you should use method X instead, or just use library Y. But not as a friendly suggestion, but bordering on a commandment. Often repeating the same advice over and over like a overzealous parrot.

Personally, I like to reinvent the wheel when I'm learning, or even just for fun, even if it turns out worse than what's been done before. But this person apparently cannot fathom recreating ANY utility for such purposes, or possibly try something that doesn't strictly follow traditional OOP practices, and will settle for nothing except their sense of perfection, and thus naturally heave their criticism sludge down my ears full force. To top it off, they eventually start justifying their advice (retardation) by listing all the incredibly complex things they've coded single-handedly (usually along the lines of "trust me, I've made/used program X for a long time, blah blah blah").

Now, I'm far from being a programming master, I'm probably not even that good, and as such I value advice and critique, but I think advice/critique has a time and place. There is also a big difference between being helpful and being narcissistic. In the past I probably would have used a somewhat stronger George Carlin style dismissal, but I don't think burning bridges is the best approach anymore.

Do you have any advice on how to deal with this kind of verbal flogging?

答: Don't just let them talk. Get them in front of a keyboard. The phrase "ok, show me" should do it. My experience is most blow hards aren't that great, and when they actually try to do what they say it doesn't work and things get real quiet.</p>


问:
Writing the minimum code to pass a unit test - without cheating!
When doing TDD and writing a unit test, how does one resist the urge to "cheat" when writing the first iteration of "implementation" code that you're testing?

For example:

Let's I need to calculate the Factorial of a number.  I start with a unit test (using MSTest) something like:

```<code>[TestClass]
public class CalculateFactorialTests
{
    [TestMethod]
    public void CalculateFactorial_5_input_returns_120()
    {
        // Arrange
        var myMath = new MyMath();
        // Act
        long output = myMath.CalculateFactorial(5);
        // Assert
        Assert.AreEqual(120, output);
    }
}
</code>```

I run this code, and it fails since the CalculateFactorial method doesn't even exist.  So, I now write the first iteration of the code to implement the method under test, writing the minimum code required to pass the test.

The thing is, I'm continually tempted to write the following:

```<code>public class MyMath
{
    public long CalculateFactorial(long input)
    {
        return 120;
    }
}
</code>```

This is, technically, correct in that it really is the minimum code required to make that specific test pass (go green), although it's clearly a "cheat" since it really doesn't even attempt to perform the function of calculating a factorial.  Of course, now the refactoring part becomes an exercise in "writing the correct functionality" rather than a true refactoring of the implementation.  Obviously, adding additional tests with different parameters will fail and force a refactoring, but you have to start with that one test.

So, my question is, how do you get that balance between "writing the minimum code to pass the test" whilst still keeping it functional and in the spirit of what you're actually trying to achieve?

答:
Writing "cheat" tests is OK, for sufficiently small values of "OK".  But recall - unit testing is only complete when all tests pass and no new tests can be written that will fail.  If you really want to have a CalculateFactorial method that contains a bunch of if statements (or even better, a big switch/case statement :-) you can do that, and since you're dealing with a fixed-precision number the code required to implement this is finite (although probably rather large and ugly, and perhaps limited by compiler or system limitations on the maximum size of a procedure's code).  At this point if you really insist that all development has to be driven by a unit test you can write a test that requires the code to compute the result in an amount of time shorter than that which can be accomplished by following all the branches of the if statement.

Basically, TDD can help you write code which implements requirements correctly, but it can't force you to write good code.  That's up to you.

Share and enjoy.


问:
Are there any technical obstacles for implementing `function* ()` syntax
In Python we have yield which is very similar to that one which is proposed in ES6 (in fact, pythonic co-routines were the main source of inspiration for implementing co-routines in

I wonder what are the reasons for choosing a separate function* () syntax for generators compared to just defining "regular" functions with yeilds - just like in python by the way? I'm talking strictly of technical issues and peculiarities. Why it had been decided that a separate form will be more appropriate?

答:
Because code that uses yield normally as variable would change its meaning:

```<code>function test() {
    var yield = 3;
    return yield + 2 //in current javascript this means return 5
                     //but if yield syntax was enabled for all
                     //functions then it would secretly change meaning
}
</code>```

Body:
Because code that uses yield normally as variable would change its meaning:

function test() {
    var yield = 3;
    return yield + 2 //in current javascript this means return 5
                     //but if yield syntax was enabled for all
                     //functions then it would secretly change meaning
}


答:
In your experience, how many tasks are there in a sprint and how long should it take to
  estimate all of them? (Estimating only half of them doesn't make much sense, does it?)

This is a bit like asking how many raindrops are in a thunderstorm. There is absolutely no way to answer this question, even if you talk about two different storms of the same size. There is no rule of thumb, no matter what the team size or sprint size.

The point of estimating hours in tasks is so that the team can learn to better estimate their stories. For example, consider two stories that you have estimated: one is estimated to be a 2, and one is a 4 or 5. When you start tasking it out you realize that both have roughly the same number of hours assigned to the tasks. What does that teach you?

The only rule of thumb I think I can give is, if your team has a stable velocity, you don't need to estimate tasks. If you find that your velocity is unstable, it's likely because your estimation skills are weak. You can strengthen them by breaking down stories into tasks at planning time as a type of sanity check for your estimation.

In your question you say your team isn't there yet, so estimation is important. If that's true, don't worry about the time you spend doing it. It will take as long as it takes. You are making an investement in your team. Yes, it will take a lot of time at first, but hopefully you'll learn from the experience. You may learn it's a waste of time, or you may learn that you're not as smart about estimating as you think.

Remember: scrum isn't a set of rules you must follow, but a set of tools to help you plan and organize your work. Any time that these tools are getting in the way of your productivity, you should stop using them. Make sure they actually get in the way of your productivity rather than give the appearance of doing so.

Title: How to estimate tasks in scrum?

Body:
Let's say we have a backlog of User Stories, each with an estimated number of Story Points, and now we're doing the Sprint Planning.

Now, the Stories should be broken down into tasks and many Scrum resources suggest that each task should be estimated in person-hours. Since all questions have been discussed by the team at this point, estimating a task should not take longer than a minute. However, since a task should not be longer than a day, assuming a three week sprint with 8 developers means 120 tasks, and taking two hours only for estimations seems to be a bit much to me.

I know that experienced teams can skip or short-cut task estimations, but let's say we're not at that stage yet.

In your experience, how many tasks are there in a sprint and how long should it take to estimate all of them? (Estimating only half of them doesn't make much sense, does it?)

Clarifications:

I know the answer depends on sprint length and team size, so let's assume 8 developers and three weeks.

The numbers mentioned might be rules of thumb, but even if they are off (eg, more tasks, less time needed to estimate each) we will end up with about 2 hours for the estimation. So maybe the question should be "What percentage of the planning meeting should be reserved for pure task estimation, and don't we have better things to do?"


答:
My previous company didn't do any site blocking, but they did put a cap on bytes transferred (It was quite large, reaching it would mean you watched movies for over six hours). We had to institute it because we had a leased line, which was billed via 95'th percentile.

Every attempt at a sensible QoS implementation left people more annoyed than anything, needed constant adjustment and still didn't solve the problem of us going (consistently) way over our bandwidth commitment. And that wasn't even the real problem .. there was plenty of bandwidth to compete for. Making one thing 'slower' than another had very little effect.

To my knowledge, nobody hit the cap. But, people did restrict their recreational use of the bandwidth to a degree that it quickly became a non-issue again, because they didn't want to have to explain why they hit the cap. It turned out to be a good compromise.

I really hate the idea of blocking, period. If you want to encourage me to do stuff like have lunch at my desk .. at least let me do some recreational reading or watch a few funny videos.

Title: What is the right level of site blocking for you as a developer?

Body:
Almost all developers who work for a large corporation find themselves on the wrong side of site blocking software. It can be both frustrating ("Just let me read that damn blog!") and helpful ("Woah! Dodged a bullet with that site").

In your opinion, what is the right level of blocking to apply to developers and why?


问:
Recommended secure approach to confirming an URL is called by a legitimate caller
I'm using a CRON on AppEngine and the cron calls my web app at a specific app.

I only want to execute functionality when called by my AppEngine app.

What's is/are recommended approach to confirming that the caller is legitimate? I don't wish to rely on no one else knowing the specific URL.

答:
As explained in RESTful web service - how to authenticate requests from other services? on StackOverflow, you have to use a shared secret of some sort.

That can be a token, username and password or a client certificate for example.


答:
You can avoid having to authenticate the request from cron at all.

Create a backend; let it be named cronbackend. Mark it as private.

Move your handler that cron needs to touch to that backend.

Now the URL has changed: instead of myapp.appspot.com/url it has become cronbackend-dot-myapp.appspot.com/url. Let cron use this URL.

Since your backend is private, it is not exposed to the outside world at all; only your frontend (your application), your cron, or manager of your queues can access it. Also, handlers on a backend can run for significantly longer.

Note that a backend and a frontend look like separate apps, are deployed independently, and billed separately. This allows for added flexibility, though.

Title: Recommended secure approach to confirming an URL is called by a legitimate caller

Body:
I'm using a CRON on AppEngine and the cron calls my web app at a specific app.

I only want to execute functionality when called by my AppEngine app.

What's is/are recommended approach to confirming that the caller is legitimate? I don't wish to rely on no one else knowing the specific URL.


问:
Design Patterns - Why the need for interfaces?
OK. I am learning design patterns. Every time I see someone code an example of a design pattern they use interfaces. Here is an example:

http://visualstudiomagazine.com/Articles/2013/06/18/the-facade-pattern-in-net.aspx?Page=1

Can someone explain to me why was the interfaces needed in this example to demonstrate the facade pattern? The program work if you pass in the classes to the facade instead of the interface. If I don't have interfaces does that mean

答:
The article you referenced is a terrible example for gaining an appreciation for what makes interfaces useful. It took me a really long time before I finally had that "aha" moment on what makes interfaces useful. The reason for it was because I thought of interfaces as glorified base classes whose name is twisted to sound action oriented, just like the article you referenced. It's no wonder I had this misperception because most articles talking about interfaces do the same thing.

The problem I had with "appreciating" interfaces was that they always seemed to morph into abstract base classes because it made the most sense. The alternative was to declare the interface, declare a derived(base) class of the interface that implemented many of the common methods that the concrete derived classes all shared. It didn't make sense to have 2 classes for most every interface just to provide the plumbing when 1 would do. So the interface inevitably simply switched to being an abstract base class.

My "aha" moment happened when I realized that even though the interface name was "action-oriented" it really was just a base class by a different name. Thus, IEngineController isn't really an interface, it is an EngineControllerBase Class. What I realized was that interfaces are most useful when they aren't tied into the derived class implementation, but instead describe distinct actions or capabilities in themselves.

Thus, IEngineController would be better (and provide for a far more illustrative article) if it was called IStartStoppable OR even have 2 separate interfaces. IStartable, IStoppable. At least for me, once I got past the definining interfaces as glorified abstract base classes stage then the value of interfaces start to shine.


问:
How to deal with requirement changes in agile development model?
I know that in agile requirement changes should not only be planned for but also embraced. But I still don't know agile how to handle these changes. </p>

答:
"Responding to change over following a plan", Is one of the four points of the Agile Manifesto.

In a typical methodology, such as Scrum, there are a number of tools that help do that.
You don't deliver everything in one hit, instead deliver incrementally, incorporating feedback into the product backlog.

The Product backlog is a prioritised wish list of features that the product owner wants. Unlike a specification, this isn't fully detailed and can be changed at the product owners discretion. The highest priority items are elaborated enough such that development can be executed and may be selected for the next Sprint.

During a Sprint developers commit to deliver a selection of the high priority items and it is at this point that changes are typically locked down. A Sprint typically lasts 1-4 weeks (I most frequently see 2 week sprints). At the end of a Sprint, there should be a potentially shippable product.


问:
Convention for using super class functions and members
Is there a Convention or common way for using super class functions and members?

For example the super class has the function protected void Foo() and protected int myInt;

In subclass would I want to refer to those simply as the Foo() and myInt or as super.foo() and super.myInt . Or some other way.

答:
The only difference I can think of between using Foo() or super.Foo() is what happens if, at some time in the future, you add a method called Foo() to the subclass for some reason, overriding that in the superclass.

If you're likely to want the call to begin using the more specific overridden implementation, which is the most likely option, you would probably want to use just Foo(). If, for some reason, you want to make it explicit that the call always call the superclass function, even if gets overridden in the subclass in the future, then you can use super.Foo() to make this explicit.

Other than this I don't think there's really any difference in how you call it, other than issues of readability etc.


答:
assuming a three week sprint with 8 developers means 120 tasks, and
  taking two hours only for estimations seems to be a bit much to me.

To me this means 8 developers spending 15 minutes to plan for the next 3 weeks. That's too much? That's like a daily stand up.

It's an estimate. Plan your first sprint. Take good notes and measurements. Your first sprint will probably be way off the mark. If this is a problem, put the time and necessary steps it takes to improve the next one. Are tasks taking longer than expected? Can each dev do as many tasks in a given sprint as they expected?

Be open and honest about what was really getting done and how long it took. If people are fearful, they'll just game the system. You'll be basing your planning decisions on bad data. If too many tasks take more than a day (or whatever you thought they should take), determine if they were broken down to small enough pieces.

Your devs may not have a full 8 hours a day to work on tasks or whatever that magic number management wants to hear to feel they are getting a full days work for a full days pay.

Would it be such a horrible thing to discover after 2 weeks you completed a 3 week sprint or you only completed 75% of the tasks at the end of the sprint? Learn from the unexpected (This is estimation, so let's not dwell on them and call them mistakes.).

The goal is to make the customer happy in the context of what they want done in the given time and resources. It's not to suck the will to live out of every programmer you have to complete this project.

So to answer your question: Just do your best to estimate your first sprint. Learn from it and adjust the next one. Repeat.

Title: How to estimate tasks in scrum?


问:
How to avoid code duplication for a system which has logic that may change year wise?
What would be the way to design a system which has logic that may change year wise?
There is an application which conducts online exams.

There are five questions for a particular subject. The questions may (or may not) change year wise.

As per my current design, the questions in database are stored year wise. There are some year specific code logic as well. In order to enable the application for another year, the year specific database records and code will be copied or duplicated.

How to avoid this code duplication?

答:
It seems you are on the right path.  A better solution might be to adjust the database structure. If you store the questions and code in different tables, you would just need to point to the respective questions and code for a particular year.

Only new questions and code would need to be added to the database.


答:
I would say this is best solved by making sure that the code that is most likely to change is as decoupled as it can be.
Try to implement the front end access though a facade pattern and have the classes implement an interface that is robust so that any changes will only affect small parts of the code and are easy to swap out.</p>

Title: How to avoid code duplication for a system which has logic that may change year wise?

Body:
What would be the way to design a system which has logic that may change year wise?
There is an application which conducts online exams.

There are five questions for a particular subject. The questions may (or may not) change year wise.

As per my current design, the questions in database are stored year wise. There are some year specific code logic as well. In order to enable the application for another year, the year specific database records and code will be copied or duplicated.

How to avoid this code duplication?