问:
Application of Single Responsibility Principle on a Button
I have a class that represents a button on the screen. This class has two methods: one for click event; the other for long-click event. Both events do different things.

So, according to Single Responsibility Principle, a class must be responsible about one thing then must be only one thing that forces you to change the class. If each event is different, should I create 2 classes for each event?

In addition, does anybody has a complex example of this principle? I can only find the case of the Employee. It's easy understand, but I would like read one that is more complex.

答:
Most real world examples that I have found are either too simple or too complex to fully explain here. I would recommend looking at BlackWasp's articles on SRP. (Much of the content of that site can be summarized as shown below.)

From the man who created the term Single Responsibility Principle:

... This principle is about people.

When you write a software module, you want to make sure that when changes are requested, those changes can only originate from a single person, or rather, a single tightly coupled group of people representing a single narrowly defined business function. You want to isolate your modules from the complexities of the organization as a whole, and design your systems such that each module is responsible (responds to) the needs of just that one business function.

Why? Because we don't want to get the COO fired because we made a change requested by the CTO. Nothing terrifies our customers and managers more that discovering that a program malfunctioned in a way that was, from their point of view, completely unrelated to the changes they requested. If you change the calculatePay method, and inadvertently break the reportHours method; then the COO will start demanding that you never change the calculatePay method again.

He goes on to later re-state the SRP in simpler terms:

Another wording for the Single Responsibility Principle is:

Gather together the things that change for the same reasons. Separate those things that change for different reasons.

Wikipedia has a simpler definition:

In object-oriented programming, the single responsibility principle states that every context (class, function, variable, etc.) should have a single responsibility, and that responsibility should be entirely encapsulated by the context. All its services should be narrowly aligned with that responsibility.

Which specifically tells you that you can have a class that causes multiple other changes, based on interaction with the specified class (or button).

It goes on to give the example of a report class:

Martin defines a responsibility as a reason to change, and concludes that a class or module should have one, and only one, reason to change. As an example, consider a module that compiles and prints a report. Such a module can be changed for two reasons. First, the content of the report can change. Second, the format of the report can change. These two things change for very different causes; one substantive, and one cosmetic. The single responsibility principle says that these two aspects of the problem are really two separate responsibilities, and should therefore be in separate classes or modules. It would be a bad design to couple two things that change for different reasons at different times.


问:
How should I break this user story into tasks
I am trying to understand how to create user stories and tasks. I have read articles stating that you should create small user stories and they should be a "vertical slice" of functionality instead of a "horizontal slice".

I have a user story:

As a buyer I want to add items to the shopping cart so that I later can buy the items.

From my understanding tasks should be the things you have to do in order to complete this user story. Am I right if the tasks should also be created as "vertical slices" instead of "horizontal". Instead of creating a task for "create shopping cart model" I would have a task "Update shopping cart service to be able to add products".

But with that task I only have one task, is it to big, should it be broken down in another way? Is it bad that a user story only have one task?

答:
I think you're thinking too hard. Let's say I come to you and say "please make me a shopping cart for a website". What are you going to to? Ignore all theory and buzzwords and dogma,  what are you going to do when you sit down at a keyboard?

Tasks are just a list of the things you need to do.

Write tests

get graphic for the "add to cart" button

...

ContentLicense: CC BY-SA 3.0


答:
I agree with Ampt's comment:

If you assume that the buttons responsibility is to take in user input and call the appropriate method, then you aren't violating the SRP.

In your case it would be more important to distinguish between functionality and presentation - to separate the GUI and the code that is run when clicking the button. Event handling is part of the GUI, so it can stay there, but coupling the actual functionality of the button to the GUI I would not recommend.

This should be your SRP focus in this particular case. As it often is with SRP, keeping presentation and code apart can be very helpful. There's a reason architectures such as MVC are so popular.

Title: Application of Single Responsibility Principle on a Button

Body:
I have a class that represents a button on the screen. This class has two methods: one for click event; the other for long-click event. Both events do different things.

So, according to Single Responsibility Principle, a class must be responsible about one thing then must be only one thing that forces you to change the class. If each event is different, should I create 2 classes for each event?

In addition, does anybody has a complex example of this principle? I can only find the case of the Employee. It's easy understand, but I would like read one that is more complex.


问:
When do you change your major/minor/patch version number?

Possible Duplicate:

  What “version naming convention” do you use?

Do you change your major/minor/patch version numbers right before you release or right after?

Example: You just released 1.0.0 to the world (huzzah!). But wait, don't celebrate too much. 1.1.0 is coming out in six weeks! So you fix a bug and do a new build. What's that build called? 1.1.0.0 or 1.0.0.xxxy (where xxxy is the build number of 1.0.0 incremented)?

Keep in mind you may have 100 features and bugs to go into 1.1.0. So it might be good to call it 1.0.0.xxxy, because you're nowhere close to 1.1.0. But on the other hand, another dev may be working on 2.0.0, in which case your build might be better named 1.1.0.0 and his 2.0.0.0 instead of 1.0.0.xxxy and 1.0.0.xxxz, respectively.

答:
If you are selling software then you will have a new major release each time sales/marketing needs to earn a bigger bonus :-).

If you have some control then:

Major releases when:

There is some incompatibility with the previous release that requires conversion etc. like from Python 2 to Python 3.

There is a whole chunk of new functionality.

Minor releases for any small changes in functionality.

Patch release for bug fixes.

ContentLicense: CC BY-SA 4.0


问:
What are the common misuses of "enum" in C?
I have seen C code where people used enum heavily. But all it does is confuse others. In many places plain integers can do the same thing with less ambiguity. What are the common misuses of enum?</p>

答:
In C++ (would have posted as comment, but for the code this works better)

```<code>enum ELength
{
   mm = -3,
   m = 0,
   km = 3,
   // ...
}

double operator*(double d, ELength scale)
{
   return d * pow(10, scale);
}

// allows:
double len = 2*mm;
</code>```

Another applicaiton would be qualifiers:

```<code> enum EConstraintMode
 {
    abs   = 1,
    rel   = 2,
    expand = 3,
 };

 struct Constraint
 {
    EConstraintMode mode;
    int value;
 }

 Constraint operator-(EConstraintMode mode, int value)
 {
    Constraint c = { mode, value };
    return c;
 }

 void SetConstraints(Constraint top, Constraint Left,....) { ... }

 SetConstraint(abs-12, rel-50, abs-12, rel-50);
</code>```

I'm still undecided if this is wickedly cool, wickedly horrible, or both. (Wouldn't use that in production code, for that reason).

ContentLicense: CC BY-SA 2.5

Body:
In C++ (would have posted as comment, but for the code this works better)

enum ELength
{
   mm = -3,
   m = 0,
   km = 3,
   // ...
}

double operator*(double d, ELength scale)
{
   return d * pow(10, scale);
}

// allows:
double len = 2*mm;

Another applicaiton would be qualifiers:

 enum EConstraintMode
 {
    abs   = 1,
    rel   = 2,
    expand = 3,
 };

 struct Constraint
 {
    EConstraintMode mode;
    int value;
 }

 Constraint operator-(EConstraintMode mode, int value)
 {
    Constraint c = { mode, value };
    return c;
 }

 void SetConstraints(Constraint top, Constraint Left,....) { ... }

 SetConstraint(abs-12, rel-50, abs-12, rel-50);

I'm still undecided if this is wickedly cool, wickedly horrible, or both. (Wouldn't use that in production code, for that reason).


问:
As back-end developers, should we learn software testing?
As a junior developer, I'm working in a company that develops software for the airline industry. We have a test team, so I don't have any motivation to learn testing software. My friend is working for a small company as an back-end developer. Their team doesn't have any specific test team, and they do their tests on their own. Should a back-end developer learn about testing software?</p>

答:
Absolutely and unequivocally: yes!

It's a core skill which you will be expected to have at a large percentage of companies you'll want to work for in the future.

As a developer, the technical aspects of testing are more interesting than than the methodological ones: learn using a unit testing framework, set up automated testing, try doing test-driven development to see how you like it.

If you want to specialize in it, performance/stress testing and security/penetration testing are quite sought-after skills.


问:
Is there a difference between duck typing and structural typing?
Duck typing is deciding on the type of an object, based on the operations it supports and the attributes it owns. Structural typing is... the same thing?

What exactly is the difference?

答:
The main difference is that structural typing is enforced during static analysis found in statically typed languages, while duck typing is a runtime phenomenon emerging from the object semantics of dynamically typed languages.

As an example, take the following Haxe code (runnable here) using structural typing:

```<code>class Test {
  static function main() {
    var duck = {
      quack: function () trace('Quack!!!'),
      fly: function () trace('So let me take ... these broken wings ...')
    };
    duck.quack();
    duck.fly();
    duck.bark();
  }
}
</code>```

The above will fail to compile with saying

Test.hx:9: characters 8-17 : { quack : Void -> Void, fly : Void -> Void } has no field bark

The compiler rejects the code, because you are accessing an undefined field on a given structural type. Equivalent JavaScript code would throw the beloved runtime exception

TypeError: undefined is not a function

Because duck typing occurs at runtime, we can make another distinction when it comes to reflective programs. It is more about asking "does it?" instead of the normal "is it?" (with the usually ensuing cast). So in pseudocode:

"classical" approach:

```<code>if (is(someObject, IDuck))
  cast(someObject, IDuck).quack()
</code>```

duck typing:

```<code>if (hasMethod(someObject, 'quack'))
  someObject.quack();
</code>```

Body:
The main difference is that structural typing is enforced during static analysis found in statically typed languages, while duck typing is a runtime phenomenon emerging from the object semantics of dynamically typed languages.

