答:
That is not one requirement, but 4 requirements. One of the characteristics is of a good requirement is that it is cohesive: it addresses one, and only one, functional or non-functional characteristic of the system. I'd enumerate each of these as separate requirements or user stories to promote traceability and verification:

```<code>- Users can open content from local machines.
- Users can open content from remote servers.
- Users can open content via FTP.
- Users can open content via web streams.
</code>```

Now that you have four user stories, you can treat them as four separate entities, with their own estimates, their own priorities, and so forth.

A release in which to deliver the feature is not a requirement of the system, but a measure of priority, so the story to be able to open content from local machines is placed ahead of the others in the product backlog (probably near the top, so it would be in an early sprint). The others can be prioritized where they fall with regards to other functionality.

The separation also promotes better relationship from the requirement/user story to the test cases that verify the functionality and gives the customer and user the ability to prioritize the four modes of operation in the event you can't deliver them all in the same sprint.

Body:
That is not one requirement, but 4 requirements. One of the characteristics is of a good requirement is that it is cohesive: it addresses one, and only one, functional or non-functional characteristic of the system. I'd enumerate each of these as separate requirements or user stories to promote traceability and verification:

- Users can open content from local machines.
- Users can open content from remote servers.
- Users can open content via FTP.
- Users can open content via web streams.

Now that you have four user stories, you can treat them as four separate entities, with their own estimates, their own priorities, and so forth.

A release in which to deliver the feature is not a requirement of the system, but a measure of priority, so the story to be able to open content from local machines is placed ahead of the others in the product backlog (probably near the top, so it would be in an early sprint). The others can be prioritized where they fall with regards to other functionality.

The separation also promotes better relationship from the requirement/user story to the test cases that verify the functionality and gives the customer and user the ability to prioritize the four modes of operation in the event you can't deliver them all in the same sprint.


问:
SOLID Application Structure and Design
A one possible structure for an application is to have it broken down into modules such as Data Access, Core, Services, UI. Now depending on what type of ORM you are using Data Access layer will have a set of entities that represent the tables in the database. The core layer will have a set of entities that represent the business logic. The service layer will have a set of DTO entities that it will communicate with to the UI. And finally the UI will have a set of View Models that it will use inside the views.

Now when we access or store information in the database we have to transform objects from one type to another. When the service calls the core it needs to transform objects from one type to another and finally the UI needs to transform the DTO's to View Models. In a lot of the cases the transformation is a simple act of copying the properties from one object to another. It is a very repetitive and time consuming task that generates large amounts of code.

My question is am I doing something wrong here. Should I only have one entity type? If so don't you think that it would have too much information in one object for data access, business logic etc... Is there a quick way to copy the properties between objects? Reflection is an option but gets complicated fast when dealing with object graphs? I know there is no silver bullet to fix this problem but there must be a number of good approaches over copying the properties by hand between the entities?

答:
I hate the idea of parallel object hierarchies just for the sake of layer purity.

This is a Core J2EE Pattern that in my view has become an anti-pattern.  People used to create DTOs because the EJB 1.0 entity model was too chatty.  I think POJOs/POCOs are smarter and don't have to resort to such contortions.

The data access layer might represent tables or objects, depending on which way you go.

The service layer maps to use cases and units of work.  It owns transactions and orchestrates processes to fulfill the wishes of clients.  It should be UI agnostic.

I'd recommend creating model objects and using them appropriately.  Just make sure that you find a way to avoid cyclic dependencies between packages/namespaces.  Don't couple all of them together.  Data access layer should know about model objects but nothing else.  Service layer should know about data access layer, model objects, other services and nothing else.  View layer should have controllers that invoke services and nothing else.

OwnerDisplayName: Lukasz

ContentLicense: CC BY-SA 3.0

Title: SOLID Application Structure and Design

OwnerDisplayName: duffymo


答:
I hate the idea of directly mapping your DB to objects and passing them around like theyre properties on a class (which we know is an anti-pattern itself)

The best way to model your application is to split it into tiers, then think what each tier requires and provides, independantly of the other tiers. ie, do not start making your UI and think of the database at all. Think what services your UI needs, these will then be mapped to a application tier that itself will require services.These services then get modelled in the DB (preferably as stored procedures so you get a nice DB API), those sprocs can then be modelled onto whatever data model you like.

The reason to do this is that it makes you think in terms of the application requirement, not the implementation. Once you start thinking of passing objects around, you're tying yourself into a fixed implementation or worse - like security issues as well (eg when it becomes just a little too convenient to access the DB directly from the UI, people will do so).

Title: SOLID Application Structure and Design

Body:
A one possible structure for an application is to have it broken down into modules such as Data Access, Core, Services, UI. Now depending on what type of ORM you are using Data Access layer will have a set of entities that represent the tables in the database. The core layer will have a set of entities that represent the business logic. The service layer will have a set of DTO entities that it will communicate with to the UI. And finally the UI will have a set of View Models that it will use inside the views.

Now when we access or store information in the database we have to transform objects from one type to another. When the service calls the core it needs to transform objects from one type to another and finally the UI needs to transform the DTO's to View Models. In a lot of the cases the transformation is a simple act of copying the properties from one object to another. It is a very repetitive and time consuming task that generates large amounts of code.

My question is am I doing something wrong here. Should I only have one entity type? If so don't you think that it would have too much information in one object for data access, business logic etc... Is there a quick way to copy the properties between objects? Reflection is an option but gets complicated fast when dealing with object graphs? I know there is no silver bullet to fix this problem but there must be a number of good approaches over copying the properties by hand between the entities?


答:
With your architecture, yes you should have multiple objects.

Always start with the domain entity as it's the primary reason for creating your application.

A service layer is created to allow the outside world to talk with your application. The api in it may or may not look exactly as your domain entities. My experience is the API diverges from the underlying model as the application grows. The DTOs are used to transfer information over process boundries and therefore to decouple the API from the model that it's a facade for. You might also want to flatten the entity, use strings instead of enums etc.

In the database you might not be able to store the information in the same way as your domain entity is modeled. You might want to denormalize to decrease the number of joins, or normalize to use less space. It all depends on the situation, and it might also vary from entity to entity.

A view might contain information from multiple entities. For instance for a user and a message. Hence the view model is combination of both of the entities. The view model may also have logic used to calculate something that the view requires. Placing that logic inside the view would make it a lot harder to test that logic.

As for streamlining the process, I would say no. There are tools like AutoMapper and similar which do the copying for you. But the problem with those is that you'll never know if you've missed something in the configuration (as they usually work by conventation and not by manual configuration). So you might refactor a field in the DTO but not in the entity resulting in that field not being copied. It's much more robust to create converter classes by hand (as they also allow you to do transformations).

I've personally used tools like that, but on the long run I also find myself wondering if it wouldn't have gone faster if I simply had created the convert classes myself. And that's why I've also stopped using libraries like that.

What I'm saying is that all different representations might seem the same at first glance, but they all have small differences that you must address. If you use the same representation for all layers you have to do compromises to make it work in all layers. Your entity quality will decrease the longer you maintain the application.

I would rather ask you if you need that service layer? Is your application complex enough mandating it? Do you need to use a RDBMS instead of a schemaless DB?

Title: SOLID Application Structure and Design


问:
Safely fixing production database data
Bugs happen and sometimes data has to be fixed in production. What is the safest way to go about this from a big company standpoint? Are there tools that can help? Here are some considerations driving this requirement...

We need to log who ran the query and what they ran

Ideally we need to give the person access to only run queries against the tables of interest and only for a short time

Whatever is running the queries needs to have some smarts about it to not allow long running and locking SQL to run without explicit permission

This process needs to be DB agnostic or at least understand DB2, Oracle, and SQL Server.

We are trying to reduce the risk of ad-hoc prod fix-up queries from doing the "wrong thing" and at the same time add some security/audtis to the process. Thoughts or Ideas?

答:
Never ever update production databases manually.

Write scripts.

Triple check them, and have multiple people do that, not just a single person doing it three times.

Include post-change validation queries in those scripts.

Whenever the situation allows, test the whole change within a transaction which is rolled back at the end, after the post-change validation has run. When confident with the results, change the rollback to a commit.

Test those scripts ad nauseam against a test database.

Make a backup prior to running the script against the production database.

Run the scripts.

Check, validate and triple check the changed data using the post-change-validation scripts.

Do a visual check anyway.

If anything seems off, back off and restore the backup.

Do not proceed with the changed data as the production data until you are absolutely sure that everything is ok and you have sign off from the (business) managers involved.

Title: Safely fixing production database data


问:
What is beautiful code?
I often read that developers must write beautiful code, but for a beginner as I am it remains obscure of what is beautiful code and how do you recognize it?

The corollary question is: How to write beautiful code and what are some practical habits to improve your code's quality?, what should I care about to make the code I write beautiful (and what shoud I learn).

答:
I agree with the answers here really, but taking a less technical approach I would say beautiful code is an expression of its authors' clarity of thought of the problem at hand which manifests itself through a well-formulated and precise yet simple language.

For me, looking through beautiful code is much like looking at a piece of art, seeing ever new details that show the maker's intention, but also how the different parts were realised, each giving an answer to so many questions, and then, finally, how its existence feels like a natural law to which everything aligns such that it can only be described with words of awe: magnificient, inspiring, beautiful.

So from that perspective, in your career as a programmer you might make discoveries of beautiful code others might neither understand because they lack the knowledge or might not find noteworthy anymore as they have been spoiled by too much beauty ;)

Beautiful code has all the pragmatic qualities as mentioned otherwise, I totally agree.

Title: What is beautiful code?


问:
Reusing open-source code that doesn’t specify a license
I am creating a module for a CMS. I found a PHP code in github that does some work for me. The author has not clearly stated the license for the code. Since it is in github and is publicly available, can I use the code in my module or should I get the author's written permission? I am planning to sell my module for a small price.</p>

