问:
Mutual observer pattern in Java
I want to improve my multi-threading and design pattern skills. As such I'm designing an Instant Messaging server.

I'm writing the Server first.

My plan so far is to have Client "Proxy" Classes to handle the socket connection for each Client. I want to have an "Exchange" Class that takes a message from a Client Proxy and hands it to the recipient Client Proxy.

I was thinking of having both the Client and Exchange observe each other in this situation via the Observer Pattern. Mutual observers as it were, with Client Proxy and Exchange being Observer and Subject.

On further thinking, should I instead have just the Exchange be the Observer and the Client Proxies as multiple Subjects for the Exchange?

-- Further thoughts

It seems people quite like the idea of mutual observation between Proxy and Exchange. I was planning on each Client Proxy running in a separate thread. Would the Exchange become the bottleneck if there's only one Object?

It sounds to me like I might need a pool of exchange objects, but I'm unsure how that would then map to the Observer pattern, even if I had some kind of broker in front of my pool of workers.

答: I think viewing both the Exchange and the Client Proxy as observers makes sense. Logically, events can happen both places so it makes sense to have each one "watching" the other for an event.</p>

OwnerDisplayName: retrodev

Title: Mutual observer pattern in Java

OwnerDisplayName: Chris Thompson


问:
How should I create a combined interface for two logically independent modules?
I'm having trouble coming up with a good way to structure the interfaces for two modules that are logically independent but whose implementations may be combined for the purposes of performance or efficiency.

My specific situation is the replacement of the separate queuing and logging modules in a message routing application with a combined database-backed implementation (let's call it DbQueueLog).  It's easy enough for DbQueueLog to implement both the IQueue and ILogger interfaces so clients of the old queuing and logging modules can use it seamlessly.  The challenge is that the most efficient and performant implementation of DbQueueLog involves combining the EnqueueMessage(Message m) and LogMessage(Message m, List<LogParams> p) methods into an EnqueueAndLogMessage(Message m, List<LogParams> p) method that minimizes the number of cross-process database calls and the amount of data written to disk.  I could create a new IQueueLog interface with these new methods, but I'm uncomfortable with what that would mean if a future iteration of the application moved back to separate queuing and logging modules.

Are there any design approaches to this situation that would allow me to build the efficient, performant DbQueueLog implementation now without permanently coupling together the application's queuing and logging modules?

Edit: The application is built on Windows using C# in case any there are any platform-specific techniques that might be available.

答:
If they are logically independent modules that happen to share in part a common implementation, you should not create a combined interface for them, because it will haunt you if you ever decide to use separate implementations again.

On the other hand, you mentioned that one of the modules is a logging module.

If all the calls to IQueue should (ideally) be accompanied by a corresponding call to the logger, then you could decide to place that responsibility with the implementation of IQueue.
A function can call EnqueueMessage and get that event logged as well at the same time without any effort.

That way, you can use your optimised implementation now, and if you ever need to split them, you can do that without affecting the users of IQueue and the logger.

If the logging interface takes additional parameters for which there is no reasonable default and the value also can't be deduced from the existing arguments to the IQueue method, then it should be clear that adding the responsibility of performing the logging to the IQueue implementation could mean that you have to change the interface of some (or all) the IQueue methods.

ContentLicense: CC BY-SA 3.0


问:
What are the pros and cons for the employer of code questions during an interview?
The Joel Test question #11 is: "Do new candidates write code during their interview?". What are arguments for and against to ask new candidates to write code during the interview and to make a decision upon it?</p>

答:
Cons:

Requires you to have a technical person in the interview

Pros:

Saves a LOT of time and heartache down the road if you prevent hiring someone who can't program

ContentLicense: CC BY-SA 2.5


问:
Mockup strategy for Responsive Web Design (from a programmer point of view)
When making mockups for Responsive Web Design projects, should I separate them by Page or by Screen Size? Which one would be more helpful when I start writing the source code?

What are the pros and cons of the following:

Page based: All the home page mockups in all different screen sizes

Screen-size based: All the pages for width <= 960px

I'm using Balsamiq Mockups to make mockups and I prefer to store all related mockups in a file like homepage, login or 960px, 768px.

答:
Screen-size is an overall approach that can covers a lot of device display of today market.
But Page based approach allows to create a perfect application designed for each mobile device screen.

Today the recommended approach is Screen-size based because the amount of devise increase every day with different screen size and characteristics.


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

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

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

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

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

Thanks in advance;

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

Well, there's always the documentation, but there's really no better way than reading the source code. The nopCommerce source code is organized fairly well, so it shouldn't be too hard.

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

I have not tried this, nor do I know anybody who has. However, just a cursory look at the code shows that the data access strategy is pretty strongly structured around the Repository pattern using Entity Framework.

http://www.nopcommerce.com/docs/71/source-code-organization-architecture-of-nopcommerce.aspx

The Nop.Data project contains a set of classes and functions for reading from and writing to a database or other data store. It helps separate data-access logic from your business objects. nopCommerce uses the Entity Framework (EF) Code-First approach. It allows you to define entities in the source code (all core entities are defined into Nop.Core project), and then get EF to generate the database from that. That's why it's called Code-First. You can then query your objects using LINQ, which gets translated to SQL behind the scenes and executed against the database.

I would say that converting to a NoSQL back-end would probably require some significant effort. There have been other SO posts discussing using RavenDb with the repository pattern. Can it be done? Sure. Can it be done in a month or two? Maybe, but it's impossible to say without knowing a lot of your specific situation's details.


问:
Method vs Function vs Procedure
Simple question, but I often hear these three terms defined with such ferocity, but which have been known to me to mean different things over the years.

What are the "correct" definitions of "Procedures", "Methods", "Function", "Subroutines", etc?

答:
good detailed answers above; the short story is that they'll all flavors of subroutines; what is meant by each term will vary according to the programming language context

in general, functions return a value, but they don't have to

methods are a generic OOP terms at present

in SQL, stored procedures have outputs but typically only return an error code, while user-defined functions must return a value (which may be a result-set)

again, the precise difference between these terms depends on who you're talking to!

Title: Method vs Function vs Procedure


问:
Memory allocation of Classes that don't have any global data and locks
```<code>    static void Main(string[] args)
    {
        var c2 = new Class2();
        var c3 = new Class3();
        var c1 = new Class1(c2, c3);
        c1.Method1();
    }

    class Class1
    {
        readonly Class2 _class2;
        readonly Class3 _class3;
        public Class1(Class2 class2, Class3 class3)
        {
            _class2 = class2;
            _class3 = class3;
        }
        public void Method1() {
            _class2.PerformM1();
            _class3.PerformM2();
        }
    }
    class Class2
    {
        public void PerformM1()
        {
            //do some operation
        }
    }
    class Class3
    {
        public void PerformM2()
        {
            //do some operation
        }
    }
</code>```

Question based on above code:

How much memory does object of Class1 has when it is created?

Does any memory increases or decreases when I perform c1.Method1();
keeping in mind that none of the classes have any global fields that
might acquire any space.

Edit

Expanding with one more question:

If creating new objects of Class1 and calling methods of c1 object does not involve much memory usage, then is it correct to say that I don't need a lock in the above provided sample code.

I can simply create n number of objects and assign individual object to individual Task( or thread)?

答:
The (possibly slightly outdated) article Drill Into .NET Framework Internals to See How the CLR Creates Runtime Objects explains that in .Net, each object takes at least 8 bytes (4 bytes for syncblock, 4 bytes for TypeHandle). Class1 has two instance fields, both of which are references. Assuming your code is running as a 32-bit application, that means 4 more bytes for each reference. That would mean each instance of Class1 takes 16 bytes in total.

Though this makes me confused about your title, because Class1 does have some state.

The only memory required directly by the call to Method1() is some stack space for the activation frame of the call. It won't allocate any memory from the heap.

Though in the end, it's most likely that all of this won't matter to you.

is it correct to say that I don't need a lock in the above provided sample code.

That's hard to say without actually seeing your code. But in general, creating one instance of a class for each task is a valid approach. And that includes types that do have some state (assuming it's not shared state).


问:
Search algorithm
I would like to create a site where users can post articles with the following optional parts:

A title

Contents (text)

Categories

Keywords

Articles will be stored in mongodb and the site will be built in node.js. Users can search the site using a normal search text box.

I'm thinking about creating the following collections:

Users

Articles

Keywords

I will then create an entry for each keyword used in the Keywords collection with an array containing all the articles that use it. If a user conducts a search, the search is broken up into keywords and each keyword is looked up in the Keywords collection. Each article is then retrieved from the db and ranked based on relevance.