As an example, take the following Haxe code (runnable here) using structural typing:

class Test {
  static function main() {
    var duck = {
      quack: function () trace('Quack!!!'),
      fly: function () trace('So let me take ... these broken wings ...')
    };
    duck.quack();
    duck.fly();
    duck.bark();
  }
}

The above will fail to compile with saying

Test.hx:9: characters 8-17 : { quack : Void -> Void, fly : Void -> Void } has no field bark

The compiler rejects the code, because you are accessing an undefined field on a given structural type. Equivalent JavaScript code would throw the beloved runtime exception

TypeError: undefined is not a function

Because duck typing occurs at runtime, we can make another distinction when it comes to reflective programs. It is more about asking "does it?" instead of the normal "is it?" (with the usually ensuing cast). So in pseudocode:

"classical" approach:

if (is(someObject, IDuck))
  cast(someObject, IDuck).quack()

duck typing:

if (hasMethod(someObject, 'quack'))
  someObject.quack();


问:
Website with a lot of sound
I am building a website with a large amount of sounds that should be played upon clicking elements. (It is a language learning website, and many words and phrases will be clickable, to hear pronunciation.)

In an earlier prototype I simply load the sounds on the page, and then play them in elements' onclick-event.

I'm worried about the overhead of loading all sounds, on every page, always, as certain pages may end up having quite a lot of them. I figure it would be way better if sounds were not loaded before the user actually clicks an element.

But then again, would this lead to too considerable waiting time between click and playback? And can I make the sound be cached, so that on consecutive playbacks it will not be loaded every time? Also, how do I go about this as elegantly, so that the markup job does not become unbearable when there are maybe a hundred or more sounds in certain pages?

What would be the best way(s) to implement this?

答:
I think you can look at a few options...

Start by Building 2 Prototypes

One prototype with all sounds pre-fetched.

One prototype with all sounds available on click.

This will allow you to actually compare if it's really that bad. Depending on how you architecture this, you probably won't need 2 separate prototype and just a configuration change (preferably with a URL request parameter, like ?sound-prefetch=false). This could come in handy later.

Local Cache

Depending on the usage of your site, it could be that a local cache would be good enough for you, if your users have modern browers supporting a local DB. Of course, this may not necessarily apply to your use case, but if it does maybe try to cache the most commonly used sounds for all users, and the recently used sounds for the current user.

Also make sure to leverage the browser's normal cache by specifying correct headers. That would work for most browsers, both modern and old.

Monitor Activity

The best way to do what's best for your users it to look at how they use your software. Do they listen to the same sounds sounds often? Do the location of the sound snippet have an impact on the likelihood of it being played (dead center of the screen, top nav bar, etc...)? Gather stats after a few days/weeks/months and see what makes the most sense to prefetch.

Compress Your Sounds

This will depend on your actual use case again, but I'd suspect that for music learning you can use pretty compressed audio files and still be able to hear quite well. So don't hesitate to crank up the compression ratios on the audio files you serve.

And by the way, what's the format of the files you serve?

How to Embed your Sounds?

How do you embed your sounds? Did you consider several approaches? You can play them using a simply JavaScript based player that will require to fetch the whole file, or maybe you can use a file format and a player that supports streaming, so that you don't need to wait for the file to be fully loaded.

Implementing your own embedded player (one for each sound), be it with JS, Applets, Flash or something else, might be a better alternative. Or maybe even a single Rich Internet Application might be a better alternative, depending on how many sounds you have per page.

Try to Give Your User a Choice

It might be best to then leverage a few of the strategies above and then give the users the chance to pick what's best for them. Your users in well-connected areas with fast broadband won't mind so much a few MBs of download per page, especially if they know what the intended purpose is, whether it's pre-fetched or not.

However, users who connect with a less than ideal bandwidth will thank you if they have the opportunity to chose how to load your pages.

Title: Website with a lot of sound


问:
More requirements in a single use case - correct?
I have been arguying with a developer who insists that 1 functional request (FR) == 1 use case (UC). I think that is nonsense as there are requirements often describing situations arising from the same point - for this the use cases have alternate flows.

For example:

```<code>FR01 - User can log in
FR02 - User's account will be locked after 3 incorrect passwords.
FR03 - Logged user can log out
</code>```

I believe all these can be nicely captured within a single use case, describing the interaction between the user and the system.

But maybe I am missing something?

EDIT: According to the book "Use Case Modeling" from Bittner, Spence:

a use case contains a set of description of requirements, the requirements
  are presented in the form of narrative rather than  an itemized list...

...

So I would say definitely more requirements can be captured within a single use case.

答:
There is no single rule to govern your situation. There are valid arguments for a single use case for all your requirements, and there are valid arguments to make each function a use case. Either is fine. Agile isn't about the methodology, it's about getting the work done.

If you can easily get all of the requirements done in a sprint, and that work can be accurately estimated, there's no need to break it down into separate stories. In fact, one could argue that doing so makes more work for the team, which is definitely not agile.

On the other hand, if some of those requirements are hard to implement and some are easy, and some you want to get into your users hands as soon as possible, breaking the story down will make your sprint easier to manager. This would result in you being able to deliver some of those features easier, which definitely is agile.

The goal is to get the work done. If doing all of that work as a single story gets you closest to that goal, do it. If making the requirements separate stores, do that.

Keep focused on your real goal, which is to deliver high quality software.


答:
Your button class does do just one thing: it manages the state of the button. The fact that the button can do multiple things or has multiple behaviors has no bearing on the single responsibility principle.

Where the principle comes to bear is in the implementation -- if the button has two behaviors, each behavior should be through a different method. Don't create one method that handles both through a series of if statements.


问:
Augmented Reality online video player
I have received a very specific requirement from a client and am not sure what solution to use.