答:
Since it is in github and is publicly available, can I use the code in my module...

NO.

...or should I get the author's written permission?

YES.

In all 166 nations that are signatories to the Berne Convention, copyright is granted to an author when the work is created. The author holds a monopoly on all copyright rights (creating modifications, creating and distributing copies, etc.). You -- as someone who is not the author -- have been granted none of those rights.

A license is a mechanism by which the rights-holder (here, the author) grants some set of rights to a recipient (here, you). You say that the author has not offered any license, which means by default that the author has reserved all of his rights. The fact that the author has made his code publicly viewable does not mean that you have been granted any rights beyond the right to view the code. The right to make derivative works and the right to redistribute the code are not rights that you currently have.

Since you mention that code is on Github, it's worth mentioning that the Github TOS have this to say about material hosted on their site:

By setting your repositories to be viewed publicly, you agree to allow others to view and fork your repositories.

Hosting on Github means that the author grants others the right to "view" and to "fork" the repository. Here, "fork" probably just means "use Github's fork feature", which creates a repository clone, hosted on Github. I admit the Github's use of the term "fork" here is ambiguous, but if my reading is correct, then in no way does this appear to grant you any right to:

copy the code outside the context of a Github fork

make any modifications to the forked code

incorporate the author's code into your own

The bottom line is: you don't have the right to distribute this code. It's possible that the author wants people to use his code freely, but neglected to include a license. Tell the author that the lack of a license has blocked your use of the code, and encourage the author to add a some mainstream OSI- or FSF-approved license to the repository.


答:
I have three criteria:

Simple: At least it must be human readable. For example, you can write a code that works at O(1) for a solution with tons of lines, but I prefer code that works with 0(n) solves with few lines. This might change for extreme situations but for the beginning simplicity is important.

Reusable: Code must be reusable, but not overwritten. If you need an operation, you should define it the way that you can use it years later.

Indentation: Maybe this is not a problem for you, but for the beginner-level, this is first thing to be solved.

Title: What is beautiful code?

Body:
I often read that developers must write beautiful code, but for a beginner as I am it remains obscure of what is beautiful code and how do you recognize it?

The corollary question is: How to write beautiful code and what are some practical habits to improve your code's quality?, what should I care about to make the code I write beautiful (and what shoud I learn).


答:
The answer by Marjan Venema is technically valid and should be followed when possible. Alas, Marjan answers from the point of view of a theorist, or a purist database administrator who likes to make things cleanly. In practice, sometimes business constraints make it impossible to do things in a clean way.

Imagine the following case:

There is a bug in the software product which causes it to stop working when it detects what it thinks being some data inconsistency in the database,

All developers who could potentially fix the bug in the application are unreachable,

The company is currently losing thousands of dollars per hour (let's say $6 000, which means $100 per minute),

The bug is affecting several tables, one of which is huge, and concerns only the data itself, not the schema,

In order to circumvent the bug, you should experiment a bit with the data, which involves both removing and changing it,

The database is large and it would take three hours to take or restore the backup,

The last full backup was taken three weeks ago; there are also daily incremental backups, and the last daily incremental backup was done 14 hours ago,

Database backups are assumed reliable; they were severely tested, including recently,

Losing 14 hours of data is not acceptable, but the loss of one to two hours of data is,

The staging environment was lastly used six months ago; it seems it is not up to date, and it may take hours setting it up,

The database is Microsoft SQL Server 2008 Enterprise.

The clean way to do things is to:

Restore the backup in staging environment,

Experiment there,

Check the final script twice,

Run the script on the production server.

Just the first step will cost $18 000 to your company. The risk is pretty low if you do the third step flawlessly, but since you work under extreme pressure, the risk would be much higher. You may end up with a script which worked perfectly well in staging, then screws the production database up.

Instead, you could have done like this:

Create a snapshot (Microsoft SQL Server supports that, and it takes seconds to revert (and nothing to create) a snapshot of a database which takes an hour to backup; I imagine that other database products support snapshots as well),

Experiment directly on the production database, reverting to the snapshot if something goes wrong.

While a purist would fix the database in a clean way and still have a risk to screw things up given the time pressure while wasting more than $20 000 of his company, a database administrator who takes in account business constraints will fix the database in a way which will minimize the risks (thanks to snapshots) while doing it quickly.

Conclusion

I'm a purist myself, and I hate doing things in a non-clean way. As a developer, I refactor the code I modify, I comment the difficult parts which couldn't be refactored, I unit-test the codebase and I do code reviews. But I also take in consideration the circumstances where either you do things cleanly and the next day you're fired, or you minimize both the risks and the financial impact by doing a quick hack which works.

If some IT guy wants doing things cleanly just for the sake of cleanness while it causes thousands of dollars of loss for the company, this IT guy have a deep misunderstanding of his job.

Title: Safely fixing production database data

Body:
Bugs happen and sometimes data has to be fixed in production. What is the safest way to go about this from a big company standpoint? Are there tools that can help? Here are some considerations driving this requirement...

We need to log who ran the query and what they ran

Ideally we need to give the person access to only run queries against the tables of interest and only for a short time

Whatever is running the queries needs to have some smarts about it to not allow long running and locking SQL to run without explicit permission

This process needs to be DB agnostic or at least understand DB2, Oracle, and SQL Server.

We are trying to reduce the risk of ad-hoc prod fix-up queries from doing the "wrong thing" and at the same time add some security/audtis to the process. Thoughts or Ideas?


问:
Handling a request to override browser behaviors (Back and Refresh)
I'm a new guy in this company and I've been tasked to research on possible workarounds with the browser behaviors to cater to the demands of our client.

A little background; what they want is to display a 'custom' dialog whenever a user would like to navigate away from a page (not the browser default) that has a form, just as how facebook does it. I've found a workaround with the Back button in the form of browser states and have it integrated in my local build of the web app. Works like a charm, though I'm not convinced this is good practice. (more of a trick if you ask me)

The problem is the Refresh event. All my research (here's one) tells me I should give up. Sigh...

So I'm looking for a way to convince my superiors that this it's a bad practice to override browser behaviors or how it's virtually impossible to override the refresh behavior; diplomatically as much as possible. (if I could do citations on articles that would further prove my point, that would be great)

Or do I continue looking for possible workarounds in the internet? (too much research effort but not much accomplishment if you ask me, but hey, what do I know?)

答:
We all know what they're asking you to do is wrong, hard to do (because its wrong), will annoy the user (because its wrong) and will encourage them to find and use workarounds (which they'll do because what you're doing is wrong).

So, you've stated you need to change the way the back button works, and also how the refresh works. The thing is, these aren't really problems they're bringing you, this is their solution and implementation for how to solve a problem.

If I were you, I would try and find out what the hell the actual problem that they're trying to solve in the first place is. Then, when you know what the problem is, you can propose some sort of alternate (and hopefully sane) solution.

I have often been tasked with implementing someone elses idea for a fix, instead of being tasked with solving a problem. Every time I have had doubts or worries about the implementation (like you're having now) I have found out the actual problem being experienced and implemented a proper solution (WARNING: may result in managers being annoyed if they're control freaks). As long as the solution is a proper fit, doesn't end up being hacky, or take too long, it should go down well.


问:
Recommended sprint length when adopting Agile?
I'm new to a small development company (half a dozen programmers and should grow to possibly a dozen eventually).  We also have a few external contractors working with us (just to add a bit of complication).

I would like to slowly start adopting Agile, or more importantly short sprints.  I was curios to know, from past experience, what would you recommend that our initial sprint length (in weeks) be?

Maybe I can even go as far as asking what is the sprint length of a very mature and experienced Agile team (shorter [2 weeks] or longer sprints [4 weeks])?

My initial thought was to use a shorter sprint, say 2 weeks and then in time, once we get the hang of things and all has smoothed out, we could simply double it to 4 weeks.

答:
DEFINITELY use shorter sprints.

Two weeks is very common, and it's what I've used before.

The entire point of agile is to get rapid feedback an adjust your course as you go - the longer the sprint, the longer you go between course adjustments. Especially when just starting out, this is problematic, because you can end up doing the wrong thing for a month before you adjust.


答:
It will depend on your team's ability to adapt to the sprint structure and discipline, but when our company transitioned we found that two weeks was too short when we were still adapting to the framework.  Consider that the first few times you do estimations, planning, retrospectives, daily stand-ups, etc. you will likely take more time to do these and learn about them initially.

I would consider starting with a 3 week iteration, and doing that 3 or 4 times.  Once your team is more comfortable, you might be able to bring it down to a 2 week iteration, or you might find that 3 weeks is the perfect comfort zone.  My first few projects I ran with 3 week iterations, and I found it was just a few days too long for my liking, and have more recently transitioned to the 2 week time span and it goes by lightning fast.

I would not recommend going to longer sprints after you get comfortable, unless you are trying to do several 1 week iterations very quickly to get everybody used to agile and then slow down to a 2 week interval.  The more often you release, the more feedback you get and the greater your agility to change directions.

Title: Recommended sprint length when adopting Agile?

Body:
I'm new to a small development company (half a dozen programmers and should grow to possibly a dozen eventually).  We also have a few external contractors working with us (just to add a bit of complication).

I would like to slowly start adopting Agile, or more importantly short sprints.  I was curios to know, from past experience, what would you recommend that our initial sprint length (in weeks) be?

Maybe I can even go as far as asking what is the sprint length of a very mature and experienced Agile team (shorter [2 weeks] or longer sprints [4 weeks])?

My initial thought was to use a shorter sprint, say 2 weeks and then in time, once we get the hang of things and all has smoothed out, we could simply double it to 4 weeks.


答:
Two or three weeks would likely be best to start with. Remember, you aren't making a life-long commitment to one or the other, so which you choose isn't critical. Pick something, anything, and stick with it for a while. Discuss how it works in your retrospectives. Once the team has enough data to make a decision, let them make that decision.

Some people think four or more weeks is a bit long for a sprint, though others think it is about right. However, since you are just getting started, having shorter sprints mean you spend a bit more time in planning meetings and retrospectives, which is good because the practice will make your team stronger.


问:
bad practice to have actions in web api controllers
I was creating a new action for a WebApi controller and tried to create a url using the following:

```<code>@Url.RouteUrl("DefaultApi", new { httproute = "", controller = "ClientApi"})
</code>```

and noticed that the default route did not have an action attribute, it looks like this:

```<code>config.Routes.MapHttpRoute(
    name: "DefaultApi",
    routeTemplate: "api/{controller}/{id}",
    defaults: new { id = RouteParameter.Optional }
);
</code>```

how come the default route doesn't have the action in the route configuration by default? is it bad practice to have it? that is to say is it bad practice to have so many actions in a web api controller that it requires to change the route.

答:
how come the default route doesn't have the action in the route configuration by default?

Because in REST, the action to be executed by the server is dictated by the HTTP method used in the request.


问:
MVVM ViewModel and Commands
I need a bit of help to understand the relationship between a viewmodel and a command, and the responsibility of the viewmodel.

I'll try to give an example (using Caliburn Micro).

I have a viewmodel class, a command class and a view with a Save button.

```<code>public class EditViewModel : Screen
{
    public bool CanSave
    {
        get { return IsDirty; }
    }

    public void Save()
    {
        var command = new SaveCommand(this); // command gets reference to VM
        command.Execute();
    }
}

public class SaveCommand
{
    private readonly EditViewModel _viewModel;

    public SaveCommand(EditViewModel viewModel)
    {
        _viewModel = viewModel;
    }

    public void Execute()
    {
       var work = _viewModel.Work;
       ..
       _viewModel.IsDirty = false;
    }
}
</code>```

When the user click Save. Save() method is called and spins up a command that saves the work.

Now my question is, should the command have a reference to the viewmodel?

No) The viewmodel will have to pass the work to the command, which will have to pass the save result back to the viewmodel, which will update itself.

Yes) The command needs a reference to the viewmodel and properties needs to be public set-able.