My questions are:

Would it be efficient to use a Keywords collection like this, should I just use the Articles collection (Using full-text search or something) or should I structure it in some other way?

How would I incorporate the ability to search the title, contents or categories for articles instead of just the keywords?

Would it be better to use something like Apache Lucene than to build this functionality myself?

答:
I would use an existing platform designed for search.  You mentioned Lucene and there are others around based on the language you are using.

If you want to create a stand alone search server that is language agnostic look at SOLR.  It is based on Lucene, so lots of support.

I personally like Sphinx, but it may not work in your situation, it all depends on the language you are using.

Title: Search algorithm


问:
Why are CIL and CLR required in .NET?
I saw this nice image here. I learned that all the compilers that support .net language convert the source code to CIL format. Now Microsoft is never bringing in .NET for all the operating system by writing a CLR for all operating systems. Then why keep such an intermediate code format and a CLR to execute that CIL. Is that not an headache to deal with. Why did Microsoft choose be like this ?

EDIT This kinda architecture has its price. It will reduce the performance, wouldn't it ? Java does this to maintain platform independence, for what reason .NET do it ? Why not keep a simple plain C like compiler. Any way will also require a compiler to convert the code to CIL if I need to add up any new language, the only difference it would make is the target language. Tat's all.

答:
.NET has an intermediate language (CIL/MSIL) and platform-specific implementations of a platform-independent runtime (CLR) for the same reason Java does. Microsoft intended C# to directly compete with Java, and it does, on the OSes that Microsoft targets (its own).

The advantages, even though .NET is only supported on Windows platforms (or other OSes that have a .NET workalike like Mono/Linux), are similar to Java:

Managed Memory Runtime - Unlike unmanaged C/C++, C#/VB.NET developers don't have to worry about strictly controlling object lifetime. Like Java, the CLR has a garbage collector that automatically frees objects in the heap that leave scope. While this may seem minor to someone used to unmanaged runtimes, it has the extreme secondary advantage of discouraging the "black magic" of pointer arithmetic that is so common in C/C++.

Platform Independence - Windows Vista and Windows 7 work differently from Windows XP. Windows 8 works still differently. Windows Mobile versions including Windows 8 Mobile work differently again. Different hardware, different architecture, different capabilities. While the target environment does still matter to a .NET developer, the amount of specialized knowledge is far reduced compared to what has to be known to build a compatible C/C++ program for all of these OSes. A C# dev gets a lot more for free.

Web application support - I haven't yet seen a client-facing, server-scripted web application written from the ground up in C++. The web server, sure, Apache, ISS, they all typically run against an unmanaged runtime for speed/efficiency reasons. However, C++ is not a language used for building web applications. C# is (as is Java). It was designed from the ground up to support the next generation of Microsoft's ASP paradigm. This is code designed to run in a sandbox; which sandbox (the ASP.NET plugin to ISS or the "desktop" CLR) is relatively unimportant.

Language/runtime independence - A C++ compiler takes C++ source code and produces assembly code for one processor architecture using one machine language. To support a different architecture and/or machine language, a completely new compiler must be written (and a completely new set of runtime libraries must be compiled). A C# compiler takes C# source code and produces CIL, which the hardware-specific JITer translates to machine code. The same JITer can translate any CIL program no matter what the source language (and there are several; C#, VB.NET, F#, and a host of "Iron" language ports like IronHaskell, IronRuby, IronLisp, etc). The same compiler can turn one language into CIL that any JITer can run, no matter the hardware. This reduces the amount of work that must be redone from scratch for every new language or platform supported by the .NET Framework.

Focus on "correct" code - For C++ devs, there are a lot of "right" ways to do something, depending on what's most important; memory efficiency, CPU efficiency, hardware independence, OS independence, etc. Code can look drastically different when each of these is the priority. C# was designed by a group that took to heart the conceptual lessons of Fowler and his colleagues (who were working to reform code design within the C++ community by teaching object-oriented principles to a community that largely moved up into it from C), as well as the practical lessons learned by the languages that came before (including Java, and its near-fanatical obedience to the almighty Object, when a good old C++-style function pointer would do the job much more cleanly and not be any less object-oriented).

For antitrust reasons, MS is careful not to be seen "interfering" too heavily in other major platforms like Android, Mac OSX/iOS and Linux; however, it does indeed have teams developing for all three of these platforms. There's an MS-developed version of Office for OSX, there are numerous applications including Office interop apps for iOS and Android, Skype (now a Microsoft product) runs on Linux, and Microsoft has even been seen contributing to the Linux kernel (primarily in a virtualization mindset).

Title: Why are CIL and CLR required in .NET?


问:
Why does HashMap allow only one null key?
A HashMap allows only one null key. Is it because it allows only unique keys?  Or is there another reason?

答:
Why is it confusing? The javadoc for HashMap.put clearly states:

Associates the specified value with the specified key in this map. If the map previously contained a mapping for the key, the old value is replaced.

It clearly states what happens when you do a put with a key which was already in the map. The specific case of key == null behaves in the same way: you can't have two different mappings for the null key (just like you can't for any other key). It's not a special case, for the context of your question.


答:
I have worked with both, and while it is possible it is certainly not recommended.

Systems that are designed around relational databases rarely can just be converted directly over to non-relational databases.  There are many different patterns to use in order to achieve efficiency.

For example, in a relational database, you might have two tables that are joined with a one-to-many relationship, such as an Order and its OrderLineItems.  This is very common in relational database design.  However, it is completely undesired in a document database like RavenDB.  Instead, you would model an entire document with all of it's children as a single "Aggregate Root".  An Order and all of its OrderLineItems would be in one document.

Switching out storage engines via a repository interface may sound like a good idea, but in practice one usually finds it to be impractical.

Title: How to factor out data layer in nopCommerce and replace MS SQL with RavenDB?

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

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

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

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

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

Thanks in advance;


问:
GitHub Organizations for a project spanning multiple repositories?
I've started a project that involves at least three repositories on GitHub.

One of the repositories is a generic documentation-and-examples dump, and the other two contain the implementation of two programs that form the backbone of the project.

Should I use a GitHub Organization to handle such a configuration?
 Or should I just dump it all to my own account, along with a dozen other, completely unrelated repositories?

答:
Short answer ...

Start out with the repositories in your personal account. From there, if/when things grow and/or get popular with the community, move them to an organization account.

GitHub Blog: Repository redirects are here!

Long answer ...

Let's look at some of your options:

1. Organization:

For more information on GitHub Organization features, be sure to read:

GitHub Blog: Introducing Organizations

If you've ever had to manage multiple GitHub accounts, desired a company-specific dashboard, wanted to add read-only collaborators, or needed to give someone else administrative control over one of your repositories, you're going to love Organizations.

Based on your question, I can't say if an Organization is right for you (my gut is telling me "no"), but maybe looking at some real world examples will help you make your decision.

Here are some examples of GitHub Organizations that I find interesting to look at:

https://github.com/gruntjs

This is one of my favorite examples of an open source Organization account. I'm mostly impressed by the naming conventions used for repositories (i.e., essentially grunt/ is the main repo and all related core/contrib code/plugins/tasks live in grunt-xxxx/ repositories).

https://github.com/github

Probably it's worth looking at GitHub's own Org. account. The naming conventions used for the repositories aren't as tight as Grunt's (IMHO), but it's a good example nonetheless. Oh, and now's probably a decent time to point out the "Members" tab, as you don't get this for personal accounts or repositories.

https://github.com/twbs

Twitter Bootstrap. I think this is a good example of an Org. account with only a few repositories (note the single repo with 58,000+ stars). Also note that Bootstrap has five members (at the time of writing this), yet those five are responsible for an insanely popular repository (contrast that to the 214 members of the GitHub Organization).

https://github.com/twitter: Twitter's main GitHub account.

A few more general examples:

https://github.com/yeoman: Build tools.

https://github.com/h5bp: HTML5 boilerplate.

https://github.com/nprapps: News industry example.

2. Personal account

As you've mentioned already, you could create repositories inside your personal account and go from there.

Will you need collaborators?

GitHub Help: Collaborating / How do I add a collaborator?

As you can see, adding collaborators is pretty painless.

Based on your question, this option sounds like the one you want.

3. Repo with multiple branches:

You could create one repository and utilize branches to organize your related bits of code.

I don't think most folks would agree that this is the best way to organize your code:

Use forever-branches or directories for project related documentation, wireframes, designs, etc.?

On the other hand, there's nothing that says you can't organize related bits of code using branches.

One personal annoyance I have with this technique is that GitHub's GUI/interface will show you this message:

... when viewing branches other than your master (that is, if your branch is ahead/behind in commits).

Tip: If you're using a more recent version of Git, you can pull specific branches using git clone -b mybranch --single-branch git://sub.domain.com/repo.git:

Clone only one branch

How to clone a single branch in git?

Related:

A successful Git branching model (a.k.a., git-flow)

GitHub Blog: GitHub Flow in the Browser

4. Hybrid approach:

Should I use a GitHub Organization to handle such a configuration? Or should I just dump it all to my own account, along with a dozen other, completely unrelated repositories?

You could use a combination of all of the above. For example:

Setup an Organization for "... generic documentation-and-examples dump, and the other two contain the implementation of two programs that form the backbone of the project".

Use your personal account for "... a dozen other, completely unrelated repositories"

Use branches for demo pages gh-pages, related code and/or documentation.

Note(s):

It's also worth mentioning that you can use a repository's WIKI for documentation purposes:

GitHub Blog: Git-powered wikis improved

GitHub Blog: Making GitHub More Open: Git-backed Wikis


问:
What is a" feature envy" code and why is it considered a code smell?
This question on SO talks about  correcting what the OP thought is feature envy code. Another example where I saw this nifty phrase being quoted is in a recently given answer here in programmers.SE. Although I did drop in a comment to that answer asking for the information I thought it would of general help to programmers following Q&A to understand what is meant by the term feature-envy. Please feel free to edit additional tags if you think appropriate.

答:
There is a possible situation when it is OK to use another class/struct methods extensively - when your class/struct is a container for data. Usually there is a little you can do with this data without external context.

Such classes can still hold some internal logic but more often they are used as containers:

```<code>class YourUid {
 public:
  YourUid(int id_in_workplace_, int id_in_living_place_, DB* FBI_database, int id_in_FBI_database);
  bool IsInvalidWorker() const { return id_in_workplace == consts::invalid_id_in_workplace; }
  bool CanMessWith() const { return !FBI_database_.is_cool(id_in_FBI_database_); }
  int id_in_workplace;
  int id_in_living_place;
 private:
  int id_in_FBI_database_;
  const DB* FBI_database_;
};
</code>```

@jhewlett in his answer refers to this article to prove that you should no use other class members extensively, but there is another code smells situation described there with advocates my example:

Long Parameter List. Limit the number of parameters you need in a given
  method, or use an object to combine the parameters.

Body:
There is a possible situation when it is OK to use another class/struct methods extensively - when your class/struct is a container for data. Usually there is a little you can do with this data without external context.

Such classes can still hold some internal logic but more often they are used as containers:

class YourUid {
 public:
  YourUid(int id_in_workplace_, int id_in_living_place_, DB* FBI_database, int id_in_FBI_database);
  bool IsInvalidWorker() const { return id_in_workplace == consts::invalid_id_in_workplace; }
  bool CanMessWith() const { return !FBI_database_.is_cool(id_in_FBI_database_); }
  int id_in_workplace;
  int id_in_living_place;
 private:
  int id_in_FBI_database_;
  const DB* FBI_database_;
};

@jhewlett in his answer refers to this article to prove that you should no use other class members extensively, but there is another code smells situation described there with advocates my example:

Long Parameter List. Limit the number of parameters you need in a given
  method, or use an object to combine the parameters.


答:
It would not be a good idea to build the search as you suggest for a number of different reasons.

You are relying on the creation of useful, accurate keywords, and the management of those keywords.  How are new keywords created?  Who is responsible for linking the right keywords to the content?

You don't have clear mechanism for ordering the search results.  How would you decide which of the articles might be the most relevant? If only a keyword is being used, all articles would have the same weight so you would have to default to something like recency or alphabetical order by title.

You are ignoring a lot of useful information about the content in the search.  The title and the body of the document will contain some information that is not contained in the keywords, unless someone spends a lot of time managing keywords.

Keywords can still play a role, but perhaps as one of many fields (including title and content) used in the search.  They could be simply be managed as an array in the main record for the article rather than a separate collection that needs to be maintained and linked to the content.

Given that you are committed to using MongoDB, I would suggest trying MongoDB's native full text search capabilities as a start.  Try indexing the title, content, and keywords (stored as an array with the article).  You can play with the weights applied to each column to determine how they impact relevance.

As @Bill Leeper suggests, standalone search engines could also be an option if you find you need something more sophisticated than what is built into MongoDB, or MongoDB's relatively new full text search doesn't work as expected.  SOLR could be a good starting point because it is language independent and very rich.

Title: Search algorithm

Body:
I would like to create a site where users can post articles with the following optional parts:

A title

Contents (text)

Categories

Keywords

Articles will be stored in mongodb and the site will be built in node.js. Users can search the site using a normal search text box.

I'm thinking about creating the following collections:

Users

Articles

Keywords

I will then create an entry for each keyword used in the Keywords collection with an array containing all the articles that use it. If a user conducts a search, the search is broken up into keywords and each keyword is looked up in the Keywords collection. Each article is then retrieved from the db and ranked based on relevance.

My questions are:

Would it be efficient to use a Keywords collection like this, should I just use the Articles collection (Using full-text search or something) or should I structure it in some other way?

How would I incorporate the ability to search the title, contents or categories for articles instead of just the keywords?

Would it be better to use something like Apache Lucene than to build this functionality myself?


问:
Is it bad practice to make an iterator that is aware of its own end
For some background of why I am asking this question here is an example. In python the method chain chains an arbitrary number of ranges together and makes them into one without making copies. Here is a link in case you don't understand it. I decided I would implement chain in c++ using variadic templates. As far as I can tell the only way to make an iterator for chain that will successfully go to the next container is for each iterator to to know about the end of the container (I thought of a sort of hack in where when != is called against the end it will know to go to the next container, but the first way seemed easier and safer and more versatile).

My question is if there is anything inherently wrong with an iterator knowing about its own end, my code is in c++ but this can be language agnostic since many languages have iterators.

```<code>#ifndef CHAIN_HPP
#define CHAIN_HPP

#include "iterator_range.hpp"

namespace iter {
   template <typename ... Containers>
       struct chain_iter;
   template <typename Container>
       struct chain_iter<Container> {

        private:
           using Iterator = decltype(((Container*)nullptr)->begin());
           Iterator begin;
           const Iterator end;//never really used but kept it for consistency

        public:
           chain_iter(Container & container, bool is_end=false) :
               begin(container.begin()),end(container.end()) {
                   if(is_end) begin = container.end();
           }
           chain_iter & operator++()
           {
               ++begin;
               return *this;
           }
           auto operator*()->decltype(*begin)
           {
               return *begin;
           }
           bool operator!=(const chain_iter & rhs) const{
               return this->begin != rhs.begin;
           }
       };
   template <typename Container, typename ... Containers>
       struct chain_iter<Container,Containers...>
       {

        private:
           using Iterator = decltype(((Container*)nullptr)->begin());
           Iterator begin;
           const Iterator end;
           bool end_reached = false;
           chain_iter<Containers...> next_iter;

        public:
           chain_iter(Container & container, Containers& ... rest, bool is_end=false) :
               begin(container.begin()),
               end(container.end()),
               next_iter(rest...,is_end) {
                   if(is_end)
                       begin = container.end();
               }
           chain_iter & operator++()
           {
               if (begin == end) {
                   ++next_iter;
               }
               else {
                   ++begin;
               }
               return *this;
           }
           auto operator*()->decltype(*begin)
           {
               if (begin == end) {
                   return *next_iter;
               }
               else {
                   return *begin;
               }
           }
           bool operator !=(const chain_iter & rhs) const {
               if (begin == end) {
                   return this->next_iter != rhs.next_iter;
               }
               else
                   return this->begin != rhs.begin;
           }
        };
   template <typename ... Containers>
       iterator_range<chain_iter<Containers...>> chain(Containers& ... containers)
       {
           auto begin =
               chain_iter<Containers...>(containers...);
           auto end =
               chain_iter<Containers...>(containers...,true);
           return
               iterator_range<chain_iter<Containers...>>(begin,end);
       }
}

#endif //CHAIN_HPP
</code>```

答: So after some advice from @jozefg and research I learned that other languages (obviously not c++) have iterators with a concept of their own ends, including python. So I have decided that it is ok to have the self stopping iterators and am keeping it in my code.</p>


问:
Why do some websites showing 0 bytes in Chrome's developer tools
I am doing a page speed optimization for my website and studying how other websites do it. I noticed that some websites such as as Facebook or Ringgitplus show 0 bytes for some of their resources in Chrome's developer tools, Network tab, while the real content size is several kilobytes.