My client would like to play an online streaming video while overlaying texts and images in a sort of augmented reality fashion. These texts and images would be tempered with/animated to fit accordingly in the video (stretched, skewed, rotated, alpha'ed etc) and these assets could possibly have to be animated TO "FOLLOW" on the videos themselves.

Therefore it would be way more than just the "average" video player.  The solution is probably to write a component that uses OpenGL but I have no "web" AR experience.

Are there any materials/research on this subject I could start with?

Last but not least, there are a few additional constraints:
- Compatibility with mobiles (Android / iOS) which prevents using Flash.
- We are just talking "web" here (no opening for mobile apps).
- Finally, I'd prefer to avoid the installation of plug-ins (i.e. Firefox plug-ins)

Thanks!

答:
WebGL

WebGL could be a solution, but mobile support is going to be rather sparse, and requires a plugin activation even for not so distant versions of modern browsers.

A Custom Video Renderer

You could probably do away with implementing a video renderer using a Canvas, though I'm not sure how much fun this would be... (Well this would quite fun as a programmer I guess, but probably not so great within the timeframe and constraints of a commercial project).

Video with Canvas Overlay

Maybe look at these blog posts for inspiration, that's mostly what I had in mind when I read your question:

http://html5doctor.com/video-canvas-magic/

https://developer.mozilla.org/en-US/docs/Web/HTML/Manipulating_video_using_canvas

It's definitely doable, though it's going to take some work. Also, make sure to clarify all these platform requirements and see what will or won't work, and to see if you can have dumbed-down alternatives for platforms you can't support (e.g. maybe just have video support and no interactivity, instead of nothing at all, etc...).

Tag Support

Tag support should be decent enough on modern platforms for <canvas> and <video>, as documented here and here, but make sure you test this properly with a quick prototype first. For instance, WebGL support isn't so great (as of October 2014), and canvas blending might also be a bit deficient (as of October 2014, it kills IE support for you). Beware of the video format you use as well.

So depending on how you want to approach this, you may have to roll out different solutions for different platforms.

Title: Augmented Reality online video player


问:
Should I bother to develop for JavaScript disabled?
Should I bother to develop for JavaScript disabled?

I feel that my time is better spent developing for the majority.

答:
There's a web-design philosophy known as Progressive Enhancement which is one you should consider. The idea is you build a basic site that is usable and workable, and then you layer onto this enhancements like jQuery and browser-specific stuff to "enhance" it. This way you get a site that works for everybody and looks nice for the majority.

If that doesn't convince you, then consider other reasons for having a site work without javascript:

It is more SEO friendly. If your site relies on JS for content and links then chances are search-engines will be ignoring large chunks of it.

Imagine you are an eCommerce site selling widgets. Now, even if only 5% of your customers disable javascript, that is a potential sales loss of 5%. Is it worth losing customers over?

Don't discriminate against the disabled. Relying on javascript means your site is not accessible and, in some cases (such as government/public sector sites), you could be breaking the law by discriminating against people.


问:
Dealing with conflicting project requirements
I tried to find an existing topic on this subject but I could not find one that was a good fit, my apologies if I was not thorough enough.

Basically we have a web application that serves multiple clients at multiple corporations (single code base - 'forked' where necessary to accommodate different needs).

This project is a fairly new one as we previously used to make a separate copy of the project per client and maintain it individually. However now that the company is growing, we are adding more staff and also attempting to minimize the code base and relying on configurations to accommodate different needs where possible, as opposed to 'forking'.

The problem I am dealing with now is that our customer relations lady (and it would appear 99% of the rest of the team) really does not understand that changing things on the fly constantly (without due consideration for the impact thereof or the conflicts that may arise) is not the right way about doing things. I mean this completely in the sense of conflicting requirements. We are pretty good at the rest (bugs, testing, scoping etc.)

For instance;
Say client X, wants a particular button red but client Y, wants the same button blue (but has possibly requested this change years after X asked for it.) Currently we just make the button blue, until X asks for it to be red again.

This is happening more regularly as our user base is growing. Even worse is when two clients in the same company want conflicting changes.

I am really just a junior developer here, but I see this problem and no one seems to be too perturbed by it, despite my constant nagging. But lately these issues have been falling into MY lap and wasting MY time.

Could anyone please suggest a way that I can try and manage these (even if just for myself).

We currently use OTRS as a client facing ticketing system (for support and requests) and VSO (TFS) for internal tasks and bugs (sometimes created as part of an OTRS request).

I administer both systems, but currently trying to find when last a request came in from a particular client to change a particular button to a particular color in version control history or tickets/emails is just not a very comprehensive nor efficient solution (also the button/color analogy is a really simplified version).

I am just starting to feel like we are headed round in circles and are eventually just going to crash.

答:
It sounds as if your problem isn't one of unclear requirements but instead of a missing role that you need on your team.  What you need is a Product Owner.

Communication is a main function of the product owner. The ability to convey priorities and empathize with team members and stakeholders are vital to steer the project in the right direction. Product owners bridge the communication gap between the team and their stakeholders. As Figure 1 shows, they serve as a proxy stakeholder to the development team and as a project team representative to the overall stakeholder community.

Quoted from Wikipedia, sources: Pichler, Roman. Agile product management with Scrum : creating products that customers love. Upper Saddle River, NJ: Addison-Wesley, 2010.

In your case specifically where you have multiple clients as stakeholders each with competing and conflicting demands, the product owner acts as a proxy and steers software requirements to deliver maximum value to all clients.  Consider the following user story from Client A:

As a [user] I need the Submit button on form A to be Blue, so that I can appease my need to see blue buttons.

Now client B has a conflicting requirement:

As a [user] I need the Submit button on form A to be Red, so that I can satisfy my hatred for the color blue.

The Product Owner listens to both stakeholder needs and decides:

As a [user] I need the Submit button color to be configurable to my needs, so that I can see my favorite color on form A.

For the development team you don't even need to know or care about the fact that Client A loves Blue and Client B despises Blue.  Your product owner for all intents and purposes is the business for you.

You are very astute for a junior developer to realize how chaotic it can be to formulate a product for different customers without a product owner.  This can cause a number of problems:

The need to fork for different customer needs.

Needing to fix bugs in many different places as each customer has a different codebase

The accumulation of technical debt which makes bug fixes and new feature development exponentially more expensive.

Why doesn't the business see the need for this then?

Sales doesn't necessarily care that developments job is harder and more prone to errors.  Your team may be very good at putting in extra effort and being vigilant about dealing with technical debt making the problems harder for them to see.

Sales isn't necessarily promising customers an OOB (Out-of-Box) software. They may very well be more interested in providing custom development to their customers than building a product.

Point 2 has an interesting facet when you consider that many ISV's make the majority of their profits on specialty or niche markets with a handful of clients.  This market might be more captive so software quality isn't as important.  Also profits year after year are more likely to come from support contracts than any other source of income.  The initial license purchase is just icing on the cake.  Sales in this case is less likely to try to appeal to a broader market and more about managing relationships with the handful of important clients that they do have.


问:
What should config files and the bootstrap do?
I already read dozens of articles and questions/answers on SO and Programmers but I can't understand what config and bootstrap files are, in the context of a web application.

So my questions are :

What information should I put in config files?

What should my bootstrap process do?

How should I call in to my applications code?

答:
Well, according to my experience of making a website, config.php is all about the connection on how to connect your database to your website.. MySQL, sql server etc.. bootstrap.php.. Mmm, I think this is a plugin which I found in some website.

Actually, config.php can be call, depends on your php files needed to be connect to a database.

Here's my code of config.php:

```<code><?php
$mysql_hostname = "127.0.0.1";
$mysql_user = "root";
$mysql_password = "";
$mysql_database = "sfac_als";

$link=mysql_connect($mysql_hostname,$mysql_user,$mysql_password) or die(mysql_error());
 $db=mysql_select_db($mysql_database) or die(mysql_error());
?>
</code>```

In this case, there's my example of config.php, where, you can see the name of database, which you are connecting to.

Body:
Well, according to my experience of making a website, config.php is all about the connection on how to connect your database to your website.. MySQL, sql server etc.. bootstrap.php.. Mmm, I think this is a plugin which I found in some website.

Actually, config.php can be call, depends on your php files needed to be connect to a database.

Here's my code of config.php:

<?php
$mysql_hostname = "127.0.0.1";
$mysql_user = "root";
$mysql_password = "";
$mysql_database = "sfac_als";

$link=mysql_connect($mysql_hostname,$mysql_user,$mysql_password) or die(mysql_error());
 $db=mysql_select_db($mysql_database) or die(mysql_error());
?>

In this case, there's my example of config.php, where, you can see the name of database, which you are connecting to.


问:
Is it possible to have a dynamically typed language without duck typing?
This question has been asked here, but received poor answers and didn't clarify the issue. I believe it justifies asking it again.

I understand that you can have duck typing with either dynamically typed languages or with statically typed ones (but examples for these are rare, such as C++'s templates).

However I'm not sure if there is such a thing as a dynamically typed language without duck typing.

Duck typing means that the type of an object is based on the operations and attributes it has at a given point in time. Is there a way to do dynamic typing without inevitably supporting duck typing?

Let's look at this Python code for exampe:

```<code>def func(some_object)
    some_object.doSomething()

something = Toaster()
func(something)
</code>```

In dynamically typed languages, the type of an object is only known at run time. So when you try to do an operation on it (e.g. some_object.doSomething()), the runtime has only one choice - which is to check whether or not the type of some_object supports doSomething(), which is exactly what duck typing is.

So is it possible to have a dynamically typed languages without duck typing? Please explain.

答:
Apparently (from what I read) Duck typing has meaning only in an
object oriented context, when functions are attached as methods to
objects. Then when you write duck.quacks(3), this will work if the
current value of duck has the method quacks.

Dynamic typing is not necessarily attached to an OO view with methods.

You can define the type real with associated operator or function
+: real*real->real, and the type rational with the associated
operator +: rational*rational->rational. Then if you write a+b, in
a dynamically checked time system, both your variables aand b may
have a + operator, but you get a run-time type error.

Dynamic typing checks for categorial consistency of values, possibly
several of them.

Duck typing checks for behavioral consistency of the code with an
object at hand (a single one, as far as I understand it).

In a sense duck typing is a form of runtime polymorphism, except for
the fact that it applies only to access methods of a single object.

However, one could possibly define a more general form of run-time
polymorphism, where the operator + to be executed would be
determined on the basis of all arguments. So that a duck and a chicken
could danse together if they share a common danse function. They could
have several so that ducks can danse also with geese with a different
function. But that seems a bit complicated. As far as I remember,
something of the kind (with probably more structure) may have been
possible with the generic functions of the language EL1, a very old
forerunner of object oriented languages.


问:
Use git to manage different deployments of the same repo
I have a web application built in PHP. I want to use Git to manage the different aspects of the deployment.

Some of the files in the web app are specific to a client (logos, database connection string, user uploaded files (ckfinder), etc. The rest is the same for everyone.

The application is heavy so I'm afraid to make it a Saas. Instead each client has his own vps. I used to have (in the past) a branch for dev a branch for production and so on.

So I was thinking to have a branch for each client. Is this a good idea?
Also I wanted to have in my local machine a different folder containing files for each client (including the common files).

PS: I reviewed many other questions and all the others questions are very similar but the answers are not what I'm looking for.

答:
Having a branch per customer is not an ideal solution, for a couple of reasons:

It doesn't scale well. You will have to create a new branch for each customer, and then manage merging code changes between all those branches. And, when you actually do need a branch for a legitimate reason (feature branch, production fix, etc.), you'll have to branch all those customer branches! Too complicated.

Logically, creating customer branches in most cases mixes up the roles of the source control system and your deployment or product management mechanisms.

A better solution would be to segregate all the possible files that are different per-customer. E.g., create a resources directory, with sub-directories for each customer containing their respective logos, connection string files, etc. Then, look into deployment tools such as Puppet, Chef, Ansible, etc. and create scripts to copy each customer's resources into their web server location when you're ready to update their site.

This way, resources are physically separated, and your processes are logically separated (source stays in Git, deployment practice is codified in script(s)) so you have artifacts representing your production pipeline.

HTH


答:
First, to make sure we're talking about the same things, I would start with some definitions.

Static typing means that type errors are reported at compile time, while dynamic typing means that type errors are reported at runtime.

Duck typing means that a piece of code requires that an object supports the operations that are used and nothing more.

Structural typing requires that an object supports a given set of operations (even if some of them may not be used).

Nominal typing requires that object is exactly of the given type, or is a subtype of that type.

So, as you can see, structural typing is stricter than duck typing and nominal typing is stricter than structural.

Now, I'm going to talk about the TypeScript language, because it nicely illustrates most of these options.

Consider the following TypeScript program:

```<code>interface Person {
    Name : string;
    Age : number;
}

function greet(person : Person) {
    alert("Hello, " + person.Name);
}

greet({ Name: "svick" });
</code>```

Since the object that's passed to greet doesn't have the Age property, this causes a compile time error, demonstrating that TypeScript uses static structural typing.

Despite the error, the code above actually compiles to the following JavaScript, which runs fine:

```<code>function greet(person) {
    alert("Hello, " + person.Name);
}

greet({ Name: "svick" });
</code>```

This shows that TypeScript also uses dynamic duck typing.

If the code instead compiled to something like:

```<code>function greet(person) {
    if (!(typeof(person.Name) == 'string' && typeof(person.Age) == 'number'))
        throw 'TypeError';

    alert("Hello, " + person.Name);
}
</code>```

Then that would be an example of dynamic structural typing, because it checks that the object has the required properties of the required types, even if the function itself doesn't require them.

If it compiled to:

```<code>function greet(person) {
    if (!(person instanceof Person))
        throw 'TypeError'

    alert("Hello, " + person.Name);
}
</code>```

That would be an example of dynamic nominal typing, because it checks the name of the type of the object, not its structure.

What this all shows is that dynamic non-duck typing is possible (both structural and nominal). But this approach isn't used very often, because it mostly combines the disadvantages of non-duck typing (you have to specify types explicitly; less flexible) and dynamic typing (type errors only show at runtime and only in the code that actually runs).

If you're going to add type annotations to make non-duck typing possible, you might as well check the types at compile time.

Title: Is it possible to have a dynamically typed language without duck typing?

Body:
This question has been asked here, but received poor answers and didn't clarify the issue. I believe it justifies asking it again.

I understand that you can have duck typing with either dynamically typed languages or with statically typed ones (but examples for these are rare, such as C++'s templates).

However I'm not sure if there is such a thing as a dynamically typed language without duck typing.

Duck typing means that the type of an object is based on the operations and attributes it has at a given point in time. Is there a way to do dynamic typing without inevitably supporting duck typing?

Let's look at this Python code for exampe:

```<code>def func(some_object)
    some_object.doSomething()

something = Toaster()
func(something)
</code>```

In dynamically typed languages, the type of an object is only known at run time. So when you try to do an operation on it (e.g. some_object.doSomething()), the runtime has only one choice - which is to check whether or not the type of some_object supports doSomething(), which is exactly what duck typing is.

So is it possible to have a dynamically typed languages without duck typing? Please explain.

Body:
First, to make sure we're talking about the same things, I would start with some definitions.

Static typing means that type errors are reported at compile time, while dynamic typing means that type errors are reported at runtime.

Duck typing means that a piece of code requires that an object supports the operations that are used and nothing more.

Structural typing requires that an object supports a given set of operations (even if some of them may not be used).

Nominal typing requires that object is exactly of the given type, or is a subtype of that type.

So, as you can see, structural typing is stricter than duck typing and nominal typing is stricter than structural.

Now, I'm going to talk about the TypeScript language, because it nicely illustrates most of these options.

Consider the following TypeScript program:

interface Person {
    Name : string;
    Age : number;
}

function greet(person : Person) {
    alert("Hello, " + person.Name);
}

greet({ Name: "svick" });

Since the object that's passed to greet doesn't have the Age property, this causes a compile time error, demonstrating that TypeScript uses static structural typing.

Despite the error, the code above actually compiles to the following JavaScript, which runs fine:

function greet(person) {
    alert("Hello, " + person.Name);
}

greet({ Name: "svick" });

This shows that TypeScript also uses dynamic duck typing.

If the code instead compiled to something like:

function greet(person) {
    if (!(typeof(person.Name) == 'string' && typeof(person.Age) == 'number'))
        throw 'TypeError';

    alert("Hello, " + person.Name);
}

Then that would be an example of dynamic structural typing, because it checks that the object has the required properties of the required types, even if the function itself doesn't require them.

If it compiled to:

function greet(person) {
    if (!(person instanceof Person))
        throw 'TypeError'

    alert("Hello, " + person.Name);
}

That would be an example of dynamic nominal typing, because it checks the name of the type of the object, not its structure.

What this all shows is that dynamic non-duck typing is possible (both structural and nominal). But this approach isn't used very often, because it mostly combines the disadvantages of non-duck typing (you have to specify types explicitly; less flexible) and dynamic typing (type errors only show at runtime and only in the code that actually runs).

If you're going to add type annotations to make non-duck typing possible, you might as well check the types at compile time.


问:
Do you spend your effort to reuse obsolete unit tests or rewrite them entirely?
I have this javascript project which has a unit test suite(about 200unit tests) that covers about 11.31% of the code that it was testing. The project has evolved greatly but the unit tests where never updated since. Now, I have two options:

Spend some time to update the existing unit tests and then write new unit tests for the rest of the code.

Rewrite Unit Tests for the entire project from scratch.

Also, only about 10% of those initial unit tests pass now.

Thoughts?

答:
Testing code is still code, intended to accomplish some function. That it's a "back room" or "back stage" function is just a detail.

Now, you have a codebase with 200 functions, that minimally accomplishes the coverage you need, and only 10% works. If this were a user-facing codebase, you'd probably conclude it wasn't worth updating as-is, where-is. That a clean slate--perhaps using more up-to-date tooling, or with new test cases more eagerly and completely covering what the module has become--would be the right way to go.

You might not need to "throw away" everything. 10% of the tests still pass, so you might start with those and cull the rest. Or at least scan and learn from existing tests (both working and possibly ones that aren't working, but might be close). My experience suggests you might find this "learning from, and occasionally copying from" the old test base accelerates your new test development. But with such a low-coverage, low-passing test base, starting with it seems more trouble and difficulty than it's worth.


问:
Is checking for cin.eof() really necessary?
I have written a simple program that reads character input from the keyboard within a For loop. My professor has taken away 10 points for not checking the input using cin.eof. I don't understand why this is necessary? Presumably any non-integer character should be acceptable. The prof specifically said not to check for integers.

I ran the program using Visual Studio 10, and entered CTRL-Z as input. The program quit anyway even though I did not specifically code for the EOF condition. Can someone explain why? And is the professor correct insisting to check for cin.eof or is this antiquated style?

Here is an example code snippet:

```<code>cout << "Enter a list of 10 words" << endl;

for (i= 0;i< MAX; i++) {
    getline(cin, input);
    Word word(input);
    noun_array[nElements]= word;
}
</code>```

答:
I ran the program using Visual Studio 10, and entered CTRL-Z as input.
  The program quit anyway even though I did not specifically code for
  the EOF condition. Can someone explain why?

The program doesn't quit.

The end-of-file character (CTRL-Z on the keyboard) sets the internal state flag of std::cin to eofbit, which must be cleared with basic_ios::clear() before following calls to getline will work properly.

The loop is executed MAX times but getline won't append characters to input.

I'm not sure this is what you want. If it works, it's probably a matter of luck.

How to check? eof() has some downsides:

Both eof() and feof() check the state of an input stream to see if an
  end-of-file condition has occurred. Such  a condition can only occur
  following an attempted read operation. If you call either function
  without previously performing a read, your code is wrong! Never loop
  on an eof function.

(From All about EOF)

The EOF state may not get set until after a read is attempted past the end of file. That is, reading the last byte from a file might not set the EOF state.

Moreover

```<code>if (!std::cin.eof())
</code>```

will test for end-of-file, not for errors.

You should prefer:

```<code>if (getline(std::cin, input))
{
  // ...
}
</code>```

See also C++ FAQ Section 15.5 and How to determine whether it is EOF when using getline() in c++?

EDIT

It should be something like:

```<code>std::cout << "Enter a list of 10 words" << std::endl;

for (unsigned i(0); i < MAX && std::getline(std::cin, input); ++i)
{
  // ...
  // Word word(input);
  // noun_array[nElements] = word;
  // ...
}
</code>```

This way the program performs its processing only with a valid input.

Body:
I ran the program using Visual Studio 10, and entered CTRL-Z as input.
  The program quit anyway even though I did not specifically code for
  the EOF condition. Can someone explain why?

The program doesn't quit.

The end-of-file character (CTRL-Z on the keyboard) sets the internal state flag of std::cin to eofbit, which must be cleared with basic_ios::clear() before following calls to getline will work properly.

The loop is executed MAX times but getline won't append characters to input.

I'm not sure this is what you want. If it works, it's probably a matter of luck.

How to check? eof() has some downsides:

Both eof() and feof() check the state of an input stream to see if an
  end-of-file condition has occurred. Such  a condition can only occur
  following an attempted read operation. If you call either function
  without previously performing a read, your code is wrong! Never loop
  on an eof function.

(From All about EOF)

The EOF state may not get set until after a read is attempted past the end of file. That is, reading the last byte from a file might not set the EOF state.

Moreover

if (!std::cin.eof())

will test for end-of-file, not for errors.

You should prefer:

if (getline(std::cin, input))
{
  // ...
}

See also C++ FAQ Section 15.5 and How to determine whether it is EOF when using getline() in c++?

EDIT

It should be something like:

std::cout << "Enter a list of 10 words" << std::endl;

for (unsigned i(0); i < MAX && std::getline(std::cin, input); ++i)
{
  // ...
  // Word word(input);
  // noun_array[nElements] = word;
  // ...
}

This way the program performs its processing only with a valid input.


答:
Duck typing is depending upon objects responding to operations (aka messages or method invocations) in a way that's appropriate to them. "If it quacks like a duck, it's sufficiently duck-like to ask it to do duck things."

For example, in Python a dict object has an update method. I can code other kinds of objects that also have an update method:

```<code>class Able(object):
    def update(self, data):
        self.data = data

class Count(object):
    def update(self, increment):
        self.count += increment
        self.times_updated += 1
</code>```

Now dict, Able, and Count instances respond to update, but they do it in ways that are appropriate to themselves.

Some languages (e.g. Python, Ruby) are very duck-typing friendly, while others (e.g. Java) are not. @back2dos gave an excellent example of structural typing, the ways the compiler will flag calls that are not explicitly defined, and the common requirement for explicit type casting in duck-unfriendly languages. Duck languages like Python check method availability at runtime (dynamically) rather than at compile-time. More important, from a usability point of view, is that they do not require type-casting to use specific methods. Any method (or property) may be requested of any object at any time. More than just "syntactic sugar," this permissiveness is what makes duck typing easy and useful.

Final point: Duck typing is not just a language feature, it's also an idiom and style of use--a feature of the programming language community and ethos, not just the language specification and compiler.

Title: Is there a difference between duck typing and structural typing?

Body:
Duck typing is deciding on the type of an object, based on the operations it supports and the attributes it owns. Structural typing is... the same thing?

What exactly is the difference?

Body:
Duck typing is depending upon objects responding to operations (aka messages or method invocations) in a way that's appropriate to them. "If it quacks like a duck, it's sufficiently duck-like to ask it to do duck things."

For example, in Python a dict object has an update method. I can code other kinds of objects that also have an update method:

class Able(object):
    def update(self, data):
        self.data = data

class Count(object):
    def update(self, increment):
        self.count += increment
        self.times_updated += 1

Now dict, Able, and Count instances respond to update, but they do it in ways that are appropriate to themselves.

Some languages (e.g. Python, Ruby) are very duck-typing friendly, while others (e.g. Java) are not. @back2dos gave an excellent example of structural typing, the ways the compiler will flag calls that are not explicitly defined, and the common requirement for explicit type casting in duck-unfriendly languages. Duck languages like Python check method availability at runtime (dynamically) rather than at compile-time. More important, from a usability point of view, is that they do not require type-casting to use specific methods. Any method (or property) may be requested of any object at any time. More than just "syntactic sugar," this permissiveness is what makes duck typing easy and useful.

Final point: Duck typing is not just a language feature, it's also an idiom and style of use--a feature of the programming language community and ethos, not just the language specification and compiler.


问:
Design - Parser.hasInfo(MyClass) vs MyClass.hasInfo()
I'm working on a document processing system.

I feel confident with a Document class which represents each document being processed.

The issue:

Each Document can have a CoverSheet, and if it does, we need to get CoverSheetInfo from this CoverSheet (for renaming and processing). But checking for a CoverSheet and coercing the info into CoverSheetInfo involves a fair amount of Apache PDFBox code.

I'm trying to decide on the best place to have this functionality.

Option 1

Document class will have these methods:

public boolean hasCoverSheet()

public CoverSheetInfo getCoverSheetInfo()

Pros:

Behavior is close to the data -- the process of checking a Document for a CoverSheet takes place in Document which seems sensible.

Cons:

This adds a lot of PDFBox - related parsing lines which make the other-wise simple set-get Document look cluttered and makes the Document class exceed 300 lines to include this functionality. Thus Option 2...

Option 2

Create a DocumentParser class which would have:

public boolean hasCoverSheet(Document document)

public CoverSheetInfo getCoverSheetInfo(Document document)

Pros:

All the PDFBox - specific parsing code is in it's own Class. I think this is a good example of enforcing Single Responsibility/Law of Demeter As I don't think Document should necessarily know how to parse information from cover sheets.

Cons:

Awkward(?) separation of behavior from data(?)

Which one seems most reasonable and how so?

Edit: I'm desperate. Any feed back would be absolutely. fricken. loved.

Edit 2

A Document is in this case a scanned mortgage document, and it will always be a PDF. A Document is created when my app finds files in a directory (one Document is made for each file found). DocumentParser should process Documents, right, File was a typo.

At this point, Document is just a wrapper around the File essentially. In Option 1, it would have CoverSheetInfo as a field and File stubFile as well as boolean regarding the existence of these things.

Here's the "story" for what I'm doing:

Someone will scan a document. It will end up in a directory. My app needs to look at that directory, and

rename the files by their cover sheet (if they have one)

make a stub out of the first 8 pages (if the file is very large)

Upload these files (and any stubs made) to Google Drive.

答:
As far as I understood,  the cover page is an important property of a document in your application. Then I'd represent it with a getter. The business classes dealing with renaming the document then only need the Document object and have no dependency to a parser which they do not care about.

How that getter is implemented is a different question. You could for example provide a mock implementation that provides a pre-defined cover page for unit testing. To solve the problem of a long class with multiple responsibilities, you could extract the parsing code to a separate class that is used by the real Document implementation.

To go one step further, the parser instance could be provided to the Document constructor. That's called dependency injection and decoples the parser from the document, so that other parsers could be used. For exapmle, the unit test of Document can use a mock implementation of the parser. There are frameworks like weld which essentially provide a factory to create classes without knowing the exact dependency (i.e. the parser).


答:
An answer by analogy:

Can you buy a convertible and never put the top down? Sure. It's probably not the best way to spend your resources, since you're paid extra for some features (e.g. convertible top, extra structural stiffening due to lack of roof as structural element) and gotten some worse results (e.g. extra road noise, possibly lower crash safety, smaller storage compartments) as a result of investing in that feature you won't use. But it's technically feasible.

It's the same with dynamic languages and duck typing. You've given up the higher efficiency and the compile-time type safety assurances of static languages. For what? Generally for the simplicity of duck typing. Variables and collections can hold anything, and you don't need to do a lot of up-front specifying just what. Mixed collections like [ 12, "gumbo", 12.4, 4+4j ] (an integer, a string, a floating point value, and a complex value) are trivial, and  you don't have the constant type-casting you see in Java code (for example).

It's possible in a dynamic language like Python to create objects that are not duck-typed:

```<code>class Hungarian(object):
    self __init__(self):
        self.value = []
    self addInt(self, intValue):
        self.value.append(intValue)
    self addFloat(self, floatValue):
        self.value.append(floatValue)
    self addComplex(self, complexValue):
        self.value.append(complexValue)
    # ...
</code>```

But as you might notice, there's no real checking of the types, and each of the methods is implemented with a duck-typed built-in structure (list). Having paid the price for dynamism, you might as well put the top down and get the resulting simplicity:

```<code>class NotHungarian(object):
    def __init__(self):
        self.value = []
    def add(self, whatever):
        self.value.append(whatever)
</code>```

Body:
An answer by analogy:

Can you buy a convertible and never put the top down? Sure. It's probably not the best way to spend your resources, since you're paid extra for some features (e.g. convertible top, extra structural stiffening due to lack of roof as structural element) and gotten some worse results (e.g. extra road noise, possibly lower crash safety, smaller storage compartments) as a result of investing in that feature you won't use. But it's technically feasible.

It's the same with dynamic languages and duck typing. You've given up the higher efficiency and the compile-time type safety assurances of static languages. For what? Generally for the simplicity of duck typing. Variables and collections can hold anything, and you don't need to do a lot of up-front specifying just what. Mixed collections like [ 12, "gumbo", 12.4, 4+4j ] (an integer, a string, a floating point value, and a complex value) are trivial, and  you don't have the constant type-casting you see in Java code (for example).

It's possible in a dynamic language like Python to create objects that are not duck-typed:

class Hungarian(object):
    self __init__(self):
        self.value = []
    self addInt(self, intValue):
        self.value.append(intValue)
    self addFloat(self, floatValue):
        self.value.append(floatValue)
    self addComplex(self, complexValue):
        self.value.append(complexValue)
    # ...

But as you might notice, there's no real checking of the types, and each of the methods is implemented with a duck-typed built-in structure (list). Having paid the price for dynamism, you might as well put the top down and get the resulting simplicity:

class NotHungarian(object):
    def __init__(self):
        self.value = []
    def add(self, whatever):
        self.value.append(whatever)


答:
Why not have a separate CoverSheet object? Then you can cleanly do

```<code>CoverSheetInfo coverInfo = null;
if(theDocument.hasCoverSheet()) {
    CoverSheet cover = theDocument.getCoverSheet();
    coverInfo = cover.getInfo();
}
</code>```

Sorry, I'm not familiar with PDFBox, so I don't know if this introduces more complexity than it solves, but (IMHO) it's a much cleaner design.

Title: Design - Parser.hasInfo(MyClass) vs MyClass.hasInfo()

Body:
I'm working on a document processing system.

I feel confident with a Document class which represents each document being processed.

The issue:

Each Document can have a CoverSheet, and if it does, we need to get CoverSheetInfo from this CoverSheet (for renaming and processing). But checking for a CoverSheet and coercing the info into CoverSheetInfo involves a fair amount of Apache PDFBox code.

I'm trying to decide on the best place to have this functionality.

Option 1

Document class will have these methods:

public boolean hasCoverSheet()

public CoverSheetInfo getCoverSheetInfo()

Pros:

Behavior is close to the data -- the process of checking a Document for a CoverSheet takes place in Document which seems sensible.

Cons:

This adds a lot of PDFBox - related parsing lines which make the other-wise simple set-get Document look cluttered and makes the Document class exceed 300 lines to include this functionality. Thus Option 2...

Option 2

Create a DocumentParser class which would have:

public boolean hasCoverSheet(Document document)

public CoverSheetInfo getCoverSheetInfo(Document document)

Pros:

All the PDFBox - specific parsing code is in it's own Class. I think this is a good example of enforcing Single Responsibility/Law of Demeter As I don't think Document should necessarily know how to parse information from cover sheets.

Cons:

Awkward(?) separation of behavior from data(?)

Which one seems most reasonable and how so?

Edit: I'm desperate. Any feed back would be absolutely. fricken. loved.

Edit 2

A Document is in this case a scanned mortgage document, and it will always be a PDF. A Document is created when my app finds files in a directory (one Document is made for each file found). DocumentParser should process Documents, right, File was a typo.

At this point, Document is just a wrapper around the File essentially. In Option 1, it would have CoverSheetInfo as a field and File stubFile as well as boolean regarding the existence of these things.

Here's the "story" for what I'm doing:

Someone will scan a document. It will end up in a directory. My app needs to look at that directory, and

rename the files by their cover sheet (if they have one)

make a stub out of the first 8 pages (if the file is very large)

Upload these files (and any stubs made) to Google Drive.

Body:
Why not have a separate CoverSheet object? Then you can cleanly do

CoverSheetInfo coverInfo = null;
if(theDocument.hasCoverSheet()) {
    CoverSheet cover = theDocument.getCoverSheet();
    coverInfo = cover.getInfo();
}

Sorry, I'm not familiar with PDFBox, so I don't know if this introduces more complexity than it solves, but (IMHO) it's a much cleaner design.


答: Testing the code you are working on is part of the discipline that makes a good programmer into a great programmer. Setting up automatic testing, using light-weight, fast test cases allows you to establish a base-line of functionality; modifying the code to fix errors or add new functionality can be incrementally tested and gives you rapid feedback on your code. This rapid feedback, when done frequently, is much more efficient in terms of re-work than building it all, compiling and testing, because you end up not going so far off the right path.</p>

Title: As back-end developers, should we learn software testing?

Body: As a junior developer, I'm working in a company that develops software for the airline industry. We have a test team, so I don't have any motivation to learn testing software. My friend is working for a small company as an back-end developer. Their team doesn't have any specific test team, and they do their tests on their own. Should a back-end developer learn about testing software?</p>


问:
Ensure that a method of a class is called after every method call of the same class, how?
I have twenty small methods (m1, m2, m3, etc..) in a class quite different between each other, and after every method i would like to do some common actions, like increasing some counters and in the case write those counters to a file. Let's call those actions ACT.

I know that I can create a method that does ACT, but then I need to call it from every other method. That is, from m1 I should call ACT as last method, from m2 I should call ACT as last method, and so on.

Is there a way to say "if someone call this list of methods of this class (i.e: m1, m2, m3 ...), please after that call that method (i.e: ACT) automatically" ? Because AFAIK is not possible.

答:
AOP is good approach to solve your problem.

But I advice you to examine your class. Twenty small methods quite different between each other in a class is a little code smell. I think your class probably violate single responsibility principle.

http://en.wikipedia.org/wiki/Single_responsibility_principle


问:
Does GCC optimize code to remove useless variable read operations?
I'm using GCC on ununtu 14.04. My program is written in c++ and in a case i need to check the amount of time the program needs to read a large integer array. what is the best way to do this without causing unnecessary compiler optimization?</p>

答:
It will optimize the reads out if it sees the result is unused, even more if the compiler sees the entire loop body is empty the entire loop may become optimized away.

You will need to do another operation with the result to ensure the reads remain. Xoring the integers together is a simple example, calling a function with it as a parameter that the compiler can't optimize away (because it may have side effects).

Having said all that just reading the array is not a useful metric in itself.


问:
Getting non-programmers to understand the development process
When starting a project for a company that's not primarily a programming company, one of the expectations is that there's a finished product at the end free of all bugs and does everything needed right away. However, that's rarely the case.

What are some ways to manage expectations and explain to non-programmers how software development differs from other types of product development?

答:
Pretty much everybody with a computer has encountered the concept of "bugs" these days, so you might start there.  "What's the most annoying way an application has ever failed on you?  Multiply that by ten, and you'll have our users' experience if we don't devote enough resources to testing and maintenance."

And don't underestimate the value of establishing a good working relationship with the non-programmers.  If you can establish that your judgment may be trusted, they'll take you seriously when you sound the alarm that X is going to fail spectacularly if you don't do Y pronto, even if they don't completely understand your reasoning.


问:
Is there any hard data on the (dis-)advantages of working from home?
Is there any hard data (studies, comparisons, not-just-gut-feel analysis) on the advantages and disadvantages of working from home?

My devs asked about e.g. working from home one day per week, the boss doesn't like it for various reasons, some of which I agree with but I think they don't necessarily apply in this case.

We have real offices (2..3 people each), distractions are still common. IMO it would be beneficial for focus, and with 1 day / week, there wouldn't be much loss at interaction and communication. In addition it would be a great perk, and saving the commute.

Related: Pros and cons of working remotely / from home  (interesting points, but no hard facts)

To clarify: it's not my decision to make, I agree that there are pro's and con's depending on circumstances, and we are pushing for "just try it". I've asked this specific question because (a) facts are a good addition to thoughts in arguing with an engineer boss, and (b) we, as developers, should build upon facts like every respectable trade.

答:
I used to run an IT department for a small business in Florida, where hurricane strikes were a very real threat.  After our first very-near miss, we started getting a lot of inquires from our customers about our disaster preparedness plans. So, we started looking at telecommuting as an integral part of our company's disaster preparedness. In the event of a looming hurricane, we figured that employees would start leaving town one to three days before a hurricane, and would stay out of town, or at least stay away from the office for perhaps weeks afterwards.  If we could largely run the business via telecommuting employees, then the company would survive as long as people could find internet access, which could be at a hotel, a relative's house, wireless air cards, etc.,   This tipped the business case from just "provides-focus" and "good for moral", to "essential to keeping customers" and "will keep the company in business."

The business continuity focus of telecommuting made it inherently easier to justify telecommuting related funds, too.  This focus also helped shift the culture of the company since upper management took a real interest the ability of the company to run in a distributed fashion.  It also removed a fundamental stress in the daily reality faced by many businesses, which is whether the business can survive a disaster.  Well, for us, a real hurricane strike would not of been pretty, or easy, but it would been survivable.

This line of reasoning doesn't apply to every company, of course.

BTW - Our shift in having a good telecommuting system also became an important employee recruiting and retention tool.  It also eased the management's conscience since we could not encourage employees to leave town, if needed,  without having a choice between safety and business operations.


答:
I agree with maple_shaft that you have a missing role but I don't agree on the same role. What you are missing is the program technical lead (or whatever title you want to call them). Assuming each client is considered a separate project then the program technical lead is responsible for knowing what's going on with all the various projects.

One of the technical lead's responsibilities is to ensure that the various projects don't step on each other. Thus, all changes should be done on a forked branch which can't get merged into the main branch until the impacts on other projects is assessed, rectified and approved by the technical lead.

Of course that won't work if the technical lead doesn't have the authority to get the other developers to redo their work because of its impacts and/or isn't vigilant in ensuring that the forks are merged into the main branch in a timely manner. If the attitude is constantly "we'll merge it later when we have time" then it can't work because you'll never have time and the codebase will have diverged far too much if you ever do get time. But, doing software effectively over the long term requires quite a bit of discipline. If you don't have that then there's no methodology that will help you.

Title: Dealing with conflicting project requirements

Body:
I tried to find an existing topic on this subject but I could not find one that was a good fit, my apologies if I was not thorough enough.

Basically we have a web application that serves multiple clients at multiple corporations (single code base - 'forked' where necessary to accommodate different needs).

This project is a fairly new one as we previously used to make a separate copy of the project per client and maintain it individually. However now that the company is growing, we are adding more staff and also attempting to minimize the code base and relying on configurations to accommodate different needs where possible, as opposed to 'forking'.

The problem I am dealing with now is that our customer relations lady (and it would appear 99% of the rest of the team) really does not understand that changing things on the fly constantly (without due consideration for the impact thereof or the conflicts that may arise) is not the right way about doing things. I mean this completely in the sense of conflicting requirements. We are pretty good at the rest (bugs, testing, scoping etc.)

For instance;
Say client X, wants a particular button red but client Y, wants the same button blue (but has possibly requested this change years after X asked for it.) Currently we just make the button blue, until X asks for it to be red again.

This is happening more regularly as our user base is growing. Even worse is when two clients in the same company want conflicting changes.

I am really just a junior developer here, but I see this problem and no one seems to be too perturbed by it, despite my constant nagging. But lately these issues have been falling into MY lap and wasting MY time.

Could anyone please suggest a way that I can try and manage these (even if just for myself).

We currently use OTRS as a client facing ticketing system (for support and requests) and VSO (TFS) for internal tasks and bugs (sometimes created as part of an OTRS request).

I administer both systems, but currently trying to find when last a request came in from a particular client to change a particular button to a particular color in version control history or tickets/emails is just not a very comprehensive nor efficient solution (also the button/color analogy is a really simplified version).

I am just starting to feel like we are headed round in circles and are eventually just going to crash.


答:
Unless I am misunderstanding your requirements, the 'volatile' keyword may be sufficient for your desire to prevent undesired optimization.  I tested the following using GCC version 4.6.3 and verified  the reading of the array elements into x was never optimized away (tested with -O0, -O1, -O2 and -O3 optimization levels).

```<code>#include <stdio.h>

int array[1024];

int main (void) {
    volatile int  x;
    int           i;

    for (i = 0; i < 1024; i++) {
        x = array[i];
    }

    return 0;
}
</code>```

I hope this helps.

Title: Does GCC optimize code to remove useless variable read operations?

Body: I'm using GCC on ununtu 14.04. My program is written in c++ and in a case i need to check the amount of time the program needs to read a large integer array. what is the best way to do this without causing unnecessary compiler optimization?</p>

Body:
Unless I am misunderstanding your requirements, the 'volatile' keyword may be sufficient for your desire to prevent undesired optimization.  I tested the following using GCC version 4.6.3 and verified  the reading of the array elements into x was never optimized away (tested with -O0, -O1, -O2 and -O3 optimization levels).

#include <stdio.h>

int array[1024];

int main (void) {
    volatile int  x;
    int           i;

    for (i = 0; i < 1024; i++) {
        x = array[i];
    }

    return 0;
}

I hope this helps.


问:
Is it better to create thread safe subclasses or make the main class thread safe?
Say we have a class that is frequently used in a single-thread context:

```<code>public class Foo
{
    public List<Bar> Data;

    public virtual void ChangeData()
    {
        for(var i =0; i < Data.Count; i++)
        {
            if(i % 4 == 0)
            {
                data[i].Baz();
            }
        }
    }
}
</code>```

If we were to decide we wanted to use the thread in a multi-threaded context (in addition to its current single-threaded usage), are there advantages (assuming it has full unit test coverage) to making a thread-safe subclass 'ThreadSafeFoo' vs. altering 'Foo' to be thread safe?

I was wondering about this because there are specific subclasses in System.Collections that are intended to be used across threads, and I wanted to know whether there was a reason this thread-safety wasn't simply rolled into List, etc.

答:
I was wondering about this because there are specific subclasses in System.Collections that are intended to be used across threads, and I wanted to know whether there was a reason this thread-safety wasn't simply rolled into List, etc.

In this specific example, it is because only a very limited subset of actions on say... Dictionary can be done performantly in ConcurrentDictionary. Subjecting all of your users to the overhead of synchronization (or the functionality limitations) is... not advised.

In the more general case, you should generally err towards using only one class. It reduces the complexity of your code. It is less code to maintain. It makes it easier for people to do "the right thing". Sometimes it's too onerous to provide the thread safety, and you get two classes. But if it's not, or it's close - just use the one.


问:
Should I write a unit test to this?
Given the following pseudocode:

```<code>List dohList = new List();
Foo foo   = A.getFoo();
if ( foo != null ) {
    Bar bar   = foo.getBar();
    if ( bar != null ) {
        FooBar fb = bar.getFooBar();
            if(fb != null) {
                dohList = fb.fillList();
            }
    }
}

return dohList;
</code>```

The whole point of the algorithm is to fill the list with elements or else return an empty list.

Should I write unit tests for the "intermediary" null checks or should I just mock the objects inside the unit tests concerning this specific method and all is good?

答:
Yes, you should unit test all of the branches of your function, especially one like this where it is easy to do so.

(though I might also recommend refactoring this code, as it violates the spirit, if not the letter of the Law of Demeter)

Title: Should I write a unit test to this?


问:
Adding quirks from an old system to a new system because that's what people are used to - a term for this?
Is there a term for the above?  When building a new system developers are sometimes  instructed (that is a different issue) to "keep things as they are", regardless of how inefficient or unusable they are, albeit in the name of usability, training or something along those lines.

Is there a term for this?  And if there is, is there any decent literature on addressing this type of problem?

答:
The overall term is cognitive bias. It has to do with how humans process information.

From WikiPedia:

A cognitive bias is a pattern of deviation in judgment, whereby inferences about other people and situations may be drawn in an illogical fashion. Individuals create their own "subjective social reality" from their perception of the input. An individual's construction of social reality, not the objective input, may dictate their behavior in the social world. Thus, cognitive biases may sometimes lead to perceptual distortion, inaccurate judgment, illogical interpretation, or what is broadly called irrationality.

More specifically, what you are referring to is called Confirmation Bias.

Confirmation bias, also called confirmatory bias or myside bias, is the tendency to search for, interpret, or prioritize information in a way that confirms one's beliefs or hypotheses. It is a type of cognitive bias and a systematic error of inductive reasoning. People display this bias when they gather or remember information selectively, or when they interpret it in a biased way. The effect is stronger for emotionally charged issues and for deeply entrenched beliefs.

Emphasis in the previous paragraph was added.

This is one reason why people have a tendency to do what they have always done.


问:
Overwriting and returning the value of the argument used as conditional of an if statement, inside the same if statement
A simplified example:

```<code>function logTheColor (color){
    if(color == "red"){
        color = "The color is red "
    } else if (color == "yellow") {
        color = "The color is yellow "
    } else {
        color =  "The color is blue"
    }
    console.log(color);
}
</code>```

Is there something wrong with overwriting the value of the variable inside an if statement, if that variable is also part of the if statement condition?  My question is not about the ways I can achieve the same in a "clean" way, I just want to know if it's right although it seems like a bad practice.

  I don't see any problem in this particular case cause I don't have to re-evaluate the "color" variable with the original content again. Am I missing something? Are there cases when it really matters?

答:
Who 'owns' the parameter passed in?

Consider the situation where the value of color gets modified by the function and its passed in by reference.  This may not always be something that you can control (pass by value vs pass by reference).

```<code>#include <iostream>
using namespace std;

void doFoo(int& arg) {
    arg++;
}

int main(void) {
    int foo = 42;
    doFoo(foo);
    cout << foo;
    return 0;
}
</code>```

https://ideone.com/RioRXb

This code prints out 43.  The function doFoo got the argument by reference and modified it.  This may be what its supposed to do, and there are certainly times to be aware of it.  But, if the function doesn't 'own' the argument when it comes in, such a side effect can be quite bad.

This concept of ownership is a real one and has implications in places.  In pre-arc Objective C, one would actually call retain and release on things if you wanted to 'own' them.  The alternative, you could make a copy of it (not what you're addressing) and own that copy.

Often, the best practice is to consider that the arguments passed in are immutable final things that you shouldn't touch.  Reassigning parameters is often seen as a questionable practice - even if the thing can't change.  The specifics of if it can change from language to language, or even silently within a language (the perceived difference in passing an Object and an int in Java).

Changing a thing

Setting aside the parameter being modified, code like this sets up the possibility/likelihood of becoming unmaintainable over time.

Modifying the condition for the if (or index in a for loop), in a series of if statements (yes, you've got an else in there) can lead to code where you depend on a value changing state in a previous if, that doesn't (and it has a different state).

This starts getting into rather contrived examples trying to demonstrate it in a short bit of code.  Often this comes about with larger blocks of code where you think that nothing later down uses it, so its safe to modify... and then someone comes in, looks at the assignments, looks at the hundred lines of code (you'll find this in code you maintain that "someone else wrote" all the time), skim to where you need to make the change... make the change, and find out that the thing you have here now, isn't the thing that was at the top of the block.

The example code just... its got a whiff of a code smell that has the scent of Same Name Different Meaning - the identical identifiers which would be addressed by Split Temporary Variable.  That this isn't a temporary variable is also problematic.

Body:
Who 'owns' the parameter passed in?

Consider the situation where the value of color gets modified by the function and its passed in by reference.  This may not always be something that you can control (pass by value vs pass by reference).

#include <iostream>
using namespace std;

void doFoo(int& arg) {
    arg++;
}

int main(void) {
    int foo = 42;
    doFoo(foo);
    cout << foo;
    return 0;
}

https://ideone.com/RioRXb

This code prints out 43.  The function doFoo got the argument by reference and modified it.  This may be what its supposed to do, and there are certainly times to be aware of it.  But, if the function doesn't 'own' the argument when it comes in, such a side effect can be quite bad.

This concept of ownership is a real one and has implications in places.  In pre-arc Objective C, one would actually call retain and release on things if you wanted to 'own' them.  The alternative, you could make a copy of it (not what you're addressing) and own that copy.

Often, the best practice is to consider that the arguments passed in are immutable final things that you shouldn't touch.  Reassigning parameters is often seen as a questionable practice - even if the thing can't change.  The specifics of if it can change from language to language, or even silently within a language (the perceived difference in passing an Object and an int in Java).

Changing a thing

Setting aside the parameter being modified, code like this sets up the possibility/likelihood of becoming unmaintainable over time.

Modifying the condition for the if (or index in a for loop), in a series of if statements (yes, you've got an else in there) can lead to code where you depend on a value changing state in a previous if, that doesn't (and it has a different state).

This starts getting into rather contrived examples trying to demonstrate it in a short bit of code.  Often this comes about with larger blocks of code where you think that nothing later down uses it, so its safe to modify... and then someone comes in, looks at the assignments, looks at the hundred lines of code (you'll find this in code you maintain that "someone else wrote" all the time), skim to where you need to make the change... make the change, and find out that the thing you have here now, isn't the thing that was at the top of the block.

The example code just... its got a whiff of a code smell that has the scent of Same Name Different Meaning - the identical identifiers which would be addressed by Split Temporary Variable.  That this isn't a temporary variable is also problematic.


问:
Why does Scala have return but not break and continue
Scala does not have break or continue, so some loop behavior takes a bit more of thinking.

Ending a loop early requires tail recursion, exceptions, or scala.util.control.Breaks (which uses exceptions).

The rationale for this is that, like goto, they are flow constructs that obscure flow, and can be accomplished in better, less surprising ways.

But it seems those same arguments could be used for return.

Why did Scala deliberately omit break and continue, but not return?

答:
Break and Continue:

In a talk about Scala, Martin Odersky gave 3 reasons not to include break or continue on slide 22:

They are a bit imperative; better use many smaller functions.

Issues how to interact with closures.

They are not needed!

And he then says, "We can support them purely in the libraries."  On slide 23, he gives code that implements break.  Although I don't quite know Scala well enough to be certain, it looks like the short snippet on that slide is all that's needed to implement break, and that continue could be implemented in code that is similarly short.

Being able to implement stuff like this in libraries simplifies the core language.

In 'Programming in Scala, Second Edition', by Martin Odersky, Lex Spoon, and Bill Venners, the following explanation is given:

You may have noticed that there has been no mention of break or continue.  Scala leaves out these commands because they do not mesh well with function literals...  It is clear what continue means inside a while loop, but what would it mean inside a function literal?  ...  There are many ways to program without break and continue, and if you take advantage of function literals, those alternatives can often be shorter than the original code.

Return:

Returns could be considered a bit imperative in style, since return is a verb, a command to do something.  But they can also be seen in a purely functional/declarative way: they define what the return value of the function is (even if, in a function with multiple returns, they only each give a partial definition).

In the same book, they say the following about return:

In the absence of any explicit return statement, a Scala method returns the last value computed by the method.  The recommended style for methods is in fact to avoid having explicit, and especially multiple, return statements.  Instead, think of each method as an expression that yields one value, which is returned.

Methods end and return a value, even if a return statement isn't used, so there can be no issues with closures, since otherwise closures wouldn't work period.

There can also be no problem meshing well with function literals, since the function has to return a value anyway.


答:
I will not say it's always wrong but it's generally a bad idea.

Function names shouldn't lie.

Function name says it logs the color.

Function name doesn't say it changes the color.

Function name lies.

Function changes color as a side effect.

Side effects in functions are not a good idea according to Uncle Bob's Clean Code

If you do that in many places in your code, the code will be a maintenance nightmare.

Please don't code as if you will throw the code away immediately. Code as if your code will be re-used in the future, not only by you but by others.

Title: Overwriting and returning the value of the argument used as conditional of an if statement, inside the same if statement

Body:
A simplified example:

```<code>function logTheColor (color){
    if(color == "red"){
        color = "The color is red "
    } else if (color == "yellow") {
        color = "The color is yellow "
    } else {
        color =  "The color is blue"
    }
    console.log(color);
}
</code>```

Is there something wrong with overwriting the value of the variable inside an if statement, if that variable is also part of the if statement condition?  My question is not about the ways I can achieve the same in a "clean" way, I just want to know if it's right although it seems like a bad practice.

  I don't see any problem in this particular case cause I don't have to re-evaluate the "color" variable with the original content again. Am I missing something? Are there cases when it really matters?


答:
If this is about design aesthetics in the user interface, then the term you are looking for is Skeuomorphism

A skeuomorph /ˈskjuːəmɔrf/ is a derivative object that retains ornamental design cues from structures that were necessary in the original. Examples include pottery embellished with imitation rivets reminiscent of similar pots made of metal and a software calendar that imitates the appearance of binding on a paper desk calendar.

Another example is the mechanical shutter sound in some modern digital cameras

Title: Adding quirks from an old system to a new system because that's what people are used to - a term for this?

Body:
Is there a term for the above?  When building a new system developers are sometimes  instructed (that is a different issue) to "keep things as they are", regardless of how inefficient or unusable they are, albeit in the name of usability, training or something along those lines.

Is there a term for this?  And if there is, is there any decent literature on addressing this type of problem?


问:
Immutable objects
Looking at questions such as these

If immutable objects are good, why do people keep creating mutable objects?

What are the drawbacks of immutable types?

At what point do immutable classes become a burden?

When is it inappropriate to make objects immutable?

it looks to me that people are asking "why not immutable?" and thought I'd ask another kind of question.

Let's say immutable objects are (mostly) good - even if you disagree, humor me for a sec.

As of now, there seem to be more than 6k Java projects on freecode.com. There's probably a lot that are mis-tagged, but also many more that are not listed. So let's say there at least a thousand of these. And we can safely count other ones, such as C#, that are equally relevant.

So do you have any examples of relatively successful big projects that use immutability to any reasonable degree? I mean, everyone can write baby examples showing how good everything is when it's immutable, but if there are 10k+ LOC, then that's a different story.

I can understand old projects - OK, historical burden, it would be a huge undertaking to rewrite e.g. Firefox to be mostly immutable. I can understand specialized things, e.g. Guava collections, which are designed like that from scratch. Are there examples of real-life applications, preferably new ones, that are like this? How much is "mutable Java" better / worse vs. "immutable Java" and in what aspects - but from practical standpoint?

答:
Without limiting the scope to Java, I'd say Cocoa is one of the big projects out there. It's used by iOS and OS X applications and I bet many of the programmers would stumble on how NSString (the basic string class) is immutable and learn to use NSMutableString. Same with data structures (NSArray, NSDictionary, etc.)

I'd also say many are using them (immutable classes) just because how they learn Cocoa without understanding why immutability is good.

Title: Immutable objects


答:
You're very close in your title. I believe the term you're looking for is Quirk Parity by Kent Beck:

"quirk parity" -- the part of a rewrite where you finally match the irrational behavior of the old system

This arises from the Common Law Feature


问:
Managing multiple versions of the same Android Library Project
I have an Android Library Project which I intensively used in a few projects. I started a new project in which I am also using this library. I want to improve some things in library (method signatures\names, interfaces, etc.). But if I change method signatures\names, interfaces, I should update old projects that use this library. That could be hard work.

I want to make new version of my library which will be not compatible with previous versions.

Is this possible without creating new project?

IDE: Android Studio.

答:
GitHub sounds like a good tool you could use. It can even be linked to Android Studio to automatically update your work. You'll be able to store multiple versions of this library. Old projects can reference the older library, while new projects can reference the new library.

Alternatively, however, why not simply recreate the library and adjust it for your needs? If the project itself has a different set of demands, surely it requires it's own library not a bent version of a previous library.


答:
You're asking for examples from the wrong programming language.  Java is one of the unfriendliest languages for immutability, both from a development culture and from a language feature perspective.  To work with immutable objects on a large scale without going insane, you need functional-style language features, which Java didn't even start to consider until Java 8, and even there are still quite limited.  That's why in Java you mostly see immutability in Strings and other relatively small data transfer objects.

Languages where you would find large projects with ubiquitous immutability include, but are not limited to, Scala, used at LinkedIn, Twitter, and FourSquare, and Erlang, used at Amazon, Facebook, and Ericsson.  The reason these are the most prominent examples is immutability becomes pretty much a requirement when dealing with massive parallelization and distributed computing.

In other words, contrary to your assumptions, it's mutable data structures that become most problematic as you scale up.  Don't get me wrong, immutability is a difficult constraint for programmers to become accustomed to at first, especially making it efficient, but once those problems are solved in small programs, they don't get inherently worse in larger programs.  That's because immutable data structures tend to engender algorithms that are much easier to decouple.

Title: Immutable objects

Body:
Looking at questions such as these

If immutable objects are good, why do people keep creating mutable objects?

What are the drawbacks of immutable types?

At what point do immutable classes become a burden?

When is it inappropriate to make objects immutable?

it looks to me that people are asking "why not immutable?" and thought I'd ask another kind of question.

Let's say immutable objects are (mostly) good - even if you disagree, humor me for a sec.

As of now, there seem to be more than 6k Java projects on freecode.com. There's probably a lot that are mis-tagged, but also many more that are not listed. So let's say there at least a thousand of these. And we can safely count other ones, such as C#, that are equally relevant.

So do you have any examples of relatively successful big projects that use immutability to any reasonable degree? I mean, everyone can write baby examples showing how good everything is when it's immutable, but if there are 10k+ LOC, then that's a different story.

I can understand old projects - OK, historical burden, it would be a huge undertaking to rewrite e.g. Firefox to be mostly immutable. I can understand specialized things, e.g. Guava collections, which are designed like that from scratch. Are there examples of real-life applications, preferably new ones, that are like this? How much is "mutable Java" better / worse vs. "immutable Java" and in what aspects - but from practical standpoint?


答:
You are asking about Java, but in your question you also mention C#, so I will answer with a significant project in that language: Project Roslyn, Microsoft's from-scratch rewrite of the C# and VB.NET compilers in C# and VB.NET uses immutable datastructures throughout. In particular, all the parse trees and semantic trees are immutable, and every operation and transformation of that tree, whether that be optimizations done by the compiler, annotations done by some static analysis tool, refactorings or code fixes done by the IDE, macros done by some user plugin or whatever else always produces a completely new tree.

So, this is a project that is commercial, large, industry-strength, performance-sensitive (AFAIK, the Roslyn C# compiler is currently within a few percent of the old C# compiler written in C++) and will very likely be at the very core of not only the next version of .NET, but also the next version of Visual Studio.

Oh, and it is also fully Open Source under the Apache Software License 2.0, so you can see how they did it: https://roslyn.codeplex.com/

Title: Immutable objects


答:
From the Jargon File:

bug-compatible /adj./ Said of a design or revision that has been badly compromised by a requirement to be compatible with fossils or
  misfeatures in other programs or (esp.) previous releases of itself.
  "MS-DOS 2.0 used \ as a path separator to be bug-compatible with some
  cretin's choice of / as an option character in 1.0."


问:
Is it wrong to make any form of business decision in a Controller?
I'm building a prototype web application using ASP.NET MVC 5. Part of the application is the display of a grid of records, each of which has a button action to 'Archive' that record. Another page displays the archived records. A WCF service provides the Model and persistence.

I have built a controller for each of the pages and in each controller I retrieve all of the records and then select either the current or archived records and display only those. There is an additional method on the current records Controller to set the Archive status of the record and then redisplay the current records.

I suspect that this is a potentially poor design as business decisions are being made in the Controllers and not the Model. Should I instead create a Model 'layer' in the MVC application with methods that return either current or archived records as required, or update the status of records, thus 'wrapping' the WCF Service, or is this adding a layer of complexity where it is not necessary?

What is the pure decision to be made based on the MVC concept? Should any business decision (even one as simple as filtering records based on status) be made in the Model and not the Controller?

答:
Generally you want thin controllers that handle request in a RESTful way, with any business logic in the models.

I would put any state related stuff such as logged in user and any request related stuff such as 'records for this user' in the controller.

I would put the database calls that are specific to current or archived records as methods in the model and then call those methods from the controller.