No seems like the cleanest way, but also requires extra work, when the work or result aren't a simple bool or similar.

I guess the root it all is. What is the relationship between a viewmodel and it's command and the responsibility of the viewmodel ?

Is there a strong 1:1 "friend" relationship between the view-model and it's command, where code has just been moved to another class. So there is nothing wrong with the command having direct access to the viewmodel.

Another understanding, the viewmodel is a very simple class, almost only with properties and contains little logic. So the logic should be in the command.

Or the viewmodel is pretty smart and should contain application-logic. Commands are really only needed when there are either too many in one viewmodel or they are a bit complicated otherwise the command code can stay in the viewmodel.

I'm just rambling I guess, please help me out to understand the viewmodel and what it's responsibility is?

答:
The command should be on the ViewModel.

In MVVM, the ViewModel is the thing that should contain all of the logic that drives the view.  The view is the simple class - just a collection of UI controls whose state is bound to properties on the ViewModel.

Josh Smith wrote a really good intro to MVVM that should clear things up for you.

Title: MVVM ViewModel and Commands


问:
What aspects make websites load faster?
I want to know what aspects in VPS hosting packages are related to performance for the website which will make it faster in loading for the end useres. And does RAM really matter?</p>

答:
That varies hugely depending on what you are going to run on the server.

For a web server you only need a reasonable amount of RAM, it doesn't make a big difference to use more. For a database server more RAM is better, there is really no upper limit until you have room in memory for caching all data in the databases and all common results.

The factors that makes a site load faster are generally:

The amount of data

The speed of the transfer

Server response time

Number of requests

The factors that makes a site seem to load faster are more complex, some important are:

Loading what's needed for initial display before the rest of the data

A page layout that needs minimal data for the initial display

Placeholders for content (e.g. images), so that the layout doesn't change much when content loads

Reaching UI responsiveness early

ContentLicense: CC BY-SA 2.5

Title: What aspects make websites load faster?


问:
Why Java doesn't make use of encapsulation with some classes?
My question is related with System.in and System.out classes (there might be others like those in the Standard library). Why is that? Isn't that a bad practice in OOP? Shouldn't it be used like: System.getIn() and System.getOut()? I've always had this question and I hope I can find a good answer here.

答:
I believe the out object is immutable, which makes it somehow safe (this is debatable) for being kept in a public final static field.

Many of the classes in the JDK do not respect the best object-oriented design principles. One reason for this is the fact that they were written almost 20 years ago, when Object-Orientation was only emerging as a mainstream paradigm and many programmers simply were not familiar with them as they are now. A very good example of bad API design is the Date & Time API, which took them 19 years to change...


问:
In Scheme, what is formally a program's state?
I think i've understood more or less what a parsed Scheme program looks like (a binary tree with atomic values on the leaves, if i have understood correctly).  Can anybody please define to me, or give a reference, what a state (or a computation) of a Scheme program is?  Is it just the current binding plus a position, or a stack of positions, on the syntax tree?  (In such a case, i would appreciate a reference for a formal definition of Scheme binding as well :).)

Is there some simple description, like the one for the Turing Machine (the program + the current content of the tape + the current position on the tape)?

答:
After looking into Alonzo Church's The calculi of lambda-conversion, and thinking a bit about rewriting systems, different definitions of algorithms, and about Lisp, I have come to mostly agree with John Clements' answer: that the state of a Scheme program is a "reduced" Scheme program.

I would like however to formulate my own version of it (which i can edit or improve if I learn more).

In my opinion, a state of a Scheme program can be viewed as a sort of a Scheme program, where instead of constant literals, arbitrary constant data values are allowed (they have to be allowed because I am not sure if, for example, an arbitrary float value can be written as a float literal).

For example, a program can execute as follows (the sequence of states):

The program:

(define x 0)
(set! x (lambda (x) (+ x 1)))
(define y 2)
(x y)
```

<p>Program state after step 1:</p>

<pre class="lang-scm prettyprint-override"><code>(define x (lambda (x) (+ x 1)))
(define y 2)
(x y)
</code>```

Program state after step 2:

(define y 2)
((lambda (x) (+ x 1)) y)
```

<p>Program state after step 3:</p>

<pre class="lang-scm prettyprint-override"><code>((lambda (x) (+ x 1)) 2)
</code>```

Program state after step 4:

(+ 2 1)
```

<p>Program state after step 5:</p>

<pre class="lang-scm prettyprint-override"><code>3
</code>```

Update. To confirm this point of view, here are quotes from Racket reference:

1.1 Evaluation Model

Racket evaluation can be viewed as the simplification of expressions to obtain values. For example, just as an elementary-school student simplifies

  1 + 1 = 2
```

  <p>Racket evaluation simplifies</p>

<pre class="lang-scm prettyprint-override"><code>  (+ 1 1) → 2
</code>```

The arrow → above replaces the more traditional = to emphasize that evaluation proceeds in a particular direction towards simpler expressions. In particular, a value is an expression that evaluation simplifies no further, such as the number 2.

[...]

1.1.4 Top-Level Variables

Given

x = 10
```

  <p>then an algebra student simplifies <code>x + 1</code> as follows:</p>

<pre class="lang-scm prettyprint-override"><code>x + 1 = 10 + 1 = 11
</code>```

Racket works much the same way, in that a set of top-level variables are available for substitutions on demand during evaluation. [...]

Each evaluation step, then, takes the current set of definitions and program to a new set of definitions and program.  Before a define can be moved into the set of definitions, its right-hand expression must be reduced to a value.

  defined:
  evaluate: (begin (define x (+ 9 1)) (+ x 1))
→ defined:
  evaluate: (begin (define x 10) (+ x 1))
→ defined:  (define x 10)
  evaluate: (begin (void) (+ x 1))
→ defined:  (define x 10)
  evaluate: (+ x 1)
→ defined:  (define x 10)
  evaluate: (+ 10 1)
→ defined:  (define x 10)
  evaluate: 11
```

  <p>Using <code>set!</code>, a program can change the value associated with an existing top-level variable:</p>

<pre class="lang-scm prettyprint-override"><code>  defined:  (define x 10)
  evaluate: (begin (set! x 8) x)
→ defined:  (define x 8)
  evaluate: (begin (void) x)
→ defined:  (define x 8)
  evaluate: x
→ defined:  (define x 8)
  evaluate: 8
</code>```

I have also read about the SECD machine, closures, and environments, but they look to me like just a peculiar implementation method.

OwnerDisplayName: Alexey

Body:
After looking into Alonzo Church's The calculi of lambda-conversion, and thinking a bit about rewriting systems, different definitions of algorithms, and about Lisp, I have come to mostly agree with John Clements' answer: that the state of a Scheme program is a "reduced" Scheme program.

I would like however to formulate my own version of it (which i can edit or improve if I learn more).

In my opinion, a state of a Scheme program can be viewed as a sort of a Scheme program, where instead of constant literals, arbitrary constant data values are allowed (they have to be allowed because I am not sure if, for example, an arbitrary float value can be written as a float literal).

For example, a program can execute as follows (the sequence of states):

The program:

(define x 0)
(set! x (lambda (x) (+ x 1)))
(define y 2)
(x y)

Program state after step 1:

(define x (lambda (x) (+ x 1)))
(define y 2)
(x y)

Program state after step 2:

(define y 2)
((lambda (x) (+ x 1)) y)

Program state after step 3:

((lambda (x) (+ x 1)) 2)

Program state after step 4:

(+ 2 1)

