答:
In a nutshell, generics solves the problem of having to use loosely typed objects.

For example, consider ArrayList vs List<T>. It allows you to have a strongly typed collection. list[0] will return type T vs arrayList[0] which will return type object.

But, you can do more with generics than just collections. Consider a generic repository used in an object relational solution:

```<code>public class Repository<T> where T : class, IBusinessOBject
{
  T Get(int id)
  void Save(T obj);
  void Delete(T obj);
}
</code>```

Generics can allow your class to encapsulate various types without requiring source level changes.

Title: What problems can be solved using Generics?

Body:
I haven't used Generics in C# for a long while. Every time I think I need to use them I either go in the wrong direction and give up or find that I don't really need them. I feel that I'm missing out or ignoring a technique which could be useful and powerful.

I'm aware of how generics are meant to be used (or at least I think I am). If you have three methods that are all doing the same thing with different types, then using generics enables you to have just one method that will work with these three types.

EDIT (in response to comment)

Are there any code smells or patterns that I should be looking out for?

Note I use List<> a lot, so I'm not ignoring generics in the the standard library. It's just that I've not written custom code using Generics for a while.

Body:
In a nutshell, generics solves the problem of having to use loosely typed objects.

For example, consider ArrayList vs List<T>. It allows you to have a strongly typed collection. list[0] will return type T vs arrayList[0] which will return type object.

But, you can do more with generics than just collections. Consider a generic repository used in an object relational solution:

public class Repository<T> where T : class, IBusinessOBject
{
  T Get(int id)
  void Save(T obj);
  void Delete(T obj);
}

Generics can allow your class to encapsulate various types without requiring source level changes.


问:
What is the (craziest, stupidest, silliest) thing a client/boss asked you to do?
See title, but I am asking from a technical perspective, not

Take my 40 year old virgin niece on a date or you're fired.

答:
At the ISP I worked for back in the mid 1990s, the boss was friends with officers from our local police and sheriff stations. They were interested in catching securities fraud. So my boss hatches a plan:

Write a program to scan websites for evidence of securities fraud. That is:

Start with IP address 0.0.0.1

End at 255.255.255.254

Scan every web page you find at each IP

This was back when pretty much every web server had a unique public-facing IP and virtual hosts didn't exist, so technically it was feasible. This was also back when a 1.5Mbps T-1 was really, really fast.

The problem? Even if we could scan ten IPs per second, the entire job would take almost 5,000 days to complete. Yep, had we gone through with such a program, it would be just now finishing its first scan of the entire Internet.

ContentLicense: CC BY-SA 2.5

ContentLicense: CC BY-SA 3.0


问:
What problems can be solved using Generics?
I haven't used Generics in C# for a long while. Every time I think I need to use them I either go in the wrong direction and give up or find that I don't really need them. I feel that I'm missing out or ignoring a technique which could be useful and powerful.

I'm aware of how generics are meant to be used (or at least I think I am). If you have three methods that are all doing the same thing with different types, then using generics enables you to have just one method that will work with these three types.

EDIT (in response to comment)

Are there any code smells or patterns that I should be looking out for?

Note I use List<> a lot, so I'm not ignoring generics in the the standard library. It's just that I've not written custom code using Generics for a while.