I read some articles that says that size is the amount being fetched and content is the actual size of the response. So when size is 0 bytes, it means it served from cache. But the same thing happened when I open the page using Incognito or clearing all my cache.

How is this possible and how can I achieve the same thing for my websites?

答:
Understanding Chrome's behavior is easiest to see in a site that supports both http and https.

If you open Developer Tools and view this image, then Chrome reports 27.1k if the image is cached and 257 bytes if it is not. You can clear your cache inside Developer Tools by right-clicking on the area on the bottom of the screen (for example next to nav_logo161.png).

Now open the link with https. Chrome reports 0 bytes whether the item is cached or not. If it is cached you get a 304, and if it is not cached you see a 200 status. But you can see in the latency that the uncached response takes much longer.

So, long story short, if you want Chrome to report 0 bytes for your web-page use https.

This bug is recorded here and here.

This bug is noticeable primarily when viewing images. The reason you notice it with the http links in the original post is that both sides actually render in https.


问:
Using Java Reflection to decouple code modules
I'm involved in a project with several modules. I found that programmers have designed one module to be easily decoupled from its dependent modules using Java Reflection. If other modules need to call a method in this module, the programmers are expecting them to use reflection to call it. This has resulted in a lot of places with hard-coded reflection calls. By hard-coded, I mean the class and method names are permanently fixed as Strings, which kind of defeats the purpose of reflection which is supposed to be for dynamic programming.

How can this be justified? I feel they are being novice about it and misusing the reflection API. I think polymorphism is the right way to decouple a module from another without breaking functionality. (Unfortunately, changing the entire code base to polymorphism is way too much maintenance.)

答:
Yes, unless reflection uses some names not available at compile time, it usually should be replaced by factories or dependency injection.

OTOH there are rare cases when exact class names are known at compile time, but classes named so are not available at build time. A classic example is JDBC, which used to use the Class.forName("com.vendor...") paradigm. The name of the JDBC driver(s) class is known at compile time, but a .jar with the specified class, or often several for several supported DBMSes, is not available.

This case is still rather special: not only it assumes that classes referenced by reflection are deployed in separate jars, it assumes that some of such classes may not be available at all. This is a reasonable assumption for a publicly-used library; I don't know if it's reasonable in your case.

Anyway, modern containers don't require client code to use reflection, they use dependency injection to provide specific replaceable implementations of e.g. JDBC drivers.

I think you should consider using a dependency-injection framework in your case. The DI framework might use reflection internally, but at least all such reflection would be concentrated in a thin well-defined layer.


问:
Notify players every x seconds in a multiplayer game
I'm working on a realtime multiplayer game using Django and gevent-socketio, I'm facing some issues:

I need to send an update of the game state to connected players every X seconds (~4 seconds), so basically I need to execute a function every x seconds which does some calculations and sends the connected players the new game state. What is the easiest way to achieve this? is using cron a good choice here or should I look for other tools like celery or ...?

Also, the function needs to operate on some data. querying the database every time the function is executed does not seems to be a good idea, where can I store the game data (which is updated frequently during the game)?

答:
Regarding #2: querying and updating a database for every change of game state is an extremely good idea, as long as you're using a right database.

Obviously things like MySQL can be subpotimal in such cases (or maybe not; it depends on the size of the game state and the complexity of your model). If you use a low-overhead NoSQL database that only stores things to disk when it has time, you'll have plenty of performance. Durability will suffer, though; a crash might lose the state.

Of course, it's silly to recompute the entire game state for each client request, if the state did not change. You can cache the hard-to-compute common part and only recompute client-dependent parts, like 'fog of war'.

This leads us to the idea of a tiered database. Your most important things, like users' inventory or monetary balance, should be stored in a durable database, like Postrges or MongoDB. (BTW it's amazing what modern Postgres is capable of, and how fast writes to Mongo can be.) The often-changing things, like fog of war, positions of missiles in flight, etc, should live in a caching layer, something like Redis or Memcached, and only be stored to the durable store when an irreversible action happens (missile hits). The most important facts about the current game tick should be computed once and stored in the caching layer, in a form that allows easy queries and immediate sending to clients.

The state of the caching layer can be lost to a crash without catastrophic consequences, and can be recomputed from the durable data.

This is, of course, somehow complex. Don't go for it until you have a working crude prototype. Use only the durable store (e.g. Postgres) until you start hitting performance problems and have identified these problems to be database-related. Then you will see what to cache.


问:
What are common categories for Kanban and Scrum JIRA boards?
One minimal Kanban-like system has three places for cards: "To do", "In progress", "Done". As I've seen Scrum and Kanban on the web, it is maybe five or six categories.

What are some of the common options for categories for Kanban and Scrum JIRA boards?

答:
Assuming Kanban (as I think the answer is less relevant for a Scrum process), the lanes that you should use depend on organizational concerns, and perhaps on your definition of done. You'll probably start to see an obvious need for things as you start working through organizational or business concerns beyond just development concerns.

In my current organization, "Ready for Acceptance", "Ready for Release" (aka Accepted), and "Released", are in there, because we consider Product Owner acceptance of a story an important gate, and it's not always an instant thing depending on the PO's other obligations with the business. We don't yet have a continuous deployment mechanism in place, so we also still have  a lane for things that need to be part of a release event, and there may be some work on our part associated with that. Then we have "Released", mostly for the benefit of recognizing progress.

In another organization, Kanban wasn't our primary process but we needed to deal with a lot of moving parts working through multiple organizational gates, as we were serving a highly regulated biotech business. Some items were "In progress," meaning in the developer's hands, but needed to be pass through a "tech writer review", a "test" effort by a traditional software test team, and Quality Assurance. (The distinction was a matter of industry standards; in traditional manufacturing, QA assures that processes work as documented, whereas "test" is a matter of quality control; our software had to go through a QA process because we got FDA approval on the condition that we followed our documented Good Manufacturing Practices as originally documented to the FDA years ago). So, in other words, although the software organization practiced enabling mechanisms for agile development like continuous integration, automated unit and integration testing, and so on, various business constraints meant we had to juggle external organizational concerns that were more reminiscent of legacy-style project management. When our development team was trying to juggle multiple work products (new features, release of old features, dealing with organizational and technical problems that sometimes spanned multiple Scrum iterations), we essentially abandoned Scrum so that we could provide visibility into what we were doing that wasn't development, and make sure everything got done. When our work was less dependent on external interests, we used more traditional Scrum-style project management again.

If I were in a small team and had few external stakeholders, I'd probably keep my board pretty simple. "Ready to pull", "In progress", "Released to Production" would feel just about right, but it wouldn't surprise me if the product owner needed some a lane to review the work before releasing to production. And in some organizations, where a new feature isn't available to everyone until some data has been gathered on how customers react to it or how it scales in production, it wouldn't surprise me to see a lane like "In A/B testing" or "Released to 10% of  users" followed by "Released to all customers".

We also have some non-shipping lane items like "technical debt", and we sometimes recognize that a story contains inadequate acceptance criteria, contradicts other existing criteria for earlier features, or has some unforeseen consequences that require further discussion or review before cowboying up and writing possibly irrelevant code. In those cases, we have a box that, if things are working sanely, will be visited only briefly, labeled "On hold."

So the lesson is simple: Figure out what your team actually needs, and draw those lanes.


问:
What are the reasons to create UIView subclass?
I've noticed that there are a lot of UIView subclasses in my legacy project. Mostly the only reason of such a subclass is to split bigger view into custom subviews and provide layout for its subviews and delegation of UIButtons actions through the view delegate protocol. So I'm wondering, is it a correct design?  </p>

答:
if you can manage all your view then there is no harm to keep number of subviews..

you can refer View hierarchy..

https://developer.apple.com/library/mac/Documentation/Cocoa/Conceptual/CocoaViewsGuide/WorkingWithAViewHierarchy/WorkingWithAViewHierarchy.html

In one of my project i had 10 subviews which were added based on my button click...

I searched and found there is no limitation given for subviews...


答:
If your view is just a container of other views, then you better use a regular (not subclassed) UIView. You compose the view (or load then nib) from a subclassed view controller.

Exceptions: when to subclass UIView:

for custom drawing

non standard touch responses (beyond the capabilities of the gesture recognizers)

Title: What are the reasons to create UIView subclass?

Body: I've noticed that there are a lot of UIView subclasses in my legacy project. Mostly the only reason of such a subclass is to split bigger view into custom subviews and provide layout for its subviews and delegation of UIButtons actions through the view delegate protocol. So I'm wondering, is it a correct design?  </p>


