问:
How to display in compositional relationship that the item knows about the container?
I'm drawing a class diagram and noticed that sometimes I got a relationship (composition or aggregation) where the item uses the container, and sometimes not.

What is the visual difference in a composition where the item class uses the container class vs where the item class doesn't know about the container class?

答:
You can add an open arrow head to the composition or aggregation line, pointing toward the child to indicate directionality in the relationship. If the child knows about the parent, then simply don't include an arrow at all. I believe this works, because composition is a stronger form of an association link. The diamond indicates a composition or aggregation relationship. Without an arrow head, it can be read as either bidirectional or unspecified. Adding an arrow head makes it specific that the relationship is one-way.

Keep in mind that it doesn't make sense for a parent to not know about its child since these relationships indicate a parent maintaining a collection of children, so an arrow head pointing to the parent doesn't make sense. The only two reasonable relationships are bidirectional (parent knows about child, child knows about parent) and a "parent knows about child, but child doesn't know about parent" directional.

Directionality, indicating that the child does not know about the parent:

Bidirectionality, indicating that the parent knows about the child (required for a composition or aggregation relationship) and the child knows about the parent, or indicating an unspecified relationship (I would expect the details about the child's member variables and methods to provide hints):


问:
Test case design - do for all positive tests exist also negative ones?
There is ambiguity in all papers I have read so I would like to ask about the following requirement:

Requirement: Being a Game master, I can access the GM menu by typing "menuInvoke".

Trying to do that as a regular player - is that a negative test or still positive in terms of verifying the requirement? Because some authors say negative testing means dealing with inputs unknown to specification, which would not be this case as the spec does say you need to be a Game master, implying it is not allowed for the other ones. However if you think like that, it is always implicit: range 1-1000 implies that nothing else can be entered, yet we test it as a negative test.

An example of ambiguity:
Login system. Some say that providing incorrect password to receive Login error is negative test but I agree with the others - it is plain positive test as the requirement definitely specifies that only a user with valid password can login.

答:
Positive Testing: To test the positive flow or happy flow of the application. Here the user's intention is to navigate to sunsequesnt screen or functionality without facing any error messages.
Negative Testing: To test the invalid data handling, error messages verification.</p>

ContentLicense: CC BY-SA 3.0


问:
How much time can I spend learning at work?
I've been working as a software developer for about 2 years by now. It seems obvious that in a field so rapidly evolving as software development, you need to spend time on learning new technologies, frameworks, etc.

I always thought I could take it for granted that if I need to learn something to solve a problem at work, I am free to spend the hours needed learning that at work as well. However, I have had discussions about this topic with various colleagues, and we were holding very different opinions, apparently on the span of two extremes:

Your employer pays you for knowing stuff. You got hired for having knowledge on the field of expertise required for doing this job, and if the field emerges so that you need to aquire more knowledge, it is only natural that you do so in your free time.

And the other extreme being

Whatever makes me more productive at work in the long run, is worth spending the time on at work, because the employer will eventually profit from that. This does of course apply to learning new techniques, but also, e.g. learning VIM to get faster, etc.

But even when discussing how long to spend time on something with the guys tending to the second extreme, we were of vastly different opinions, ranging from "an hour every now and then is okay" to "however long it takes".

Does your workplace encourage learning new skills and if so what processes do they have to encourage this? How much time do you spend learning new things (and not writing production code) during your day as a programmer?

答:
I think this problem is too various to abstract it in a small set of simple rules, so I'll try to make some examples to show what my opinion is.  (Maybe some scenario is not very realistic, take it as an abstraction).

Case A:

Your project:   Develop a J2EE enterprise web application of some kind

Your knowledge: You know about "Java Enterprise", but it is the first time you
              actually get your hand on it (obviously you are a Junior)

You should:     Probably spend a good amount of time learning best programming practices and experimenting before starting the "real work"

Case B:

Your project:  Develop a parser from a language to another, in a more-or-less trival way

Your knowledge:You are a formal-language/parsers specialist with tons of experience.

You should:    Probably not spend any time (or very little) studying what you already know or learning other things

Case C:

Your project:  Develop a p2p library for android

Your knowledge: You know about networks, sockets, and TCP protocol, just you happen to not know the UDP protocol

You should:    Spend an average amount of time learning what the UDP protocol is and how to use it, if you know that it will help you in your project.

I think that in the IT world, some kind of learning while working is a natural fact in most of the cases, for the facts that technologies continue to evolve, and that even though you can be a professional, you may not know every single technology you are required to use or task you are required to do always at 100%, since there really are a lot.

The employer should also be aware, that computer scientists are not oracles, and that requiring to develop an e-commerce web application is not the same thing as buying a shower-box (I am sure they all are).

That said, given that an employer always has a project to work on, i think he should probably concentrate his learning and experimenting on the purpose of the project, or at least on the field of the project, so that his knowledge can grow aligned with his achievements.


问:
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>

答:
Here are the main ones in order of best improvement for time spent. Some of these will be more of a bottleneck depending on what data you're dealing with.

Front End:
There are easy wins on the front end. Cut down the number of requests with image sprites and aggregating css/js files. Make sure gzip and cache headers are being used.

Hardware:
Hardware can be cheap compared to your time. Throw more ram at the problem. Perhaps put your database on another server to cut down disk io.

Static Files:
Put static files on another domain and don't use cookies. You could use static.mydomain.com. It helps to serve these with a light weight server like nginx, this will cut RAM usage a lot.

A CDN is an easy option for this. 0.1 seconds is considered to be fast in usability. I'm in Australia so you've probably lost me no matter how fast you serve up the files.

Server side caching:
Setup a reverse proxy, it's much more efficient to have Nginx serving pages to slow mobile connections than have a heavy apache process waiting idle for the response to finish.

Memcached is an easy way of caching things in memory for fast retrieval.

Database Tuning:
Keep track of what queries are running slow. Add indexes on the columns you are using. Cut down the number of joins by denormalising where appropriate. You'll need to put the database on a second server at one stage. A lot of RAM can help as the indexes can then be kept entirely in RAM.

If you're interested in clustered hosting I would look at some of the presentations from facebook and youtube, wikipedia engineers on how they've done it.

edit some videos:
Youtube scaling: http://video.google.com/videoplay?docid=-6304964351441328559#
Django/General Scaling workshop: http://python.mirocommunity.org/video/1689/pycon-2010-django-deployment-w

Also one thing I may have forgot was if you have search a dedicated search engine like Solr/Sphinx can help.

ContentLicense: CC BY-SA 2.5

Title: What aspects make websites load faster?


问:
how to pluralize 'special' terms e.g. class names
Quite often I find myself referring in text to objects which have strict naming conventions e.g. Java objects, processes, services.  I find myself in a dilemma over how to pluralize these names.

It seems wrong to pollute the meaningful name by adding an 's' - or worse, a plural that modifies the rest of the name like SomethingUtility -> SomethingUtilities.  What if someone does a text search looking for the name?  Or cuts and pastes from my comment to search through a log file?

I have sometimes resorted to an ungrammatical apostrophe, but this can confuse plural with ownership.

Is there any better solution?

答:
If the class name cannot be converted into proper English, while retaining it's sense, then that's usually indicative of bad class naming. That is, if you're talking about a ShippingMethodRepository, then there's rarely a reason not to write "shipping-method repository" and thus "shipping-method repositories". This is easier for most people to read, because of the subtle visual clues in compound modifiers and such.

In the few cases where you feel a need to point to the class-name, if you give each situation some thought, you'll probably find that you're missing either the word "instance" or "class" in your sentence. I suggest putting it back in as a matter of course -- it is easy to cause confusion by not being specific.

As a bonus, this will make it easier to pluralise. ie. "ShippingMethodRepository instance" becomes "ShippingMethodRepository instances". (You'll probably find that you never need to pluralise class in this context.)


问:
Is there a point to unit tests that stub and mock everything public?
When doing unit tests the "proper" way, i.e. stubbing every public call and return preset values or mocks, I feel like I'm not actually testing anything. I'm literally looking at my code and creating examples based on the flow of logic through my public methods. And every time the implementation changes, I have to go and change those tests, again, not really feeling that I'm accomplishing anything useful (be it mid- or long-term). I also do integration tests (including non-happy-paths) and I don't really mind the increased testing times. With those, I feel like I'm actually testing for regressions, because they have caught multiple, while all that unit tests do is show me that the implementation of my public method changed, which I already know.

Unit testing is a vast topic, and I feel like I'm the one not understanding something here. What's the decisive advantage of unit testing vs integration testing (excluding the time overhead)?

答:
Though the op has already marked an answer, I am just adding my 2 cents here.

What's the decisive advantage of unit testing vs integration testing (excluding the time overhead)?

And also in response to

When doing unit tests the "proper" way, i.e. stubbing every public call and return preset values or mocks, I feel like I'm not actually testing anything.

There is a helpful but not exactly what OP has asked:

Unit Tests work but there are still bugs?

from my little experience on testing suites, I understand that Unit Tests are always to test the most basic method level functionality of a class. In my opinion every method either public, private or internal deserves to have a dedicated unit tests. Even in my recent experience I had a public method that was calling other small private method. So, there were two approaches:

don't create a unit test(s) for private method.

create a Unit Test(s) for a private method.

If You think logically, the point of having a private method is: main public method is getting too large or messy. In order to solve this You refactor wisely and create out small chunks of code that deserve to be separate private methods which in turn make Your main public method less bulky. You refactor by keeping in mind that this private method might be reused later on. There can be cases in which there are no other public method depending upon that private method, but who knows about future.

Considering the case when private method is reused by many other public methods.

So, If I had chosen approach 1: I would have duplicated Unit tests and they would have been complicated, as You had number of Unit Tests for each branch of public method as well as private method.

If I had chosen approach 2: the code written for unit tests would be relatively less, and it would be much easier to test.

Considering the case when private method is not reused
There is no point of writing a seperate unit test for that method.

As for as Integration Tests are concerned, they tend to be exhaustive and more of high level. They will tell You that given a input, all of Your classes should come to this final conclusion.To understand more about usefulness of integration testing please see the mentioned link.


问:
Why is a tooltip's attribute labelled 'title='?

HTML 4 supports a "title" attribute that can be inserted inside any HTML tag. Inserting this attribute effectively gives the element a tooltip that pops up when the mouse moves over it.

It just seems like a bad word choice.. or am I missing something?

答:
I think the tooltip is an implementation decision of browsers, not the intended used expressed in the specification.

I'm inclined to believe that the title attribute was intended for screen readers other and DOM parsers.


问:
How to handle the large website rss feed
Portal website usually have very large number of posts. For example I have 50,000 posts in website. I even created the google sitemap as chunks and included it in main site map file. But I have no idea how to deal with RSS feed.

50,000 posts in RSS feed file size will be very huge, how to handle the situation?

答: You're asking if it is important to include all links in RSS - look at other huge services - nytimes.com displays only 25 links in it's feed. It's up to RSS readers software to fetch your feed often enough to get all  I guess.</p>


问:
How to keep my Activity code readable and maintainable?
I have written a rather small App with only one activity. From my understanding an activity has to be seen as kind of a view and controller in one class.

But even for a little app, with 3 dialogs (made with AlertDialogBuilder and all those anonymous inner classes that come with it) my activity has 500+ LOC and became very hard to maintain. The activity houses mainly android lifecycle handlers and view handling. Business logic is very little.

How to handle activity classes to keep them readable and maintainable?

答:
Below are the points you need to remember:

Always bifurcate your codes in different methods. I mean for example, if you are registering the various event listeners then make one method "registerListeners()"

```<code>public void registerListeners() {
     // your button, listview....components event listeners codes
}
</code>```

then in onCreate(), call this method. By doing this, you have all registered listener codes at one place and they more readable and searchable.

getting all controls ID will be in another method named "initControls"

```<code>public void initControls() {
     buttonSave=(Button)findviewById(R.id.save);
     listviewItem=(ListView)findviewById(R.id.listviewItem);
     // etc..etc...components
}
</code>```

then in onCreate(), call this method. By doing this, you will have all controls id at one place and it will look very neat and clean. you can search it very easily.

```<code>onCreate() {
     //after setcontentview
     initControls();
     registerListeners();
}
</code>```

Hope, this helps you to explore more on code writing. :)

Body:
Below are the points you need to remember:

Always bifurcate your codes in different methods. I mean for example, if you are registering the various event listeners then make one method "registerListeners()"

public void registerListeners() {
     // your button, listview....components event listeners codes
}

then in onCreate(), call this method. By doing this, you have all registered listener codes at one place and they more readable and searchable.

getting all controls ID will be in another method named "initControls"

public void initControls() {
     buttonSave=(Button)findviewById(R.id.save);
     listviewItem=(ListView)findviewById(R.id.listviewItem);
     // etc..etc...components
}

then in onCreate(), call this method. By doing this, you will have all controls id at one place and it will look very neat and clean. you can search it very easily.

onCreate() {
     //after setcontentview
     initControls();
     registerListeners();
}

Hope, this helps you to explore more on code writing. :)