答:
Essentially, generics are a technique for aiding separation of concerns, or the single responsibility principle (SRP), as well as the DRY (Don't Repeat Yourself) principle. Without generics, you will sometimes see type or method names that reference both another type and a task, for example PersonCsvWriter, CustomerRecordSearch or ProductCollection. Unless these types derive from or consume other types that separate these responsibilities, then they are doing two things: e.g. PersonCsvWriter converts Person objects into sets of fields, and writes those fields to a CSV file. This makes your code harder to reuse. If you see this type of thing, it may be a code smell telling you that generics could be put to use.

I'd look out for this particularly if you are defining interfaces or abstract classes. Interfaces define roles in your application and don't make a lot of sense unless there can be multiple providers of that role. If the role is to work with other types, and the interface is not generic, it is very hard to re-implement it. For example, an IMapper<TFrom, TTo> is obviously a lot more reusable than a ICustomerToCustomerViewModelMapper.

You can of course be loosely-generic by treating everything as objects, using reflection and/or casting at runtime (as C#1 coders will remember). This isn't type-safe, having the obvious drawback of making your code harder to debug by allowing it to fail at runtime.


答:
Unless you're programming in Ada, where it comes up all the time, the opportunity to create new generic code is fairly rare.  For me, it comes up maybe once every three to five years, long enough that I have to look up the syntax.

The way to tell you need it is when you find yourself copying and pasting code, changing only the types, and you try to fix it using inheritance and it doesn't help.


问:
Why use a database instead of just saving your data to disk?
Instead of a database I just serialize my data to JSON, saving and loading it to disk when necessary. All the data management is made on the program itself, which is faster AND easier than using SQL queries. For that reason I have never understood why databases are necessary at all.

Why should one use a database instead of just saving the data to disk?

答:
A file system fits the description of a NoSQL database, so I'd say you should definitely consider using that when deciding on how to store your data and not just dismiss it off hand in favor of RDBMS, like some answers seems to suggest here.

One issue with file systems (and NoSQL in general) is handling relationships between data. If that is not major blocker here, then I'd say skip the RDBMS for now. Also remember the positive sides of using a file system as storage:

Zero administration

Low complexity, easy to set up

Works with any operating system, language, platform, libraries etc

Only configuration setting is the directory

Trivial to test

Trivial to examine with existing tools, backup, modify etc

Good performance characteristics and well tuned by the operating system

Easy for any developer to understand

No dependencies, no extra drivers

Security model is trivial to understand and is a base part of operating system

Data is not externally accessible

ContentLicense: CC BY-SA 4.0


问:
Audit trails and recording actions
Background

A discussion that has come up at work recently is how we handle audit logging and the recording of events.  We are integrating with a 3rd party app so triggers are a no no from the off so we are handling it in code.  We've written a number of prototype components for handling it but nothing feels right as yet.  The main issue being we want to create Facebook style time lines for the users to see what action have happened recently but these don't seem to fit well with how we record audits.

My question is how would be best to handle this type of scenario?

Should we tailor the audit log tables to fit the requirements of the front end?

Should we have separate tables to handle the "Actions" and have the
events and auditing separate

Should we look to a more message based architecture so this will be more like an Event sourcing type component?

Input from somebody who has done this type of system would be much appreciated.

答:
Should we tailor the audit log tables to fit the requirements of the front end?

No.  Generally this is better when you tailor the audit log tables to fit the requirements of auditors and then worry about the front-end later.

Should we have separate tables to handle the "Actions" and have the events and auditing separate

Yes.  This gives you more control over events, and adding new ones as you need.

Should we look to a more message based architecture so this will be more like an Event sourcing type component?

I prefer to keep things simple and merely store in the db.  However a message-based architecture may work well if you are integrating into a multi-tier application and your code is somewhere in the middleware.   But here it depends on what you need and we'd need to talk more specific requirements than we have here.

Title: Audit trails and recording actions


问:
Fastest way to find the closest point
I have a list in Python 2.7 of about 10000 point co-ordinates, like

```<code>[(168, 245), (59, 52), (61, 250), ... (205, 69), (185, 75)]
</code>```

Is there a faster way to search for all the points in a bounding box, instead of just iterating over the entire list each time and checking if the co-ord is inside the 4 sides??

I'm using this "algoritm" to see if any point, which is randomly moving, has come inside the stationary bounding box..(if it helps)

答:
What does "constantly moving" mean?

For example, if these points represent particles moving with a constant velocity and only affected by hard-sphere collision with other particles and with the wall, then it's possible to compute the time to intersection of each particle with the bounding box, and the compute the time for next collision. The time for next intersection can be kept in a priority queue, and when an intersection or collision occurs, you need only compute, in O(n) time, the next intersection of that particle/those particles with every other particle.

The mechanics of this are outlined in http://introcs.cs.princeton.edu/java/assignments/collisions.html , and summarized by Karl Bielefeldt earlier.

If the movement is random, but the changes are small and bounded then there's an upper limit on how far things can move. Use that as a bound. For example, if the max speed is 0.1 units per evaluation and your bounding box is the cell (10,10)-(11,11) then you can easily determine the particles within, say, 10 units of that cell, and know that there's no way any other particle can reach that cell for 100 evaluations.

If the coordinates change drastically each and every time, then the O(n) linear search is the best solution because any data structure (quadtree, hash grid, etc) takes at least O(n) time to set up, if only because it needs to visit each point.

Title: Fastest way to find the closest point


问:
What endpoints should I provide, if any, to permit connectivity testing for my web services?
What endpoints should I provide, if any, to permit connectivity / availability testing for my web services / Web API?

TL;DR

I am developing both the server and client in an enterprise environment. The client will interface with the server via an RESTful Web API. I would like to provide an indication to the user that they have correctly entered the Web API's root URL correctly. I would also like to implement connectivity monitoring of the API in the future.

None of the public APIs (Facebook, Twitter etc) that of have looked have a dedicated end point for connectivity testing. There are a number of web sites that provide availability monitoring of public APIs. One of them, Watchmouse, reported they preform their availability testing by actually exercising the API (logging in, perform an action, and testing the results).

On the other hand calling the root URL for CouchDB returns and configurable message and the CouchDB version.

Should I provide dedicated endpoints for connectivity / availability testing? If so what endpoints? Or should I just exercise existing endpoints?

答:
If the root returns a well-defined document that is unique to your server, then any client can tell that it was entered correctly. Why do you wish something more?

In addition to p.s.w.g's suggestion of a 'GetVersion()', you can also do a HEAD request and see if the server responds. Would an expected value for the "Server:" response header suffice?

You want to 'implement connectivity monitoring of the API in the future.' Will you support multiple versions? That is, the problem with a GetVersion() API is that you have to change clients and servers at the same time. Otherwise, a v2 client will refused to connect to a v3 server, even if the v3 service is backwards compatible so that v2 and v3 clients can connect to it.

One way to handle this is to have the root return a document containing a list of service points, where the points are versions. Personally, that's what I do. For example, it may point to services handled on other machines.

Another is to include a version value in the request and let the server figure out what to do. A third is to just go ahead and try new API entry points, and if there's a failure then the server isn't new enough.

Perhaps more useful than something which returns the server version is a summary diagnostic page, which shows that the server is up, that it's able to connect to the database (if you have one), etc. But the determination of what it does depends on your situation.


问:
Strategies for using a code metric evaluation tool
Should code quality metric evaluation tools like Sonar be integrated with IDE for running local analysis or should they be a part of the build process (like integrated with maven) for continuous inspection or should it be a combination of both? How can we leverage the power of such tools to the maximum extent possible?</p>

答: I would say that it should be used in both places, if possible. Ideally, your analysis tool would catch most of the code problems on a developer's workstation when the developer runs it locally and keep the code in source control cleaner. And having it run nightly in a batch would find any problems that do get checked in, and they can be focal points of the next code review - assuming that code that is flagged as problematic but still gets checked in is more complex to resolve and should be discussed before changing it from what works to what meets standards.


问:
Java serialization - advantages and disadvantages, use or avoid?
Serialization is used for persistence in Java. It may be okay to persist a few objects using serialization. But, for a large number of objects, ORM, Database etc might be better. It seems that serialization is useful only for small jobs. May be I am wrong. So please tell me
what are the advantages of serialization over non-serialization methods ? When should it be used and when should it be avoided ?

This question came to my mind after seeing DZone article Is Object Serialization Evil?

And these are the lines that gave rise to my question:

If you look at Java and its session objects, pure object serialization is used. Assuming that an application session is fairly short-lived, meaning at most a few hours, object serialization is simple, well supported and built into the Java concept of a session. However, when the data persistence is over a longer period of time, possibly days or weeks, and you have to worry about new releases of the application, serialization quickly becomes evil. As any good Java developer knows, if you plan to serialize an object, even in a session, you need a real serialization ID (serialVersionUID), not just a 1L, and you need to implement the Serializable interface. However, most developers do not know the real rules behind the Java deserialization process. If your object has changed, more than just adding simple fields to the object, it is possible that Java cannot deserialize the object correctly even if the serialization ID has not changed. Suddenly, you cannot retrieve your data any longer, which is inherently bad.

Now, may developers reading this may say that they would never write code that would have this problem. That may be true, but what about a library that you use or some other developer no longer employed by your company? Can you guarantee that this problem will never happen? The only way to guarantee that is to use a different serialization method.

答:
I use object serialization to allow post-mortem analysis in case of an unexpected error in production.  The inputs to a calculation are serialized to a data file.  If an error is reported, a simple program can reload the inputs and rerun the calculation with a debugger attached.  Or a groovy shell can be used to reload the objects and modify them if desired.

We also use serialization to pass Java objects through HTTP to a web service.  Much easier than serializing to and from text.  The disadvantage is that the client and server installations must be deployed together, but that's not problem since we control both ends.


答:
This is funny because I find myself writing generic classes and operations all the time. Perhaps because I'm working more on framework level code than client side. Some examples include Generic Repositories, Event Aggregators, and CQRS Command Handlers among others.

Generics are mostly useful in framework level code to enable reuse. If you're just consuming the frameworks, you might not find yourself creating generic functions as much.


问:
Using a database for each module in a system
I was reading this question:

I was trying to standardize and modularize some functions (Email
  Management Module, CMS Module & etc) by implementing a 3-tier
  architecture concept where each module would have its own independent
  module database. So that in the future all we'd need to do is just
  code a presentation layer, reuse the BLL layer, DAL Layer and
  database.

My follow-up question is whether it is a good idea to place all the database tables from each module into the same database, or whether they should be separated into entirely separate databases? I am using PostgreSQL. My worries are:

Problems with running data analysis if data is in many different databases

Problems pinning down database performance issues if we use the same database for all modules

In ability to join tables across modules if we some time in the future discover that our modularization is flawed for creating a certain feature

答:
Yes, that could be a problem if you want to analyze multiple databases at once. You could migrate and merge all of the data into a single analysis database and do your analysis there. That means you'll have to design a schema that will avoid any name clashes between tables and other objects, and a process to do the migration but it can be done.

Yes, that could also be a problem.

Yes, that could also be a proble, although each module could also have a data-access API to allow others access to data. This would make it difficult to have queries that join across databases, but it would be possible. Database links are also possible in Oracle (they allow a query run in one database direct access to objects in another), but I can't speak for other vendors' products.

And then then there's extra maintenance issues of having separate databases for each module, such as ensuring that they are all set up correctly, all of them are being backed up correctly, etc...

On the other hand, if you really do plan to have scenarios where there are many modules and they are not all deployed with each other, having separate databases might make sense when setting up new deployments. And adding new modules might be easier if you can ensure that the installation won't have to touch any existing databases.


问:
What API is required for code completion/syntax highlighting/similar IDE features?
I've been developing a little language in my own time, and I've got a fairly bare-bones prototype that implements some of the most basic features. Now I'm looking at scaling up, and I don't want to make a nasty architectural mistake where I have to massively refactor everything to support these features. So I'd like to know about the key API features required. Right now, I have

The lexer can operate on any input buffer using iterators, the tokens are available for inspection before passing to the parser, and I also provide a hook for comments.

The parser can operate on any token stream (not hard coded to my lexer at all), and the AST construction can be swapped out. I also annotated my AST with location information. Also, the AST is readily available for inspection prior to analysis.

Finally, many of the analysis features are lazily evaluated, so it's easy to get their semantic representation from the AST. But I'm not sure what features those semantic representations need to be readily available for such efforts.

Any suggestions as to what is necessary in this regard?

答: In regards to your question headline: "What API is required for code completion/syntax highlighting/similar IDE features?", it might be useful to check out the Qt Creator Development Suite if you looking to develop your own IDE. Qt allows for the deployment of cross-platform software, and it supports many of the features listed above (code completion, syntax highlighting, etc.). Not sure if this is what you were looking for, but between the question headline and the question description I got a little confused.</p>


问:
How to maintain synchronised state across threads - is this a good use for a Singleton?
I hear a lot about "Singletons are always bad" around the place. I don't hate on them to that degree but I try not to use them if I have a better alternative.

In this case I have a system that handles a lot of requests, each of which comes in on its own thread. Every request that comes in needs to be allocated its own unique sequential Id.

Currently I have a Singleton class whose role is to initiate this Id at start-up then maintain it while the system runs. The Singleton is created/retrieved and the Id value incremented in a thread safe way, as one would expect. It is actually handed out to the threads on creation by Dependency Injection, but the core of the class is a classic Singleton built around a static representation of the current Id value.

Given that we are only likely to do more work that requires a multi-threaded approach, I would be interested to know whether there is a way I could implement this type of functionality in a way that allows data to be maintained synchronously across threads that are otherwise unaware of each other, without using the much feared Singleton pattern?

答:
By having a singleton, you're then adding the singleton creation, access and state manipulation to your multithreading concerns.

Further, you're assuming that your request handler is going to only have one in the entire system. This is incorrect. Yes, you might only need one now. But what about unit tests? Are you really not going to run them concurrently? What about sub-systems that may eventually want their own request dispatch? What about possibly decorating or compositing that dispatch?

No, you have some object that takes requests and assigns them an ID for that handler. If they change scopes, then you can either simply re-ID the request or have a single shared ID provider for your different request handlers.


答:
There is a difference between a singleton and an instance that can be shared between multiple clients. You seem to want the latter (if not, think again!). For that, a singleton has no advantage and many of the usual downsides. Just permit any number of instances, but don't actually create several ones when you want sharing. You already have the infrastructure right for this (passing the object via dependency injection). You probably only need to make the constructor public and get rid of the singleton infrastructure.

So it costs practically nothing, and you gain:

Simplicity: Luckily, not making something a singleton is slightly easier than making it a singleton.

Testability: When you want to test something involving this ID allocator, you can just create a new one instead of depending on some global state of some singleton.

Extensibility: Should you at one point need several independent sources of sequential IDs in one process, you can just create another instance.

Title: How to maintain synchronised state across threads - is this a good use for a Singleton?

Body:
I hear a lot about "Singletons are always bad" around the place. I don't hate on them to that degree but I try not to use them if I have a better alternative.

In this case I have a system that handles a lot of requests, each of which comes in on its own thread. Every request that comes in needs to be allocated its own unique sequential Id.

Currently I have a Singleton class whose role is to initiate this Id at start-up then maintain it while the system runs. The Singleton is created/retrieved and the Id value incremented in a thread safe way, as one would expect. It is actually handed out to the threads on creation by Dependency Injection, but the core of the class is a classic Singleton built around a static representation of the current Id value.

Given that we are only likely to do more work that requires a multi-threaded approach, I would be interested to know whether there is a way I could implement this type of functionality in a way that allows data to be maintained synchronously across threads that are otherwise unaware of each other, without using the much feared Singleton pattern?


答:
If you want to combine data from different modules in any way, then you really want a single database.

The proper way to compartmentalize things within one database is to use schemas:

Schemas have separate namespaces, so using a schema for each module ensures that there will be no clashes between modules.  email.table1 will never clash with cms.table1.

Permissions can be set at a schema level, so the email module could be only allowed to access the email section, for example.

I don't think that having a single database will create any problems with regard to module installation/removal.  It is really no big deal to add and remove tables/schemas in a database.

As for performance, if you have performance problems you generally have to drill down and see what queries are causing the problems anyway.  I don't think it will make much of a difference whether it is in one database or several.

Title: Using a database for each module in a system

Body:
I was reading this question:

I was trying to standardize and modularize some functions (Email
  Management Module, CMS Module & etc) by implementing a 3-tier
  architecture concept where each module would have its own independent
  module database. So that in the future all we'd need to do is just
  code a presentation layer, reuse the BLL layer, DAL Layer and
  database.

My follow-up question is whether it is a good idea to place all the database tables from each module into the same database, or whether they should be separated into entirely separate databases? I am using PostgreSQL. My worries are:

Problems with running data analysis if data is in many different databases

Problems pinning down database performance issues if we use the same database for all modules

In ability to join tables across modules if we some time in the future discover that our modularization is flawed for creating a certain feature


问:
Should a new class refactored out of an existing one have history pointing back to it's progenitor
If I split one class into two classes should both classes have history in source control tracing back to the original class that contained both; or should the new class be added as a new file without any history tracing back?

When splitting a large class into two similar sized parts this seems like the natural approach since the older versions of the combined class will have large amounts of relevant history for both descendents.  When I'm just pulling one or two methods out to create a helper class, having the complete history for the new class be >90% changes in the parent that affected code that wasn't split out seems like a recipe for confusion in the future.

答:
I'm not sure this type of thing is necessary.

Your initial check in of the new class might say "Split ClassX and created ClassY and ClassZ based on it because....."

If a user really needs to trace back they can still find the original history.


答:
You need both, as they address linked but distinct situations :
The local run is all about making quick improvements when coding or immediately after. It also offer the comfort of your IDE (it is the best place to browse for code, as you have everything nearby). In addition, you can push developers to run it before committing, to have a first "quality firewall" in place.

The dashboard is all about the team. The fact that it is public did help a lot in my experience - no on want to be responsible of the "bad" project, so it did push to some kind of virtuous circle. In addition, it is very convenient to be able to arrive, open a browser and take a look "how did we this week" ? The dashboard also have the historical view, which is really important (more often than not, the trend is more important that the result - you want to be improving, that is what matter).

As you noted, Sonar actually allows both usage, which is nice (you want the same rule in the IDE and in the build).

Title: Strategies for using a code metric evaluation tool

Body: Should code quality metric evaluation tools like Sonar be integrated with IDE for running local analysis or should they be a part of the build process (like integrated with maven) for continuous inspection or should it be a combination of both? How can we leverage the power of such tools to the maximum extent possible?</p>


答:
If done correctly, separating business concerns into different databases (or at least different schemas) is a virtue.

Please see Martin Fowler's description of the CQRS Pattern:

As our needs become more sophisticated we steadily move away from [treating an information system like a CRUD datastore]... The change that CQRS introduces is to split that conceptual model into separate models for update and display... There's room for considerable variation here. The in-memory models may share the same database, in which case the database acts as the communication between the two models. However they may also use separate databases, effectively making the query-side's database by a real-time ReportingDatabase. In this case there needs to be some communication mechanism between the two models or their databases.

And NServiceBus Architectural Principles:

Command Query Separation

A solution that avoids this problem separates commands and queries at the system-level, even above that of client and server. In this solution there are two "services" that span both client and server - one in charge of commands (create, update, delete), the other in charge of queries (read). These services communicate only via messages - one cannot access the database of the other...

And Command and Query Responsibility Segregation (CQRS)

Command and Query Responsibility Segregation

Most applications reads data more frequently than they write data. Based on that statement, it would be a good idea to make a solution where easily you can add more databases to read from, right? So what if we set up a database dedicated just for reading? Even better; what if we design the database in a way so it’s faster to read from it? If you design your applications based on the patterns described in CQRS architecture, you will have a solution that is scalable and fast at reading data.


问:
What's the term describing this system for generating user interfaces?
So, there's this idea, which you already know: Define the layout of your UI by creating a tree of panels. The leaf nodes on the tree are what we used to call 'controls' way back in the day-- the things that the user interacts with, radio buttons and listboxes and such. The internal nodes are mostly concerned with layout; this kind of panel stacks its child panels vertically, that kind puts its children into a grid, etc.

It's COMMON. Most of the UI-generating systems I've seen in the past twenty years are implementations of this, and the ones that aren't borrow from it.

What's the word for this idea?

EDIT: I'm looking for a word, or a phrase, for the pattern I'm describing. It's a big, high-level pattern, and it's become nearly universal. AWT, HTML forms with the controls in table cells, Swing, XAML, Android, and ASP.NET all use it or borrow from it. There's an idea here, on the same level as concepts like "windowing system" or "mesh network." What do we call it?

I suspect that the real answer is, "there's no consensus on a name for it yet." Which would, itself, be really interesting.

答: A website wireframe is a visual guide that represents the skeletal framework of a website. The wireframe depicts the page layout or arrangement of the website’s content, including interface elements and navigational systems, and how they work together. http://en.wikipedia.org/wiki/Website_wireframe </p>


问:
How to start a development project when there are too many potential stakeholders
I've just taken on a new job at a college as (the sole) Web application developer.

The college has a number of disparate but all pretty badly coded legacy systems. Mostly built in PHP they deal with things like attendance, exam results, marking etc.

My first job is to build a system that incorporates a lot of this data, which is currently resting in various databases without any kind of friendly API to pull it out (the existing systems are coded in vanilla PHP with no separation of data and view) with a new platform for recording pastoral information about students and presents it to tutors and senior staff in a useful manner so they can react to issues with students quickly.

In our first meeting, there were 18 people! There was no clear leader or voice that represented the majority. No identifiable client. The meeting swung from detailed implementation ideas on minor features from heads of faculty to arguments about whether we should use Excel spreadsheets or not for data input!

As you can imagine my head was spinning at the end. I actually had a lot of good ideas but I couldn't get them heard. This is a very new role for me, before I was part of a development team in a marketing agency. We had very well defined roles: Project Manager, Client, Designer, Developer.

I'd like to know if any seasoned developers or managers out their can give me some pointers on how I can whip my colleagues up into something that resembles a project team. Is agile the way to go? How would you approach handling all the disparate voices? It's clear that some process needs to be put in place very quickly, I'm just not sure what that is.

答:
I would not expect any "agile development process" here as a solution to your current problem. First thing for you should be: clear your mission. That means:

clarify what your own responsibilities are

clarify what the responsibilities of the other stakeholders are

identify who is responsible for each of the legacy systems

if there is no client (yet) for your web application, find one who is going to use it in the future and ask for permission to incorporate him as a representative user of your system (a person you can discuss the requirements with)

if there are different stakeholders with different goals, collect their requirements (for example, by interviewing them one-by-one, not 18 people alltogether in one room). Write the results on a list. Afterwards, start priorizing.

write down a roadmap (the big picture) and a small spec for release 0.1 and make your boss as well as the representative client agree to it formally

EDIT: see GlenH7`s comment

This can take a while, you will probably don't write much code at this stage of the project. In such a situation, you should do some "requirements engineering" first. But start small, think big. Once you have developed your first release, you will have something to show around, discuss requirements again with the stakeholders etc.


答:
I would call it declarative definition. (ie you define 'what' the UI looks like, not the steps of 'how' to draw it).

The UI may be defined as a tree, but that is because the UI is a tree by it's own nature. The UI would still be a tree if defined in an imperative way with pointers to parent/child objects. I think declarative versus imperative is what matters.

Title: What's the term describing this system for generating user interfaces?

Body:
So, there's this idea, which you already know: Define the layout of your UI by creating a tree of panels. The leaf nodes on the tree are what we used to call 'controls' way back in the day-- the things that the user interacts with, radio buttons and listboxes and such. The internal nodes are mostly concerned with layout; this kind of panel stacks its child panels vertically, that kind puts its children into a grid, etc.

It's COMMON. Most of the UI-generating systems I've seen in the past twenty years are implementations of this, and the ones that aren't borrow from it.

What's the word for this idea?

EDIT: I'm looking for a word, or a phrase, for the pattern I'm describing. It's a big, high-level pattern, and it's become nearly universal. AWT, HTML forms with the controls in table cells, Swing, XAML, Android, and ASP.NET all use it or borrow from it. There's an idea here, on the same level as concepts like "windowing system" or "mesh network." What do we call it?

I suspect that the real answer is, "there's no consensus on a name for it yet." Which would, itself, be really interesting.


问:
Why shouldn't I use the repository pattern with Entity Framework?
During a job interview, I was asked to explain why the repository pattern isn't a good pattern to work with ORMs like Entity Framework. Why is this the case?</p>

答: The reason why you probably would do that is because it's a little redundant. Entity Framework gives you a wealth of coding and functional advantages, that's why you use it, if you then take that and wrap it in a repository pattern you are throwing those advantages away, you might as well be using any other data access layer.</p>

OwnerDisplayName: StringBuilder


问:
What does the "4" in LCOM4 mean?
I know that methods in a class should have high cohesion which roughly translates to having all the methods use all the instance variables directly or indirectly. I know that LCOM4 (Lack of cohesion)metric is useful for having a quantitative figure of how much cohesive the methods in a class are. A class with a LCOM4 value of 1 will be considered pretty good while a class with LCOM4 value of, say, 10 is considered a poorly designed class and this probably tells that we are better off decomposing the original  class into 10 separate classes. All this is okay but what does the 4 signify in LCOM4 metrics?

答:
LCOM4 is the fourth version of LCOM.

See http://www.aivosto.com/project/help/pm-oo-cohesion.html#LCOM4, under the subheading "Readings for LCOM4."

Title: What does the "4" in LCOM4 mean?


问:
Language design suggestion on database query
I am designing a new programming language.

I am designing a syntax to implement queries. Currently this is how it works.

The database is accessible through entity object.

on this sample I have "entity.manufacturers"  and "entity.products" table

To get manufacturer with an ID of 1:

```<code>   var @manufacturer = entity.manufacturers where id = 1;
</code>```

To query all products for @manufacturer:

```<code>    // Get all manufacturers products
    var @products = entity.products under @manufacturer;
    // No need to specify what links both since system already knows how entity is related
</code>```

Currently I am using "under" as a keyword to get all records for @manufacturer. I want it to make sense by just reading the code.

If you can give suggestions on a better syntax or keywords on how to implement this that will be awesome.

答:
I don't think under is the right word here as it makes to many assumptions about the nature of the relationship between two entities, when all you really need to indicate is fact that they are related. In many entity relationship, one entity may be thought of as under another, but this is certainly not the case for all entity relationships.

I'd use the word by instead, as in

```<code>var @products = entity.products by @manufacturer;
</code>```

Or on, as in

```<code>var @products = entity.products on @manufacturer;
</code>```

Since it hints that you are creating a simplified join syntax.

Body:
I don't think under is the right word here as it makes to many assumptions about the nature of the relationship between two entities, when all you really need to indicate is fact that they are related. In many entity relationship, one entity may be thought of as under another, but this is certainly not the case for all entity relationships.

I'd use the word by instead, as in

var @products = entity.products by @manufacturer;

Or on, as in

var @products = entity.products on @manufacturer;

Since it hints that you are creating a simplified join syntax.


问:
Web Developer or Software Engineer?
A question that I have been asking myself and really confused which path to take.

So I need your guys help as to the pros and cons of these 2 professions in today's world. I love web applications development as the Web is the best thing to happen in this age and nearly everyone gets by on the World Wide Web. And also tend to keep learning about new technologies and about web services.

On the other hand I like software engineering also for the desktop applications as I have had experience with development small scale software in VB.Net, Java, C++, etc.

Which path has more scope and better future? What's your view?

答:
I think a steady long-term career arc might be specializing in custom enterprise internal applications for the web in C# and Java.

Not my preferred cup of coffee, but I think it'll be a great bill-paying job.

Title: Web Developer or Software Engineer?


答:
It's much easier to ignore some history later than to try to splice it back in.  In general you want to favor the least destructive option.  People primarily review source control history for three reasons:

To find out which change introduced a bug.

To discern the reasons why a section of code is in there.

To find out what has changed since the last release or the last time you updated.

Copying history for a split file contributes little if any confusion for any of those use cases.  The worst that happens is you have to sift through some irrelevant commits, and you generally have to do that anyway.  On the other hand, not having the history past a certain point makes the first two use cases much more difficult.

Title: Should a new class refactored out of an existing one have history pointing back to it's progenitor

Body:
If I split one class into two classes should both classes have history in source control tracing back to the original class that contained both; or should the new class be added as a new file without any history tracing back?

When splitting a large class into two similar sized parts this seems like the natural approach since the older versions of the combined class will have large amounts of relevant history for both descendents.  When I'm just pulling one or two methods out to create a helper class, having the complete history for the new class be >90% changes in the parent that affected code that wasn't split out seems like a recipe for confusion in the future.


答:
Separate the ones who really want this project to work from the herd.

Due to a lot of politics, someone put together this meeting with a list of attendees where the membership was determined by who would get the most upset if I don't invite them. It happens. This goal was fullfilled but as the developer, you found that nothing was decided. No one was assigned what to do. If you're lucky, they managed to schedule the next meeting or god forbid, they set a reoccuring meeting on the 3rd Tuesday of each month.

Next will come the formation of committees, sub-committes, and task forces. This is betteer, but you'll find them all equally worthless.

Finally, you're going to find out who really cares about this project. Who really wants to put in the time to do it right. Hopefully, this person(s) will have a supervisor that will allow them the time to do this and not just make it another item on their already lengthy todo list. Find these people ASAP! Help them manage their boss's expectations and get an agreed amount of commitment.

Get something in front of as many people in the original group who will even bother to return. They may all be smart and/or educated people but they're not going to read a bunch of specs. They'll like some things, hate others and want more. It doesn't hurt to write down suggestions, but try to get that party to follow-up with some skin in the game. Don't promise to do everything. Just address what can be done in the near future.

If you end up having to deal with more than 5 people on a regular basis, it's because some manager made several of their people get involved who don't really want to be there.

Title: How to start a development project when there are too many potential stakeholders

Body:
I've just taken on a new job at a college as (the sole) Web application developer.

The college has a number of disparate but all pretty badly coded legacy systems. Mostly built in PHP they deal with things like attendance, exam results, marking etc.

My first job is to build a system that incorporates a lot of this data, which is currently resting in various databases without any kind of friendly API to pull it out (the existing systems are coded in vanilla PHP with no separation of data and view) with a new platform for recording pastoral information about students and presents it to tutors and senior staff in a useful manner so they can react to issues with students quickly.

In our first meeting, there were 18 people! There was no clear leader or voice that represented the majority. No identifiable client. The meeting swung from detailed implementation ideas on minor features from heads of faculty to arguments about whether we should use Excel spreadsheets or not for data input!

As you can imagine my head was spinning at the end. I actually had a lot of good ideas but I couldn't get them heard. This is a very new role for me, before I was part of a development team in a marketing agency. We had very well defined roles: Project Manager, Client, Designer, Developer.

I'd like to know if any seasoned developers or managers out their can give me some pointers on how I can whip my colleagues up into something that resembles a project team. Is agile the way to go? How would you approach handling all the disparate voices? It's clear that some process needs to be put in place very quickly, I'm just not sure what that is.


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

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

答: Perhaps try walking them through, one-on-one or in small groups ideally, use cases of software you have to develop.  As they describe the use cases, identify points in the case where different things could happen (unexpected but not unreasonable cases).  Start to enumerate them, ask for some clarifications, and illustrate all the decisions and directions that need to be made or settled on, and the trade-offs being made in doing so.  Keep going until they are stumped and can't give you an answer.  Get them to understand that, what you're doing now with them, is exactly what you do all day, probably on your own, probably with a lot less clear direction, both deciding the course and writing the code, for hundreds or thousands of use cases that may or may not even be laid out by anyone.  And when there's a case you had not thought of yourself, you can't guarantee what the program will do.  Maybe it does the "right" thing, maybe note.  And that's what a bug is.  And that's why writing software takes time.  The less time you have, the less cases that you had a chance to consider and accommodate, and the more likely the program will not do the "right" thing in an unknown circumstance.</p>


问:
Redis strategy for activity log data
Our application requires an activity log of actions that a user has done. For example:

3/19/2013

-------------

9:37 AM Chuck Norris scrapped 3 robots.

9:15 AM Chuck Norris fought 3 robots.

Currently this is done with a gigantic query that compiles all of a user's activity on a given day. The query is so slow that that application literally forbids you from looking at more than a single day's activity at a time. These results could be aggressively cached in Redis.

My question is: what is a good Redis key strategy for storing these activities?

I need to be able do a lookup primarily based on the user ID and a date range. I've played with the following possibilities, but nothing has really leaped out at me as the optimal solution.

```<code>-- psuedo-code, obviously --
HMSET user:5345:activity date "3/19/2013" time "9:37 AM" action "Some action"
LPUSH user:5345:activity (json)
LPUSH user:5345:activity:2013:03:19 (json)
</code>```

All three of these have significant tradeoffs. Assume a user hasn't logged in for four months - they might actually want to see their activity from four months ago at the top of the list. The second option gives me that, but there are trade-offs in that direction as well (like not being able to specifically query by date).

Any thoughts on a better way to approach this?

答:
Interesting challenge (!) because dates are sparse.

Here's a thought: if you can find a way to represent dates as numbers (minutes past the year 2000?), then you could try a Sorted Set. The set would be keyed on the user ID. The score would be the numeric date representation. The value would be the log entry.

Then you can use ZRANGEBYSCORE to get log entries within a date range. Also, it should be easy/efficient to "get the N most recent log entries".

Example: ZADD user:23432:activity 1363800946 data

Title: Redis strategy for activity log data


答:
Come up with a list of ideas which you think would solidify / improve the existing systems based on your observations and their "needs" and ensure you focus on where you can achieve actual visible gains. Include on that list each idea you think would be useful, as well as any standout "reasonable" suggestion from the non-devs.

Build a feature list of things that "should" be included in your development efforts. Give each member "voting" power, maybe in the form of "sticky stars" and find out what the whole actually wants by each member placing stars next to what they think is important. Some people may end up with more stars if they sign the check, have final say, etc.. After that hopefully you, and everyone else, will see what is important to the whole, and hopefully they will agree to the priority, which will then translate into a roadmap

1). Survey the Team - Find out what each member considers important / needed / top priority

2). Get something out there, quickly - Dont try to solve all of the problems all at once, get the "bare minimum" functionality out there and have them approve, then collectively advance it based on feedback of the users.

3). Use their feedback and the feedback of other users to guide the development process

(Build, Assess Feedback, Build, Assess Feedback) Rinse and Repeat.

Also, you might consider putting "effort points" or estimated hours to complete.. that might also aid in prioritization.


问:
I don't know C. And why should I learn it?
My first programming language was PHP (gasp).  After that I started working with JavaScript.  I've recently done work in C#.

I've never once looked at low or mid level languages like C.

The general consensus in the programming-community-at-large is that "a programmer who hasn't learned something like C, frankly, just can't handle programming concepts like pointers, data types, passing values by reference, etc."

I do not agree. I argue that:

Because high level languages are easily accessible, more "non-programmers" dive in and make a mess

In order to really get anything done in a high level language, one needs to understand the same similar concepts that most proponents of "learn-low-level-first" evangelize about.

Some people need to know C; those people have jobs that require them to write low to mid-level code. I'm sure C is awesome, and I'm sure there are a few bad programmers who know C.

Why the bias?  As a good, honest, hungry programmer, if I had to learn C (for some unforeseen reason), I would learn C.  Considering the multitude of languages out there, shouldn't good programmers focus on learning what advances us? Shouldn't we learn what interests us?  Should we not utilize our finite time moving forward?  Why do some programmers disagree with this?

I believe that striving for excellence in what you do is the fundamental deterministic trait between good programmers and bad ones.

Does anyone have any real world examples of how something written in a high level language—say Java, Pascal, PHP, or JavaScript—truly benefited from a prior knowledge of C? Examples would be most appreciated.

答:
I don't think any of the answers here are really what the OP was looking for, so I'm going to throw in my own opinion.

Look, I'm an unapologetic C snob.  My attitude is that if you don't know C, then to some extent you don't really know what you're doing as a programmer.  So, I think I'm the sort of "biased" person you're talking about here.

However, in practice, whether or not you really know what you're doing as a programmer doesn't necessarily prevent you from developing really awesome, useful software using high-level tools.  I mean, the creator of Stack Overflow, Jeff Atwood, apparently doesn't even know C, and yet I would say Stack Overflow is a pretty damn good web application.

Whether or not you decide to learn C (or C++, or assembly) depends on what type of programmer you want to be.  If you just want to develop cool web apps or business apps, that's fine - no real need to learn C.  But if you want to really excel at what you do - if you want to work on really cool projects that push the state of the art, then you really need to take yourself seriously enough as a programmer to really understand how computers work.  Since C is essentially the OS lingua franca, as well as the language that powers just about everything else (from the Linux kernel to most Java VMs, to the Python and Ruby interpreters, SQL databases, web servers, and just about every device driver), an intimate understanding of the language goes a long way.

Not to mention that knowing C (or C++) opens up a huge opportunity for contributing to large open-source projects that impact millions (or hundreds of millions) of people.  Want to work on improving the Python interpreter, or the Chromium web browser?  Well, you need to know C for the first and C++ for the latter.

That's why comparing C to dead natural languages like Latin or outdated technologies like the horse and carriage is completely wrong.  A large portion of our 21st century software infrastructure is powered by C code, which is why C remains as relevant today as ever.

So, whether or not you should learn C really depends on what you want out of your career as a programmer.


答: KISS - Make an itinerary. Thank everyone for coming, review it, do it. Side tracking will slow down if you address it by sharing their concern and ask them to stay AFTER the meeting. Make decisions by vote where there is controversy to keep most happy. Motivation towards participating in any system is directly related to the individuals belief in it's methods.</p>


答:
Designing good concrete syntax is ridiculously hard.  And unfortunately, while the best syntax in the world can't save a lame language, bad syntax can (has) doom(ed) good languages.

If this is a toy language, "full speed ahead" say I! But if you want to create a practical language for people to use, I have the following observations based on my personal experiences.  YMMV:

focus on the semantics and abstract syntax of your language.  This is the core of a language, and how people will learn and understand it.  Figure out how elements of the language can be defined, combined, and abstracted.  Absolutely do not let concrete syntax dictate the semantics or abstract syntax of your language.

keywords, braces, semicolons -- these are all totally irrelevant as far as abstract syntax and semantics are concerned.  There can be multiple concrete syntaxes for the exact same language.

implementing features as libraries is usually preferable to implementing them as syntax

syntax is hard to fix

syntax is hard to extend

syntax is hard to compose

syntax is not accessible at run-time

So my answer to your question is: design your abstract syntax and semantics first.  Without seeing those, it's very hard to come up with a good concrete syntax.  Once you have those, a concrete syntax should be much easier to derive.

Or you could just go with Lisp. ;)

Also, since you mentioned I want it to make sense by just reading the code, I should point out that designing a syntax that reads like plain English, yet is also simple, unambiguous and powerful has never been done (to my knowledge).  I do not believe this is possible (although I hope I am wrong).

Title: Language design suggestion on database query

Body:
I am designing a new programming language.

I am designing a syntax to implement queries. Currently this is how it works.

The database is accessible through entity object.

on this sample I have "entity.manufacturers"  and "entity.products" table

To get manufacturer with an ID of 1:

```<code>   var @manufacturer = entity.manufacturers where id = 1;
</code>```

To query all products for @manufacturer:

```<code>    // Get all manufacturers products
    var @products = entity.products under @manufacturer;
    // No need to specify what links both since system already knows how entity is related
</code>```

Currently I am using "under" as a keyword to get all records for @manufacturer. I want it to make sense by just reading the code.

If you can give suggestions on a better syntax or keywords on how to implement this that will be awesome.


答:
Cost and Time.

Time

Set expectations that you would deliver X in Y amount of time. It will have nothing more, nothing less. Then tell them what the next version will have in what time. At first they might get surprised to believe that building X takes Y amount of time - this is where you explain the time taken and complexities of building a software. If they are not surprised, either you estimated very less time or they knew better than you think about building software.

Cost

This is from Steve McConnel's Code Compete book(quoting from memory, so pardon me if I couldn't convey it with the same effect) - It is easy for customers to ask for new features. As a product manager, you should not say to what customer asks. You should estimate how much effort and cost it takes to build that new feature. They will slowly understand that the new feature is not really worth the money/time or perhaps that they don't even require it. I'm not suggesting that you use this a weapon to scare them, but use it honestly and it might help in driving the point home.

Title: Getting non-programmers to understand the development process

Body:
When starting a project for a company that's not primarily a programming company, one of the expectations is that there's a finished product at the end free of all bugs and does everything needed right away. However, that's rarely the case.

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


问:
What should a test method test?
Suppose we're unit testing a class with xUnit-like framework - so a test class is created for class-under-test. Now, how much should be tested by individual test methods?

Should there be one-to-one mapping between methods-under-test and test methods:

```<code>class TestMath {

    testSqrt() {
        assertEquals(Math.sqrt(4), 2);

        assertException(Math.sqrt(-2));
    }
}
</code>```

Or is it better to have one test method per "scenario":

```<code>class TestMath {

    testSqrtOfPositiveNum() {
        assertEquals(Math.sqrt(4), 2);
    }

    testSqrtOfNegativeNum() {
        assertException(Math.sqrt(-2));
    }
}
</code>```

Which is better and what are pros and cons of both methods?

答: Personally I prefer the scenario approach, it more closely resembles how the code will be used  and is less likely to break just do to some change in the way the underlying code works.</p>

Title: What should a test method test?


问:
Audit trails and recording actions
Background

A discussion that has come up at work recently is how we handle audit logging and the recording of events.  We are integrating with a 3rd party app so triggers are a no no from the off so we are handling it in code.  We've written a number of prototype components for handling it but nothing feels right as yet.  The main issue being we want to create Facebook style time lines for the users to see what action have happened recently but these don't seem to fit well with how we record audits.

My question is how would be best to handle this type of scenario?

Should we tailor the audit log tables to fit the requirements of the front end?

Should we have separate tables to handle the "Actions" and have the
events and auditing separate

Should we look to a more message based architecture so this will be more like an Event sourcing type component?

Input from somebody who has done this type of system would be much appreciated.

答:
As long as you are aware that the actions outside the application will not be logged (I personally would not try to do auditing except through triggers but third part products are usually a separate problem because you have a limited ability to change the db itself.), the approach is OK.

What is generally needed in auditing though is an approach where you store in separate tables for each table audited (to avoid the audit table causing locks). Next you store what you will need to know to revert the data and find the culprit if the change is a problem as well as what an auditor will want to know.

So we store both the old and new values, we store the id of the person making teh change and the name of application that sent in the change (We have multiple applications hitting the same database) and we also store the datetime of the change (very critical in finding all th3 records that need to be reverted from a  bad production push that happened on 02/01/2013 at midnight).

Becasue our changes are often in groups and not just one record at a time, each audit table is also split up into  a table that stores the info about the insert/update or delete (datetime, person, application, type of change) and one that stores the specific records changed or inserted or deleted. That way if you find one bad record change, you can see if there were possibly other records changed by the same person or application at the same time.

While you are designing teh system, go ahead and write the sql you need to revert data to it's old form. Even if you don't intend to use auditing for that, there is about a 100% chance you wil use it that way once the data is there. Sionce that usually happens under rpessure, ti s better to have a script or stored proc ready for reverting data.

Title: Audit trails and recording actions


答:
What a great slug-fest!
(As they supposedly say: Is this a private fight, or can anybody join in?)

I was a professor, and what I found (after some trial-and-error) was that it was much easier to lead students through the intricate concepts of programming if they understood, at a base level, just what a computer was doing. Not in all the nitty details, but the basic principle, like what memory is, what instructions are, etc. What I like about C is it's close to the machine.

That's not to say other teachers came to the same place. They started off in the high-level language (BASIC :-) and went forward from there, with no obvious ill effects.

So bottom line, Stephen, you could be right. I wouldn't think so, but I've been wrong before.

Title: I don't know C. And why should I learn it?

Body:
My first programming language was PHP (gasp).  After that I started working with JavaScript.  I've recently done work in C#.

I've never once looked at low or mid level languages like C.

The general consensus in the programming-community-at-large is that "a programmer who hasn't learned something like C, frankly, just can't handle programming concepts like pointers, data types, passing values by reference, etc."

I do not agree. I argue that:

Because high level languages are easily accessible, more "non-programmers" dive in and make a mess

In order to really get anything done in a high level language, one needs to understand the same similar concepts that most proponents of "learn-low-level-first" evangelize about.

Some people need to know C; those people have jobs that require them to write low to mid-level code. I'm sure C is awesome, and I'm sure there are a few bad programmers who know C.

Why the bias?  As a good, honest, hungry programmer, if I had to learn C (for some unforeseen reason), I would learn C.  Considering the multitude of languages out there, shouldn't good programmers focus on learning what advances us? Shouldn't we learn what interests us?  Should we not utilize our finite time moving forward?  Why do some programmers disagree with this?

I believe that striving for excellence in what you do is the fundamental deterministic trait between good programmers and bad ones.

Does anyone have any real world examples of how something written in a high level language—say Java, Pascal, PHP, or JavaScript—truly benefited from a prior knowledge of C? Examples would be most appreciated.


答: The second approach is better.  If one of the tests fail, you will instantly know what the problem is.  If your test methods check many conditions, if one of them fails, you will have to dig through it to figure out what the problem is.</p>

Title: What should a test method test?

Body:
Suppose we're unit testing a class with xUnit-like framework - so a test class is created for class-under-test. Now, how much should be tested by individual test methods?

Should there be one-to-one mapping between methods-under-test and test methods:

```<code>class TestMath {

    testSqrt() {
        assertEquals(Math.sqrt(4), 2);

        assertException(Math.sqrt(-2));
    }
}
</code>```

Or is it better to have one test method per "scenario":

```<code>class TestMath {

    testSqrtOfPositiveNum() {
        assertEquals(Math.sqrt(4), 2);
    }

    testSqrtOfNegativeNum() {
        assertException(Math.sqrt(-2));
    }
}
</code>```

Which is better and what are pros and cons of both methods?


答:
The general rule is have one assert per test.

As far as the level to which you should test.  I like to extract core logic into logic engines that can be tested using low level method level unit tests.  But also have higher level tests that run at a scenario level.  This way the high level tests speak the functionality of the whole system and the low level tests make sure that all the paths are tested correctly.  When something breaks you can see where it is that it has broken but also how the break will manifest at a higher level.

In your case I would definitely split it out into two tests so that you can see exactly what has broken rather than just knowing that something has broken.

Title: What should a test method test?


问:
Checking if my app is using any undocumented parts of the API
I just read through this question, but I am still confused.

How can I know if my app is using undocumented API calls before submitting to it to the app store? Are there any tools I can use?

答: Based on the answers I've found online, I do not believe there is anyway to dynamically be notified if you are using an undocumented API while coding. For the most part, it is assumed programmers would know ahead of time if they are using a third-party API that is not documented/approved by Apple. All the related answers suggest using the Validate step after you make an archive of your app: https://stackoverflow.com/questions/9815498/detecting-private-apis</p>


问:
How to use MVC in practice
I'm very confused. I can't even begin to understand how MVC would be implemented outside of web development. This might seem like too general a question, but how would one apply MVC. I have the following general questions:

Are M, V, and C all meant to be one class each, or many. If many, how would
that work.

Most classes I've made previously have had their data inside them, not in a separate class. How would this work with MVC?

1) For instance, lets say you have a class where you take care of a virtual dog. I would think that you would make a Dog class with, for example, a "bark" command that would play a sound along with a name variable and a coat_color variable. I know this is very simple, but how would this fit inside MVC? It seems that you would end up with MC and V, where the information (model) AND the controls were in the Dog class, which would maybe access swing, or whatever library, to update the view.

2) Or, what about a program like sims (simplified version) where each person would have their own information... would you put all that info in another class?

Sorry if these are all based on giant misconceptions, but I'm pretty confused. Right now I'm using Java, if that matters for MVC...

答:
You're a little all over the map there, perhaps getting ahead of yourself thinking about video games and dogs and what not.  The easiest way to think of MVC is to think of the responsibilities of the things in the acronyms.  At its core level, each of the components answers a question:

Model:  "What should we show the user?"

View:   "How should we show it to the user (what will it look like)?"

Controller: "How do I figure out which models and views to show the user?"

So, I'd suggest digesting that a bit and perhaps focusing your questions a little.  MVC is a "presentation pattern," meaning that it's not the basis for your entire application nor is it a philosophy or a universal approach to software development.  All it really gives you is a way to separate the responsibilities involved in presenting information to your users.  In this sense, you can use it on the web or the desktop or anywhere that you show things to users.

Title: How to use MVC in practice


答:
Undocumented methods aren't listed in the public headers. If you're using any such methods you will have had to declare them yourself in a category or gone out of your way to call them using a method like performSelector:@selector(...) or through some Objective-C runtime function.

In other words, it's unlikely that you'll call an undocumented method by accident.

The only reason to worry is if you're using code that someone else wrote and which you haven't taken the time to read through, or if you're perhaps using a library created by someone else for which you don't even have the source code. In that case, it's up to you to talk to the developer or otherwise satisfy yourself that the code in question doesn't use undocumented methods.

Title: Checking if my app is using any undocumented parts of the API

Body:
I just read through this question, but I am still confused.

How can I know if my app is using undocumented API calls before submitting to it to the app store? Are there any tools I can use?


问:
In TDD, if I write a test case that passes without modifying production code, what does that mean?
These are Robert C. Martin's rules for TDD:

You are not allowed to write any production code unless it is to
make a failing unit test pass.

You are not allowed to write any more
of a unit test than is sufficient to fail; and compilation failures
are failures.

You are not allowed to write any more production code
than is sufficient to pass the one failing unit test.

When I write a test that seems worthwhile but passes without changing production code:

Does that mean I did something wrong?

Should I avoid writing such tests in the future if it can be helped?

Should I leave that test there or remove it?

Note:  I was trying to ask this question here: Can I start with a passing unit test?  But I wasn't able to articulate the question well enough until now.

答:
It means that either:

You wrote the production code that fulfills the feature you want without writing the test first (a violation of "religious TDD"), or

The feature that you need happens to be already fulfilled by the production code, and you're just writing another unit test to cover that feature.

The latter situation is more common than you might think.  As a completely specious and trivial (but still illustrative) example, let's say that you wrote the following unit test (pseudocode, because I'm lazy):

```<code>public void TestAddMethod()
{
    Assert.IsTrue(Add(2,3) == 5);
}
</code>```

Because all you really need is the result of 2 and 3 added together.

Your implementing method would be:

```<code>public int add(int x, int y)
{
    return x + y;
}
</code>```

But let's say I now need to add 4 and 6 together:

```<code>public void TestAddMethod2()
{
    Assert.IsTrue(Add(4,6) == 10);
}
</code>```

I don't need to rewrite my method, because it already covers the second case.

Now let's say that I found out that my Add function really needs to return a number that has some ceiling, let's say 100.  I can write a new method that tests this:

```<code>public void TestAddMethod3()
{
    Assert.IsTrue(Add(100,100) == 100);
}
</code>```

And this test will now fail.  I must now rewrite my function

```<code>public int add(int x, int y)
{
    var a = x + y;
    return a > 100 ? 100 : a;
}
</code>```

to make it pass.

Common sense dictates that if

```<code>public void TestAddMethod2()
{
    Assert.IsTrue(Add(4,6) == 10);
}
</code>```

passes, you don't deliberately make your method fail just so that you can have a failing test so that you can write new code to make that test pass.

Body:
It means that either:

You wrote the production code that fulfills the feature you want without writing the test first (a violation of "religious TDD"), or

The feature that you need happens to be already fulfilled by the production code, and you're just writing another unit test to cover that feature.

The latter situation is more common than you might think.  As a completely specious and trivial (but still illustrative) example, let's say that you wrote the following unit test (pseudocode, because I'm lazy):

public void TestAddMethod()
{
    Assert.IsTrue(Add(2,3) == 5);
}

Because all you really need is the result of 2 and 3 added together.

Your implementing method would be:

public int add(int x, int y)
{
    return x + y;
}

But let's say I now need to add 4 and 6 together:

public void TestAddMethod2()
{
    Assert.IsTrue(Add(4,6) == 10);
}

I don't need to rewrite my method, because it already covers the second case.

Now let's say that I found out that my Add function really needs to return a number that has some ceiling, let's say 100.  I can write a new method that tests this:

public void TestAddMethod3()
{
    Assert.IsTrue(Add(100,100) == 100);
}

And this test will now fail.  I must now rewrite my function

public int add(int x, int y)
{
    var a = x + y;
    return a > 100 ? 100 : a;
}

to make it pass.

Common sense dictates that if

public void TestAddMethod2()
{
    Assert.IsTrue(Add(4,6) == 10);
}

passes, you don't deliberately make your method fail just so that you can have a failing test so that you can write new code to make that test pass.


答:
It says you can't write production code unless it's to get a failing unit test to pass, not that you can't write a test that passes from the get-go. The intent of the rule is to say "If you need to edit production code, make sure that you write or change a test for it first."

Sometimes we write tests to prove a theory. The test passes and that disproves our theory. We don't then remove the test. However, we might (knowing that we have the backing of source control) break production code, to make sure that we understand why it passed when we didn't expect it to.

If it turns out to be a valid and correct test, and it isn't duplicating an existing test, leave it there.

Title: In TDD, if I write a test case that passes without modifying production code, what does that mean?

Body:
These are Robert C. Martin's rules for TDD:

You are not allowed to write any production code unless it is to
make a failing unit test pass.

You are not allowed to write any more
of a unit test than is sufficient to fail; and compilation failures
are failures.

You are not allowed to write any more production code
than is sufficient to pass the one failing unit test.

When I write a test that seems worthwhile but passes without changing production code:

Does that mean I did something wrong?

Should I avoid writing such tests in the future if it can be helped?

Should I leave that test there or remove it?

Note:  I was trying to ask this question here: Can I start with a passing unit test?  But I wasn't able to articulate the question well enough until now.


答:
Heres something to think about. You used the example of a Dog class. then you ask yourself - what do dogs do? well they "bark". so lets make a method to Bark.

so then you have your Dog controller, and you put a Bark method in it. and then maybe you put specific things about Barking - the loudness, the tone, etc in a Bark Model.

and then you create methods for other actions like Walk and Eat and put them in your controller. and everything is working great and looks very logical.

But next your customer wants your dog to "whine" -- while begging. should you create a whine method? should you create a begging method and put something in about whining in there?

The problem was in the very first method we made. when we made a method called Bark, we set ourselves up to have a cluttered controller that can't grow. we should have asked the next question: What is Barking? its a sound that dogs can make. can dogs make other sounds? yes.

So what we REALLY need - before Barking - is a simple method in the Controller called makeDogSound or getDogSound etc, which then calls a Model DogSounds.

Then we can easily add more types of dog sounds to the Model - whine, growl, bark, woof - and the Controller is not changed! We can send different types of dog sounds to the view - again the controller is not changed in any way - its retrieving the sound from the model, and sending it to the view.

the controller is like a mailman - he picks up letters and delivers them. he does not look inside the letter!

eventually the DogSounds model could reference other models depending upon the type of dog. this can get very complex - but the structure in the controller - and how it delivers the assets to the view - remains consistent.

Title: How to use MVC in practice

Body:
I'm very confused. I can't even begin to understand how MVC would be implemented outside of web development. This might seem like too general a question, but how would one apply MVC. I have the following general questions:

Are M, V, and C all meant to be one class each, or many. If many, how would
that work.

Most classes I've made previously have had their data inside them, not in a separate class. How would this work with MVC?

1) For instance, lets say you have a class where you take care of a virtual dog. I would think that you would make a Dog class with, for example, a "bark" command that would play a sound along with a name variable and a coat_color variable. I know this is very simple, but how would this fit inside MVC? It seems that you would end up with MC and V, where the information (model) AND the controls were in the Dog class, which would maybe access swing, or whatever library, to update the view.

2) Or, what about a program like sims (simplified version) where each person would have their own information... would you put all that info in another class?

Sorry if these are all based on giant misconceptions, but I'm pretty confused. Right now I'm using Java, if that matters for MVC...


问:
Managing an undercover SVN repository
The project I am working on is version controlled by SVN, and the unspoken rule at work is to commit only when a new stable feature is added (in order to have a "clean" revision history with no revert) so I work sometimes for a few days without commiting.

However I am kind of a commiting maniac (several commits per day on my previous git projects) and this workflow doesn't suit me. Ideally I would like to fork the project, commit unstable version under the "submarine repo" and merge into the stable one whenever the feature is stable enough ( my unstable commits must not appear in the stable repo). How can I do this ?

With SVN : I've look for Vendor Branches and Externals but I didn't really find what I want.

With Git : is it possible to use Git on the undercover unstable repo and SVN for the stabilized repo without conflicts between the two CVS during merges ?

答:
With Subversion you can operate in a branch which for all intents and purposes will keep incomplete code out of the trunk.

With Git you can operate locally prior to pushing all of your changes to master, or as with subversion you can operate in multiple branches.

The main advantage to using Git over subversion, other than the fact it is a DVCS is that merging is far more trivial than it is with Subversion.

How can I do this ?

Do your development work in a branch for your VCS/DVCS of choice. Only merge back to the trunk when your feature is stable and you're happy with it.

With Git : is it possible to use Git on the undercover unstable repo and SVN for the stabilized repo without conflicts between the two CVS during merges ?

This question/answer on Stack Overflow shows you how to sync and push Git to Subversion. Hopefully it provides the level of technical detail you need.

Title: Managing an undercover SVN repository


答:
I would use the patch management tool Quilt. It is very light weight and efficient for making numerous small changes to a large tree, and simple to use.

When it comes time to commit to the big repo you can either apply all the patches and make one big commit, or commit them one by one.

With Quilt you can be a perfectionist, because it is easy to rewrite history. You can navigate up and down the stack of patches and fix your older work, essentially perfecting each patch. If you migrate your patches individually to a version control system, the whole thing then looks like a perfect unit of work. All logically independent changes belonging to that piece of work are in numerous separate patches, and yet there is no evidence that there had been any debugging, since there are no repeated changes to the same piece of code to get it working.

Title: Managing an undercover SVN repository

Body:
The project I am working on is version controlled by SVN, and the unspoken rule at work is to commit only when a new stable feature is added (in order to have a "clean" revision history with no revert) so I work sometimes for a few days without commiting.

However I am kind of a commiting maniac (several commits per day on my previous git projects) and this workflow doesn't suit me. Ideally I would like to fork the project, commit unstable version under the "submarine repo" and merge into the stable one whenever the feature is stable enough ( my unstable commits must not appear in the stable repo). How can I do this ?

With SVN : I've look for Vendor Branches and Externals but I didn't really find what I want.

With Git : is it possible to use Git on the undercover unstable repo and SVN for the stabilized repo without conflicts between the two CVS during merges ?


答:
I imagine you should scan the job ads for a few weeks and see what comes up regularly. I find here the biggest languages are C# and Java. My geographical area has a strong mobile development culture because of RIM, so that's a strong element I consider as well. Further, I don't particularly love doing graphics design, whereas I love CSS, JavaScript and the various libraries, PHP, and ASP.

You don't mention too much about your existing knowledge and background. Build a well-rounded foundation, find a project, and get coding. Having coding experience and general knowledge of programming regardless of language specifics is useful.

Title: Web Developer or Software Engineer?

Body:
A question that I have been asking myself and really confused which path to take.

So I need your guys help as to the pros and cons of these 2 professions in today's world. I love web applications development as the Web is the best thing to happen in this age and nearly everyone gets by on the World Wide Web. And also tend to keep learning about new technologies and about web services.

On the other hand I like software engineering also for the desktop applications as I have had experience with development small scale software in VB.Net, Java, C++, etc.

Which path has more scope and better future? What's your view?


问:
How do you find the first common element in two arrays
How do you find the first common element in two arrays?

My attempt:

I looped through each at the same time and add the current value to a separate set for each of the lists. Also, check if the current element is already in the other list's set.

I have no idea if this works though and if so, why? I know it finds a common element but does it find the first common element? I can't think of counter examples but I'm having trouble convincing myself it's definitely correct. Also, even if it is correct, is there a better way of finding the first common element?

答:
This is a Set Intersect. In .NET, I think the LINQ Intersect() method could be used. Java and others should have their own.

Note that you'd need to be careful about whether the implementation preserves array index order. E.g. in .NET, calling First() might not return the first by array index order.

For the low-level implementation of a Set Intersect, I would need to consult an Algorithms book. :)


答:
Sorting the arrays will not work. By changing the order you will not be able to determine which element matches first.

The intersect solution will also not work. To use it you'd have to copy both arrays to a set class, which by definition does not preserve order.

Your answer is correct. I would consider using hashsets to reduce search time.

Body:
How do you find the first common element in two arrays?

My attempt:

I looped through each at the same time and add the current value to a separate set for each of the lists. Also, check if the current element is already in the other list's set.

I have no idea if this works though and if so, why? I know it finds a common element but does it find the first common element? I can't think of counter examples but I'm having trouble convincing myself it's definitely correct. Also, even if it is correct, is there a better way of finding the first common element?


问:
Preventing crawler from interfering with user tracking
I'm scraping text from various webshops (no images/videos or other data). I'm no expert on user tracking, so I'd like to know if there's a way for me to write my crawler so it won't interfere with the webshop owners tracking. Perhaps this is already the case since the crawler isn't storing any cookies, requesting images or anything else but the actual pages, but I'd like to be sure.

What would I do when requesting the pages to ensure that nothing is tracked in Google Analytics for instance? Should I send an e-mail to the owners telling them to filter a specific user-agent or...?

I've seen How to be a good citizen when crawling web sites? where the last answer states that one should add "crawler" or "spider" in the user-agent. I'm not sure what to make of that as I can't find anything to back it up.

(The crawler is written in node.js and uses the request-module to download websites)

EDIT:
For anyone interested, here's the infinitely simple crawler I've made. It doesn't obey robots.txt because I'm specifying what kind of links I want to follow myself (and I'm too lazy right now to write something that obeys robots.txt):

```<code>var request = require("request")
, cheerio = require("cheerio")
;

exports.crawl = function(options) {
    var links = [].concat(options.url) // Takes either an array of url's or just a string.
    , ongoingRequests = 0
    , index = 0
    , done = false
    ;
    process.nextTick(ticker);
    function ticker() {
        if(ongoingRequests < options.maxRequests && index < links.length && !done) {
            var url = links[index++];
            ongoingRequests++;
            if(options.debug) console.log("Downloading " + url);
            request({ url: url, encoding: options.encoding || "utf-8" }, function(err, response) {
                ongoingRequests--;
                if(err) {
                    return;
                }
                if(!done) {
                    var $ = cheerio.load(response.body)
                    , shouldContinue = options.data($, response, url)
                    ;
                    if(shouldContinue === false) {
                        console.log("Crawler interrupted.");
                        options.done();
                        done = true;
                    }
                    var  newLinks = options.extractLinks($).filter(function(url, i) { return links.indexOf(url, i + 1) === -1; });
                    if(options.debug && newLinks.length) console.log(newLinks);
                    links = links.concat(newLinks);
                    if((index - 1) % 5 === 0) console.log("Current index: " + (index - 1) + ", links found so far: " + links.length);
                }
            });
        } else if(!ongoingRequests) {
            if(!done) {
                options.done();
                done = true;
            }
            return;
        }
        process.nextTick(ticker);
    }
};
</code>```

Use it like this:

```<code>var crawler = require("../crawler");

crawler.crawl({
    url: "http://website.com"
    , debug: true
    , maxRequests: 5
    , data: function($, response, url) {
        if(url.indexOf("/product/") === -1) {
            return;
        }
        console.log("extract stuff from $ using CSS-selectors and a nice jQuery-like API");
    }
    , done: function() {
        console.log("DONE!!");
    }
    , extractLinks: function($) {
        return $("a").map(function() {
            return $(this).attr("href");
        }).filter(function(url, i, a) {
            if(!url || url[0] !== "/") {
                return false;
            }
            return i === a.indexOf(url) // Remove duplicates
            && url.indexOf("/cart") === -1
                    && url.indexOf(".htm") > -1
            ;
        }).map(function(url) {
            return "http://website.com" + url;
        });
    }
});
</code>```

答:
Google Analytics tracking is implemented as javascript that runs in the browser.
Your crawler only requests the page, it does not execute any javascript that may be found on it.
So, there's no reason for you to worry about messing with the user tracking.</p>


问:
Java serialization - advantages and disadvantages, use or avoid?
Serialization is used for persistence in Java. It may be okay to persist a few objects using serialization. But, for a large number of objects, ORM, Database etc might be better. It seems that serialization is useful only for small jobs. May be I am wrong. So please tell me
what are the advantages of serialization over non-serialization methods ? When should it be used and when should it be avoided ?

This question came to my mind after seeing DZone article Is Object Serialization Evil?

And these are the lines that gave rise to my question:

If you look at Java and its session objects, pure object serialization is used. Assuming that an application session is fairly short-lived, meaning at most a few hours, object serialization is simple, well supported and built into the Java concept of a session. However, when the data persistence is over a longer period of time, possibly days or weeks, and you have to worry about new releases of the application, serialization quickly becomes evil. As any good Java developer knows, if you plan to serialize an object, even in a session, you need a real serialization ID (serialVersionUID), not just a 1L, and you need to implement the Serializable interface. However, most developers do not know the real rules behind the Java deserialization process. If your object has changed, more than just adding simple fields to the object, it is possible that Java cannot deserialize the object correctly even if the serialization ID has not changed. Suddenly, you cannot retrieve your data any longer, which is inherently bad.

Now, may developers reading this may say that they would never write code that would have this problem. That may be true, but what about a library that you use or some other developer no longer employed by your company? Can you guarantee that this problem will never happen? The only way to guarantee that is to use a different serialization method.

答:
Serialization is rarely used in practice.

As already mentioned the most common use case for serialization is to store objects as blobs in a session database. This works well for two reasons: sessions tend to be short lived, and the session database how no knowledge of how to map arbitrary objects to a relational model.

For data that needs to be retained for long periods of time (like an Amazon shopping cart) the best practice is to store that data in a database.

The session persistence mechanism ensures that a user with an active session is returned to the same server. The session database is only accessed when a server fails and the user is redirected to a new server. The new server detects an active session, but does not find it in memory, so it tries to retrieve it from the session database in an attempt to provide a seamless experience to the user.

There are two problems with this approach:

First, flushing session data to the session database is a slow process. Flushing session data too often degrades performance, and most servers are configured to flush every 30 seconds, or every minute, or longer. This "seemless" failover solution is never 100% effective.

Second, my experience is most clients agree that throwing up an error message asking the user to log in and try again during the rare instances that a server fails. In this case, we turn off the session database altogether and enjoy the performance boost.

Another use of serialization is to provide faster response times by using frameworks like Flex that use serialization and compression of object graphs for server-client interactions.

As other have pointed out, there are some creative and useful reasons to employ serialization, but these are rare in practice.

Historically serialization is difficult to implement correctly and reliability, restricting it's use to a small number of cases. Most developers will never serialize objects themselves, but may rely on frameworks who do it behind the scenes.