问:
How do I test a file reader?
I am working on a project with a few file formats. Some formats are specified by .xsds, others by documentation on their respective websites, and some are custom in-house formats that have no documentation. Mwahahahaha.

What's the problem?

I would like to test my file readers, but I'm not entirely sure how to go about doing this. The flow of the application is as such:

```<code>file.___  ===> read by FileReader.java ===> which creates a Model object
</code>```

where the FileReader interface is

```<code>public interface FileReader {
    public Model read(String filename);
}
</code>```

The Model has a number of attributes that are populated when the file is read. It looks something like

```<code>public class Model {
    List<String> as;
    List<String> bs;
    boolean isAPain = true;
    // ...
}
</code>```

What have I tried?

My only idea was to create file "generators" for each file format. These generators are basically builders which take in a few variables (eg. number of comments to generate in a file), and output a sample file which I then read in and compare the resulting Model with the variables I used to initially generate the file.

This has a few problems, though:

The files that it generates don't look like real files. The generator is in no way aware of context.

It's hard to recognize if the generator has generated for edge cases since I'm the one manually setting the variables. This method is barely better than me creating a dozen sample files.

Are there any better ways to do this?

EDIT: Changed unit to integration since that's what I actually mean.

EDIT2: Here is an example of the edge cases I mentioned.

Each file represents a graph made up of vertices and edges. These vertices and edges can be attached in different ways, so:

```<code>v1 -- e1 --> v2 <-- e2 -- v3
</code>```

is different from

```<code>v1 -- e1 --> v2 -- e2 --> v3
</code>```

in that the direction of the edges matter. I'm not sure if this is in the scope of the question, but it's hard to think up all of the pertinent edge cases when I manually set the number of vertices, number of edges, and just generate the connections randomly.

答:
First, lets talk about what your goals are:

you obviously don't want to test "file formats" - you want to to test your different FileReader implementations

you want to find as many different types of errors as possible by automatic tests

To reach that goal in full, IMHO you have to combine different strategies:

first, real unit testing: your FileReader implementations will consist of many different parts and functions. Write small tests which test each of them in isolation; design your functions in a way they don't really need to read the data out of a file. These kind of tests will help you to test most of your edge cases.

second, generated files: those are what I would call integration tests. Such files will help you to track down failures different from point 1, for example, combinations of specific parameters, errors in file access etc. To create good test cases, it will also be helpful to learn about some classic techniques like grouping test cases into equivalence classes or boundary value testing. Get a copy of this book by Glenford Myers to learn more about that. The Wikipedia article about software testing is a good resource, too.

third, try to get real-world data: it can be hard to verify that these files are evaluated correctly by your FileReaders, but it may be worth it to do this since it often finds bugs not revealed by the first two strategies. Some people would call these kind things also "integration tests", others prefer "acceptance tests", but in fact the term does not really matter.

IMHO there is no "short-cut" approach which would bring you the benefit of all three strategies "for the price of one". If you want to detect edge cases as well as failures in standard cases as well as real-world cases, you have to invest at least some - more probably a lot - effort. Luckily, all of those approaches can be used for creating automatic, repeatable tests.

Beyond that, you should make sure your FileReaders don't mask any errors when reading that data - create in-built checks/assertions, throw exceptions when something goes wrong internally etc.. This gives your testing code a much better chance to detect errors, even when you don't have an explicit test file or test case for an unexpected situation.

Title: How do I test a file reader?


问:
C# basic window content convention
I'm learning C# using visual studio express 2012, and I cannot find a source online that explains window content convention.  What I mean by this is, what's the appropriate way to change the context / pass variables from the main window to different contexts?

I've been able to change the content of my window by creating and editing new UserControl classes.  As for parameter passing, I've experimented with having a static mainwindow with public fields and passing mainwindow field values through action functions (with little success).

Is the appropriate way to handle changing the main window's context creating multiple usercontrol classes?  If this is the case, should I be creating a tree with the main window as the root and the usercontrol classes as child elements?

Most of the questions I find when searching for an answer revolve around forms or new windows, which lead me to question whether usercontrol is the correct item for changing context.  If I'm missing a tutorial or simple explanation I apologize in advance :D

答:
What you want to look at is using the MVVM architectural pattern which strongly leverages the data binding feature of the .net framework (which is particularly good if you use WPF).

In this pattern, view models are represented by classes which are passed to the user control using the DataContext property. You can then use DataTemplate to fashion the UI as you wish at runtime according to the different types you use for your view models.

Title: C# basic window content convention


问:
Should unit test expected results be hardcoded?
Should the expected results of a unit test be hardcoded, or can they be dependant on initialised variables?  Do hardcoded or calculated results increase the risk of introducing errors in the unit test?  Are there other factors I haven't considered?

For instance, which of these two is a more reliable format?

```<code>[TestMethod]
public void GetPath_Hardcoded()
{
    MyClass target = new MyClass("fields", "that later", "determine", "a folder");
    string expected = "C:\\Output Folder\\fields\\that later\\determine\\a folder";
    string actual = target.GetPath();
    Assert.AreEqual(expected, actual,
        "GetPath should return a full directory path based on its fields.");
}

[TestMethod]
public void GetPath_Softcoded()
{
    MyClass target = new MyClass("fields", "that later", "determine", "a folder");
    string expected = "C:\\Output Folder\\" + string.Join("\\", target.Field1, target.Field2, target.Field3, target.Field4);
    string actual = target.GetPath();
    Assert.AreEqual(expected, actual,
        "GetPath should return a full directory path based on its fields.");
}
</code>```

EDIT 1: In response to DXM's answer, is option 3 a preferred solution?

```<code>[TestMethod]
public void GetPath_Option3()
{
    string field1 = "fields";
    string field2 = "that later";
    string field3 = "determine";
    string field4 = "a folder";
    MyClass target = new MyClass(field1, field2, field3, field4);
    string expected = "C:\\Output Folder\\" + string.Join("\\", field1, field2, field3, field4);
    string actual = target.GetPath();
    Assert.AreEqual(expected, actual,
        "GetPath should return a full directory path based on its fields.");
}
</code>```

答:
There are a lot of concepts possible, made some examples to see the difference

```<code>[TestMethod]
public void GetPath_Softcoded()
{
    //Hardcoded since you want to see what you expect is most simple and clear
    string expected = "C:\\Output Folder\\fields\\that later\\determine\\a folder";

    //If this test should also use a mocked filesystem it might be that you want to use
    //some base directory, which you could set in the setUp of your test class
    //that is usefull if you you need to run the same test on different environments
    string expected = this.outputPath + "fields\\that later\\determine\\a folder";

    //another readable way could be interesting if you have difficult variables needed to test
    string fields = "fields";
    string thatLater = "that later";
    string determine = "determine";
    string aFolder = "a folder";
    string expected = this.outputPath + fields + "\\" + thatLater + "\\" + determine + "\\" + aFolder;
    MyClass target = new MyClass(fields, thatLater, determine, aFolder);

    //in general testing with real words is not needed, so code could be shorter on that
    //for testing difficult folder names you write a separate test anyway
    string f1 = "f1";
    string f2 = "f2";
    string f3 = "f3";
    string f4 = "f4";
    string expected = this.outputPath + f1 + "\\" + f2 + "\\" + f3 + "\\" + f4;
    MyClass target = new MyClass(f1, f2, f3, f4);

    //so here we start to see a structure, it looks more like an array of fields
    //so what would make testing more interesting with lots of variables is the use of a data provider
    //the data provider will re-use your test with many different kinds of inputs. That will reduce the amount of duplication of code for testing
    //http://msdn.microsoft.com/en-us/library/ms182527.aspx

    The part where you compare already seems correct
    MyClass target = new MyClass(fields, thatLater, determine, aFolder);

    string actual = target.GetPath();
    Assert.AreEqual(expected, actual,
        "GetPath should return a full directory path based on its fields.");
}
</code>```

To summarise: In general your first just hardcoded test makes most sense to me because it is simple, straight to the point etc. If you start hardcoding a path too many times just put it in the setup method.

For more future structured testing I would go to check out datasources so you can just add more data rows if you need more testing situations.

Body:
There are a lot of concepts possible, made some examples to see the difference