Program state after step 5:

3

Update. To confirm this point of view, here are quotes from Racket reference:

1.1 Evaluation Model

Racket evaluation can be viewed as the simplification of expressions to obtain values. For example, just as an elementary-school student simplifies

  1 + 1 = 2

Racket evaluation simplifies

  (+ 1 1) → 2

The arrow → above replaces the more traditional = to emphasize that evaluation proceeds in a particular direction towards simpler expressions. In particular, a value is an expression that evaluation simplifies no further, such as the number 2.

[...]

1.1.4 Top-Level Variables

Given

x = 10

then an algebra student simplifies x + 1 as follows:

x + 1 = 10 + 1 = 11

Racket works much the same way, in that a set of top-level variables are available for substitutions on demand during evaluation. [...]

Each evaluation step, then, takes the current set of definitions and program to a new set of definitions and program.  Before a define can be moved into the set of definitions, its right-hand expression must be reduced to a value.

  defined:
  evaluate: (begin (define x (+ 9 1)) (+ x 1))
→ defined:
  evaluate: (begin (define x 10) (+ x 1))
→ defined:  (define x 10)
  evaluate: (begin (void) (+ x 1))
→ defined:  (define x 10)
  evaluate: (+ x 1)
→ defined:  (define x 10)
  evaluate: (+ 10 1)
→ defined:  (define x 10)
  evaluate: 11

Using set!, a program can change the value associated with an existing top-level variable:

  defined:  (define x 10)
  evaluate: (begin (set! x 8) x)
→ defined:  (define x 8)
  evaluate: (begin (void) x)
→ defined:  (define x 8)
  evaluate: x
→ defined:  (define x 8)
  evaluate: 8

I have also read about the SECD machine, closures, and environments, but they look to me like just a peculiar implementation method.


答:
Here's an example of your view model class using MVVM Light Toolkit:

```<code>public class EditViewModel : ViewModelBase
{
    public EditViewModel()
    {
        SaveCommand = new RelayCommand(noParameter => Save());
    }

    private void Save()
    {
        // Save code goes here.
    }

    public static ICommand SaveCommand { get; private set; }
}
</code>```

The RelayCommand class will relay all uses of the SaveCommand property to the Save() method in the view model class. The command itself does not need to reference the view model class since it is a member of the view model class.

Title: MVVM ViewModel and Commands

Body:
I need a bit of help to understand the relationship between a viewmodel and a command, and the responsibility of the viewmodel.

I'll try to give an example (using Caliburn Micro).

I have a viewmodel class, a command class and a view with a Save button.

```<code>public class EditViewModel : Screen
{
    public bool CanSave
    {
        get { return IsDirty; }
    }

    public void Save()
    {
        var command = new SaveCommand(this); // command gets reference to VM
        command.Execute();
    }
}

public class SaveCommand
{
    private readonly EditViewModel _viewModel;

    public SaveCommand(EditViewModel viewModel)
    {
        _viewModel = viewModel;
    }

    public void Execute()
    {
       var work = _viewModel.Work;
       ..
       _viewModel.IsDirty = false;
    }
}
</code>```

When the user click Save. Save() method is called and spins up a command that saves the work.

Now my question is, should the command have a reference to the viewmodel?

No) The viewmodel will have to pass the work to the command, which will have to pass the save result back to the viewmodel, which will update itself.

Yes) The command needs a reference to the viewmodel and properties needs to be public set-able.

No seems like the cleanest way, but also requires extra work, when the work or result aren't a simple bool or similar.

I guess the root it all is. What is the relationship between a viewmodel and it's command and the responsibility of the viewmodel ?

Is there a strong 1:1 "friend" relationship between the view-model and it's command, where code has just been moved to another class. So there is nothing wrong with the command having direct access to the viewmodel.

Another understanding, the viewmodel is a very simple class, almost only with properties and contains little logic. So the logic should be in the command.

Or the viewmodel is pretty smart and should contain application-logic. Commands are really only needed when there are either too many in one viewmodel or they are a bit complicated otherwise the command code can stay in the viewmodel.

I'm just rambling I guess, please help me out to understand the viewmodel and what it's responsibility is?

Body:
Here's an example of your view model class using MVVM Light Toolkit:

public class EditViewModel : ViewModelBase
{
    public EditViewModel()
    {
        SaveCommand = new RelayCommand(noParameter => Save());
    }

    private void Save()
    {
        // Save code goes here.
    }

    public static ICommand SaveCommand { get; private set; }
}

The RelayCommand class will relay all uses of the SaveCommand property to the Save() method in the view model class. The command itself does not need to reference the view model class since it is a member of the view model class.


答:
The definition for the in and out fields within the System class are:

```<code>public final static PrintStream out;
public final static InputStream in;
</code>```

These are constants.  They happen to be objects too, but they are constants.  It is very much the same as the Math class:

```<code>public static final double E = 2.7182818284590452354;
public static final double PI = 3.14159265358979323846;
</code>```

Or in the Boolean class:

```<code>public static final Boolean TRUE = new Boolean(true);
public static final Boolean FALSE = new Boolean(false);
</code>```

Or in the Color class:

```<code>public final static Color white     = new Color(255, 255, 255);
public final static Color black     = new Color(0, 0, 0);
public final static Color red       = new Color(255, 0, 0);
</code>```

When accessing a public constant that doesn't change, there isn't a significant advantage to encapsulate it - conceptually or performance based.  Its there.  It isn't going to change.

There is no real difference between Color.white and System.out.

Title: Why Java doesn't make use of encapsulation with some classes?

Body: My question is related with System.in and System.out classes (there might be others like those in the Standard library). Why is that? Isn't that a bad practice in OOP? Shouldn't it be used like: System.getIn() and System.getOut()? I've always had this question and I hope I can find a good answer here.

Body:
The definition for the in and out fields within the System class are:

public final static PrintStream out;
public final static InputStream in;

These are constants.  They happen to be objects too, but they are constants.  It is very much the same as the Math class:

public static final double E = 2.7182818284590452354;
public static final double PI = 3.14159265358979323846;

Or in the Boolean class:

public static final Boolean TRUE = new Boolean(true);
public static final Boolean FALSE = new Boolean(false);

Or in the Color class:

public final static Color white     = new Color(255, 255, 255);
public final static Color black     = new Color(0, 0, 0);
public final static Color red       = new Color(255, 0, 0);

When accessing a public constant that doesn't change, there isn't a significant advantage to encapsulate it - conceptually or performance based.  Its there.  It isn't going to change.

There is no real difference between Color.white and System.out.


答:
This answer is great and true.

I wanted to add that in some cases compromises were made for usability's sake.

Objects of type String can be instantiated without new, event when String is not a primitive:

```<code>String s = "Hello";
</code>```

String being a non-primitive, should be instantiated like this:

```<code>String s = new String("Hello");          // this also works
</code>```

But the compiler allows for the shorter, less OO option, because String is by far the most widely used class in the API.

Also arrays can be initialized in a non-OO way:

```<code>int i[] = {1,2,3};
</code>```

Weird enough, an object is either an instance of a class or an array. Meaning arrays are a completely separate type of class.

Arrays have a length public field which is not a constant. Also there's no documentation on the class arrays are an instance of. ( not to confuse with Arrays class or java.reflect.Array ).

```<code>int a = myArray.length;    // not length()
</code>```

Body:
This answer is great and true.

I wanted to add that in some cases compromises were made for usability's sake.

Objects of type String can be instantiated without new, event when String is not a primitive:

String s = "Hello";

String being a non-primitive, should be instantiated like this:

String s = new String("Hello");          // this also works

But the compiler allows for the shorter, less OO option, because String is by far the most widely used class in the API.

Also arrays can be initialized in a non-OO way:

int i[] = {1,2,3};

Weird enough, an object is either an instance of a class or an array. Meaning arrays are a completely separate type of class.

Arrays have a length public field which is not a constant. Also there's no documentation on the class arrays are an instance of. ( not to confuse with Arrays class or java.reflect.Array ).

int a = myArray.length;    // not length()


答:
Safely fixing production database data. What is the safest way to go about this from a big company standpoint? Are there tools that can help?

It is a bad practice and an invitation gate for more data problems and issues. There is even a phrase that describes this approach as "Quick and Dirty".

Continuing fixes/updates directly on a production server is very dangerous, as it will cost you/your company a fortune (law suits, bad/dirty data, lost businesses, etc.)

However, bugs will be there and need to be fixed. The de-facto industrial standard is to apply patches / (deployment scripts) on a Staging (pre-production environment with latest copy of prod database) and let data analyst/ QA to verify the fix. Same script should be version controlled and applied to the Prod environment to avoid issues.

There are number of good practices mentioned in this related post - Staging database good practices

Good set of references to look are:

How fast can you get a fixed bug into production?

Software Development Costs Pyramid

How Much Time Should be Allotted for Testing & Bug Fixing

Title: Safely fixing production database data


答:
Caliburn uses "conventions" to Autowire functions as commands to command targets. So your Save function on your ViewModel gets neatly wrapped up into a command behind the scenes (read the section on Action Matching in the Caliburn documentation on Conventions) to learn how it works.

Essentially, you can skip creating commands at all, because caliburn uses conventions to remove some of the ceremony of MVVM for you.

Title: MVVM ViewModel and Commands


问:
How would you evaluate object oriented design skills?
what kind of insights or questions would lead you to determine a person's OOAD skills.</p>

答:
You could show some half-assed OO design of a simple problem, and discuss what it does, what's good and bad about it, whether it's flexible enough, what could be improved, and how.

If you need to get the discussion going, ask what the person thinks about some aspect of the code, but not with a leading question.

Important is to remember that the discussion is important, not that you knew the answers beforehand. Any decent developer should be able to point out something about the code that you didn't even think of before.