答:
Why? It's a historical artifact from the early days of the internet.  It originated with the HTML 1.2 draft (1993) and was integrated with the HTML 2.0 specification.  It's purpose was to indicate the title of the document--as simple as that.

Deeper dive:

In the beginning, the purpose of HTML was to provide a markup language that could be used for books and documents--not our modern understanding of web pages.

Back in those days, they had this great tag called "Title"

```<code><TITLE> Moby Dick</TITLE>
</code>```

The purpose of the TITLE tag was to declare the title of the document that you were viewing.

However, when you provided a link, you could add a title to that as well, so that the user knew what the next document was:

```<code><A TITLE="Moby Dick" HREF="...">Next Book</A>
</code>```

After that point, the title attribute moved to the other tags.  Later, when you added a "title" to a picture, the browsers chose not to display that immediately on the webpage, but to add it to the tooltip.  As it moved to other elements, it just became the tooltip.

Title: Why is a tooltip's attribute labelled 'title='?

Body:
HTML 4 supports a "title" attribute that can be inserted inside any HTML tag. Inserting this attribute effectively gives the element a tooltip that pops up when the mouse moves over it.

It just seems like a bad word choice.. or am I missing something?

Body:
Why? It's a historical artifact from the early days of the internet.  It originated with the HTML 1.2 draft (1993) and was integrated with the HTML 2.0 specification.  It's purpose was to indicate the title of the document--as simple as that.

Deeper dive:

In the beginning, the purpose of HTML was to provide a markup language that could be used for books and documents--not our modern understanding of web pages.

Back in those days, they had this great tag called "Title"

<TITLE> Moby Dick</TITLE>

The purpose of the TITLE tag was to declare the title of the document that you were viewing.

However, when you provided a link, you could add a title to that as well, so that the user knew what the next document was:

<A TITLE="Moby Dick" HREF="...">Next Book</A>

After that point, the title attribute moved to the other tags.  Later, when you added a "title" to a picture, the browsers chose not to display that immediately on the webpage, but to add it to the tooltip.  As it moved to other elements, it just became the tooltip.


答:
The W3C HTML standard on the title attribute:

This attribute offers advisory information about the element for which it is set...

Values of the title attribute may be rendered by user agents in a variety of ways. For instance, visual browsers frequently display the title as a "tool tip" (a short message that appears when the pointing device pauses over an object). Audio user agents may speak the title information in a similar context. For example, setting the attribute on a link allows user agents (visual and non-visual) to tell users about the nature of the linked resource:

```<code>...some text...
Here's a photo of
<A href="http://someplace.com/neatstuff.gif" title="Me scuba diving">
   me scuba diving last summer
</A>
...some more text...
</code>```

The title attribute is a not a tooltip. It is "advisory information about the element" that particular user agents may choose to render as a tooltip.

The title attribute is a mechanism to attach a text description directly onto an element; the particular UI implications of this information are implementation-dependent. The only requirement imposed by the WHATWG HTML standard about the visual representation of title's "advisory information" is that the information should be viewable somehow:

User agents should inform the user when elements have advisory information, otherwise the information would not be discoverable.

Body:
The W3C HTML standard on the title attribute:

This attribute offers advisory information about the element for which it is set...

Values of the title attribute may be rendered by user agents in a variety of ways. For instance, visual browsers frequently display the title as a "tool tip" (a short message that appears when the pointing device pauses over an object). Audio user agents may speak the title information in a similar context. For example, setting the attribute on a link allows user agents (visual and non-visual) to tell users about the nature of the linked resource:

...some text...
Here's a photo of
<A href="http://someplace.com/neatstuff.gif" title="Me scuba diving">
   me scuba diving last summer
</A>
...some more text...

The title attribute is a not a tooltip. It is "advisory information about the element" that particular user agents may choose to render as a tooltip.

The title attribute is a mechanism to attach a text description directly onto an element; the particular UI implications of this information are implementation-dependent. The only requirement imposed by the WHATWG HTML standard about the visual representation of title's "advisory information" is that the information should be viewable somehow:

User agents should inform the user when elements have advisory information, otherwise the information would not be discoverable.


问:
Source code "prints" at release
Is there a best practice for how to document the source code you're releasing?

Currently, we have a table of the versions of the software, what SVN tag it's labeled as, what SVN rev that tag was created at and the SVN URL.

Then, our CM (Configuration Management) department wants us to include a file listing of all the source files we're including for the .zip that we provide them which is just a zip of the tag we're releasing.

I'm more fishing for ideas to update our print template, hopefully with good arguments to remove the file listing.

答:
I'm not sure about what you're exactly asking for. If you need a zip of the files at a certain release/tag, here's what git offers:

git archive --output myzip.tar.gz mytag

Maybe there's a similar concept for `svn', too.

Title: Source code "prints" at release


问:
how to create database in which new columns have to be added periodically?
I want to create a database that tracks different projects and their finances. As finances are tracked monthly, a new column has to be created for each month. I could create all tables together at the start, yeah, but I guess it would be bad development strategy. Also I would be guessing the number of months. I will be creating an application to monitor those projects (like graphs and such)... so maybe I could code the program to do it at regular intervals.</p>

答:
Your problem is solved by not adding columns at run-time. You need to apply normalization.

You use two tables:

PROJECTS containing a PROJECT_ID field (generated ID, guaranteed unique and unchanging)

PROJECT_FINANCES containing PROJECT_ID (foreign key), PERIOD (date), AMOUNT (number)

Each time you have a new month, you add rows for each project to the PROJECT_FINANCES table. No need to add tables or columns in production.


问:
Do delegates defy OOP
I'm trying to understand OOP so I can write better OOP code and one thing which keeps coming up is this concept of a delegate (using .NET). I could have an object, which is totally self contained (encapsulated); it knows nothing of the outside world... but then I attach a delegate to it.

In my head, this is still quite well separated as the delegate only knows what to reference, but this by itself means it has to know about something else outside it's world! That a method exists within another class!