[TestMethod]
public void GetPath_Softcoded()
{
    //Hardcoded since you want to see what you expect is most simple and clear
    string expected = "C:\\Output Folder\\fields\\that later\\determine\\a folder";

    //If this test should also use a mocked filesystem it might be that you want to use
    //some base directory, which you could set in the setUp of your test class
    //that is usefull if you you need to run the same test on different environments
    string expected = this.outputPath + "fields\\that later\\determine\\a folder";

    //another readable way could be interesting if you have difficult variables needed to test
    string fields = "fields";
    string thatLater = "that later";
    string determine = "determine";
    string aFolder = "a folder";
    string expected = this.outputPath + fields + "\\" + thatLater + "\\" + determine + "\\" + aFolder;
    MyClass target = new MyClass(fields, thatLater, determine, aFolder);

    //in general testing with real words is not needed, so code could be shorter on that
    //for testing difficult folder names you write a separate test anyway
    string f1 = "f1";
    string f2 = "f2";
    string f3 = "f3";
    string f4 = "f4";
    string expected = this.outputPath + f1 + "\\" + f2 + "\\" + f3 + "\\" + f4;
    MyClass target = new MyClass(f1, f2, f3, f4);

    //so here we start to see a structure, it looks more like an array of fields
    //so what would make testing more interesting with lots of variables is the use of a data provider
    //the data provider will re-use your test with many different kinds of inputs. That will reduce the amount of duplication of code for testing
    //http://msdn.microsoft.com/en-us/library/ms182527.aspx

    The part where you compare already seems correct
    MyClass target = new MyClass(fields, thatLater, determine, aFolder);

    string actual = target.GetPath();
    Assert.AreEqual(expected, actual,
        "GetPath should return a full directory path based on its fields.");
}

To summarise: In general your first just hardcoded test makes most sense to me because it is simple, straight to the point etc. If you start hardcoding a path too many times just put it in the setup method.

For more future structured testing I would go to check out datasources so you can just add more data rows if you need more testing situations.


问:
What are the pros and cons for the employer of code questions during an interview?
The Joel Test question #11 is: "Do new candidates write code during their interview?". What are arguments for and against to ask new candidates to write code during the interview and to make a decision upon it?</p>

答:
One pro is that it shows that somebody does have basic knowledge of programming or whatever (the last time I encountered that, I was surprised how basic the SQL question was).  It also can serve as a basis for a technical discussion, asking why the candidate did such and such, and how it could be improved.

It does take time in the interview, which could be used for other things.  Moreover, writing code on a whiteboard is not a natural environment, and some people will have more and less serious problems with it.  It could cause you to miss a developer who just gets nervous without normal tools or references.


答:
In early iOS, there was no ViewController. Some things we might now do with a ViewController today were done by the view; it sounds like some of your view classes are doing things like that.

On the whole, it's not a terrible code smell if the subclass is small. When the subclass gets too messy, sprout new classes to manage the aggregation (MyController) and delegation (MyViewDelegate) responsibilities.


问:
iOS: Multiple images or single scaling image
I have a fiery debate running in the office.
We have an app with two buttons of different size. (One is 40 px wide and one is 150 px wide).
They have the exact same look in terms of background image.

I would like to know which is best practice:

1: Make one image for the background that is 40px wide, and another image which is 150px wide.

OR

2: Make one image (150px) and scale down and re-use for the 40px button.

I'm not sure what performance overhead the scaling operation has, and I need to offset that against the size of the app if we go with seperate images for every different sized control.

Thanks!

答:
You can create a resizable image to customize the background of several standard UI elements, such as popovers, buttons, navigation bars, tab bars, and toolbars (including the items on these bars). Providing resizable images for these elements can result in better app performance.

For many UI elements, you can also specify end caps in addition to a background appearance. An end cap defines an area of the image that should not be resized. For example, you might create a resizable image that includes four end caps that define the four corners of a button. When the image is resized to fill the button’s background area, the portions defined by the end caps are drawn unchanged.

Depending on the dimensions of the resizable image you supply, iOS either stretches or tiles it as appropriate to fill a UI element’s background area. To stretch an image means to scale up the image, without regard for its original aspect ratio. Stretching is performant, but it isn’t usually desirable for a multipixel image that can distort. To tile an image is to repeat the original image as many times as necessary to fill the target area. Tiling is less performant than stretching, but it's the only way to achieve a textured or patterned effect.

As a general rule, you should supply the smallest image (excluding end caps) that will result in the look you want. For example:

If you want a solid color with no gradient, create a 1 x 1 point image.
If you want a vertical gradient, create an image that has a width of 1 point and a height that matches the height of the UI element’s background.
If you want to provide a repeating textured appearance, you need to create an image with dimensions that match the dimensions of the repeating portion of the texture.
If you want to provide a nonrepeating textured appearance, you need to create a static image with dimensions that match the dimensions of the UI element’s background area.


问:
How to deal with the notion of time in UI/Integration tests
There are some well-known techniques for dealing with the notion of time in unit tests. These allow you to write unittests that always work with a specific time so the outcome of the test is predictable and can be verified. However, these techniques do not work with integration tests/UI test as the test and the application itself are separated (very much so in web applications where your application under test could be deployed on a separate server).

For example, let's assume we are developing an appointment system that needs to implement a 'suggest the first available appointment date'-button. If the button is clicked, it needs to suggest the first available timeslot for the next business day. This means that if the button is clicked on any given day of the week except friday it should suggest a slot in the next day, BUT on friday and saturday it should suggest a slot on monday.

How would one go about testing this requirement?