答:
In most organisation's I have worked updating data in the live environment was always done by a small group of people with the access rights to do so, typically with a job title such as DBA. As updates could only be done by the small number of people there's at least a chance that they gain familiarity with the data and therefore reduces (but not eliminates) the risk of problems.

The person writing the update script would do so in test (as per other answers) and get serious sign off from non-techies (those who know the system, plus someone with senior authority) that the features appear to be 'right again' in addition to their own paranoid testing. The scripts, and the data, would be independently verified by another techie (often the DBA role I mentioned) on test before being ran into production. The results would be checked against the anticipated values (unique for every scenario, but often things like rowcounts etc.)

In one company I worked for, taking backups wasn't a realistic option, but all rows to be updated were written off to a text file for reference BEFORE the update, and then again AFTER the update should anyone ever need to refer to it. The scripts and this data kept in a properly organised Data Change Log.

Every business is unique, and the risks on updating some data is clearly greater than in others.

By having a process that makes people have to jump through hoops to do these updates, hopefully you promote a culture that makes people want to treat this as a last resort, and create a healthy "double check, triple check" attitude around this stuff.

Title: Safely fixing production database data


问:
Sort an array in a specific order - not ascending/descending
I'm working on an algorithm that works best if the inputs are passed to it in a particular order, so I want to sort them that way. The difference is drastic enough for me to consider re-sorting the array.

Consider an array a with length n. I want to sort it the following way, and return the array of indices of a instead of the values:

I define another array w, also of length n. I want to sort such that the first element is closest to the first element of w. Then, from the rest of the elements (excluding the one already sorted), the second element is closest to the second element of w, and so on.

For example a = {5.5, 6.5, 2.4, 3.1}, w = {1, 2, 6, 5}.

2.4 is closest to 1, so output[0] = 2, the index of 2.4.

2.4 is closest to 2, but already processed, so choose 3.1, output[1] = 3.

Next come 0 and 1, in that order. 0 is chosen because it comes first, although both are equidistant.

So, output = {2, 3, 0, 1} and the sorted array would be sorted = {2.4, 3.1, 5.5, 6.5} (each index is used to find the corresponding element).

I can only think of brute-forcing this algorithm. Can there be a more efficient way to do it?

答: Would this work?  Sort both arrays numerically, remembering the original indexes for w so you can restore it quickly.  Then use w's unsort on a.  This would give you a result of {2, 3, 1, 0} rather than {2, 3, 0, 1}, but that might be a better answer, depending how you look at it, and it would be a bit faster than brute forcing it.


答:
Read the book Head First Design Patterns. All the examples in the book start with an Object Oriented problem and than end up in the Design pattern. They also tell why certain OOP's concepts will achieve limitted results and why certain are better than others.

Even though a Design Pattern book this book is full of OOP's problems :-)

Title: How would you evaluate object oriented design skills?

Body: what kind of insights or questions would lead you to determine a person's OOAD skills.</p>


问:
Browser as a rich client platform
In Java there is a notion of "rich client platform" - it's a framework for building desktop applications, provides common features like help browser, window layout management, etc. Prominent frameworks are Eclipse and Netbeans.

Now I am curious if something like that can be done on top of web browser? I heard about XULRunner, Chrome extensions, NPAPI and such but hesitant to dive further (my current idea is to fork Chromium).

Basically, is there a way from a (serverless) browser application:

Work with filesystem (Open/Save/open OS file browser)

Start OS processes (e.g. some utilities) and parse their output.

Access dynamic libraries.

Alter browser UI (e.g. remove home/address bar, redo menus)

Package as something easily deployed throw the app stores.

Can this be done without forking the browser? What should I read about?

Updated Requirements:
Essentially I am looking for "PhoneGap for PCs" - but I really like how I could reuse Chromium UI (tabs, preferences, etc) if I forked it.
I'm prototyping on Mac, will setup a Linux build. I am not interested in Windows at this point...

答:
If I'm correct about your plan to make a desktop application, and not actually use the browser itself all that much, then Awesomium or a similar framework may interest you. You're still coding the back-end stuff in C#/C++, or whatever language you prefer, but your UI (the strength of HTML/CSS) can be coded using web technologies.

Also, if you don't mind reducing your target audience to 1/10th, Windows 8 lets you code apps using HTML/CSS/JS.

Title: Browser as a rich client platform


问:
Should I extract specific functionality into a function and why?
I have a large method which does 3 tasks, each of them can be extracted into a separate function. If I'll make an additional functions for each of that tasks, will it make my code better or worse and why?

Obviously, it'll make less lines of code in the main function, but there'll be additional function declarations, so my class will have additional methods, which I believe isn't good, because it'll make the class more complex.

Should I do that before I wrote all the code or should I leave it until everything is done and then extract functions?

答:
The problem you are posing is not a problem of coding, conventions or coding practice, rather, a problem of readability and ways text editors shows the code you write.
This same problem is apearing also in the post:

Is it OK to split long functions and methods into smaller ones even though they won't be called by anything else?

Splitting a function into sub-functions make sense when implementing a big system with the intent to encapsulate the different functionalities it will be composed of.
Nevetheless, sooner or later, you will find yourself with a number of big functions. Some of them are unreadeable and difficult to maintaint wether you keep them as single long functions or split them is smaller functions. This is particularly true for the functions where the operations you do, are not necessary in any other place of your system.
Lets pickup one of such a long function and consider it in a broader view.

Pro:

Once you read it, you have a complete idea on all the oprations the function does (you can read it as a book);

If you want to debug it, you can execute it step by step without any jump to any other file/part of the file;

You have the freedom to access/use any variable declared at any stage of the function;

The algorithm the function implements its fully contained in the function (encapsulated);

Contra:

It takes many pages of your screen;

It takes long to read it;

It is not easy to memorize all the different steps;

Now lets imagine to split the long function into several sub-functions and look at them with a broader prospective.

Pro:

Except the leave-functions, each function describes with words (names of sub-functions) the different steps done;

It takes very short time to read each single function/sub-function;

It is clear what parameters and variables are affected at each sub-function (separation of concerns);

Contra:

It is easy to imagine what a function like "sin()" does, but not as easy to imagine what our sub-functions do;

The algorithm is now disapeared, it is now distributed in may sub-functions (no overview);

When debugging it step by step, it is easy to forget the deepness level function call you are coming from (jumping here and there in your project files);

You can easily loose context when reading the different sub-functions;

Both solutions have pro and contra. The actual best solution would be having editors which allow to expand, inline and for the full depth, each function call into its content.
Which would make, splitting functions in sub functions the only best solution.


答:
Now I am curious if something like that can be done on top of web browser?

No you don't. If you start with a browser, you'll have to strip down everything on the browser. If you plan to create a desktop application from web technology, IMO it's more reasonable to start from the rendering engine, which is Webkit or Gecko and their JS engine and build up what you needed from there.