Have I got myself it total muddle here, or is this a grey area, or is this actually down to interpretation (and if so, sorry as that will be off topic I'm sure). My question is, do delegates defy/muddy the OOP pattern?

答:
No. Encapsulation doesn't insist that an object "not know anything about the outside world." It generally says two things:

Other objects don't need to know how an objects does what it says it does.

All methods and attributes related only to serving a particular class are contained in that class.

The second point is often stated in various manners that can gives an impression that objects shouldn't rely on outside stuff; but this is a highly impractical understanding, if not an impossible one. Consider a really basic class:

```<code>class Document {
  public String Title;
  public String Body;
}
</code>```

Even without any further definition, our Document class already knows about "outside" things: It knows about Strings! (String is an externally defined class.) And, ignoring the potential XSS issues for a moment, we might make a method that looks like this:

```<code>public String GetHtmlBlurb() {
  return "<div><b>" + Title.Substring(0, 60) + "</b> "
    + body.Substring(0, 120) + "</div>";
}
</code>```

The Substring method doesn't exist in our Document definition either! It's an externally defined method in the String class! But, this is perfectly expected, acceptable, generally necessary OO code. With the exception of classes built exclusively around primitives (do primitives really even exist in .NET?), a class is defined in terms of other classes (external stuff, the outside world, etc.).

Regarding delegates, we could have similarly defined our Document to work with a variety of Body types we have no other information about. All we might require is some way of producing a substring wherein there are multiple ways of doing so (perhaps one version adds elipses in certain cases). All our Document cares about is the ability to call some method that claims to be a Subtring-like method.

```<code>class Document {
  public String Title;
  public Func<Int32, Int32, String> BodySubstring;

  public String GetHtmlBlurb() {
    return "<div><b>" + Title.Substring(0, 60) + "</b> "
      + BodySubstring(0, 120) + "</div>";
  }
}
</code>```

In brief: A delegate is just a reference to a method, rather than the full object we might otherwise include as a property. The difference is that our delegate doesn't require the object to be of a certain type: only that a particular method have a certain signature. Our class doesn't know what the object does and doesn't insist on knowing anything about it. So, in that respect, it actually knows less about "the outside world."

Perhaps it's not an infringement on encapsulation. Perhaps it's uberencapsulation.

Title: Do delegates defy OOP

Body:
No. Encapsulation doesn't insist that an object "not know anything about the outside world." It generally says two things:

Other objects don't need to know how an objects does what it says it does.

All methods and attributes related only to serving a particular class are contained in that class.

The second point is often stated in various manners that can gives an impression that objects shouldn't rely on outside stuff; but this is a highly impractical understanding, if not an impossible one. Consider a really basic class:

class Document {
  public String Title;
  public String Body;
}

Even without any further definition, our Document class already knows about "outside" things: It knows about Strings! (String is an externally defined class.) And, ignoring the potential XSS issues for a moment, we might make a method that looks like this:

public String GetHtmlBlurb() {
  return "<div><b>" + Title.Substring(0, 60) + "</b> "
    + body.Substring(0, 120) + "</div>";
}

The Substring method doesn't exist in our Document definition either! It's an externally defined method in the String class! But, this is perfectly expected, acceptable, generally necessary OO code. With the exception of classes built exclusively around primitives (do primitives really even exist in .NET?), a class is defined in terms of other classes (external stuff, the outside world, etc.).

Regarding delegates, we could have similarly defined our Document to work with a variety of Body types we have no other information about. All we might require is some way of producing a substring wherein there are multiple ways of doing so (perhaps one version adds elipses in certain cases). All our Document cares about is the ability to call some method that claims to be a Subtring-like method.

class Document {
  public String Title;
  public Func<Int32, Int32, String> BodySubstring;

  public String GetHtmlBlurb() {
    return "<div><b>" + Title.Substring(0, 60) + "</b> "
      + BodySubstring(0, 120) + "</div>";
  }
}

In brief: A delegate is just a reference to a method, rather than the full object we might otherwise include as a property. The difference is that our delegate doesn't require the object to be of a certain type: only that a particular method have a certain signature. Our class doesn't know what the object does and doesn't insist on knowing anything about it. So, in that respect, it actually knows less about "the outside world."

Perhaps it's not an infringement on encapsulation. Perhaps it's uberencapsulation.


问:
Data Aggregation of CSV files java
I have k csv files (5 csv files for example), each file has m fields which produce a key and n values. I need to produce a single csv file with aggregated data.

I'm looking for the most efficient solution for this problem, speed mainly. I don't think by the way that we will have memory issues. Also I would like to know if hashing is really a good solution because we will have to use 64 bit hashing solution to reduce the chance for a collision to less than 1% (we are having around 30000000 rows per aggregation).

For example

```<code>file 1: f1,f2,f3,v1,v2,v3,v4
        a1,b1,c1,50,60,70,80
        a3,b2,c4,60,60,80,90

file 2: f1,f2,f3,v1,v2,v3,v4
        a1,b1,c1,30,50,90,40
        a3,b2,c4,30,70,50,90

result: f1,f2,f3,v1,v2,v3,v4
        a1,b1,c1,80,110,160,120
        a3,b2,c4,90,130,130,180
</code>```

algorithm that we thought until now:

hashing (using concurentHashTable)

merge sorting the files

DB: using mysql or hadoop or redis.

The solution needs to be able to handle Huge amount of data (each file more than two million rows)

a better example: file 1

```<code>country,city,peopleNum
england,london,1000000
england,coventry,500000
</code>```

file 2:

```<code>country,city,peopleNum
england,london,500000
england,coventry,500000
england,manchester,500000
</code>```

merged file:

```<code>country,city,peopleNum
england,london,1500000
england,coventry,1000000
england,manchester,500000
</code>```

The key is: country,city. This is just an example, my real key is of size 6 and the data columns are of size 8 - total of 14 columns.

We would like that the solution will be the fastest in regard of data processing.

答:
Since the key-fileds are always the first colums i would sort the source rows (whithout the header) by the keys and then advance in both files line  by line similar to Merge_algorithm used in Mergesort.

But instead of sorting the 2 csv-lists to one you compute the sum of elements that are in both list. Elements that are in one list only are simply copied.

The algorithm looks similar to this:

```<code>While (NOT EndOfFile(left-item) AND NOT EndOfFile(right-item))
  if (EndOfFile(right-item) OR left-item.key < right-item.key) store(left-item); advance left-item;
  if (EndOfFile(left-item) OR left-item.key > right-item.key) store(right-item); advance right-item;
  if (left-item.key = right-item.key) store(sum(right-item, left-item)); advance right-item; advance left-item
</code>```

Title: Data Aggregation of CSV files java

Body:
Since the key-fileds are always the first colums i would sort the source rows (whithout the header) by the keys and then advance in both files line  by line similar to Merge_algorithm used in Mergesort.

But instead of sorting the 2 csv-lists to one you compute the sum of elements that are in both list. Elements that are in one list only are simply copied.

The algorithm looks similar to this:

While (NOT EndOfFile(left-item) AND NOT EndOfFile(right-item))
  if (EndOfFile(right-item) OR left-item.key < right-item.key) store(left-item); advance left-item;
  if (EndOfFile(left-item) OR left-item.key > right-item.key) store(right-item); advance right-item;
  if (left-item.key = right-item.key) store(sum(right-item, left-item)); advance right-item; advance left-item


问:
Abstract class + Inheritance vs Interface
Hello fellow programmers,

I am reading a book on C# and the author is comparing Abstract classes and Interfaces. He claims that if you have the following "abstract class:"

```<code>abstract class CloneableType
{
public abstract object Clone();
}
</code>```

Then you cannot do this:

```<code>public class MiniVan : Car, CloneableType
{}
</code>```

This, I understand. However he claims that because of this inability to do multiple inheritance that you should use an interface for CloneableType, like so:

```<code>public interface ICloneable
{
object Clone();
}
</code>```

My question is, isn't this somewhat misleading, because you can create an abstract class which is "above" class Car with the method Clone, then have Car inherit that class and then Minivan will inherit Car with all these methods, CloneAble class -> Car class -> Minivan Class.

What do you think?
Thanks.

答: Abstract classes are used to "Setup" any class that is inherited from it, meaning that it can have default implementations of its properties and methods that all derived classes would then inherit. So for example if a derived class will inherit the startEngine default implementation, but not necessarily need to implement its own version, it can use its own version of the base class startEngine, and interface cannot have any completed methods, and would require you to define your own in every case. This allows in many cases better code re-usability, since the default implementation has all of the default methods and properties if you change something in your derived class it will not likely break previous code, where as with an interface, you have to go though and find all of the instances where the interface is being used and make the changes.  </p>


答:
There is no good reason for the choice of the attribute name title. The name has been fixed now, anyway, so the choice is practically irrelevant, except in teaching.

Historically, title was first defined for links only, and it was seen as specifying an “advisory title” for the linked document – a bit extravagant formulation, which means that it is an external title, i.e. a title (name) of the linked document as provided by the linking document.

Although the title attribute is still popular in some circles, it is being replaced by “CSS tooltips”, which provide much better rendering and control over it – and do not (normally) use a title attribute at all.


问:
Is it better to specialize in a single field I like, or expand into other fields to broaden my horizons?
This is a dilemma about which I have been thinking for quite a while.

I'm a graduate student and my topics of interest are programming language design, code analysis, compilation, etc. So far, this field has been very interesting and rewarding for me, so I was thinking about finding a job in that field and continuing to specialize in it. I feel like it's a relatively solid field which won't "get out of style" anytime soon. I've always thought that in such complex fields it's better to be a real expert than just another guy who superficially understand what the experts are talking about.

On the other hand, I feel that by specializing this way I really limit my future option. I have always been a strong believer in multidisciplinary approaches to problems. Maybe I should go search for a general programming job in which I could gain experience in other fields, as well as occasionally apply my favorite field for solving problems. Specializing in only one or two fields can prevent me from thinking outside the box and cause stagnation.

I would really like to hear more opinions about this choice. The truth is I'm already leaning towards one of the choices, so basic psychology says nothing will change my mind, but I would still love to hear some feedback.

答:
Generalist vs. Specialist is an article from CIO.com but there are probably dozens of similar articles or blog posts of people trying to see if one is better than the other.  Each has its advantages and disadvantages.  Anyone that wants to say one totally trumps the other may well be biased to some degree.

Don't forget that there is a possible illusion on each side of your choice.  What you see as a specialization may have various flavors to it.  For example, would you consider web developers overall to be specialists or generalists?  Some could see that as a specialization and others may still see it as being rather broad as many web-based applications these days can have all kinds of components that can require different expertise to some degree.

While the areas you list would make me think you want to work for a software company, there may be some parts of Information Technology that could use similar skills in a way.  You could get into how much customization is done on various off-the-shelf software to make it work and how well is this an investment for most companies to give an off-the-cuff example.


问:
How should we handle extra cosmetic features in Scrum sprints?
I was reading the Scrum documents and it says that the tasks in Sprint should be "potentially shippable".

I am confused by what this means. Suppose in Sprint 1 the goal was, "user registration form".

How much detail do I need to add for something to be ready to ship? For example:

I can show the simple form with fields without any fancy styling and mark them as done

I can just do client side validation as mark as done but server side is also the option or both

I can also add some jQuery fancy tool tips, hover overs, captcha, colors, labels for the form

Then there is whole lot of styling about how to show error messages on screen

I can do endlessly on one topic. So how do we divide that and when I can think of that as shipping ready.

Or do I need to write each smallest possible thing like showing errors, popup or light box text as subtasks and put them as sprint. This would lead to 1000s of tasks for whole project.

I mean then again if some work for Internet Explorer and some for Firefox then again do I need to divide those as tasks as well. Time has to be spent on them and when manager asks me what you did in that time, I won't have any tasks to tell but in reality they all are part of User registration

答:
Agree this with the product owner and the Scrum team, not the internet.  This should be determined in your Definition of Done, and will be largely dependent on how the team works.

Although the feature should be 'shippable' (I hate this term in Scrum) it could be argued that the functionality is shippable without the UI.  Many people suffer this misconception in Scrum - the aim of a sprint is to get as many stories as possible (ideally all) 'Done', but it most definitely does not need to be built into something that could be released.

It is important to iron things like this out early, so everyone across the team is working to a common goal.  The ethos of Scrum is communication, so ask the Scrum team and draw a logical conclusion.

You may work in a team where UI is generally handled separately, for example by a different team or once UI experts decide how the form should look etc.   Alternatively, in a small project/team it may be expected that the UI is built as you go.

As long as the team all know the answer, it is irrelevant what the answer is.


问:
Parallel Class/Interface Hierarchy with the Facade Design Pattern?
About a third of my code is wrapped inside a Facade class. Note that this isn't a "God" class, but actually represents a single thing (called a Line). Naturally, it delegates responsibilities to the subsystem behind it.

What ends up happening is that two of the subsystem classes (Output and Timeline) have all of their methods duplicated in the Line class, which effectively makes Line both an Output and a Timeline. It seems to make sense to make Output and Timeline interfaces, so that the Line class can implement them both. At the same time, I'm worried about creating parallel class and interface structures.

You see, there are different types of lines AudioLine, VideoLine, which all use the same type of Timeline, but different types of Output (AudioOutput and VideoOutput, respectively). So that would mean that I'd have to create an AudioOutputInterface and VideoOutputInterface as well. So not only would I have to have parallel class hierarchy, but there would be a parallel interface hierarchy as well.

Is there any solution to this design flaw?

Here's an image of the basic structure (minus the Timeline class, though know that each Line has-a Timeline):

NOTE: I just realized that the word 'line' in Timeline might make is sound like is does a similar function as the Line class. They don't, just to clarify.

答:
What ends up happening is that two of the subsystem classes (Output
  and Timeline) have all of their methods duplicated in the Line class,
  which effectively makes Line both an Output and a Timeline.

The above sentence sounds like bad design.

I would expect that most of the methods in a facade class invoke at multiple subsystem classes or at least multiple methods in a single subsystem class.

If you facade is doing lots of simple delegation (example, facade method doSomething simply calls another class' doSomething), you probably should refactor.

Specifically, if a delegate class does not interact with the rest of the subsystem, the client should probably should probably interact with the delegate directly, instead of through the facade.


问:
Java - Why do we call an array a "vector"?
I am reading a book on Java Programming, and want to confirm I understand the  definition of the word "vector".  Wikipedia says vector is "A one-dimensional array", source http://en.wikipedia.org/wiki/Vector.

Wouldnt it be simpler to call the array simply an array?  Is there any reason we need to use such fancy language as "vector"?  Is there a difference between an array and a vector?

Source: Cracking the Coding Interview, 4th Edition, by Gayle McDowell, page 47.

FAQ

Q - Why didnt you post this on english.stackexchange.com?

A - Because I think only computer science oriented people will have a good answer.

答:
It's just sloppy editing.

Early versions of Java did not include ArrayList.  Instead of ArrayList, Vector was used.  ArrayList was added later and is now used instead of Vector for most purposes.  I expect that the book was written before ArrayList was added, and that when the text was updated, this reference to vector was not.

I suggest you avoid this sort of "learn it all in ten minutes" book.  Generally they are written quickly and sloppily.  This level of knowledge won't get you a job in a serious shop.

Instead seek out well-reviewed books by recognized users of the technology covered and read for understanding.


问:
Find index of item closest to value, but is also less than value
Let's say I have a sorted array of ints like so:

```<code>int[] numbers = new[] { 10, 20, 27, 30, 55, 70 };
</code>```

What is the most efficient way, given a value, to find the value in that array (or the index of it) that is closest to the value but is not greater than the value?

For instance, given the value 26, it would return the 20.

Please note that the values in the array are dynamically assigned once when the program starts, but will not change for the duration of the program.

The simple solution that I'm using now is this:

```<code>int GetNumber(int value)
{
    foreach (int number in numbers)
    {
        if ((value -= number) <= 0)
            return number;
    }

    return -1;
}
</code>```

It works, but it's not extremely fast. I'm hoping there's some kind of algorithm that allows me to "map" values to ranges or something that will make lookups faster.

If it helps to know, I've used simple ints in my example, but the actual project I'm working on is a kind of segmented memory space where each of the segments are adjoined, but are of various sizes. This algorithm would allow me to pass in a memory address and get back the corresponding memory segment.

This is the actual method that is currently in use:

```<code>public MappedMemoryArea GetArea(int address)
{
    foreach (MappedMemoryArea area in _areas)
    {
        if (address < area.Size)
            return area;
        address -= area.Size;
    }

    return null;
}
</code>```

I have full control over the MappedMemoryArea type, so if adding a property to it would be beneficial for this purpose, it's totally doable.

答: This calls for a straightforward binary search - only instead of returning failure when the bounds converge without a hit, you return the next lowest index. (Unless the total number of values is so small that it easily fits into memory - then a complete cache is the way to go.)</p>


问:
First of the The Ten Commandments for C++ Programmers by Steve Oualline correctly transcribed?
I do not have the book “Practical C++ Programming” by Steve Oualline but I was reading his Ten Commandments for C++ programmers at The Ten Commandments for C++ Programmers and I was wondering if the first has been correctly transcribed? For reference the transcription is:

Thou shalt not rely on the compiler default methods for construction, destruction, copy construction, or assignment for any but the simplest of classes. Thou shalt forget these “big four” methods for any nontrivial class.

He seems to be advocating manually defining copy construction and copy assignment. Is that a correct interpretation of his first commandment?

Edit: Although at present I am leaving Adrian's answer as the accepted one I would like anyone who views this question to read Jerry's. I did specifically ask whether the above text is accurately transcribed and not about its merit (which is probably a more interesting discussion). But Jerry does make some good points about its merit (or lack thereof) which are similar to my opinions of it. I just wanted to make sure I had the quote right before I constructed a thorough argument of why I disagree with it.

答:
I think this is probably inaccurately transcribed in one respect. The sentence: "Thou shalt forget these “big four” methods for any nontrivial class." is probably intended to read: "Thou shalt not forget these “big four” methods for any nontrivial class."

Other than that, it looks to me like it's probably accurately transcribed. Unfortunately, the advice is mostly out of date. The book in question was written in 1995 and updated in 1997. A lot has happened in the 15+ years since then that renders this advice obsolete.

The advice is based on the notion of a non-trivial class implementing "remote ownership" -- i.e., containing one or more pointers to data it owns (that will probably be allocated on the free store, but somewhere outside the object itself in any case). Obvious examples are things like std::string and std::vector, each of which normally allocates a block of memory to hold the data in the container (and the string or vector object itself contains only the pointer and a little bookkeeping data, such as the size of the allocated block and the number of items in that block that are currently in use).

The reason I say that's out of date is that in most cases,  you should not be using raw pointers for remote ownership at all. Instead, you should typically use a smart pointer (e.g., unique_ptr or shared_ptr) to manage the remote ownership. That smart pointer should implement the remote ownership "policy" (copying, assignment, destruction) of the data it owns.

Then the non-trivial class will simply aggregate an instance (or more than one, depending) to manage its remote data. In the process, it gets the correct ownership policy implemented by those smart pointers. As a result, it usually won't need to implement any of the above at all.

That typically leaves only construction to be handled by the non-trivial class. Even that will typically just "distribute" data out to the base class and/or aggregated objects, so the body of the ctor is often empty:

```<code>class foo {
    std::unique_ptr<T> data;
public:
    foo(T const &input) : data(std::make_unique(input)) : {}
};
</code>```

Bottom line: a non-trivial class should present a logical view of an abstraction. It should deal almost exclusively with the logic of the abstraction it represents. It should rarely (if ever) directly deal directly with low-level, language-oriented issues such as allocation, deletion, and copying of memory needed to represent the abstraction it represents.

Those issues should nearly always be dealt with by lower-level classes also designed to represent an abstraction -- but in this case, a fairly simple abstraction of "remotely owned data", that knows how to handle things like copying, assigning, and destroying the data it owns, with little or no help from the class that owns it (e.g., the owning class passing some function arguments to tell how to destroy the owned data). At least in many (most?) typical cases, one of the pointer classes in the standard library (such as the aforementioned unique_ptr or shared_ptr) will be entirely adequate to this task.

As a result, you should rarely need to define your own copy constructor, copy assignment or destructor. These issues should typically be handled by lower-level classes devoted to providing remote ownership. There is, however, still a fair argument to be made that for non-trivial classes, these should still be defined (at least in most cases) but defined as = default; in most cases.

References and further reading:

https://web.archive.org/web/20151006051620/http://flamingdangerzone.com/cxx11/rule-of-zero/

http://herbsutter.com/2013/05/29/gotw-89-solution-smart-pointers/

ContentLicense: CC BY-SA 4.0

Body:
I think this is probably inaccurately transcribed in one respect. The sentence: "Thou shalt forget these “big four” methods for any nontrivial class." is probably intended to read: "Thou shalt not forget these “big four” methods for any nontrivial class."

Other than that, it looks to me like it's probably accurately transcribed. Unfortunately, the advice is mostly out of date. The book in question was written in 1995 and updated in 1997. A lot has happened in the 15+ years since then that renders this advice obsolete.

The advice is based on the notion of a non-trivial class implementing "remote ownership" -- i.e., containing one or more pointers to data it owns (that will probably be allocated on the free store, but somewhere outside the object itself in any case). Obvious examples are things like std::string and std::vector, each of which normally allocates a block of memory to hold the data in the container (and the string or vector object itself contains only the pointer and a little bookkeeping data, such as the size of the allocated block and the number of items in that block that are currently in use).

The reason I say that's out of date is that in most cases,  you should not be using raw pointers for remote ownership at all. Instead, you should typically use a smart pointer (e.g., unique_ptr or shared_ptr) to manage the remote ownership. That smart pointer should implement the remote ownership "policy" (copying, assignment, destruction) of the data it owns.

Then the non-trivial class will simply aggregate an instance (or more than one, depending) to manage its remote data. In the process, it gets the correct ownership policy implemented by those smart pointers. As a result, it usually won't need to implement any of the above at all.

That typically leaves only construction to be handled by the non-trivial class. Even that will typically just "distribute" data out to the base class and/or aggregated objects, so the body of the ctor is often empty:

class foo {
    std::unique_ptr<T> data;
public:
    foo(T const &input) : data(std::make_unique(input)) : {}
};

Bottom line: a non-trivial class should present a logical view of an abstraction. It should deal almost exclusively with the logic of the abstraction it represents. It should rarely (if ever) directly deal directly with low-level, language-oriented issues such as allocation, deletion, and copying of memory needed to represent the abstraction it represents.

Those issues should nearly always be dealt with by lower-level classes also designed to represent an abstraction -- but in this case, a fairly simple abstraction of "remotely owned data", that knows how to handle things like copying, assigning, and destroying the data it owns, with little or no help from the class that owns it (e.g., the owning class passing some function arguments to tell how to destroy the owned data). At least in many (most?) typical cases, one of the pointer classes in the standard library (such as the aforementioned unique_ptr or shared_ptr) will be entirely adequate to this task.

As a result, you should rarely need to define your own copy constructor, copy assignment or destructor. These issues should typically be handled by lower-level classes devoted to providing remote ownership. There is, however, still a fair argument to be made that for non-trivial classes, these should still be defined (at least in most cases) but defined as = default; in most cases.

References and further reading:

https://web.archive.org/web/20151006051620/http://flamingdangerzone.com/cxx11/rule-of-zero/

http://herbsutter.com/2013/05/29/gotw-89-solution-smart-pointers/


问:
Are t-shirt estimates a good way to conduct initial estimates?
I've read articles with very conflicting arguments on t-shirt estimates. Neither article seemed all that credible so I thought I would bring this up here.

Are t-shirt estimates a good idea?

For those who haven't heard of this: T-shirt estimates are the practice of giving very vague and high level estimates when given vague, high level requirements, and no resources to estimate.

They are based on t-shirt sizes and as such are broken down into: XS, S, M, L, XL, etc.

I don't see any problem in them in principle. Requirement gathering, requirements research and proper estimation all require time. Much of the time, 'clients' can request premature estimates and the ability to use t-shirt estimations allows for answers that are obviously overly vague and can't be held to any standard. At the time, this satisfies the 'clients' as they at least something to base their thinking on.

Conversely, if you were to give the same client the answer of 5,000 hours but gave the stipulation that this was just a guess and put that in bold, red, and blinking text. You run the risk of the client 'forgetting' this and then getting upset when these hours change drastically when a proper estimate is done.

答:
A manager's S is probably a programmer's L, and a programmer's L when being asked to give an estimate in under 30 seconds is often an XXXL in real life.

And of course your cautious programmer may say L whereas your flippant one says M.

So, they're only as good as the communication between the two people having the discussion.  At my small, close-knit firm where we're in good relations, my manager knows "shouldn't take too long" means "thinking about it for 10 seconds I don't see any glaring problems." But he also knows I would have to think about it a lot longer to be more sure no huge snags are hit. And, if you rely on t-shirt estimates, be sure you're only making commitments as good as your data.

Don't fall for the trap where these sound quantitative. They are qualitative. Thinking of how my firm operates, this table is problem accurate for how we would use them:

S - "shouldn't take too long."  (Later:  oh wait, this thing needs to be done too)

M - "doesn't sound that hard."  (But it involves a lot of components and one of them might be harder to code on or scale than I realize right now.)

L - "that's not easy."  (A week or two.  You probably don't want to do it unless it's an actual real project.)


问:
When comparing floats, what do you call the threshold of difference?
I'm comparing floats in Java right now and the simplest formula is:

```<code>Math.abs(a - b) < THRESHOLD
</code>```

When naming your variable for the threshold of difference, should you name it delta or epsilon? Specifically, which of the two is the correct term for the smallest value that a floating-point number can represent?

Is the term programming language specific, or is it universal across languages?

答:
Epsilon in maths and engineering

In maths and engineering in general:

Delta is generally used to refer to a difference, which can be of any scale.

Epsilon is generally used to refer to a negligible quantity.

and epsilon seems more appropriate in your case.

Epsilon in computer science

In computer science in particular, the term epsilon also refers to machine espilon which measures the difference between 1.0f and the smallest float which is strictly larger than 1.0f. That latter number is 1.00000011920928955078125f for floats in Java and can be calculated with:

```<code>float f = Float.intBitsToFloat(Float.floatToIntBits(1f) + 1);
</code>```

The definition of machine epsilon is consistent with the general use of epsilon described above.

Comparing floats

Note however that before comparing floats for "proximity", you need to have an idea of their scale. Two very large and supposedly very different float can be equal:

```<code>9223372036854775808f == 9223372036854775808f + 1000000000f; //this is true!
</code>```

And inversely, there might be many possible float values (and several orders of magnitude) between two small floats which differ by the machine epsilon "only". In the example below, there are 10,000,000 available float values between small and f, but their difference is still well below the machine epsilon:

```<code>float small = Float.MIN_VALUE; // small = 1.4E-45
float f = Float.intBitsToFloat(Float.floatToIntBits(small) + 100000000); // f = 2.3122343E-35
boolean b = (f - small < 0.00000011920928955078125f); //true!
</code>```

The article linked in GlenH7's answer investigates float comparison further and proposes several solutions to overcome these issues.

Body:
Epsilon in maths and engineering

In maths and engineering in general:

Delta is generally used to refer to a difference, which can be of any scale.

Epsilon is generally used to refer to a negligible quantity.

and epsilon seems more appropriate in your case.

Epsilon in computer science

In computer science in particular, the term epsilon also refers to machine espilon which measures the difference between 1.0f and the smallest float which is strictly larger than 1.0f. That latter number is 1.00000011920928955078125f for floats in Java and can be calculated with:

float f = Float.intBitsToFloat(Float.floatToIntBits(1f) + 1);

The definition of machine epsilon is consistent with the general use of epsilon described above.

Comparing floats

Note however that before comparing floats for "proximity", you need to have an idea of their scale. Two very large and supposedly very different float can be equal:

9223372036854775808f == 9223372036854775808f + 1000000000f; //this is true!

And inversely, there might be many possible float values (and several orders of magnitude) between two small floats which differ by the machine epsilon "only". In the example below, there are 10,000,000 available float values between small and f, but their difference is still well below the machine epsilon:

float small = Float.MIN_VALUE; // small = 1.4E-45
float f = Float.intBitsToFloat(Float.floatToIntBits(small) + 100000000); // f = 2.3122343E-35
boolean b = (f - small < 0.00000011920928955078125f); //true!

The article linked in GlenH7's answer investigates float comparison further and proposes several solutions to overcome these issues.


答: In mathematics, delta is used to represent some difference from a value, epsilon is used to represent an arbitrary error value.  In this case, epsilon would be the conventional name.</p>

Title: When comparing floats, what do you call the threshold of difference?

Body:
I'm comparing floats in Java right now and the simplest formula is:

```<code>Math.abs(a - b) < THRESHOLD
</code>```

When naming your variable for the threshold of difference, should you name it delta or epsilon? Specifically, which of the two is the correct term for the smallest value that a floating-point number can represent?

Is the term programming language specific, or is it universal across languages?


问:
Was C designed to facilitate Object-Oriented programming?
I am trying to broaden my understanding of the history and development of object-oriented programming, and I am curious to find out
if C was designed to facilitate Object-Oriented programming? (like C++ and Objective-C definitely are) or if it was, on the contrary, simply just a clever exploitation of the language's constructs.

I cannot seem to find any sources, including K&R, where the original authors comment on this approach.

Recently I have been looking into OOP in ANSI-C, which is described in Object-Oriented Programming With ANSI-C by Axel Schreiner.

For a freely available PDF version visit http://www.cs.rit.edu/~ats/books/ooc.pdf.

A slightly different approach is used in the part of the Linux kernel dealing with file systems, visit http://lwn.net/Articles/444910/ for more info.

The common idea is to put function pointers in a struct along with fields in order to 'emulate' a class' methods and data members.

Chronology

From Wikipedia.org/wiki/Object-oriented_programming#History

Objects as a formal concept in programming were introduced in the 1960s in Simula 67

While Wikipedia.org/wiki/C_programming#K.26R_C states that

In 1978, Brian Kernighan and Dennis Ritchie published the first edition of The C Programming Language.

The chronology seem to suggests that K&R must have been well aware of OOP.

So again:

Was C designed to facilitate Object-Oriented programming?

答: While the idea of OOP existed prior to the development of C, with Simula predating C by 5 years or so, none of C's language constructs actively encourage and facilitate OOP.  This doesn't mean that you can't do OOP, you just have to create it yourself.  Two examples that immediately come to mind are early C++ compilers that output C code & the Gnome project's extensive use of GObject to bring objects to C developers.</p>


问:
How do you unit test a User Interface?
I use JavaScript with JQuery for a Rails application. I have some dynamic behaviour in this one. As a Ruby developper, I like TDD/BDD, specialy with RSpec. For the moment, I test my JavaScript manualy. It's not the best way because a change, somewhere, can break the code somewhere else. The is a lot of avantages of using TDD.

Testing in javascript seems to be complicated because it should test a lot of user interaction. I can test the behaviour in complete integration, with Capybara for example, but my tests will be very slow.

For example, I have a form with dynamic behaviour. In this form, I have 5 or 6 dynamic fields which change if I select an option, choose a radio button or check a checkbox. In some cases, there is ajax calls. For this form, I think I can make about 20 tests just for a form. Is it really usefull to have this tests?

So, what's your rules for a standard web application?

答:
At work we've just started to use jasmine to test our javascript. There's a bit of a learning curve (but if you're familiar with RSpec it won't be too bad) and it may require a bit of a change in how you structure you code but overall it's been a really positive experience.

Keep in mind this is behavior testing for your code. This isn't a replacement for acceptance and integration testing.

Title: How do you unit test a User Interface?


答: Configuration Management (CM) folks don't think like programmers.  They think more like auditors.  The reason they want a list of the files is because they want to verify that they got them all.  Yes, this seems silly to a programmer, but it seems natural to someone who doesn't trust a single source of information.  Ideally, your list of files would not merely be an svn status -v or an ls -lR, but a human-mediated list of the specific files necessary to build your system and which you intend to provide.  Thus, for example, you would not list or provide the generated source files from a code generator that runs during the build process, even if they happen to be in your workspace at the time you build the ZIP file.

Title: Source code "prints" at release

Body:
Is there a best practice for how to document the source code you're releasing?

Currently, we have a table of the versions of the software, what SVN tag it's labeled as, what SVN rev that tag was created at and the SVN URL.

Then, our CM (Configuration Management) department wants us to include a file listing of all the source files we're including for the .zip that we provide them which is just a zip of the tag we're releasing.

I'm more fishing for ideas to update our print template, hopefully with good arguments to remove the file listing.


答:
Only Test if it Brings Value

I don't test typically, but if I did I certainly wouldn't aim for any percentage number of coverage or loading tests in front of everything I wrote but rather focus on handling of things I don't control and things that  were coded poorly that I don't have time to rewrite.

If behavior of things I do control and that I did in fact write is unpredictable, my problem isn't that I don't have tests, it's that I wrote piss-poor code that will be ungainly and a beast to maintain regardless of how soon I  find out that it's acting up (which is usually right away on the client-side if you haven't allowed it to be overwhelmed by pointless complexity). You only get so much time and UI tends to involve too many factors to attempt to micromanage the process of writing it successfully with something like a test-first TDD approach. I prefer a focus on keeping the code clean, obvious, minimal and robust.

Bury the DOM

IMO, the key to discovering things that are within reason to test is to bury all the client-side stuff in objects that can be manipulated more at an app-level of architecture. The goal being that at the highest level - so implementation and re-usable code typically - you just have plain vanilla objects. You're not looking at ajax methods being fed large sets of options and $ and document.getViaRidiculouslyExplicitlyNamedMethod, You're looking at stuff like comboFactory.build('combo_class_name') that any server-side dev that was mostly clueless about the client-side could figure out how to use.

What this does for you is split minutiae of the DOM-related stuff where keeping things robust isn't as simple as loading tests in front of every little thing you write, from the more app-level data flow concerns that you can actually think of in terms of a flow chart. That's where I would focus testing efforts if I wanted them.

So in the case of your crazy dynamic form:

If your ajax is all bundled up into service objects or a part of some silly seamless data layer that hides the async communication factor completely, you don't need to test in the context of the form. Service calls work or they don't. They can be tested independently.

For the dynamically populated form inputs, The vast majority of these inputs load from one other thing getting set. I wouldn't consider something like that worth testing as it's more likely to break due to DOM shenanigans tied to CSS or an HTML if your services already check out. So, maybe Selenium at the most. but unit tests don't really make sense to me there. Test-first-TDD never made sense to me but especially not for something like that.

Thoughtful Architecture First

If we have an ultra-complicated form with inputs populating themselves and mutating based on all 20 other input states in that form, assuming I had no power to call for a redesign (which would typically be the real problem in that case), I would go with a data-bound event-driven approach such that each input manipulation alters one set of data, triggering events on the data object itself that might cause other portions of your data model to mutate but the inputs themselves at most set the piece of data they care about and listen for changes to that set of data resulting in at most a handful of different types of behavior.

For each input, that's two simple avenues with minimal branching that work or don't work and we're  not likely to change in a way where potential fail-points aren't obvious and it's easy to hand test thoroughly before committing. That keeps the spider web of relationships confined to whatever your data abstraction is, narrowing all the more uncertain stuff down to something that itself only cares about what's left when other data elements get altered.

The question is what you value most, what I've just described or something a little bit more tangled and confusing but with tests all over it. My opinion is fairly strongly weighted on the former, but if you can manage both, power to you.

In UI, the DRY principle is paramount, IMO. Don't add tests unless there's a good argument that they'll add value over more time spent carefully crafting a code base in the first place such that it's easy to read, easy to modify, and easy to re-use portions of elsewhere. All three of those things require a number of other widely acknowledged critical heuristics in the craft of coding for which there is no substitute in my experience. Those are what drive my architecture and as a result it's not hard to add tests most of the time if I want to but I would never let a testing strategy actually drive my architecture. I'm only just starting to become more of a generalist but I'm fairly convinced at this point that these priorities work well for more than just web UI.

Title: How do you unit test a User Interface?

Body:
I use JavaScript with JQuery for a Rails application. I have some dynamic behaviour in this one. As a Ruby developper, I like TDD/BDD, specialy with RSpec. For the moment, I test my JavaScript manualy. It's not the best way because a change, somewhere, can break the code somewhere else. The is a lot of avantages of using TDD.

Testing in javascript seems to be complicated because it should test a lot of user interaction. I can test the behaviour in complete integration, with Capybara for example, but my tests will be very slow.

For example, I have a form with dynamic behaviour. In this form, I have 5 or 6 dynamic fields which change if I select an option, choose a radio button or check a checkbox. In some cases, there is ajax calls. For this form, I think I can make about 20 tests just for a form. Is it really usefull to have this tests?

So, what's your rules for a standard web application?


答:
A lot of individuals I know come from the mindset of the testing occurs from a person, not from a coded test.  This is, of course, the lack of a proper understanding of TDD using tools like QUnit (one of my favorites).  I used QUnit for a JavaScript game framework to ensure my components did the job.

It depends on how complex your JS really is, how the JS is been designed (unit testing requires it developed in a modular fashion).  If it's directly tied to the DOM, it will be more difficult, but not impossible, to test.  If you're only testing a few assignments, I wouldn't worry about it per se; however, if a lot of your UI is javascript-based, I would consider using a framework, and modularizing the code where possible.

Title: How do you unit test a User Interface?


问:
What does it mean to "promote" a file?
I hear this term around the office, and know it's relevant to software development lifecycle. What does "promote" mean? Context: e.g. to promote a file. </p>

答:
The full context is probably "promote a file to production" or something like that.  It just means that the file is to be moved to the "more important" or "more critical" system.  Presumably this only happens after code-review, testing, Q&A sign-off and so forth.

Analogy: a team leader is "promoted" to a manager.

How is a file moved from one environment to another, when it is promoted?

That is entirely dependent on how you build and deploy stuff to your test and production environments.

But for instance, suppose you use Git for your version control, and you have one branch for your test environment and another for your production environment.  In that case, you might promote a file (or more likely a changeset comprising changes to a number of files) by merging the changes in your test branch to your production branch, rebuilding the production code and deploying it.  (Or you could do a reset to make the HEAD of the production branch the same as the last commit for the changeset on the test branch.  Or you could cherry-pick ...)

Title: What does it mean to "promote" a file?


答:
In a well set up software development shop you will have various separated environments. "Sandbox", "development", "integration test", "User Acceptance Test", "Performance Test" and finally "Production" (or "beta" and  "General Release" if you are selling/distributing software).

This should be a progression of quality and rigorousness of testing. From "gee whiz I can compile it" in the sandbox environment to "I absolutely guarantee this works according to spec, as long as you don't pull the plug".

Moving a piece of software from one environment to the next is known as "promoting" it. Promotion should be preceded by some sort of quality assurance and testing to prove that the component is fit to be promoted.

Title: What does it mean to "promote" a file?

Body: I hear this term around the office, and know it's relevant to software development lifecycle. What does "promote" mean? Context: e.g. to promote a file. </p>


问:
How do I introduce clean code?
My team has about 18 members and the code is generally good, using TDD and good specifications makes for working code. But I think they abuse comments in favor of writing cleaner, more readable code.

I would like to introduce them to the concept and I'm wondering how can I do that on a larger scale without sitting with each and every one of them on their code and explaining how it could be improved.

This is different from the suggested duplicate because I believe I already know how to write clean code.  What I'm looking for is how do I introduce my team to writing clean code?

答:
have them watch the videos. http://cleancoders.com
he does a bunch of wacky stuff in the videos so its never boring.

Suggest to start with Ep 15. Get your group together and spend a few minutes discussing how to design an app for a simple coffee maker? and then watch   http://cleancoders.com/codecast/clean-code-episode-15/show

this video clearly shows the common mistakes in application design and then the big payoff using clean code. and its fun to watch so it should engage your team.

Title: How do I introduce clean code?


答: In the most basic sense, this is just using the associated command from the version control system in common-language "office talk." Occasionally, the command to move a file from a developer's workspace into a higher level of the version control tree ("Test", "QA", etc) is promote.

Title: What does it mean to "promote" a file?


问:
Is it possible to escape the GPL by deriving the same work from multiple sources?
Suppose you have an arbitrary code base, C, possibly composed of multiple programs, none of which fall under a copyleft license.

Suppose this code, taken together, does the same job as a nice integrated program, A licensed under some copyleft license like the GPL, but that for whatever reason the GPL code is superior (faster, cleaner, less buggy, whatever).

Now suppose that for each feature in C, you find the equivalent feature in A and, through careful step-by-step refactoring, create two chains of patches that converge on a third program, B.

In other words, you can show step by step, via patches, how to derive any of the three programs from any of the others:

```<code>A <--> B <--> C
</code>```

It seems that through this procedure, you have extracted value from A and even created a derived work, but the new work doesn't necessarily resemble A, and there is a clear chain of evidence showing that B was derived from a different code base entirely.

My question is:

Would a "dialectic" implementation like this provide the same legal effect as a traditional "clean room" implementation?

Note: feel free to replace the licenses of A and C with your most and least favorite options, respectively. The question is about the process in general.

答:
No.

Copyright doesn't work by "if you could".  It works by "if you did".  If you took C and modified it to get B, you are bound by C's license regardless of how close B is to A.  In theory, if you took a 10,000 line GPL file, deleted all but the first line, and wrote arbitrary code after it, you'd still be bound by the GPL.  In your initial example, if you create any chain of patches from C to B, you are bound by C's license regardless of what you do with A.  What you do with A is completely and utterly irrelevant to the matter.

Note that if you read source to C, walk into another room and type it from memory, you are still creating a derivative work.  A "clean room" implementation rests on the people doing the implementing having no direct knowledge of the original.  That is, someone reads C, figures out the interfaces, creates a basic design document describing those interfaces and gives it to someone else to implement.

Of course if it ever gets to trial, it becomes a matter of whether lawyers can prove based on a preponderance of that evidence that this is what you did and in practice the bulk of this evidence will center around whether you had access to the original and how similar your work is to the original.  Lawyers are going to lay out your work B and work C in front of either a judge or a jury and say "@tangentstorm had access to C and B is very similar, therefore he likely copied the work and is bound by C's license".

A would enter into it is if you claimed that your B derived from A and that similarity to C is pure coincidence.  The more knowledge of C you can be shown to have, and the more similar B is to C, the harder this will be.  You can certainly claim that you derived B from A and use patches/etc. as a defense, but if you actually used the process you describe, this would be perjury.

(Also note that this is civil law, where questions are of "preponderance of evidence", not "beyond reasonable doubt" like criminal cases.  In other words, 51% likelihood not 99.99% likelihood.)

In the situation like you describe, your best options are either to ignore C completely and derive from A alone or derive from C and abide by the GPL.  Trying to "get around" is both unethical and opens you up to legal risk.

NOTE:  I should state that I am NOT a lawyer, and if you are planning on anything like the original question, you should see a real one.  The general takeaway from this answer should really be that you are metaphorically asking if you've found a good way of poking a stick into a hornets nest.


答:
This A <--> B <--> C makes a nice logical thought experiment, but I can't understand the practical application.

I only see two possibilities:

1) A --> B <-- C

If B truly is derived from both (as you suggested), in other words, met-in-the-middle, then it is derived from C, as a means of linking A and C (and vice versa, though that doesn't seem to matter).

There would be no way to arrive at a middle, B, without direct knowledge and work from A, aside from a statistical impossibility as Steven Burnap says.

2)

Or if B is not derived from both, then it is derived from one, and the path to the other is reverse engineered using that source.

In this case, you either went A --> B --> C in which case you are bound by the license.  Or you went

C --> B --> A in which case you could argue you aren't bound by the license, but why would you have created the B --> A link at all?  In this case, if you'd stopped at C --> B, you'd be fine.

So either...

You are bound by the license.

or you did something you didn't need to do.

Title: Is it possible to escape the GPL by deriving the same work from multiple sources?

Body:
Suppose you have an arbitrary code base, C, possibly composed of multiple programs, none of which fall under a copyleft license.

Suppose this code, taken together, does the same job as a nice integrated program, A licensed under some copyleft license like the GPL, but that for whatever reason the GPL code is superior (faster, cleaner, less buggy, whatever).

Now suppose that for each feature in C, you find the equivalent feature in A and, through careful step-by-step refactoring, create two chains of patches that converge on a third program, B.

In other words, you can show step by step, via patches, how to derive any of the three programs from any of the others:

```<code>A <--> B <--> C
</code>```

It seems that through this procedure, you have extracted value from A and even created a derived work, but the new work doesn't necessarily resemble A, and there is a clear chain of evidence showing that B was derived from a different code base entirely.

My question is:

Would a "dialectic" implementation like this provide the same legal effect as a traditional "clean room" implementation?

Note: feel free to replace the licenses of A and C with your most and least favorite options, respectively. The question is about the process in general.


答:
No.

As I understand your proposal, you would be creating a copy of A by artifice.

You don't need to use a computer to copy a work, reading one work and re-producing it is still violating copyright. Copyright law does vary by jurisdiction, but AFAIK is fairly consistent in meaning. Basically, if you copy a work, whether it be computer software, a book, music, or whatever, a copy is a copy, and violates copyright.


问:
What is this (anti?)pattern called? (or how to describe it)
The case where a source-level operator actually describes an operation to take place at some future point, thunking the real operator together with its operands.

I don't know if this has any kind of general name, or perhaps it's too low-level a design element to be thought of as a "pattern" at all, but anyway it's an element that is frequently seen in a number of situations:

If I understand correctly (not a frequent C++ user), Boost::Phoenix does this to represent its lambdas and lazy operations, e.g. overloading + to actually capture the arguments along with the real + function for their type

Parser combinators in functional languages (or something like Spirit) look like operators on data, but actually build a parser that runs later

Other EDSLs (in languages with operator overloading) seem to do this a lot, e.g. functional reactive programming libraries tend to invisibly build procedures that will do what the operation looks like it's doing right now

(Again, if I understand correctly) IO in Haskell builds an imperative computation out of pure components that is then "executed" by dark magic hidden in the language runtime, while looking like it's just executing the functions in-place

At a simpler level, Greenspunning an embedded mini-Lisp into a C program could be considered the same thing: S-expressions can be built out of calls to C functions, to be run later (this last one would probably usually be considered the antipattern case), letting you look like you're passing "a lambda" to a C function, when you're really passing interpreter data

It's obviously not an antipattern in all cases, as in some of those it's the only way to use the tool in question (doing it in C might earn one a beating though). I don't think it's "Greenspunning" or "using an EDSL" by itself, as it can be more generic and widely applicable than that. I don't think it's the Interpreter pattern, although I may not have correctly understood that one: the computation is being built directly by executing host language code (so it effectively exists at compile-time, but usually not as a first-class language construct), rather than parsed out of a string or other runtime loaded data.

In all cases, what seems to happen is that an operation looks like it's doing one thing (not necessarily very convincingly, if it's C and you need to write out Add instead of overloading +, but same idea), while actually packaging that action up for later consumption. Something like a "computation builder" pattern? But I haven't found that term in use.

I don't have a practical problem to solve here; it's just bugging me that there seems to be a common design element that I can't put a name to.

(Question originally posted at StackOverflow, moved by hand)

答:
What you seem to be describing is Lazy Evaluation. Computations to be performed when the result is needed, rather than when it appears in the source code.

In Haskell, this is done by hiding these computations behind monadic abstractions. In C++, the abstractions are similar, but more explicit, and partially hidden behind overloaded operators and expression templates.

Similarly, your cited example of "Greenspunning" of a Lisp-like construct in C is not an antipattern, but rather a data-driven lazily-evaluated DSL, and seems, actually, to be one of the most common patterns of an FFI for Lisp and Scheme interpreters (especially in ECL, Chicken, tinyscheme and others), since C lacks the means to construct and pass unexecuted functions as data.

You will notice that these patterns do not appear in languages which have first-class function objects.


问:
How to handle complex views (consisting of several parts) in MVC web application
Lets say I am writing a blog web application using MVC pattern. Typical layout for the main page of the blog application is - some kind of a post index in the main part, and aside there are some addition parts, like timeline, tag navigation panel, subscribing panel, etc. Those controls also appear on a single post view, and may appear on other views I have.

My question is - how should I handle those panels aside in my views and controllers. I see three approaches here:

Create a big viewmodel class that contains all the information
required for rendering the view s (either index or single post).
That case I could make these aside panels a partial views, and
calling them from the view being rendered passing part of that big
viewmodel. The drawback is - I will have the code filling viewmodel
spread amongst various controller method, meaning code is
duplicated. Which is quite bad.

Create another layer of view rendering. Say, the topmost layer of
rendering recives a alreay rendered parts of html, or functions
which when called outputs an html. The layer under this  "combining
partials layer" would give just partial views for each panel I want,
include main content. The drawback here - memory usage. Most modern frameworks renders htmls directly to output stream, but in this approach partial views would be rendered into string objects first - which leads to memory overhead.

Use something like "RenderAction" from asp.net mvc, which calls a
controller method from a view. I think this is a worst solution of 3
given, because it drops an MVC approach.

The question is not tied to any specific framework, I want to understand the general way of doing things like that.

UPDATE

After an answer given, I've found out that post is not clear. So reasonable update here:

Under viewmodel term I understand an object that contains all the data required to render a particular view.

All of three approaches involve building partial views with their own viewmodel. For example (using C# syntax):

```<code>class SinglePostViewModel {
  string Text {get;set;}
  string Title {get;set;}
  string Slug {get;set;}
  DateTime PublishedDate {get;set;}
  ...
}

class TagNavigationPanelViewModel {
  string TagText {get;set;}
  int PostsCount {get;set;}
}

class CalendarNavigationPanelViewModel {
  DateTime YearAndMonth {get;set;}
  int PostsCount {get;set;}
}
</code>```

My question is - how to nicely combine those partial views together.

答:
I see another method that, unless I've misunderstood your post, hasn't been mentioned:

The main view, post, would have its model. This model would consist of ONLY the properties necessary to display this post (author,title,body, etc). Then, every piece of the post view that you can think of (timeline, tag navigation panel, subscribing panel, etc), would be split into their own views and each one would have its own model. This way, you can build up those models in your controller when you need them.

It might sound like an unnecessary amount of extra work to split these out like this, but it lends itself to the single responsibility principle. Keep each "view/model" focused on itself so that it can be re-used anywhere it is needed.

If you feel that your code is beginning to duplicate itself, which it might depending on your situation, you should consider writing some sort of "helper class." This helper class would handle all of the model build-up in one place, and all other duplicate code would be stripped down to a helper class call.


问:
Can we call final field as object's constant?
We call static final fields as constant, rather I should say Class constant.
So can we call just final fields as Object's constant? Is it right to say this?

```<code>Edited ::
</code>```

Consider the following code :

```<code>class JustFinal
{
    final int a=20;
    final int b;

    JustFinal(int x, int y){
        //a=x;
        b=y;
    }

    public static void main(String arg[])
    {
        JustFinal jf = new JustFinal(100,200);
    }
}
</code>```

In the above code field a will have a same value for all the object instances and field b can have a different value for a different object instance. Shouldn't we call the final field a as CONSTANT and final field b as OBJECT's CONSTANT?

答:
Any value that is determined at compile time and is unable to be changed can be considered a constant.

In your example code, you shouldn't be using final by itself at the class level if you are trying to have all instances of the object have the same value for a. Using the static modifier means that the value is only initialised once and then shared among objects of the same type, you should also make it private unless you want to share the constant with other classes. In your example, each instance of JustFinal will initialise int a=20; rather than all using the same copy (although the JIT will probably optimise this out for you).

Ultimately you can call a and b whatever you like, as long as people understand you. But if you used the phrase "objects constant" in conversation with me I'd have no idea what you were talking about.

The difference between a constant (defined at compile time) and a variable that, once assigned cannot have it's value changed, is mutability (not to be confused with immutable objects).

I'd use the term "immutable property/variable" over "objects constant".


问:
Will high reputation in Stack Overflow help to get a good job?
In a post, Joel Spolsky mentioned that 5 digit Stack Overflow reputation can help you to earn a job paying $100k+. How much of that is real?

Would anyone like to share their success in getting a high paid job by virtue of their reputations on Stack Exchange sites?

I read somewhere that, a person got an interview offer from Google because a recruiter found his Stack Overflow reputation to be impressive. Anyone else with similar stories?

答:
The head of computer science at my university insisted that my high grades would open doors.  That only seemed to be the case at the university itself.  In fact, some employers I interviewed with considered my grades to be somewhat low, because my school had lower 'grade targets' than the university local to that company.

Stack Overflow reputation demonstrably helps your chances in getting a career with Stack Overflow.  Beyond that, it really depends on the company.


答:
What I am doing is a variation/combination of your points 1 and 3.
I combine the viewmodels in a container class, and use that as a "main" viewmodel. The pass the parts as models to the partials.

Following your example, I would create this viewmodel for the default page:

```<code>class DefaultViewModel {
  public List<SinglePostViewModel> Posts ...
  public TagNavigationPanelViewModel Tags ...
  public CalendarNavigationPanelViewModel Calendar ...
  ...
}
</code>```

In Default.cshtml

```<code>@model DefaultViewModel
...html for rendering the default page...

@Html.Partial("_TagNavigationPanel", Model.Tags)
...etc...
</code>```

In _TagNavigationPanel.cshtml

```<code>@model TagNavigationPanelViewModel
...html+razor for rendering the tags...
</code>```

Then, follow the same approach for a single post page:

```<code>class SinglePostPageViewModel {
  public SinglePostViewModel Post ...
  // no tags in single view, for example..
  // public TagNavigationPanelViewModel Tags ...
  public CalendarNavigationPanelViewModel Calendar ...
  // But a list of related, perhaps?
  public List<RelatedPosts> RelatedPosts
  ...
}
</code>```

And build your views (cshtml(s)) accordingly

Title: How to handle complex views (consisting of several parts) in MVC web application

Body:
Lets say I am writing a blog web application using MVC pattern. Typical layout for the main page of the blog application is - some kind of a post index in the main part, and aside there are some addition parts, like timeline, tag navigation panel, subscribing panel, etc. Those controls also appear on a single post view, and may appear on other views I have.

My question is - how should I handle those panels aside in my views and controllers. I see three approaches here:

Create a big viewmodel class that contains all the information
required for rendering the view s (either index or single post).
That case I could make these aside panels a partial views, and
calling them from the view being rendered passing part of that big
viewmodel. The drawback is - I will have the code filling viewmodel
spread amongst various controller method, meaning code is
duplicated. Which is quite bad.

Create another layer of view rendering. Say, the topmost layer of
rendering recives a alreay rendered parts of html, or functions
which when called outputs an html. The layer under this  "combining
partials layer" would give just partial views for each panel I want,
include main content. The drawback here - memory usage. Most modern frameworks renders htmls directly to output stream, but in this approach partial views would be rendered into string objects first - which leads to memory overhead.

Use something like "RenderAction" from asp.net mvc, which calls a
controller method from a view. I think this is a worst solution of 3
given, because it drops an MVC approach.

The question is not tied to any specific framework, I want to understand the general way of doing things like that.

UPDATE

After an answer given, I've found out that post is not clear. So reasonable update here:

Under viewmodel term I understand an object that contains all the data required to render a particular view.

All of three approaches involve building partial views with their own viewmodel. For example (using C# syntax):

```<code>class SinglePostViewModel {
  string Text {get;set;}
  string Title {get;set;}
  string Slug {get;set;}
  DateTime PublishedDate {get;set;}
  ...
}

class TagNavigationPanelViewModel {
  string TagText {get;set;}
  int PostsCount {get;set;}
}

class CalendarNavigationPanelViewModel {
  DateTime YearAndMonth {get;set;}
  int PostsCount {get;set;}
}
</code>```

My question is - how to nicely combine those partial views together.

Body:
What I am doing is a variation/combination of your points 1 and 3.
I combine the viewmodels in a container class, and use that as a "main" viewmodel. The pass the parts as models to the partials.

Following your example, I would create this viewmodel for the default page:

class DefaultViewModel {
  public List<SinglePostViewModel> Posts ...
  public TagNavigationPanelViewModel Tags ...
  public CalendarNavigationPanelViewModel Calendar ...
  ...
}

In Default.cshtml

@model DefaultViewModel
...html for rendering the default page...

@Html.Partial("_TagNavigationPanel", Model.Tags)
...etc...

In _TagNavigationPanel.cshtml

@model TagNavigationPanelViewModel
...html+razor for rendering the tags...

Then, follow the same approach for a single post page:

class SinglePostPageViewModel {
  public SinglePostViewModel Post ...
  // no tags in single view, for example..
  // public TagNavigationPanelViewModel Tags ...
  public CalendarNavigationPanelViewModel Calendar ...
  // But a list of related, perhaps?
  public List<RelatedPosts> RelatedPosts
  ...
}

And build your views (cshtml(s)) accordingly