(I know it is possible to work around the issue for this specific example but bear with me - there are always situations where the test cannot supply the data to work from. I didn't want to supply an overly complicated example.)

答:
Make sure time is grabbed by a single function in a single library / by a well defined interface throughout your application's code, and provide a special "testing mode" in your application where that function delivers always the same sequence of date/time values. Run the application during the tests only in that testing mode. If you need different starting values for different tests, your "testing mode" will need that value as a configurable parameter.

there are always situations where the test cannot supply the data to work from

If you encounter such a situation, and you need some special data supplied for a specific test, then you have to change your product to make that possible. It is IMHO a fallacy that test frameworks or test environment should allow tests without a single change to the "subject under test". The idea of "maintenance hatches" was no invention of the software industry, and "design for testability" is something you have to work for, it does not come for free.


答:
Cons: None. Any time you spend setting up a PC, designing a code test, and reviewing it will save untold headache in the future.

Pros: "Trust, but verify" - Ronald Regan. So many times I've seen and heard of people finally let go from a position, where in the interview you'd think you were getting a rock star. The proof is in the pudding; I want to see what they can do. It will represent what happens once you invest time and money hiring someone and stick a new project in front of them.

Title: What are the pros and cons for the employer of code questions during an interview?

Body: The Joel Test question #11 is: "Do new candidates write code during their interview?". What are arguments for and against to ask new candidates to write code during the interview and to make a decision upon it?</p>


问:
Generic repository unit testing best practice?
How can I unit test my generic repository?

Unit testing code:

```<code>[TestClass]
public class UnitTestLanguage
{
    private IUnityContainer _unityContainer;
    private IUnitOfWork _uow;
    private IGenericRepository<Language> _languageRepository;

    [TestInitialize]
    public void TestInitialize()
    {
        _unityContainer = new UnityContainer();
        _uow = _unityContainer.Resolve<UnitOfWork>();
        _languageRepository = _uow.GetRepository<Language>();
    }

    [TestCleanup]
    public void TestCleanup()
    {
        _uow = null;
        _unityContainer = null;
        _languageRepository = null;
    }

    [TestMethod]
    public void TestMethodInsertLanguage()
    {
        var newLanguage = new Language { Name = "test_language" };
        _languageRepository.Insert(newLanguage);
        var insertedRowCount = _uow.SaveChanges();

        var insertedLanguage = _languageRepository.Find(newLanguage.Id);
        _languageRepository.Delete(newLanguage);
        var deletedRowCount = _uow.SaveChanges();

        Assert.AreEqual(insertedLanguage.Name, newLanguage.Name);
        Assert.AreEqual(1, insertedRowCount);
        Assert.AreEqual(1, deletedRowCount);
    }
}
</code>```

I use something like above. But I dont know this is the correct way to test repository. I cant find useful tutorial/article. How should be unit testing with generic repository CRUD operations?

答:
Apart from Luc's suggestion to test one functionality per test (method), I would suggest not to use unity for setting up the unit under test. Strictly speaking, this is no unit test anymore, because it tests both your repository and the configuration of unity.

This might not be a problem for now, but it can easily become one in the future. Consider, for example, the situation that someone extends you language repository by some online-lookup functionality. The respective request interface would probably be retrieved though DI. In consequence, your tests may suddenly start to fail at random, because of occasional connection timeouts.

From my experience I prefer to be strict about dependencies in unit tests, i.e., every input is replaced manually by a respective mock. This is the only way you can make sure that a test failure actually relates to some problem with the unit (or the expectations your tests express).


答:
a better way is to use interfaces and some method to locate the implementing classes

the interfaces preempt the need for reflection in the calling code, this is doable during a refactor, just extract the interfaces (and data objects) and put them where the client code can reference it and replace all reflection with a call to the interface

there are several ways of finding the implementing classes: one of them is used by the ImageIO service system, it involves a file in the META-INF folder of the jar containing the implementing module and including the jar in the classpath

Title: Using Java Reflection to decouple code modules

Body:
I'm involved in a project with several modules. I found that programmers have designed one module to be easily decoupled from its dependent modules using Java Reflection. If other modules need to call a method in this module, the programmers are expecting them to use reflection to call it. This has resulted in a lot of places with hard-coded reflection calls. By hard-coded, I mean the class and method names are permanently fixed as Strings, which kind of defeats the purpose of reflection which is supposed to be for dynamic programming.

How can this be justified? I feel they are being novice about it and misusing the reflection API. I think polymorphism is the right way to decouple a module from another without breaking functionality. (Unfortunately, changing the entire code base to polymorphism is way too much maintenance.)


问:
Weird UIView transforms in Retina iPhone
I'm having a problem I don't understand. I'm developing an OpenGL app for iOS. Because at some points I want to force the orientation of the view programatically, and Apple for whatever reason doesn't make it easy (or even possible), I'm doing it by hand.

I return always NO in shouldAutoRotateToInterfaceOrientation, and when I want to change the orientation (to portrait, for example), I do something like this in the UIView:

```<code>[self setTransform:CGAffineTransformMake(1, 0, 0, 1, 0, 0)];
[self setBounds:CGRectMake(0, 0, 768, 1024)];
</code>```

This works fine.

In order to support Retina devices, I started checking [UIScreen mainScreen].scale, and setting self.contentScaleFactor accordingly. I also modified the code above to account for the new dimensions, like this:

```<code>[self setTransform:CGAffineTransformMake(1, 0, 0, 1, 0, 0)];
[self setBounds:CGRectMake(0, 0, 2*768, 2*1024)];
</code>```

Same rotation, different size. The weird result with this is that I get a "screen" with the right size, but offsetted half a screen to the bottom and the left. To correct for this, I need to do the following:

```<code>[self setTransform:CGAffineTransformMake(1, 0, 0, 1, 0, 0)];
[self setBounds:CGRectMake(-768, -1024, 2*768 - 768, 2*1024 - 1024)];
</code>```

This works, but it's ugly, I also need to make similar corrections when I get touch coordinates, and worst of all, I don't understand what's going on or why the above "correction" works.

Can anyone shed some light on this issue?

答:
In OpenGL ES all your transformation need to be make on OpenGL ES context.
And on your view layer you need to set scaleFactor on view object which is GLKView type.

```<code>view.contentScaleFactor = [UIScreen mainScreen].scale;
</code>```

And do not forget to set the glViewPort.

```<code>glViewport(0,
           0,
           _screenWidth*self.view.contentScaleFactor,
           _screenHeight*self.view.contentScaleFactor);
</code>```

Body:
In OpenGL ES all your transformation need to be make on OpenGL ES context.
And on your view layer you need to set scaleFactor on view object which is GLKView type.

view.contentScaleFactor = [UIScreen mainScreen].scale;

And do not forget to set the glViewPort.

glViewport(0,
           0,
           _screenWidth*self.view.contentScaleFactor,
           _screenHeight*self.view.contentScaleFactor);


问:
Handling Dynamic amount of Strings for persistent and runtime storage in an IOS App
Background

I am dynamically building an FQL query statement and because of the nature of the app, I exclude FB family members, this is the base portion of the query and remains fairly static. The query returns the  FB profile pic and I display it on the UI.

However, after the FB friends are displayed on the UI, I want to give the user the option to select a returned FB friend to never be returned in future queries and to return a new user in that users place

Currently I am storing the other returned member uid's as a temporary exclusion in a Mutable Array, to prevent duplicate members being on the screen at once, I am also storing the excluded member in a different mutable array.

I then build the query statement dynamically inserting the exclusion of all of the uids in the temp array and in the excluded array and then I dump the temp array after I return a new user in the place of who they picked to exclude.

Questions

What are some recommendations on the following:

storing these excluded uids(strings) during the apps lifetime? resort to a persistent storage method(core data/sqlite) or store in an array that is a part of a user object (NSUSer Defaults seems like a bad choice as this list can potentially be very long)

What are recommendations on some persistent storage so that exclusions can be taken into a query statement after the app is shutdown and started up (core data/sqlite/nsuserdefaults seem to be the only options here, userdefaults seems to be the least favorable because the reason mentioned above)

What are recommendations on injecting these unknown amount of uids(strings) into an FQL query statement which will be a string itself?

答:
Best will be to store all your FQL objects to Core Data and filter them with some property, like this.

```<code> typedef enum {
     kFamily = 0,
     kActiveFriend = 1,
     kNonActiveFriend = -1
    } TypeCheck;

    @interface CoreDataFQLObject : NSManagedObject
    @property (nonatomic, retain) NSNumber *checkType;
    @end
</code>```

A hint enum is a integer in Core Data.
You need to prevent non friend user to appear on new log in account.
For that you can delete .sqlite file and recreate again when user is try to login with another account credential.
Or you can make a Core Data scheme with one to many rule for user who was just logged in  "me()". Do not forget to check for duplication on insert operation.

Body:
Best will be to store all your FQL objects to Core Data and filter them with some property, like this.

 typedef enum {
     kFamily = 0,
     kActiveFriend = 1,
     kNonActiveFriend = -1
    } TypeCheck;

    @interface CoreDataFQLObject : NSManagedObject
    @property (nonatomic, retain) NSNumber *checkType;
    @end

A hint enum is a integer in Core Data.
You need to prevent non friend user to appear on new log in account.
For that you can delete .sqlite file and recreate again when user is try to login with another account credential.
Or you can make a Core Data scheme with one to many rule for user who was just logged in  "me()". Do not forget to check for duplication on insert operation.


问:
Best Way to Access Hardware per COM Serial Port over USB Adapter
We are starting a total new Branch at our firm. I am usually developing database interfaces or internal server/client applications/tools for our company, but I never had to do something with hardware.

Szenario

My Boss want to sell a device, which has a touch-screen to set up the many, many features. However, the configuration of the device can be very time consuming. He wants to give a software free for a good customer and for a litte charge to "small" customers. The customer should only be able to use the software, if he registers at our system, so that he can't copy the software without a notice by us.

Requirements

The device has a build in USB cable. If you plug it in your computer it opens a new COM serial port. The software has the following requirements:

Configurating different presents for the device

Reading and writing the presets to the device

Software will refuse to start, if the user has no registration at our server

The user can store his presets at our server and share it with other customers

One preset, copied over and over to multiple devices

My boss has seen similar system (he said something about logitech harmony remote controls) and it is now on me, to create the architecture.

Server Side:
The server is not that kind of problem. We have enough different machines to suite any kind of favour (IIS, LAMPP, Apache/Tomcat etc.) I could take MSSQL or MySQL DBase to store the data, thats not the problem.

Client Side:
This is the tricky part for me. I never did something with hardware. My boss suggested I should use Silverlight. I claimed that I want to do it with a native application. But what is the best combination?

Total Client-Side (C++, C# or Java are the languages I could write)

Mixed Structure #1 Silverlight + Native "Driver" Application

Mixed Structure #2 Java-Applet + Native "Driver" Application

Browser Only - Silverlight or Java-Applet?

Any other suggest

The device is for a special customer group who's getting personal trained with any purchase so security risks like unsafe code or dangerous browser plugins are no negative selling argument.

I did some research about COM Serial Port connection with Silverlight and P/Invoke but I don't want to start without a discussion what would be the best way.

答:
I have done plenty of serial comms work over the years, and writing a native application is the way to go.  It allows you to properly install the application and ensure it has sufficient OS privileges to access the COM port, rather than praying that the user's web browser is configured to even prompt the user to allow access.

You do need to consider some error conditions, such as the device being removed whilst you are in the serial comms code, but this is a viable route.

Question for you though, Why sell the devices un-configured and expect the customer to configure them, which means that they will generate lots of support questions when the process goes less than smoothly.

Why not preconfigure before you ship the device? There are bound to be things that you can do internally to simplify the configuration process when you are able to control the installation environment.


答:
With apologies to Scott Whitlock:

Cons:

none

Pros:

Saves a LOT of time and heartache down the road if you prevent hiring someone who can't program

Requires you to have a technical person in the interview


问:
Multiple conditions in a function using PSR
I'm trying use the PSR conventions in all my projects, but today I view some code of my co-worker and I disagree.

```<code>if ($cond == 1 AND $cond == 2) {
    // to-do
}
</code>```

For me, the correct is:

```<code>if (($cond == 1) AND ($cond == 2)) {
    // to-do
}
</code>```

What is the correct use of the PSR?

答:
Per the PHP Framework Interop Group's PSR definitions, this particular case is not addressed:

https://www.php-fig.org/psr/psr-2/

I don't see any guidance on the usage of logical operators as "words", i.e. "and", "or", "not", etc versus symbols, i.e. "&&", "||", "!" within boolean expressions.

If I were to follow precedence and make my own extension of the above PSR reference, I could only conclude that the word "AND" should be written as "and" given the preference for lower case when using reserved words...

ContentLicense: CC BY-SA 4.0


问:
Is it bad practice to make an iterator that is aware of its own end
For some background of why I am asking this question here is an example. In python the method chain chains an arbitrary number of ranges together and makes them into one without making copies. Here is a link in case you don't understand it. I decided I would implement chain in c++ using variadic templates. As far as I can tell the only way to make an iterator for chain that will successfully go to the next container is for each iterator to to know about the end of the container (I thought of a sort of hack in where when != is called against the end it will know to go to the next container, but the first way seemed easier and safer and more versatile).

My question is if there is anything inherently wrong with an iterator knowing about its own end, my code is in c++ but this can be language agnostic since many languages have iterators.

```<code>#ifndef CHAIN_HPP
#define CHAIN_HPP

#include "iterator_range.hpp"

namespace iter {
   template <typename ... Containers>
       struct chain_iter;
   template <typename Container>
       struct chain_iter<Container> {

        private:
           using Iterator = decltype(((Container*)nullptr)->begin());
           Iterator begin;
           const Iterator end;//never really used but kept it for consistency

        public:
           chain_iter(Container & container, bool is_end=false) :
               begin(container.begin()),end(container.end()) {
                   if(is_end) begin = container.end();
           }
           chain_iter & operator++()
           {
               ++begin;
               return *this;
           }
           auto operator*()->decltype(*begin)
           {
               return *begin;
           }
           bool operator!=(const chain_iter & rhs) const{
               return this->begin != rhs.begin;
           }
       };
   template <typename Container, typename ... Containers>
       struct chain_iter<Container,Containers...>
       {

        private:
           using Iterator = decltype(((Container*)nullptr)->begin());
           Iterator begin;
           const Iterator end;
           bool end_reached = false;
           chain_iter<Containers...> next_iter;

        public:
           chain_iter(Container & container, Containers& ... rest, bool is_end=false) :
               begin(container.begin()),
               end(container.end()),
               next_iter(rest...,is_end) {
                   if(is_end)
                       begin = container.end();
               }
           chain_iter & operator++()
           {
               if (begin == end) {
                   ++next_iter;
               }
               else {
                   ++begin;
               }
               return *this;
           }
           auto operator*()->decltype(*begin)
           {
               if (begin == end) {
                   return *next_iter;
               }
               else {
                   return *begin;
               }
           }
           bool operator !=(const chain_iter & rhs) const {
               if (begin == end) {
                   return this->next_iter != rhs.next_iter;
               }
               else
                   return this->begin != rhs.begin;
           }
        };
   template <typename ... Containers>
       iterator_range<chain_iter<Containers...>> chain(Containers& ... containers)
       {
           auto begin =
               chain_iter<Containers...>(containers...);
           auto end =
               chain_iter<Containers...>(containers...,true);
           return
               iterator_range<chain_iter<Containers...>>(begin,end);
       }
}

#endif //CHAIN_HPP
</code>```

答: Iterators is actually considered to be more or less a design miss which is still in mostly because of legacy and slow adoption of ranges, which is a much more powerful concept ( which is what your case more or less is ). Take a look at http://www.slideshare.net/rawwell/iteratorsmustgo and the boost range library.</p>


问:
Is it possible to build a custom email client for Gmail using Java APIs?
Is it possible to build a custom email client for Gmail using Java APIs?

Or only Google can do that?

答:
Yes you can
here is an example I made for college project, try change the yahoo server to Gmail server  </p>

```<code>      import java.io.BufferedReader;
      import java.io.IOException;
      import java.io.InputStreamReader;
      import java.io.OutputStreamWriter;
      import java.io.PrintWriter;
      import java.net.Socket;
      import java.net.UnknownHostException;
      import javax.swing.JOptionPane;

      public class Email {

      public static void main(String[] args) throws UnknownHostException,IOException    {

      Socket so = new Socket("smtp.mail.yahoo.com",25); // you change this to google's email sever

         BufferedReader inputStream = new BufferedReader(new InputStreamReader(so.getInputStream()));
PrintWriter outputStream   = new PrintWriter(new OutputStreamWriter(so.getOutputStream()),true);

    String enemail   =  JOptionPane.showInputDialog(null, "Enter your e-mail in BASEA64 code");
    String password  =  JOptionPane.showInputDialog(null, "Enter your password in BASEA64 code");
    String from      =  JOptionPane.showInputDialog(null, "From");
    String to        =  JOptionPane.showInputDialog(null, "To");
    String subject   =  JOptionPane.showInputDialog(null, "Subject");
    String msg       =  JOptionPane.showInputDialog(null, "Message");

    outputStream.println("HELO ");
    System.out.println(inputStream.readLine());

    outputStream.println("AUTH LOGIN");
    System.out.println(inputStream.readLine());

    //You enter your e-mail here , in BASE64 code

    outputStream.println(enemail);
    System.out.println(inputStream.readLine());

    //You enter your password here , in BASE64 code
    outputStream.println(password);
    System.out.println(inputStream.readLine());

    outputStream.println("VRFY");
    System.out.println(inputStream.readLine());

    outputStream.println("MAIL FROM:<"+from+">");
    System.out.println(inputStream.readLine());

    outputStream.println("RCPT TO:<"+to+">");
    System.out.println(inputStream.readLine());

    outputStream.println("DATA");
    System.out.println(inputStream.readLine());

    outputStream.println("Subject:"+subject);
    outputStream.println("FROM :<"+from+">");
    outputStream.println("TO :<"+to+">");
    outputStream.println(msg);
    outputStream.println("");
    outputStream.println(".");
    so.close();

             }

 }
</code>```

Body:
Yes you can
here is an example I made for college project, try change the yahoo server to Gmail server

      import java.io.BufferedReader;
      import java.io.IOException;
      import java.io.InputStreamReader;
      import java.io.OutputStreamWriter;
      import java.io.PrintWriter;
      import java.net.Socket;
      import java.net.UnknownHostException;
      import javax.swing.JOptionPane;

      public class Email {

      public static void main(String[] args) throws UnknownHostException,IOException    {

      Socket so = new Socket("smtp.mail.yahoo.com",25); // you change this to google's email sever

         BufferedReader inputStream = new BufferedReader(new InputStreamReader(so.getInputStream()));
PrintWriter outputStream   = new PrintWriter(new OutputStreamWriter(so.getOutputStream()),true);

    String enemail   =  JOptionPane.showInputDialog(null, "Enter your e-mail in BASEA64 code");
    String password  =  JOptionPane.showInputDialog(null, "Enter your password in BASEA64 code");
    String from      =  JOptionPane.showInputDialog(null, "From");
    String to        =  JOptionPane.showInputDialog(null, "To");
    String subject   =  JOptionPane.showInputDialog(null, "Subject");
    String msg       =  JOptionPane.showInputDialog(null, "Message");

    outputStream.println("HELO ");
    System.out.println(inputStream.readLine());

    outputStream.println("AUTH LOGIN");
    System.out.println(inputStream.readLine());

    //You enter your e-mail here , in BASE64 code

    outputStream.println(enemail);
    System.out.println(inputStream.readLine());

    //You enter your password here , in BASE64 code
    outputStream.println(password);
    System.out.println(inputStream.readLine());

    outputStream.println("VRFY");
    System.out.println(inputStream.readLine());

    outputStream.println("MAIL FROM:<"+from+">");
    System.out.println(inputStream.readLine());

    outputStream.println("RCPT TO:<"+to+">");
    System.out.println(inputStream.readLine());

    outputStream.println("DATA");
    System.out.println(inputStream.readLine());

    outputStream.println("Subject:"+subject);
    outputStream.println("FROM :<"+from+">");
    outputStream.println("TO :<"+to+">");
    outputStream.println(msg);
    outputStream.println("");
    outputStream.println(".");
    so.close();

             }

 }