Some IDEs embed a HTML rendering engine for either their web development toolkit or their help viewer. ChromeOS and FirefoxOS are build on the idea that all their native applications are written in HTML/CSS/JS; Windows's Metro apps, Mac's Dashboard Widget, and the old Yahoo Widget are self-contained application written using HTML/CSS/JS. Then there is also Adobe AIR (that's mostly flash though).

Mozilla played around with Prism (no, not that PRISM), which is meant to be a platform for writing desktop application using web technologies, although this project is no longer active. I believe that - instead of bringing web technology to desktop application - they want to bring desktop capabilities to the web instead (i.e. pushing for Canvas, WebGL, Geolocation API, Web Worker, Web Socket, File API, Indexed Database API, ASM.js, etc). Although it's notable that Firefox OS is going to that other direction.

Title: Browser as a rich client platform

Body:
In Java there is a notion of "rich client platform" - it's a framework for building desktop applications, provides common features like help browser, window layout management, etc. Prominent frameworks are Eclipse and Netbeans.

Now I am curious if something like that can be done on top of web browser? I heard about XULRunner, Chrome extensions, NPAPI and such but hesitant to dive further (my current idea is to fork Chromium).

Basically, is there a way from a (serverless) browser application:

Work with filesystem (Open/Save/open OS file browser)

Start OS processes (e.g. some utilities) and parse their output.

Access dynamic libraries.

Alter browser UI (e.g. remove home/address bar, redo menus)

Package as something easily deployed throw the app stores.

Can this be done without forking the browser? What should I read about?

Updated Requirements:
Essentially I am looking for "PhoneGap for PCs" - but I really like how I could reuse Chromium UI (tabs, preferences, etc) if I forked it.
I'm prototyping on Mac, will setup a Linux build. I am not interested in Windows at this point...


答:
You probably want the Chromium Embedded Framework, which is apparently used by a fair number of high profile applications.

The Chromium Embedded Framework (CEF) is an open source framework for
  embedding a web browser control based on Google Chrome, it is a
  convenient way to implement an HTML 5 based GUI in a desktop
  application or to provide browser capabilities to an application. It
  comes with bindings for C, C++, Delphi, Java, .NET, Python and runs on
  Linux, Mac OS X and Windows.
  (wikipedia)

From the sound of it, you could write the bulk of your application in HTML+JavaScript+CSS, relying on some "host" language to provide access to system resources.

Another option, particularly if your target is non-Windows platforms, is to actually write a web application that either rests on apache or comes with a simple web server, like PHP's built-in web server. Launching the application, in the latter case, would be a matter of invoking both server component and the browser (after the server component picks a port to listen on).

If your target platform were Windows, the concept of a trusted HTML Application has been around for quite awhile. You'd basically write an HTML page (including javascript, vb script, and styling), give it a .hta extension, and it would operate like a trusted application.

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

From there, you'd be able to access Windows Script Host functionality.

That said, if your target environment is Windows, it's probably easier to just build your application with C# in Visual Studio, which is available in an "Express" (free) version.

Title: Browser as a rich client platform


问:
What do other languages offer when it comes to infrastructure technology that could indicate its advantage over C in the future?
I have been going through interview questions and I saw one which made me stop and think for a while. It starts with a quote and asks about your interpretation and whether you agree or not.

"For infrastructure technology, C will be hard to displace." - Dennis Ritchie

From a bit of background reading you can find that he was the mastermind behind C language as well as the UNIX OS. At the time it was a phenomenal improvement and at the forefront of cutting edge techniques. I feel that C++ and Java are becoming increasingly popular languages, but C will always be an important language.

What do other languages offer when it comes to infrastructure technology that could indicate its advantage over C in the future. On a side note, does anybody know which year this quote was made? I just want the opinions of people who use these languages a lot, I myself use python language and would love to learn a bit more about the framework around C and it's importance firsthand.

答:
For all of its advantages, C is an unsafe language; it lacks many of the safety guarantees that other languages have, such as:

Array bounds checking

Type safety

Garbage collection (to avoid memory leaks)

Despite these disadvantages, C is "closer to the metal," making it a very high-performing language, and offering real-time performance guarantees.  This is why it is often used to write kernels and device drivers, where performance really matters.

In reality, the most important part of an operating system (it's "kernel") is quite small; it can be written in C, while most of the other parts of the OS could be written in a more "modern" language.


问:
Java vs C#: What should a junior programmer (just finished degree) consider when entering the programming world?
I just want to hear some pro and con's - it's obvious that there is no right answer

So would Java be a better choice for a long term career? Or should I opt for .Net since it could be the platform having all the latest advances?

I just want to hear others point of view, so please don't close this question just because it's being subjective

答:
The number one benefit of Java over .NET is it's platform independence.You can only write .NET codes for Windows environment.

I have somewhat of limited experience in both and in my opinion, if you are only going to be developing applications for Windows, then .NET is better.

Also, those who come from C++ background, would fit into C# easily because a lot of the base structures are same. This is true of Java also, but I feel C++ is closer to C# than Java. After all, C# actually means, c++++.

Someone more adept in both technologies can given better and diverse range of suggestions.

OwnerDisplayName: oneWhoNeedGuidenss


问:
How can you denote the access modifiers "friend" and "protected friend" in UML?

The symbols for access modifiers that I know are relevant for many different languages:

public:        +

  private:       -

  protected:  #

  package:    ~ (or none)

However, in VB.NET there are other such access modifiers -- friend, and protected friend (these are called internal and protected internal in c#). What are the UML symbols for these access modifiers?

Is friend close enough to "package access" that it could be denoted with a tilde "~"? Would that then mean that protected friend could be denoted as "#~"?

答:
According to CSU Santa Barbara's web site:

We sometimes need an operation that has full access to a classes
  private information and yet must not be applied to a single object. In
  C++, for example, we have "friend functions" and "friend operations".
  These are indicated by placing the stereotype "<<friend>>" in front of
  the operation in the UML class diagram.

So you just annotate it and it is understood by other UML users.


问:
Is modifying an object's __dict__ to set its properties considered Pythonic?
I have a class that inflates objects from rows found in a database (or another source, e.g. MongoDB, a CSV file, etc.). To set the object's properties, it does something like self.__dict__.update(**properties) or obj.__dict__.update(**properties).

Is this considered Pythonic? Is this a good pattern that I should continue to use, or is this considered bad form?

答:
In Python 3.3, a new type was added, types.SimpleNamespace(), and in the documentation it is described thus:

The type is roughly equivalent to the following code:

```<code>class SimpleNamespace:
    def __init__(self, **kwargs):
        self.__dict__.update(kwargs)
    def __repr__(self):
        keys = sorted(self.__dict__)
        items = ("{}={!r}".format(k, self.__dict__[k]) for k in keys)
        return "{}({})".format(type(self).__name__, ", ".join(items))
</code>```

Note the __init__ method of the type; you cannot get a better endorsement of the technique than the Python documentation.

Body:
In Python 3.3, a new type was added, types.SimpleNamespace(), and in the documentation it is described thus:

The type is roughly equivalent to the following code:

class SimpleNamespace:
    def __init__(self, **kwargs):
        self.__dict__.update(kwargs)
    def __repr__(self):
        keys = sorted(self.__dict__)
        items = ("{}={!r}".format(k, self.__dict__[k]) for k in keys)
        return "{}({})".format(type(self).__name__, ", ".join(items))

Note the __init__ method of the type; you cannot get a better endorsement of the technique than the Python documentation.


问:
Safely fixing production database data
Bugs happen and sometimes data has to be fixed in production. What is the safest way to go about this from a big company standpoint? Are there tools that can help? Here are some considerations driving this requirement...

We need to log who ran the query and what they ran

Ideally we need to give the person access to only run queries against the tables of interest and only for a short time

Whatever is running the queries needs to have some smarts about it to not allow long running and locking SQL to run without explicit permission

This process needs to be DB agnostic or at least understand DB2, Oracle, and SQL Server.

We are trying to reduce the risk of ad-hoc prod fix-up queries from doing the "wrong thing" and at the same time add some security/audtis to the process. Thoughts or Ideas?

答:
I have updated data many times in running production databases. I agree with the answer above, that this would never be standard operating procedure.

It would also be expensive (we would look over eachothers shoulders and discuss 2 or 3 maybe)

And the golden rule: always make a select statement to show what would be done before doing an update/delete/insert statement

The golden rule being enforced by the other two people in the team!

Title: Safely fixing production database data


问:
C Equivalent of Perl Unpack & Pack
I have some perl code that uses pack and unpack to transform the data in a way that I don't understand.

```<code>$unpacked_data = pack('b*', join('', unpack('(b7)*', $packed_data)))
</code>```

Where $packed_data = a Byte Array of say, 2341 bytes, and with the above perl statement, unpacks to 2048 bytes of data.

Can someone explain this statement to me in terms of C?  So far, I know this:

b = A bit string (ascending bit order inside each byte, like vec()).

If the repeat count is * , the offset is relative to the start of the packed string.

答:
I believe that you have the sizes of the strings backwards.

If we start with 2048 bytes, that's 16384 bits.  Which is then broken up into 2341 groups of 7, each of which is put into a byte with the top bit 0.  (And the trailing bits in the last one are padded with 0.)

One would presume that the operation actually began with someone's idea for how to (poorly) compress pure ASCII text - namely since the top bit in each character is always 0, just store the first 7 bits.  This operation seeks to reverse that compression.  Which means that this will lose data when it runs across any data with the top bit set - for example if there is UTF8 unicode in the input.

If you know the original author of that code, this might make a good teaching moment.  Explain why data loss is not acceptable, show that person https://code.google.com/p/snappy/, and make the world a better place when crappy code doesn't break unexpectedly.

Title: C Equivalent of Perl Unpack & Pack


问:
Maintaining log stream after file name change
I'm trying to log to a file and move it about every 30 seconds.  I'm using the os.rename function (which I do from a supervisord process) in python to move the current log to a timestamped log (which will then be processed by another python script) and then I continue to log to the old stream from my uwsgi server.

I've also tried the RotatingFileHandler and the timed version, but they don't seem to work properly.  I wasn't sure if that was a function of using it with the uwsgi server or not.

My question is, what is the simplest and most efficient way to continue logging to the same file name after the file it was "pointing to" has been moved?

答:
Once Python opens a filehandle, it will continue to point to that file even if the file is renamed.  (This is OS specific behavior, but that is the POSIX defined behavior for Unix.)

Therefore you either need to do the log rotation from inside of the Python process, or else make the file that you write to be a named pipe that itself handles log rotation.  The latter is probably easier to set up.  http://www.linuxjournal.com/article/2156 is an old, but still relevant, article on how to do this under Unix.


答:
pack and unpack are functions within perl that can do some data transformations.

The innermost part of this is (b7)* - and you are correct that this is a bit string.  However, it is only taking 7 bits at a time:

From: http://perldoc.perl.org/functions/pack.html

the b and B formats pack a string that's that many bits long. Each such format generates 1 bit of the result. These are typically followed by a repeat count like B8 or B64.

You are taking a string that is 8 bits long, chops off the high bit and rewriting it back out as 8 bit data chunks.

Starting from the beginning of the input string, each 8-tuple of characters is converted to 1 character of output. With format b , the first character of the 8-tuple determines the least-significant bit of a character; with format B , it determines the most-significant bit of a character.

If the length of the input string is not evenly divisible by 8, the remainder is packed as if the input string were padded by null characters at the end. Similarly during unpacking, "extra" bits are ignored.

For this, you would be taking something that is probably ASCII or similar 7 bit data that always has its high bit as 0, stripping off the leftmost bit (see below), and rewriting it out as a constant stream of data (rather than every 8th bit being 0).

The key to this is that it reads in 8 bits at a time with the b and only uses 7 of them.

Of note, there's a little bit of additional 'huh' going on in this code from how one typically looks at data and numbers.  The b is reading the data little endian. This means that the leftmost bit is the one that is stripped off.

Lets take the string az and unpack it with b7.  The result is 1000011 0101111 (I put a space there so that I could more easily read it and separate the bits).

'a' in binary is 01100001 and 'z' is 01111010 as big indian.  Note the leftmost bit is 0.

unpack('(b7)*','az') will read it little endian (backwards from what one typically think) and drop the least significant (little endian) bit which is the leftmost one.

Now, that the always 0 leftmost bit of some (probably) ascii is gone, the entire thing is rewritten back out.

```<code>0110000101111010
^!      ^!
</code>```

becomes

```<code>11000011111010
!      !
</code>```

(the ^ and ! show equivalent spots between the lines)

Title: C Equivalent of Perl Unpack & Pack

Body:
I have some perl code that uses pack and unpack to transform the data in a way that I don't understand.

```<code>$unpacked_data = pack('b*', join('', unpack('(b7)*', $packed_data)))
</code>```

Where $packed_data = a Byte Array of say, 2341 bytes, and with the above perl statement, unpacks to 2048 bytes of data.

Can someone explain this statement to me in terms of C?  So far, I know this:

b = A bit string (ascending bit order inside each byte, like vec()).

If the repeat count is * , the offset is relative to the start of the packed string.

Body:
pack and unpack are functions within perl that can do some data transformations.

The innermost part of this is (b7)* - and you are correct that this is a bit string.  However, it is only taking 7 bits at a time:

From: http://perldoc.perl.org/functions/pack.html

the b and B formats pack a string that's that many bits long. Each such format generates 1 bit of the result. These are typically followed by a repeat count like B8 or B64.

You are taking a string that is 8 bits long, chops off the high bit and rewriting it back out as 8 bit data chunks.

Starting from the beginning of the input string, each 8-tuple of characters is converted to 1 character of output. With format b , the first character of the 8-tuple determines the least-significant bit of a character; with format B , it determines the most-significant bit of a character.

If the length of the input string is not evenly divisible by 8, the remainder is packed as if the input string were padded by null characters at the end. Similarly during unpacking, "extra" bits are ignored.

For this, you would be taking something that is probably ASCII or similar 7 bit data that always has its high bit as 0, stripping off the leftmost bit (see below), and rewriting it out as a constant stream of data (rather than every 8th bit being 0).

The key to this is that it reads in 8 bits at a time with the b and only uses 7 of them.

Of note, there's a little bit of additional 'huh' going on in this code from how one typically looks at data and numbers.  The b is reading the data little endian. This means that the leftmost bit is the one that is stripped off.

Lets take the string az and unpack it with b7.  The result is 1000011 0101111 (I put a space there so that I could more easily read it and separate the bits).

'a' in binary is 01100001 and 'z' is 01111010 as big indian.  Note the leftmost bit is 0.

unpack('(b7)*','az') will read it little endian (backwards from what one typically think) and drop the least significant (little endian) bit which is the leftmost one.

Now, that the always 0 leftmost bit of some (probably) ascii is gone, the entire thing is rewritten back out.

0110000101111010
^!      ^!

becomes

11000011111010
!      !

(the ^ and ! show equivalent spots between the lines)


问:
Using mod_rewrite for a Virtual Filesystem vs. Real Filesystem
I started working in a department that uses a CMS in which the entire "filesystem" is like this:

create a named file or folder - this file is given a unique node (ex. 2345) as well as a default "filename" (ex. /WelcomeToOurProductsPage) and apply a template

assign one or more aliases to the file for a URL redirect (ex. /home-page-products - can also be accessed by /home-page-products.aspx)

A new Rewrite command is written on the .htaccess file for each and every alias

Server accesses either /WelcomeToOurProductsPage or /home-page-products and redirects to something like /template.aspx?tmp=2&node=2345 (here I'm guessing what it does - I only have front-end access for now - but I have enough clues to strongly assume)

Node 2345 grabs content stored in a SQL Db and applies it to the template.

Note: There are no actual files being created on the filesystem. It's entirely virtual. This is probably a very common thing, but since I have never run across this kind of system before two months ago, I wanted to explain it in case it isn't common. I'm not a fan at all of ASP or closed-sourced systems, so it may be that this is common practice for ASP developers.

My question, that has taken far too long to ask, is: what are the benefits of this kind of system, as opposed to creating an actual file hierarchy? Are there any drawbacks to having every single file server call redirected? To having the .htaccess file hold rewrite rules for every single alias?

答:
Making all your linked pages a redirect is pretty horrible for SEO purposes -- the search engines will just see the somepage.aspx?node=1234 not your "pretty" urls. Rewriting the url behind the scenes is still ugly but a bit better.

You should really take a look at URL routing here -- that is going to do you alot better than dynamic url rewrites. The biggest downside there is that, without alot of voodoo, you are looking at a full app domain bounce anytime you add a page and that is after you get through the mechanical issues of mapping configuration values (the rewrites) to database values.

With URL routing you can setup a route like /{pageName} which will stuff that /home-page-products into the pageName variable. You then have an indexed list of pageNames that are mapped to the actual content. The Url itself never changes or is even rewritten on the back-side and it lets you swap out pages easily. You can even have multiple /{pageName} options go to the same page.


问:
Naming conventions for Java classes that have a static main method?
After reading gnat's answer to Why a static main method in Java and C#, rather than a constructor? I take his answer to mean that the purpose of a Java class with a static main method is to define a program entry point and that it is not meant to be the program itself.

There may be a better way to do this, but I usually have the class with the static main method to do something simple like this:

```<code>public class MenuLauncher
{
    public static void main(String[] args) {
        Menu menu = new Menu();
        menu.run();
    }
}
</code>```

Would the code above be the best practice for OOP where the class with static main doesn't do much more than launch or start program logic contained within a separate non-static object; after-all main is static so wouldn't the MenuLauncher class itself be very limited? Since main is a starting point I don't see any other purpose for the class other than to be a point of entry.

Is there a Java naming convention commonly used for classes that contain a main method and serve the purpose of being a program entry-point?

答:
They are called the Main-Class, whether or not they are called Main and whether or not they do little or much.

They usually have the logic required for starting up the program.

In CLI apps they usually validate parameters.

In Desktop app they open the main menu like yours or open the main window.

If you read the MANIFEST files in a jar file, you would find they are called that.

```<code>Manifest-Version: 1.0
Created-By: xxx
Built-By: xxx
Build-Jdk: 1.6.0_04
Main-Class: myPackage.MenuLauncher
</code>```

Body:
They are called the Main-Class, whether or not they are called Main and whether or not they do little or much.

They usually have the logic required for starting up the program.

In CLI apps they usually validate parameters.

In Desktop app they open the main menu like yours or open the main window.

If you read the MANIFEST files in a jar file, you would find they are called that.

Manifest-Version: 1.0
Created-By: xxx
Built-By: xxx
Build-Jdk: 1.6.0_04
Main-Class: myPackage.MenuLauncher


答: Will ask him to write down the business objects, classes, and interfaces/methods for a room or any other virtual entity</p>


问:
What is the intention behind asking weight of plane?
I was asked this question "How would you find weight of Aeroplane" in an interview and I am not sure why this question was one of the two question asked in the interview.

I tried to answer it using all possible ways but could not give the correct answer.(found the correct answer after google search)

How much such questions decide your selection in the interview?

Here was my approach:
1. If measurement of plane is given then i will calculate volume and multiply by density, will consider fuel weight plus other dead weight.
2. Using water displacement method if i can put plane in water and somehow measure how much water is displaced.

But found using google search that right approach was to put place on a ship and mark the level of water on the hull, then remove plane and then ship will go up.
And start putting weight on the ship till marked hull reaches the water level.

答:
The 'intention' is to judge what kind of problem solver you are.

But... Google recently let it be known that such questions are a huge waste of time that serve no purpose other than making the interviewer feel smart.  They actually crunched the numbers and found no correlation between how a candidate did on the questions and how successful they were at their jobs.  It turns out that the most effective way to judge a candidate is by asking them about their experience and then following up with questions.  (Which so happens to be the approach this brilliant individual has been promoting for years: https://softwareengineering.stackexchange.com/a/14666/897)

So to answer your other question about how much this sort of thing impacts your chances of being hired... at Google (or any other company with a shred of common sense), zero impact.  Unfortnately, much of the world is comprised of sheep who just follow the leader, and there are undoubtably a lot of companies that are still using these kinds of questions because they read in some 10 year magazine article that Google and Microsoft do it.

(source found through google news, but there's tons of other articles about it)
http://venturebeat.com/2013/06/20/google-says-tricky-job-interview-brainteasers-were-a-waste-of-time/


答:
I am roughly in agreement with the assertions that this is a 'brainteaser' intended to see how you think.  However, this is a real world problem, and it isn't trivial. The Air Force has 'Load Masters' whose only job is to figure out whether a given cargo manifest will fly, and if so how to balance and secure it.

So you start with the 'empty weight' of the plane, which (as is pointed out above) you get from the flight manual AKA the manufacturer.  It isn't quite this simple, because commercial aircraft in particular have different seating and accessory configurations, and these affect total weight.  Therefore, strictly speaking, you have to know the weight of the individual aircraft, not the model. This stuff is in the aircraft cockpit, and if you're asked to write code for it it's the employer's responsibility to provide you with the data.

Then you add weight of freight, weight of passengers, and weight of fuel.  Freight is fairly routine, however weight of passengers gets interesting, because there can be major differences, and normally airlines don't ask. A flight to Orlando with a bunch of kids is different from flights in and out of New Orleans, which tend to be adults indulging in culinary hedonism.

The fuel issue is then figured from the empty weight + freight + passengers (times miles + alternate + 45 minute reserve). Fuel needed depends on expected operating altitude and to a lesser extent the temperature and humidity of the departure airport - less dense air means longer takeoff runs.

If you had been able to get this far you would have probably overrun the interviewer, unless they're a pilot or unless the company you were going to work for is an airline.  A lot of the time the 'long way around' solutions are exactly what frighten the interviewer. They would rather you just look up the starting numbers and then start computing the end result from the respective variables.

Of course, I could have just led you down the wrong track - this is what I would have said, but if all they wanted to know was the empty weight then your formula would have to have been based on the (length * diameter of the fuselage * thickness of the skin * weight of the material) + (wing area * average thickness of the wing * weight of material) + (rough volume of engine * density of the materials in the engine * number of engines).  It sounds like they gave you more than one chance.  Next time someone asks you'll know.

Title: What is the intention behind asking weight of plane?

Body:
I was asked this question "How would you find weight of Aeroplane" in an interview and I am not sure why this question was one of the two question asked in the interview.

I tried to answer it using all possible ways but could not give the correct answer.(found the correct answer after google search)

How much such questions decide your selection in the interview?

Here was my approach:
1. If measurement of plane is given then i will calculate volume and multiply by density, will consider fuel weight plus other dead weight.
2. Using water displacement method if i can put plane in water and somehow measure how much water is displaced.

But found using google search that right approach was to put place on a ship and mark the level of water on the hull, then remove plane and then ship will go up.
And start putting weight on the ship till marked hull reaches the water level.


问:
Is using protected inheritance to hide (but exploit) implemented interface from the public ok?
Recently, we had a discussion about code using protected inheritance in order to hide the fact (to client code) a class inherits from a specific base class but to exploit this fact in the implementation.

The following code demonstrates this. It compiles with recent versions of GCC and clang++ (it uses C++11 features):

#include <vector>
#include <iostream>

class IObserver
{
public:
    virtual void update() = 0;
};

class Model
{
    std::vector<IObserver*> m_observers;
    int m_number = 0;
public:
    void addObserver(IObserver& observer) {
        m_observers.push_back(&observer);
    }
    void setNumber(int value) {
        m_number = value;
        notifyObservers();
    }
    int number() const {
        return m_number;
    }
protected:
    void notifyObservers() {
        for (auto pObserver : m_observers)
            pObserver->update();
    }
};

// We want to hide the fact class 'View' has 'IObserver' interface.
class View : protected IObserver
{
    Model* m_pModel;
public:
    View(Model& model) : m_pModel(&model) {
        model.addObserver(*this); // Exploit the fact we are an 'IObserver'.
    }
protected:
    void update() override {
        std::cout << m_pModel->number() << std::endl;
    }
};

int main(int argc, char *argv[])
{
    Model model;
    View view(model);

    //view.update(); // ERROR: 'update' is a protected member of 'View'.

    model.setNumber(1);
    model.setNumber(2);
}
```

The 'View' class inherits 'IObserver' interface but uses 'protected' modifier. So correspondingly, the public method 'update' inherited from that interface is protected. In the constructor, class 'View' adds itself as an observer to the 'Model' instance passed in as a parameter. Running the executable will output '1' and '2' in two separate lines, so the code runs as expected.

Now this solution was intensely discussed in our team but in the end there were some questions we could not answer with a common agreement:

Is this code actually legal w.r.t. to the C++ standard? The issue here is that, in the constructor, the 'View' class passes a reference to itself to method 'Model::addOberver' which expects a reference to an 'IObserver' instance with a public 'update' method. However, as the 'View' class uses protected inheritance, this method now is protected. So when 'Model::notifyObservers' method is called within 'Model::setNumber' method, the View's 'update' method will be called "from outside" in spite of the fact it is actually protected. (The C++ FAQ Lite states: "[protected inheritance] allows derived classes of the protected derived class to exploit the relationship to the protected base class". So this sounds like the code above is a corresponding use case.)

Assumed it is legal code, is it also good design? The fact we discussed a lot and didn't come to a common agreement might be a hint that it is not. Some of our colleagues had the opinion that a class' interface is solely defined by its public methods. And if 'View' class wants to pass a reference to itself to a method expecting an 'IObserver' instance it must use public inheritance. Some others (including myself) didn't agree with this strict definition. The implementation knows about the fact it has (and can provide) an 'IObserver' interface, so why should it not exploit this knowledge and expose the protected interface to code it wants to? In C++ we are able to define both, a public interface for "normal" client code and a protected interface for client code that wants to specialize/extend the class. So from this point of view, a class' interface is defined by its public and its protected interface. It just depends on which kind of client code "looks at" a class' interface.

If the goal is to hide away 'IObserver' interface from the public, is using the pImpl idiom solely for this purpose worth it? Because we were not able to come to a common conclusion regarding the first two questions we decided to "workaround" them by using the pImpl idiom and public inheritance in the implementation class. So we now have a class 'View' that does not inherit from 'IObserver' class at all. Instead, a class 'ViewImpl' now inherits from 'IObserver' publicly. While we agreed that this is "good design" it made our implementation more complex, we have one indirection more, and we now have to maintain nearly twice as much code. Furthermore, we need to maintain inheritance hierarchies for both, the public and the implementation classes. (Of course, these are well-known drawbacks from using the pImpl idiom.)

I appreciate your opinions regarding these three questions a lot!!! So many thanks in advance :-)

答:
We can establish that it is legal (i.e. valid) C++ because it compiles.  You've used it on GCC and clang and I've done exactly same thing with MSVC++ so that covers the majority of the compiler market.

This is why protected/private (btw, I would use private) modifier was introduced. It allows your class to implement callback interfaces which are needed for other classes it is using internally, but a) the rest of the world doesn't need to know that you are using those other classes and b) the rest of the world should not be able to even call on any of those functions because they are meant to be hidden and used only by internals.

When I transitioned from C++ to C#, I actually felt weird that I couldn't have private interface inheritance.  If something is an implementation detail and not intended to be seen/used by the public, it should be kept hidden and I think the method you described is a great and simple way of doing that.

Using pImpl just generates more overhead. When you allocate your objects (obviously assuming dynamic allocation), you end up going to the heap twice as many times. You also reduce the locality of your code because now View and ViewImpl might be in different pages in memory and will cause more cache misses. And you've increased the amount of boiler plate code you have to write because now you are forwarding all public interface calls from the View to ViewImpl.

This is all just my opinion but in the end, I cannot think of any reason not to have private interface inheritance.  I've written code like this for 6+ years and never had any readability/maintainability problems because of it.


问:
Why Java doesn't make use of encapsulation with some classes?
My question is related with System.in and System.out classes (there might be others like those in the Standard library). Why is that? Isn't that a bad practice in OOP? Shouldn't it be used like: System.getIn() and System.getOut()? I've always had this question and I hope I can find a good answer here.

答:
The real reason is that this is a legacy issue.  The System.in,out,err constants were part of Java 1.0 ... and probably a lot further back.  By the time it was clear that the design had problems, it was too late to fix it.  The best they could do was to add the System.setIn,setOut,setErr methods in Java 1.1 and then deal with the language specification issues1.

This is similar to the issue of why there is a static System.arraycopy method whose name violates the Java naming conventions.

As to whether this is "bad design" or not, I think it is.  There are situations where the current non-OO handling is a serious problem.  (Think ... how can you run one Java program inside another when their "standard IO" stream requirements conflict.  Think ... unit testing code that entails changing the streams.)

However, I can also relate to the argument that the current way of doing things is more convenient in a lot of cases.

1 - It is interesting to note that the System.in,out,err variables get special mention in the JLS as having "special semantics".  The JLS says that if you change the value of a final field, the behaviour is undefined ... except in the case of these fields.


答:
Discuss an open ended design problem with the person. See how s/he proceeds to build a model of the system, what kind of questions are asked, how the design changes in response to new information.

A great example - mentioned by Steve Yegge in one of his blog posts - is to ask the person to come up with an object model for XML.


问:
Do MVC web frameworks favor anemic domain model in order to avoid duplication?
Binding directly the form to your model helps a lot to get rid of boiler plate code, but that means that your model must have a getter/setter for each property otherwise it wouldn't be possible. Another choice would be to create another layer (DTO) only to carry the data to/from the form and then you can have a rich domain model not necessarily with getter/setter for each attribute but that means duplication of fields and validation code.

For instance, right now I'm doing a web mail application. We know that we already have the Java Mail API, a good rich domain model. However, the way it is designed makes it impossible to bind my web form to that model. I am forced to create a DTO to capture the data and then pass it to the Java Mail API. Just like this example if my domain model would be like this one, the same would happen.

From Spring MVC documentation:

Instead, it is often preferable to bind directly to your business objects.

Reusable business code, no need for duplication. Use existing business objects as command or form objects instead of mirroring them to extend a particular framework base class.

Do MVC web frameworks such as Spring MVC and Struts 2, favor anemic domain model in order to avoid duplication?

答:
In Martin Fowler's article you linked, he says of the Anemic Domain Model:

At first blush it looks like the real thing. There are objects, many named after the nouns in the domain space, and these objects are connected with the rich relationships and structure that true domain models have.

The catch comes when you look at the behavior, and you realize that
there is hardly any behavior on these objects, making them little more
than bags of getters and setters.   Indeed often these models come with
design rules that say that you are not to put any domain logic in the
the domain objects.

The fundamental horror of this anti-pattern is that it's so contrary to the basic idea of object-oriented design; which is to combine data and process together.  What's worse, many people think that anemic objects are real objects, and thus completely miss the point of what object-oriented design is all about.

However, having said that, he also says this:

Putting behavior into the domain objects should not contradict the solid approach of using layering to separate domain logic from such things as persistence and presentation responsibilities. The logic that should be in a domain object is domain logic - validations, calculations, business rules - whatever you like to call it.

This is where View Models come in.

View Models contain two things:

All of the data that is required to execute a view, and

Any logic that is required to render the view, but which can be pushed back into the ViewModel, rather than cluttering the view.

If the ViewModel does not contain any logic, then it is could properly be called an Anemic Model.  But it is not an anemic model of the domain.  While it might contain data from domain objects, the ViewModel object's sole reason for existence is to separate domain logic from presentation, just as Fowler observes.

The resulting arrangement makes it much simpler to focus on layout and user interaction in the View, without being concerned about how that interaction might pollute the domain objects and their logic, or vice versa.  It is the layer of separation that Fowler describes.

See Also

The View Model Pattern

Isn't MVC Anti-OOP?

ContentLicense: CC BY-SA 4.0