答:
At best I would think the analyst can make recommendations on team makeup if there is no team currently, but whoever the Developer Manager/Lead is should be making the decision based on the velocity (or other metric of tracking) of the people he is working with. This assumes that there is already a working development organization in the company.

In the case of a company (that happens to have an analyst but no Software Organization?!) I should think the Analyst can at most suggest what the starting makeup of the team should be and I should think that very soon they hire senior level developer that can take a lead role and help the Analyst get back to their job rather than try to manage a bunch of developers.

At least in my 25 years of development I never saw a Business Analyst or Software Analyst leading the Software Development team. I have run into cases where they offered their opinion on team makeup but in this day and age of Agile Software Development Life-cycle being more or less normal, I haven't seen this the case. I also don't recall this being a part of the hefty ITIL process, but I would have to check to be sure.

Title: Should the analyst define the programmers and their seniority needed by the project?

Body:
It might be obvious, but I am not sure.

Should the analyst who interview the client, gather and analyse requirements then give an estimate, also specifies how many and with how much experience developers should be required to develop it?

Maybe I'am not so sure on how I go about this allocation thing, maybe this is just not my work.


问:
What is the basic process and tools needed for crawling a source code repository for the purpose of data mining?
This all is with respect to Microsoft project CodeBook:
CodeBook

There is huge amount of code in the repository, many classes , a call hierarchy of functions, testcases etc. I am interested in knowing how this crawling process takes place, and how this data is sorted?

答:
I know that there is some research in the area of social network analysis to large software projects with regards to both knowledge management as well as the identification of defects, but to the best of my knowledge, it's mostly academic at this point. I did find Supporting Collaborative Software Development through the Visualization of Socio-Technical Dependencies, a paper by researchers at the University of California, Irvine and Universidade Federal do Pará which mentions an Eclipse plugin for such work. The plugin website also links to some other publications by this group.

A professor at my university also has some academic interests in defects and software security through similar approaches. Before I graduated, he gave a presentation related to some of his work. I believe the presentation was based on this paper, titled Predicting Failures with Developer Networks and Social Network Analysis. It doesn't appear to be what you're looking for exactly, but there might be some interesting related work in network analysis based on source code repositories.

I took a quick glance at the CodeBook project that you linked to. It appears that in order to get the level of detail that they are describing, you need some kind of knowledge about the organization of the project. That might be difficult with an open-source project, but I would expect that you can at least learn the basis of the analysis that they are doing.

At the very least, perhaps these papers might give you some other documents, publications, or keywords that you can use to help get started. Some keywords to perhaps get you started: social network analysis, socio-technological dependencies, distributed software development, developer network.

ContentLicense: CC BY-SA 3.0


问:
Test driven vs Business requirements constant changing
One of the new requirement of our dev team set by the CTO/CIO is to become test driven development, however I don't think the rest of the business is going to help because they have no sense of development life cycles, and requirements get changed all the time within a single sprint. Which gets me frustrated about wasting time writing 10 test cases and will become useless tomorrow.

We have suggested setting up processes to dodge those requirement changes and educate the business about development life cycles. What if the business fails to get the idea? What would you do?

答:
To make it more clear, a requirement requires the site to be able to
  upload an image and resize to below 500kb if actual size is over
  500kb.

Requirement change might be this feature is not needed (most of the
  time is after they have seen it, they realized they don't actually
  need it)

We have suggested setting up processes to dodge those requirement
  changes and educate the business about development life cycles. What
  if the business fails to get the idea?

First, it sounds like you might need to do more dummy prototyping. Meaning working, clickable mockups who don't actually store or retrieve any real data, but who emulate what the software would behave like. So for webapps, this would mean fully done HTML/CSS/JavaScript that lets user 'click through' the software, even though you have very little coding done. Perhaps that can help users see what it is they are asking for before you invest the work in coding it up.

Next, its really not up to the IT department to decide how the business does it's work. And it could be that the business values nimbleness over reliability for its software needs. So getting something changed TODAY is more valuable that making sure a given feature works 100% of the time, as opposed to 95.5% of the time. Only the business itself can decide this. Unless your department is getting slammed for quality issues, perhaps you should consider that the business is totally OK with shifting requirements and non-test-driven code. Your CTO/CIO says he wants you to be "test-driven", but if the business requirements are routinely "get this change done by 4pm" then you just can't have both.


问:
What do you optimize for?
Generally speaking, what type of optimizations do you typically slant yourself towards when designing software?

Are you the type that prefers to optimize your design for

Development time (i.e., quick to write and/or easier to maintain)?

Processing time

Storage (either RAM, DB, Disc, etc) space

Of course this is highly subjective to the type of problems being solved, and the deadlines involved, so I'd like to hear about the reasons that would make you choose one form of optimization over another.

答:
Design

low coupling, modular

concise, well defined, functional areas

well documented

continuously refactor for cruft

Maintenence

reproducible build and debug

unit tests

regression tests

source control

... after that everything else

... finally, optimise for performance ;-)

ContentLicense: CC BY-SA 2.5

Title: What do you optimize for?


问:
Is there any complications or side effects for changing final field access/visibility modifier from private to protected?
I have a private final field in one class and then I want to address that field in a subclass. I want to change field access/visibility modifier from private to protected, so I don't have to call getField() method from subclass and I can instead address that field directly (which is more clear and cohessive). Will there be any side effects or complications if I change private to protected for a final field?

UPDATE: from logical point of view, it's obvious that descendant should be able to directly access all predecessor fields, right? But there are certain constraints that are imposed on private final fields by JVM, like 100% initialization guarantee after construction phase(useful for concurrency) and so on. So I would like to know, by changing from private to protected, won't that or any other constraints be compromised?

答:
I think you are referring to the "freeze of final fields" on successful object instantiation:

When a constructor terminates normally, the thread performs freeze actions on all final fields defined in that class.

as stated in http://www.cs.umd.edu/~pugh/java/memoryModel/semantics.pdf

I guess this is a confusing subject, Alex Miller (former colleague at Terracotta), wrote up on it here : http://tech.puredanger.com/2008/11/26/jmm-and-final-field-freeze/

Anyways, I guess what I'm trying to say is that freeze happens on all final fields, not only private final ones... At least that's my understanding of JMM. And of such, have coded to that and haven't been proven wrong... until now ! ;)


问:
When can I publish a software tool written at work?
I'm working on a software problem at work that is fairly generic, but I can't find a library I like to solve it, so I'm considering writing one myself (at least a bare-bones version).  I'll be writing some if not all of the 1.0 version at work, since I need it for the project. If turns out well I might want to bring the work home and polish it up just for fun, and maybe release it as an open-source project.  However, I'm concerned that if I wrote the 1.0 version at work I may not be allowed to do this from a legal sense.  Obviously I could ask my boss (who probably won't care), but I'm curious how other programmers have dealt with this issue and where the law stands here.  My one sentence question is, When is it okay (legally/ethically) to open-source a software tool originally written by you for work at work?  What if you have expanded the original source significantly during off-hours?

Follow-up: Suppose I write the whole thing at home on my time then simply use it at work, does that change things drastically?

Follow-up 2: Note that I'm not trying to rip off my employer (I understand that they're paying me to build products that they own)--I'm just wondering if there's a fair way of doing this for all involved... It would be nice if some nonprofit down the road could use my code and save them some time.  Also, there's another issue at stake.  If I write the library for a very simple, generic thing (like HTML tables in Javascript), does that mean I can never again do so on my own time without putting myself at legal risk (even if it was a whole new fresh rewrite or a segment of a larger project).  Am I surrendering my right to write code for this sort of project for the rest of my life (without this company's permission), since the code at work might still be somewhere in my brain influencing me? This seems related to software patents, as a side-note.

答:
It is almost never OK, legally or ethically, to release products that you have created using your employer's resources or while being payed by the employer for your time without permission.

However, it depends on your employment contract. If you were paid by the company and/or used company resources to produce the product, chances are that the work belongs to your company. You need to go through your supervisor and your legal department. Depending on your employment contract, there might also be restrictions on working on related technologies or using knowledge gained at your employer in projects, even if you work on them using personal resources on your own time.

If you are using paid time, company resources, or are developing something that might be considered related to the business of your company, always seek guidance from your manager and/or legal department to ensure that you aren't violating any agreements and to get the appropriate permission to work on projects. Typically, it's easier to do this before you begin work as it might change the approaches that you take on the project.

Writing products for the use at work on your own time is questionable and depends on the regulations that your employer must adhere to. At the very least, you could be interfering with your employers schedule, budget, and estimates by taking work off-line. In some cases, you could be violating the contractual regulations by creating products outside of time that is tracked and billed appropriately.


答:
If turns out well I might want to bring the work home and polish it up
  just for fun, and maybe release it as an open-source project.

You should be crystal clear with your employer about your intentions at the outset. Come to an agreement about how that'll all work before you get started so that there are no hurt feelings, misunderstandings, disappointments, etc. The work you do for your employer is your employer's property.

When is it okay (legally/ethically) to open-source a software tool originally written by
  you for work at work?

When you have permission from your supervisor (and perhaps legal department) to distribute their property.

What if you have expaned the original source significantly during off-hours?

Doesn't matter. You're working with your employer's property -- changing a few lines here and there doesn't change that fact. It may still be theirs even if you change every single line in the project. Check with your lawyer for details, but don't expect good news.

Now, your employer may be perfectly happy to distribute the library under some open source license. If it's not something they consider part of their competitive advantage, or if they want to have the library maintained but don't necessarily want to do all the work to maintain it themselves, or if they want to garner some good will, or whatever, then things can work out. Just remember that it's their decision.

Title: When can I publish a software tool written at work?

Body:
I'm working on a software problem at work that is fairly generic, but I can't find a library I like to solve it, so I'm considering writing one myself (at least a bare-bones version).  I'll be writing some if not all of the 1.0 version at work, since I need it for the project. If turns out well I might want to bring the work home and polish it up just for fun, and maybe release it as an open-source project.  However, I'm concerned that if I wrote the 1.0 version at work I may not be allowed to do this from a legal sense.  Obviously I could ask my boss (who probably won't care), but I'm curious how other programmers have dealt with this issue and where the law stands here.  My one sentence question is, When is it okay (legally/ethically) to open-source a software tool originally written by you for work at work?  What if you have expanded the original source significantly during off-hours?

Follow-up: Suppose I write the whole thing at home on my time then simply use it at work, does that change things drastically?

Follow-up 2: Note that I'm not trying to rip off my employer (I understand that they're paying me to build products that they own)--I'm just wondering if there's a fair way of doing this for all involved... It would be nice if some nonprofit down the road could use my code and save them some time.  Also, there's another issue at stake.  If I write the library for a very simple, generic thing (like HTML tables in Javascript), does that mean I can never again do so on my own time without putting myself at legal risk (even if it was a whole new fresh rewrite or a segment of a larger project).  Am I surrendering my right to write code for this sort of project for the rest of my life (without this company's permission), since the code at work might still be somewhere in my brain influencing me? This seems related to software patents, as a side-note.


问:
Database Schema Usage
I have a question regarding the appropriate use of SQL Server database schemas and was hoping that some database gurus might be able to offer some guidance around best practice.

Just to give a bit of background, my team has recently shrunk to 2 people and we have just been merged with another 6 person team. My team had set up a SQL Server environment running off a desktop backing up to another desktop (and nightly to the network), whilst the new team has a formal SQL Server environment, running on a dedicated server, with backups and maintenance all handled by a dedicated team. So far it's good news for my team.

Now to the query. My team designed all our tables to belong to a 3-letter schema name (e.g. User = USR, General = GEN, Account = ACC) which broadly speaking relate to specific applications, although there is a lot of overlap. My new team has come from an Access background and have implemented their tables within dbo with a 3-letter perfix followed by "_tbl" so the examples above would be dbo.USR_tblTableName, dbo.GEN_tblTableName and dbo.ACC_tblTableName.

Further to this, neither my old team nor my new team has gone live with their SQL Servers yet (we're both coincidentally migrating away from Access environments) and the new team have said they're willing to consider adopting our approach if we can explain how this would be beneficial.

We are not anticipating handling table permissions at schema level, as we will be using application-level logins and the 7-character prefixes are not an issue as we're using LINQ so the tables can simply be renamed in the DMBL (although I know that presents some challenges when we update the DBML).

So therefore, given that both teams need to be aligned with one another, can anyone offer any convincing arguments either way?

答:
This is far from an authoritative answer on using schemas, but generally you want to use them for one of two reasons:  Security isolation or portability of related objects.

Security

It's possible to assign security permissions based on schema, which greatly simplifies complicated structures.  Think of an HR system where some people need to see hours, managers need to see files, but only specific individuals need to see anything related to pay.  If you put the pay stuff in a Salary schema you isolate from the rest of the data pretty effectively.

This can be done separately with other methods like views or granting permissions to specific objects but if you want to separate a group of related objects this is an easy way to go.

Portability

Some folks believe schemas make objects more portable.  Continuing our previous example, if you need to put the Salary data and related objects into another database or on another server, if they are entirely contained in that schema it would (potentially) be less work to move them all since you script out all objects in that schema.

In practice if you stick to a naming convention you can get the same effect without using a schema.

So, if you don't have security concerns with these objects, and you don't think you will ever need to move them (and you are going to use a strict naming convention ANYWAYS) then it's really a toss up as to which would be preferred.

Title: Database Schema Usage


问:
What should I use for a package name if I don't have a domain?

Possible Duplicate:

  What is the point of Java’s package naming convention?

  What package name to choose for a small, open-source Java project?

I write Java (and derivative languages with package names) for personal use, but I don't have a personal domain name, so the standard packaging naming convention doesn't hold.  Since the same convention is used in Maven group-id's, the problem is the same there.

What should I use for the root of my package name?

答:
```<code>com.ross
org.ross
personal.ross
</code>```

Really, who cares? It's probably not important if you don't know what to choose. Or you wouldn't ask.

Body:
com.ross
org.ross
personal.ross

Really, who cares? It's probably not important if you don't know what to choose. Or you wouldn't ask.


答: One idea would be to use your name, like org.cross.

Title: What should I use for a package name if I don't have a domain?

Body:
Possible Duplicate:

  What is the point of Java’s package naming convention?

  What package name to choose for a small, open-source Java project?

I write Java (and derivative languages with package names) for personal use, but I don't have a personal domain name, so the standard packaging naming convention doesn't hold.  Since the same convention is used in Maven group-id's, the problem is the same there.

What should I use for the root of my package name?


问:
Should the analyst define the programmers and their seniority needed by the project?
It might be obvious, but I am not sure.

Should the analyst who interview the client, gather and analyse requirements then give an estimate, also specifies how many and with how much experience developers should be required to develop it?

Maybe I'am not so sure on how I go about this allocation thing, maybe this is just not my work.

答:
This is something of a difficult problem that you face in consulting - you need to give a rough cost to get a contract signed before allocating resources.  There just isn't a great answer to a lot of these problems, but here's a few tips:

1)  You might want to first attack the problem by 'breaking it down' into smaller tasks that you can have a chance at estimating.  Something like "I need to create a billing system, which will require that I have a database, a login feature, a list of current invoices, a way to edit a single invoice, a way to approve an invoice for payment, etc., etc.)

The smaller pieces you can define, the better chance you'll have at producing a reliable estimate.

2)  See if you can't shoehorn a dev or two (buy her lunch!) into giving some advice - even at a high level you can define a "large" task, a "small" task, etc.  Try to break the "large" tasks down even further if you can.

3)  Now if you have a rough number in mind (think large chunks here - "this might be XXX days of work"), then you can think about resource assignment.

But to echo an earlier comment - I've never seen an 'analyst' ultimately responsible for estimation and resource assignment; to come up with a reliable estimate you do need someone with enough experience (and preferably a track record of actually tracking "estimates vs. results") to know what amount of effort certain tasks might take.  (Again, preferably the opinions of "more than one" of these people.)

The problem is similar to me planning a house building project:  I can draft a bunch of back of the envelope projections, but at some point I'm going to have to get the opinion of a carpenter who actually builds houses.


答: Imagine you'd get a domain. I'd bet neither org.cross nor com.ross from the other answers are free, but something more complicated is. Go to a web domain registrator page and query what's free (you don't need to buy or reserve the domain). This is how I'm doing it since years; I still need no domain, but the one I chose is still free.


答: Development time, absolutely. I also optimize for bandwidth, but I don't go to binary.</p>

Title: What do you optimize for?

Body:
Generally speaking, what type of optimizations do you typically slant yourself towards when designing software?

Are you the type that prefers to optimize your design for

Development time (i.e., quick to write and/or easier to maintain)?

Processing time

Storage (either RAM, DB, Disc, etc) space

Of course this is highly subjective to the type of problems being solved, and the deadlines involved, so I'd like to hear about the reasons that would make you choose one form of optimization over another.


答:
According to section 17.5 of the JLS, final fields have the same Java Memory Model semantics regardless of access. In fact, there are no private fields in the code examples from that section. They all have default access.

Just keep in mind the rules laid out in the JLS: all bets are off if you allow another thread to see a reference to your object before all of the constructors have completed.

Also, there are two gotchas for calling overridable methods from the superclass constructor: the overriden method in the subclass will see default values for fields (even final ones) that haven't been written yet, and they also might publish a reference to the partly-constructed instance. These caveats should be documented both on the constructor and on the methods that the constructor might invoke. Or better yet, don't call overridable methods from the constructor in the first place.

Title: Is there any complications or side effects for changing final field access/visibility modifier from private to protected?

Body:
I have a private final field in one class and then I want to address that field in a subclass. I want to change field access/visibility modifier from private to protected, so I don't have to call getField() method from subclass and I can instead address that field directly (which is more clear and cohessive). Will there be any side effects or complications if I change private to protected for a final field?

UPDATE: from logical point of view, it's obvious that descendant should be able to directly access all predecessor fields, right? But there are certain constraints that are imposed on private final fields by JVM, like 100% initialization guarantee after construction phase(useful for concurrency) and so on. So I would like to know, by changing from private to protected, won't that or any other constraints be compromised?


答:
Easy answer:

Never.

Here's the problem: According to the laws of most modern countries, you hold a copyright over everything you write by default. This holds true even when you write it for someone else, such as your employer.

Obviously, this is problematic for anyone who is interested in hiring a software developer.

To solve this, software companies have you sign a Non-Disclosure Agreement (NDA). Within this NDA, it explicitly states that you relinquish the copyright of all code you write for that employer. Doesn't matter when you did it. It's all the same.

In other words: The code that you wrote does not belong to you. It belongs to the employer, and you are not allowed to publish it.

I've never heard of a developer not signing an NDA, so unless you're in some really remote region of the world, its a safe bet to say that you signed an NDA when you were hired.

If your employer is interested in publishing it for some reason, then it is a different story (and if you're iterested, you could also try to convince them that it is the correct thing to do). But that's the only way.


问:
Should I implement BackBone.js into my ASP.NET WebForms applications?

Background

I'm trying to improve my group's current web app development pattern. Our current pattern is something we came up with while trying to rich web apps on top of ASP.NET WebForms (none of us knew ASP.NET MVC). This is the current pattern:

!

Our application is using the WinForms Framework.

Our ASPX pages are essentially just HTML, we use almost no WebControls.

We use JavaScript/jQuery to perform all of our UI events and AJAX calls.

For a single ASPX page, we have a single .js file.

All of our AJAX calls are POSTs (not RESTful at all)

Our AJAX calls contact WebMethods which we have defined in a series of ASMX files.

One ASMX file per business object.

Why Change?

I want to revise our pattern a bit for a couple of reasons:

We're starting to find that our JavaScript files are getting a bit unwieldy.

We're using a hodgepodge of methods for keeping our local data and DOM updates in sync. We seem to spend too much time writing code to keep things in sync, and it can get tricky to debug.

I've been reading Developing Backbone.js Applications and I like a lot of what Backbone has to offer in terms of code organization and separation of concerns. However, I've gotten to the chapter on RESTful app, I started to feel some hesitation about using Backbone.

The Problem

The problem is our WebMethods do not really fit into the RESTful pattern, which seems to be the way Backbone wants to consume them.

For now, I'd only like to address our issue of disorganized client side code. I'd like to avoid major rewrites to our WebMethods.

My Questions

Is it possible to use Backbone (or a similar library) to clean up our client code, while not majorly impacting our data access WebMethods? Or would trying to use Backbone in this manner be a bastardization of it's intended use?

Anyone have any suggestions for improving our pattern in the area of code organization and spending less time writing DOM and data sync code?

答:
It will depend largely on how you've architected and written your code, but it is possible to retrofit your application to allow for using Backbone.js (and no, I don't think it's necessarily a bastardization).

What you'll need to do is translate your calls somewhere to something that your web services can understand. There are potentially two ways to do this:

Create a server-side API wrapper that sends and receives REST calls. Basically, you'd create an "API"/"router" class that the Backbone application interfaces with. This API translates the REST calls into something that your web services understand. It then translates the information from the webservices back into a RESTful response that the Backbone application understands. (This works really easily if your WebMethods can be called directly from other functions on the servers (IE - "var foo = bar.GetData()" or whatever).)

Override Backbone's sync methods with your own. It is also possible to override the built-in Sync function with your own. Doing this will allow you to build a Sync function set that can understand the type of data you're sending and receiving. This would translate the REST commands (get, set, update, delete) from the applications into commands that comply with your web services.

I personally recommend putting a wrapper around your server side code if possible, so that you can update it in the future, without having to rework your client side code again. However, if you have to go the route of option 2, try to write the rest of your Backbone application as though your web services were a RESTful API, that way you can easily replace your Sync functions with the vanilla Backbone.Sync once you've converted your server.


问:
Patterns for a tree of persistent data with multiple storage options?
I have a real-world problem which I'll try to abstract into an illustrative example.

So imagine I have data objects in a tree, where parent objects can access children, and children can access parents:

```<code>// Interfaces
interface IParent<TChild> { List<TChild> Children; }
interface IChild<TParent> { TParent Parent; }

// Classes
class Top : IParent<Middle> {}
class Middle : IParent<Bottom>, IChild<Top> {}
class Bottom : IChild<Middle> {}

// Usage
var top = new Top();
var middles = top.Children; // List<Middle>
foreach (var middle in middles) {
    var bottoms = middle.Children; // List<Bottom>
    foreach (var bottom in bottoms) {
        var middle = bottom.Parent; // Access the parent
        var top = middle.Parent; // Access the grandparent
    }
}
</code>```

All three data objects have properties that are persisted in two data stores (e.g. a database and a web service), and they need to reflect and synchronise with the stores. Some objects only request from the web service, some only write to it.

Data Mapper

My favourite pattern for data access is Data Mapper, because it completely separates the data objects themselves from the communication with the data store:

```<code>class TopMapper {
    public Top FetchById(int id) {
        var top = new Top(DataStore.TopDataById(id));
        top.Children = MiddleMapper.FetchForTop(Top);
        return Top;
    }
}

class MiddleMapper {
    public Middle FetchById(int id) {
         var middle = new Middle(DataStore.MiddleDataById(id));
         middle.Parent = TopMapper.FetchForMiddle(middle);
         middle.Children = BottomMapper.FetchForMiddle(bottom);
         return middle;
    }
}
</code>```

This way I can have one mapper per data store, and build the object from the mapper I want, and then save it back using the mapper I want.

There is a circular reference here, but I guess that's not a problem because most languages can just store memory references to the objects, so there won't actually be infinite data.

The problem with this is that every time I want to construct a new Top, Middle or Bottom, it needs to build the entire object tree within that object's Parent or Children property, with all the data store requests and memory usage that that entails. And in real life my tree is much bigger than the one represented here, so that's a problem.

Requests in the object

In this the objects request their Parents and Children themselves:

```<code>class Middle {
    private List<Bottom> _children = null; // cache
    public List<Bottom> Children {
        get {
            _children = _children ?? BottomMapper.FetchForMiddle(this);
            return _children;
        }
        set {
            BottomMapper.UpdateForMiddle(this, value);
            _children = value;
        }
    }
}
</code>```

I think this is an example of the repository pattern. Is that correct?

This solution seems neat - the data only gets requested from the data store when you need it, and thereafter it's stored in the object if you want to request it again, avoiding a further request.

However, I have two different data sources. There's a database, but there's also a web service, and I need to be able to create an object from the web service and save it back to the database and then request it again from the database and update the web service.

This also makes me uneasy because the data objects themselves are no longer ignorant of the data source. We've introduced a new dependency, not to mention a circular dependency, making it harder to test. And the objects now mask their communication with the database.

Other solutions

Are there any other solutions which could take care of the multiple stores problem but also mean that I don't need to build / request all the data every time?

答:
The undesirable part of your approach comes from having the data objects themselves unfreezing (loading, deserialising) themselves.

This is not a simple problem!

Ideally you want your data objects being quite simple, and some external agent being responsible for deserialising and serialising them using data that lives on disk, or on the network, etc.

One approach to this might use reflection and object introspection and fancy things like that.

Another approach might use to use "generic objects". A generic object can store an arbitrary amount of properties (i.e. fields/variables). Each field can be one of a few set types: int, string, byte array, reference to another generic object (that one is important), etc. So you can then model your data objects as generic objects.

The advantage of using "generic objects" is that you can then have a mechanism external (or super) to the generic object class through which its properties are accessed. This mechanism recognises when a field hasn't yet been loaded, and can fetch it from the appropriate source. It an also handle cache writing, e.g. fetching data from remote source, writing to to local cache.

The above is a very general sounding description, but it's not a trivial thing to implement so it might be hard to get any more specific without getting very verbose.

See also this SO question: https://stackoverflow.com/questions/9200545/recommended-pattern-for-lazy-loading-portions-of-object-graph-from-cache

Also note that Core Data in iOS is an object grapher which handles lazy loading (faulting) -- your problem area is very similar to what Core Data addresses.

Core Data is an object graph and persistence framework provided by
  Apple [...] It allows data organised by the relational
  entity–attribute model to be serialised into XML, binary, or SQLite
  stores. The data can be manipulated using higher level objects
  representing entities and their relationships. Core Data manages the
  serialised version, providing object lifecycle and object graph
  management, including persistence.


问:
UML - Class Diagrams Order -> Products
I have a class diagram that is like this:

```<code>< Order > (1) CAN HAVE (M) < products >
</code>```

But therefore Order has the following:

```<code>Order_Id
Customer_Id
Order_date_day
Order_date_month
Order_date_yeah
</code>```

But I do not know how it would handle the Products? Because, I couldn't have ProductID because that would mean that each item in this class would have to have a separate instance for each product (E.g. someone ordered 100 products, but only placed 1 order).

Could I have an Product object in class Order? If so, how do I represent that in UML?

答:
The one-to-many relationship between Order and Product translates as a list of Products. For example in Java Order would have a member of type List<Product>.

But I recommend having an OrderDetail class instead because you will soon find  that you have to have and amount or quantity of the product, and it doesn't belong in either Order or Product.

EDIT:

In UML Order would have a "composition" which is a line with a black diamond shape on the Order side and a ">" (not a triangle) on the OrderDetail side.

If you decide to use Product instead of OrderDetail then you should have an "agregation" which has a white diamond shape.

The difference is that a composition means OrderDetail has no meaning outside an Order whereas agregation means that Products can exist by themselves outside an Order.

Title: UML - Class Diagrams Order -> Products


问:
Why not use unmanaged safe code in C#
There is an option in C# to execute code unchecked. It's generally not advised to do so, as managed code is much safer and it overcomes a lot of problems.

However I am wondering, if you're sure your code won't cause errors,
and you know how to handle memory then why (if you like fast code) follow the general advice?

I am wondering this since I wrote a program for a video camera, which required some extremely fast bitmap manipulation. I made some fast graphical algorithms myself, and they work excellent on the bitmaps using unmanaged code.

Now I wonder in general, if you're sure you don't have memory leaks, or risks of crashes, why not use unmanaged code more often?

PS my background: I kinda rolled into this programming world and I work alone (I do so for a few years) and so I hope this software design question isn't that strange. I don't really have other people out there like a teacher to ask such things.

答:
Because being "sure" about correctness or any other constraint in the mathematical sense (i.e. you have proof) is a very hard problem for imperative languages. Programs often have a such high number of states that it's not possible to verify them even with checking each possible state. And creating a constructive proof is not something you can automate.

So the reason is that the insurances that managed execution provides most often over-weigh the small performance gain that you would get with unsafe code. Of course, this depends on the specific use-case, too.

Title: Why not use unmanaged safe code in C#


答:
Whatever virtualization technology I'm using

Remember the days when systems with more than 512 MB of RAM were considered bleeding edge? I spend my days writing code for the prior.

I work mostly on low level programs that run on the privileged domain in a Xen environment. Our ceiling for the privileged domain is 512 MB, leaving the rest of the RAM free for our customers to use. It is also typical for us to limit the privileged domain to just one CPU core.

So here I am, writing code that will run on a brand new $6k server, and each program has to work (ideally) within a 100kb allocated ceiling, or eschew dynamic memory allocation completely.

Concisely, I optimize for:

Memory footprint

Sorts (where most of my code spends most of its time)

I also have to be extremely diligent when it comes to time spent waiting for locks, waiting for I/O or just waiting in general. A substantial amount of my time goes into improving existing non blocking socket libraries and looking into more practical methods of lock free programming.

Every day I find it a little ironic that I'm writing code just like I did 15 years ago, on systems that were bought last month, due to advancements in technology.

This is typical for anyone working on embedded platforms as well, though even many of those have at least 1GB at their disposal. As Jason points out, it is also typical when writing programs to be run on mobile devices. The list goes on, Kiosks, thin clients, picture frames, etc ..

I'm beginning to think that hardware restrictions really separate programmers from people who can make something work without caring what it actually consumes. I worry (down vote me if you must) what languages that completely abstract type and memory checking to the collective pool of common sense that (used to be) shared amongst programmers of various disciplines.

Title: What do you optimize for?


答:
Well, it's mostly a case of the age old adage

Don't optimize

(for experts only) Don't optimize yet

But actually I can think of three main reason to avoid unsafe code.

Bugs:
The critical part of your question is "if you're sure your code won't cause errors". Well, how can you be absolutely totally sure? Did you use a prover with formal method that guaranteed your code correct? One thing is certain in programming, and that is that you will have bugs. When you take off a safety, you allow new sort of bugs to creep trough. When you let the garbage collector take care of the memory for you, a lot of problem go away.

Not always as fast as you think: The other point is : depending on the problem, the gain may not be that great. Although I can't seem to find them right now, I remember a study by Google comparing the speed of Java, Scala, Go and C++. Once optimized to the ground, of course C++ was much faster. But the algorithm programmed in the "idiomatic" way were not really that much faster. Idiomatic in the sense that they were using standard structure and idioms (stl container, no unrolled loop, etc). Microsoft did a similar experiment with C# and C++. Raymond Chen, one of the top Microsoft Engineer, had to write his own implementation of std::string to beat C#. (see: http://www.codinghorror.com/blog/2005/05/on-managed-code-performance-again.html) For much less effort, you got pretty decent performance in managed code, so its often  not worth the trouble.

Reusability: Unsafe code can only be used in a full trust environment. For example, in an ASP.NET server, you usually can't use unsafe code, since it would be pretty easy to introduce a vulnerability by buffer overflow. Another example would be clickonce. Or if your application was accessed from a network share. So if you plan to use your code in a variety of deployment scenario, unsafe code is out of the game.

So basically : its frowned upon because it may introduce unnecessary bugs, it may well be for no gain at all, and it reduce the reusability of your code.

But if your scenario really require it for performance (and you have data to prove it), you are an experienced programmer that know how to handle memory and your code will be used in a controlled environment, then sure, go for it.

Title: Why not use unmanaged safe code in C#

Body:
There is an option in C# to execute code unchecked. It's generally not advised to do so, as managed code is much safer and it overcomes a lot of problems.

However I am wondering, if you're sure your code won't cause errors,
and you know how to handle memory then why (if you like fast code) follow the general advice?

I am wondering this since I wrote a program for a video camera, which required some extremely fast bitmap manipulation. I made some fast graphical algorithms myself, and they work excellent on the bitmaps using unmanaged code.

Now I wonder in general, if you're sure you don't have memory leaks, or risks of crashes, why not use unmanaged code more often?

PS my background: I kinda rolled into this programming world and I work alone (I do so for a few years) and so I hope this software design question isn't that strange. I don't really have other people out there like a teacher to ask such things.


问:
Strategy for avoiding duplicate object ids for data shared across devices using iCloud
I have a data intensive iOS app that is not using CoreData nor does it support iCloud synching (yet). All of my objects are created with unique keys. I use a simple long long initialized with the current time. Then as I need a new key I increment the value by 1. This has all worked well for a few years with the app running isolated on a single device.

Now I want to add support for automatic data sync across devices using iCloud. As my app is written, there is the possibility that two objects created on two different devices could end up with the same key. I need to avoid this possibility.

I'm looking for ideas for solving this issue. I have a few requirements that the solution must meet:

1) The key needs to remain a single integral data type. Converting all existing keys to a compound key or to a string or other type would affect the entire code base and likely result in more bugs than it's worth.

2) The solution can't depend on an Internet connection. A user must be able to run the app and add data even with no Internet connection. The data should still resolve properly later when the data syncs through iCloud once a connection is available. I'll accept one exception to this rule. If no other option is available, I may be open to requiring an Internet connection the first time the app's data is initialized.

One idea I have been toying around with in my head is logically splitting the integer key into two parts. The high 4 or 5 bits could be used as some sort of device id while the rest represents the actual key. The fuzzy part is figuring out how to come up with non-conflicting device ids that fit in a few bits. This should be viable since I don't need to deal will millions of devices. I just need to deal with the few devices that would be shared by a given iCloud account.

I'm open to suggestions. Thanks.

Update:

After giving this some more thought, I've decided to take the short term hit and do this the right way. Using a GUID is definitely the best long term option for this. Using this approach eliminates the need to do any of the various options to deal with handing out key ranges or translating keys once an Internet connection is made.

My original requirement prevented the GUID option because neither SQLite nor iOS support a simple, 128-bit integer type. Since I have a large existing code base that is written such that my keys are simple integer types, it will require a major refactoring of both the code and the database schema.

In the end, I've decided that the short term pain of doing this refactoring out weighs the long term issues of dealing with a klunky solution. Taking the hit now gives me a much simpler and less error prone solution that will last the long term.

答:
It really depends on how the keys are used, and the consequences of accidental duplicates.
Some obvious choices:

(1) the exact time (down to nanosecond if possible) is statistically certain to be unique among a few devices.  Just using a sufficiently precise time as the key is likely to have an overall reliability greater than a more complicated scheme.

(2) Make every key a per-device key, and assign a real unique key when the device synchs to the cloud.  Maintain a dictionary in the cloud.
(2a) generate temporary keys serially.  When you first synch, aquire a block of permanant keys and renumber.

(3) issue blocks of a billion of so keys to devices the the first time they attach, let the devices subissue keys as needed.


问:
TDD in JavaScript
I'm about to participate in a Coding Kata and I would like to do it in JavaScript.

What tools and libraries do I need for TDD in JavaScript?

答: I have had fantastic luck with Jasmine and Sinon JS frameworks. We use these tools now and even have them hooked into TFS to automate the test running when our server is being built. TFS kicks off Sinon and Jasmine. Take a look at them. Jasmine is more of a BDD framework and Sinon the unit testing. We also use QUnit on a couple projects.</p>

Title: TDD in JavaScript


答:
In a way, unmanaged code is a form of payment: you buy faster execution with the extra development effort. Indeed, the unmanaged code requires more time to develop, to debug, and to maintain. Getting it exactly right is a challenge for most participants. In a way, this is similar to programming in assembly: sure, you can squeeze more power out of your CPU if you write in assembly*, but you "spend" a lot more effort going that route.

Sometimes, the difference in development time is very significant - days instead of hours. However, the difference in execution speed is not nearly as dramatic. That is why the development of unmanaged code is reserved for situations similar to the one that you described in your post - localized, self-contained, implementations of resource-hungry algorithms, such as audio and video processing.

Essentially, the answer to your question is similar to the answer of why doesn't everyone drive Ferrari: it's a much better car, right? (Un)fortunately, not everyone can afford it.

* The advancements of the past few decades in the optimization technology in compilers have narrowed down this gap so much that it is no longer a sure bet, though.

Title: Why not use unmanaged safe code in C#


答: As Lars Viklund points out in his comment, you might look into UUIDs -- they're 128-bit numbers used for unique IDs and have good stats for uniqueness. If you can't find a function to generate one (though I'm sure Apple has one), Version 4 is pretty easy to implement.</p>

Title: Strategy for avoiding duplicate object ids for data shared across devices using iCloud

Body:
I have a data intensive iOS app that is not using CoreData nor does it support iCloud synching (yet). All of my objects are created with unique keys. I use a simple long long initialized with the current time. Then as I need a new key I increment the value by 1. This has all worked well for a few years with the app running isolated on a single device.

Now I want to add support for automatic data sync across devices using iCloud. As my app is written, there is the possibility that two objects created on two different devices could end up with the same key. I need to avoid this possibility.

I'm looking for ideas for solving this issue. I have a few requirements that the solution must meet:

1) The key needs to remain a single integral data type. Converting all existing keys to a compound key or to a string or other type would affect the entire code base and likely result in more bugs than it's worth.

2) The solution can't depend on an Internet connection. A user must be able to run the app and add data even with no Internet connection. The data should still resolve properly later when the data syncs through iCloud once a connection is available. I'll accept one exception to this rule. If no other option is available, I may be open to requiring an Internet connection the first time the app's data is initialized.

One idea I have been toying around with in my head is logically splitting the integer key into two parts. The high 4 or 5 bits could be used as some sort of device id while the rest represents the actual key. The fuzzy part is figuring out how to come up with non-conflicting device ids that fit in a few bits. This should be viable since I don't need to deal will millions of devices. I just need to deal with the few devices that would be shared by a given iCloud account.

I'm open to suggestions. Thanks.

Update:

After giving this some more thought, I've decided to take the short term hit and do this the right way. Using a GUID is definitely the best long term option for this. Using this approach eliminates the need to do any of the various options to deal with handing out key ranges or translating keys once an Internet connection is made.

My original requirement prevented the GUID option because neither SQLite nor iOS support a simple, 128-bit integer type. Since I have a large existing code base that is written such that my keys are simple integer types, it will require a major refactoring of both the code and the database schema.

In the end, I've decided that the short term pain of doing this refactoring out weighs the long term issues of dealing with a klunky solution. Taking the hit now gives me a much simpler and less error prone solution that will last the long term.


答:
I recently began playing around with Jasmine and Mocha. Although they're very easy to write (and to read too) they're a mess to work with. I also found Test'em scripts, which is a small Node.js application that automatically tests your Jasmine/Mocha scripts.

Both of them are great, and paired with Testem, they make Javascript/Coffeescript/ very, very easy. Also, if you want to get started quickly, check nettuts screencast (No links left, sorry!) on Testem/Jasmine/Mocha. That's what got me interested on all of them in the first place.

Title: TDD in JavaScript

Body:
I'm about to participate in a Coding Kata and I would like to do it in JavaScript.

What tools and libraries do I need for TDD in JavaScript?


答:
User experience.

This is the only value that matters to your customer.

Development Time is less important. I can write a fully featured command line application a lot faster than a GUI, but if Mrs. Jane can't figure out how to make it spit out reports she wants, it's useless.

Maintenance is less important. I can repair a a seesaw really quickly, but if it's in the middle of a forest, users can't find it.

Processing Time is less important. If I make a car that goes 0 to light speed in 60 seconds, users can't steer.

Aesthetics is less important. I can paint a Mona Lisa, but if she's hidden behind a wall no one gets to see her.

User Experience is the only value that matters. Making an application that does exactly what the user wants in the way the user expects is the ultimate achievement.

Title: What do you optimize for?


问:
Obtain reference to Parent object during instantiation
I have a situation where a custom class is a property of another class.

What I need to be able to do, if it is possible at all, is obtain a reverse to the "parent" class (ie the the class that holds the current class as a property).

For Instance:

```<code>Public Class Class1
  ...
  public readonly property Prop11 as Class2
  public property Prop12 as String
  ...
End Class

Public Class Class2
  ...
  private _par as Class1
  private _var21 as string
  ...
  Public Sub New(...)
    me._par = ????
    ...
  End Sub
  public readonly property Prop21 as string
    Get
      return me._par.Prop12 & me._var21
    End Get
  End Property
  ...
End Class
</code>```

Ultimately, I am trying to access other properties within Class1 from Class2 as they do have substance for information from within Class2.  There are several other classes within Class1 that provide descriptive information to other classes contained within it as properties but the information is not extensible to all of the classes through Inheritance, as Class1 is being used as a resource bin for the property classes and the application itself.

Diagram, lazy design ;):

```<code>Application <- Class1.Prop12
Application <- Class1.Prop11.Prop21
</code>```

Question:

Is it possible to get a recursion through this design setup?

答: The easiest way to do that is have Class1.Prop21 control the lifetime of Class2, this will allow it to assign the Parent relationship.

ContentLicense: CC BY-SA 4.0


答:
In short, nothing prevents you in doing all that work and managing bits and bolts of your program in C++ environment. As you are pretty sure that you can correctly manage all the memory hoops and leaks without garbage collector then you are welcome to do that in C++ :)

In contrary, C# has advantages providing safe/managed and strongly-typed development environment to run safely in .NET framework.

The possible back-draw of programming un-managed code is the longer development time, allocation of time for detailed testing. You will of course gain processing speed and more control over how your software is running.

Thus, the option to work with un-managed code in .NET Framework starting from 4.0 is an option for edge cases when you sure that it might bring you gains over not using it...

Title: Why not use unmanaged safe code in C#


答:
One idea I have been toying around with in my head is logically splitting the integer key into two parts. The high 4 or 5 bits could be used as some sort of device id while the rest represents the actual key. The fuzzy part is figuring out how to come up with non-conflicting device ids that fit in a few bits

IMO This is the best Option. (I like having the device ID tied to the data)

My second Option would be to have the server Issue a block of ID to the client on sync.
So when the client syncs to the Server the server tells the Client Id's 10000-20000 are yours. The next time the client syncs if there it has less then 5k Ids left, the server gives it and additional 5k id's.. If the client runs out of Ids it MUST sync.. (Its a good idea to not let the Client build up an infinite amount of data without syncing anyhow)


答:
I don't think the rest of the business is going to help because they have no sense of development life cycles, and requirements get changed all the time within a single sprint.

One thing that business generally listens to is anything that has an impact on the budget. If constantly changing requirements is being done frivolously, then you will want to create an argument with detailed examples to show how such change impacts team efficiency, creates overlapping work, and costs the company money.  If on the other hand, the changes are necessary and could result in a loss to the company if not done, then you may simply need to wear it, and find a way to deal with constantly changing requirements.

It's been my experience however, that when things are changing at such a high rate as you have suggested, it may be for the following reasons:

The concept is experimental, in which case you may wish to be spiking all of these changes rather than implementing them directly into production code.

The concept has not been thoroughly analysed, which suggests that the product hasn't really been thought through and the requirement is to code the product while it is being thought up.

Constant market and competitive pressures result in knee-jerk change

A poor relationship between project drivers, managers, and the implementation team, in terms of the ability for all of the stakeholders to communicate freely about the need for change.

Poor prioritization of tasks, and this can be a fault of both management and implementation staff.

Sometimes project owners don't really know how the product is supposed to work, because they have a basic concept in mind, however they feel they need to see how it works first before making up their minds. This can be because the problem domain isn't very well understood, or because they haven't really thought about how a business function will translate into a software-based solution. Prototyping can be beneficial in such cases. You can easily prototype GUIs with mock objects if the changes are cosmetic, or you can use unit tests as a means to test and tune changes that are algorithmic. The key though is to ensure that changes are applied as systematically as possible, in order to keep the process relatively lean and less costly.

We have suggested setting up processes to dodge those requirement changes and educate the business about development life cycles.

This is a good start and allows you a means to engage with management to try and effect positive outcomes in a measured and structured manner. Education is the most effective method for dealing with problems where developers and management are out of sync ideologically.  However, in order to get the greatest benefit, the education needs to be two-way, as does the communication.  You need to teach yourselves and management to communicate your needs, and to help each other to understand the motivations which drive those needs.  Saying that it's "too hard" or "a lot of work" or "a time waster" will only come across as complaining and being "lazy".  Your reasoning needs to be clear, and in a language that will show that you are working to achieve positive outcomes for the company and the product you are working on, and that your motives are with these best interests in mind. Likewise, you may need to learn to accept the reasons that the suits give you for why they feel the need to change things so rapidly. Perhaps between you you will be able to find a good workable middle ground when both sides are able to understand each other's point of view.

What if the business fails to get the idea? What would you do?

If you don't achieve the outcome you are hoping for, perhaps the timing isn't right.  Perhaps your arguments need to be made differently.  Perhaps you have it all wrong and need to learn more about what the other side is thinking. Ultimately if your particular approach fails, it's up to you to decide how important it is to you to have dealt with.  However, rather than concern yourself with what may or may not happen, think positively and simply decide what you can do about today. Tomorrow's problems aren't necessarily guaranteed and not worth the stress of worrying about until they actually occur.

One final point to consider.  Your CTO is possibly concerned about many of the same problems that you are.  Certainly having a decree to adopt TDD suggests to me that this may very well be the case given that TDD is highly effective in situations where the code is often subject to change. In a test-first scenario, tests don't become useless the next day because the provide you with a safety net to work within, allowing you to apply changes rapidly and confidently. However, you will still need to find a way to manage the expectations of the people requesting changes in order to help to manage change efficiently.

Title: Test driven vs Business requirements constant changing

Body:
One of the new requirement of our dev team set by the CTO/CIO is to become test driven development, however I don't think the rest of the business is going to help because they have no sense of development life cycles, and requirements get changed all the time within a single sprint. Which gets me frustrated about wasting time writing 10 test cases and will become useless tomorrow.

We have suggested setting up processes to dodge those requirement changes and educate the business about development life cycles. What if the business fails to get the idea? What would you do?


问:
How to add precedence to LALR parser like in YACC?
Please note, I am asking about writing LALR parser, not writing rules for LALR parser.

What I need is...

...to mimic YACC precedence definitions. I don't know how it is implemented, and below I describe what I've done and read so far.

For now I have basic LALR parser written. Next step -- adding precedence, so 2+3*4 could be parsed as 2+(3*4).

I've read about precedence parsers, however I don't see how to fit such model into LALR. I don't understand two points:

how to compute when insert parenthesis generator

how to compute how many parenthesis the generator should create

I insert generators when the symbols is taken from input and put at the stack, right? So let's say I have something like this (| denotes boundary between stack and input):

ID = 5 | + ..., at this point I add open, so it gives

ID = < 5 | + ..., then I read more input

ID = < 5 + | 5 ... and more

ID = < 5 + 5 | ; ... and more

ID = < 5 + 5 ; | ...

At this point I should have several reduce moves in normal LALR, but the open parenthesis does not match so I continue reading more input. Which does not make sense.

So this was when problem.

And about count, let's say I have such data < 2 + < 3 * 4 >. As human I can see that the last generator should create 2 parenthesis, but how to compute this? After all there could be two scenarios:

( 2 + ( 3 *4 )) -- parenthesis is used to show the outcome of generator

or (2 + (( 3 * 4 ) ^ 5) because there was more input

Please note that in both cases before 3 was open generator, and after 4 there was close generator. However in both cases, after reading 4 I have to reduce, so I have to know what generator "creates".

答:
Consider the following rules:

```<code>[1] E -> E + E
[2] E -> E * E
[3] E -> num
</code>```

Without precedence, it would produce a shift/reduce error when encountering the second operator. The table looks something like this:

```<code>    num     +       *       $       E
0   S2      ---     ---     ---     1
1   ---     S3      S4      Accept  ---
2   ---     R3      R3      R3      ---
3   S2      ---     ---     ---     5
4   S2      ---     ---     ---     6
5   ---     R1/S3   R1/S4   R1      ---
6   ---     R2/S3   R2/S4   R2      ---
</code>```

With precedence, you are saying which of "shift" and "reduce" you want in the case of conflicts.

If the first operator has a lower precedence, you shift.

If the first operator has a higher precedence, you reduce.

If the operators have equal precedences, and both are

left associative, you reduce.

right associative, you shift.

otherwise, you fail.

Cleaning up the errors in the table, you get something like this:

```<code>    num     +       *       $       E
0   S2      ---     ---     ---     1
1   ---     S3      S4      Accept  ---
2   ---     R3      R3      R3      ---
3   S2      ---     ---     ---     5
4   S2      ---     ---     ---     6
5   ---     R1      S4      R1      ---
6   ---     R2      R2      R2      ---
</code>```

Body:
Consider the following rules:

[1] E -> E + E
[2] E -> E * E
[3] E -> num

Without precedence, it would produce a shift/reduce error when encountering the second operator. The table looks something like this:

    num     +       *       $       E
0   S2      ---     ---     ---     1
1   ---     S3      S4      Accept  ---
2   ---     R3      R3      R3      ---
3   S2      ---     ---     ---     5
4   S2      ---     ---     ---     6
5   ---     R1/S3   R1/S4   R1      ---
6   ---     R2/S3   R2/S4   R2      ---

With precedence, you are saying which of "shift" and "reduce" you want in the case of conflicts.

If the first operator has a lower precedence, you shift.

If the first operator has a higher precedence, you reduce.

If the operators have equal precedences, and both are

left associative, you reduce.

right associative, you shift.

otherwise, you fail.

Cleaning up the errors in the table, you get something like this:

    num     +       *       $       E
0   S2      ---     ---     ---     1
1   ---     S3      S4      Accept  ---
2   ---     R3      R3      R3      ---
3   S2      ---     ---     ---     5
4   S2      ---     ---     ---     6
5   ---     R1      S4      R1      ---
6   ---     R2      R2      R2      ---


问:
What are some famous one-liner or two-liner programs and equations?
I'm experimenting with a new platform and I'm trying to write a program that deals with strings that are no longer than 60 characters and I'd like to populate the data store with some famous or well-known small chunks of code and equations, since programming and math goes along with the theme of my software. The code can be in any language and the equations from any discipline of mathematics, just so long as they're less than a total of 60 characters in length. I suspect people are gonna break out some brainfuck for this one.

For example,

```<code>#include<stdio.h>
int main(){printf ("Hi World\n");return 0;}
</code>```

60 characters exactly!

Thanks so much for your wisdom!

答:
When I first figured out the bash forkbomb, I thought it was really sweet.</p>

```<code>:(){ :|:& };:
</code>```

Body:
When I first figured out the bash forkbomb, I thought it was really sweet.

:(){ :|:& };:


问:
Render Ruby object to interactive html
I am developing a tool that discovers network services enabled on host and writes short summary on them like this:
```
init,1
└── login,1560 --
    └── bash,1629
        └── nc,12137 -lup 50505
{
    :net => [
        [0] "*:50505 IPv4 UDP "
    ],
    :fds => [
        [0] "/root (cwd)",
        [1] "/",
        [2] "/bin/nc.traditional",
        [3] "/xochikit/ld_poison.so (stat: No such file or directory)",
        [4] "/dev/tty2",
        [5] "*:50505"
    ]
}
```

It proved to be very nice formatted and useful for quick discovery thanks to colors provided by the awesome_print gem. However, its output is just a text. One issue is that if I want to share it, I lose colors. I'd also like to fold and unfold parts of objects, quickly jump to specific processes and what not? Adding comments, for example. Thus I want something web-based.

What is the best approach to implement features like these? I haven't worked with web interfaces before and I don't have much experience with Ruby.

Update:

Maybe I didn't write my willings clear enough.

I think I want something that behaves like Chromium's chrome://chrome/settings/ (or better, of course). Is there maybe an erb template or manual showing how to implement that? I thought this is a thing needed often enough.

答:
Try using a Rack middleware to pygmentize things: https://github.com/bry4n/rack-pygments

Edit per Walter's suggestions:

You've got serializable Ruby objects and it sounds like you want to render them to web pages.  I'd recommend starting with something like Sinatra for the web framework, Pygments for the code coloring/highlighting, and from there perhaps handroll a little jQuery plugin to make indented code blocks collapsible.

Notes: I recommend Pygments because I like it and because Github uses it.  The Rack middleware above is intended to allow you to automagically pygmentize code at the server level by adding a tag to the code block you'd like to see marked up.

Title: Render Ruby object to interactive html


答:
This depends pretty much on what contractual relationship you have with your employer...

Intellectual property

By default, many organisations are now more willing to open-source generic functions/classes to benefit the wider programming/coding community, but there are those that don't and can't from an intellectual property perspective - to commercially protect what they have.

If your code utilises any type of reference to your employers IP, or trade secrets then it's perhaps understandable that they may refuse.

Open source

Essentially and by default, you are entitled to release any piece of software you write in your own time and as long as it doesn't conflict with the terms of your employment contract - or - compete with what they do in any aspect.

The best advice I could give is to approach your employer and discuss the matter openly. This will provide you with:

The attitude of your employer towards open-source/community programming

Reflect/highlight their understanding of software and it's inherent/wider value

Your rights as to what they perceive you being able to do/not do

Any employer, who refuses to allow you to expand your thinking/learning and indeed contribute to the wider community (and solve bigger,wider problems) should tell you a lot about where you work. Companies often think more widely than they have prior about releasing code as it doesn't just benefit them - but it has to be in a form that doesn't threaten them in anything that they do.

My time/their time

As with other answers - you can't use your employers time to build your own software; either ethically or principally. Treat them separately unless your employer is willing to commit to releasing code.

In some cases, programmers fuse their own time and work time to create something great - which, every party benefits from and perhaps the ideal outcome to your question.


问:
Is it okay to define a [] method in ruby's NilClass?
Ruby by default does not include the method [] for NilClass

For example, to check if foo["bar"] exists when foo may be nil, I have to do:

```<code>foo = something_that_may_or_may_not_return_nil
if foo && foo["bar"]
  # do something with foo["bar"] here
end
</code>```

If I define this method:

```<code>class NilClass
  def [](arg)
    nil
  end
end
</code>```

Something like that would make this possible, even if foo is nil:

```<code>if foo["bar"]
  # do something with foo["bar"]
end
</code>```

Or even:

```<code>if foo["bar"]["baz"]
  # do something with foo["bar"]["baz"] here
end
</code>```

Question:
Is this a good idea or is there some reason ruby doesn't include this functionality by default?

EDIT July 2017: My core complaint was the unwieldy foo && foo["bar"] && foo ["bar"]["baz"] idiom required to access nested values when at any point the value may be nil. As of Ruby 2.3, Array#dig and Hash#dig exist, which addresses my concern. Now I can use the following idiom!

```<code>if foo && foo.dig("bar", "baz")
  # do something
end

# Note that errors will still occur if a value isn't what you expect. e.g.
foo = { "a" => { "b" => "c" } }
foo && foo.dig("a", "b", "c") # raises TypeError: String does not have #dig method
</code>```

答:
I'd recommend you use Hash#fetch to access hash entries when you're unsure they'll be present.  This way if the requested key is not found you'll get a KeyError which you can handle appropriately.  When you blindly access nonexistent keys you get subtly confusing errors that wind up with you trying to act on unexpected nils in odd places elsewhere in your code.

```<code>> { a: { b: 1 } }[:a][:z].to_s
=> ""
> { a: { b: 1 } }.fetch(:z).fetch(:b).to_s
KeyError: key not found: :z
</code>```

Aside: I developed my taste for Hash#fetch after watching Avdi Grimm's RubyTapas Episode #8.  I pay money for that and so far it's worth it.

Body:
I'd recommend you use Hash#fetch to access hash entries when you're unsure they'll be present.  This way if the requested key is not found you'll get a KeyError which you can handle appropriately.  When you blindly access nonexistent keys you get subtly confusing errors that wind up with you trying to act on unexpected nils in odd places elsewhere in your code.

> { a: { b: 1 } }[:a][:z].to_s
=> ""
> { a: { b: 1 } }.fetch(:z).fetch(:b).to_s
KeyError: key not found: :z

Aside: I developed my taste for Hash#fetch after watching Avdi Grimm's RubyTapas Episode #8.  I pay money for that and so far it's worth it.


问:
Generating Deep Arrays: Shallow to Deep, Deep to Shallow or Bad idea?
I'm working on an array structure that will be used as the data source for a report template in a web app.

The data comes from relatively complex SQL queries that return one or many rows as one dimensional associative arrays. In the case of many, they are turned into two dimensional indexed array.

The data is complex and in some cases there is a lot of it.  To save trips to the database (which are extremely expensive in this scenario) I'm attempting to get all of the basic arrays  (1 and 2 dimension raw database data) and put them, conditionally, into a single, five level deep array.  Organizing the data in PHP seems like a better idea than by using where statements in the SQL.

Array Structure

```<code>    Array of years(
            year => array of types(
                            types => array of information(
                                                total => value,
                                                table => array of data(
                                                                index => db array
                                                                    )
                                                        )
                                )
                )
</code>```

My first question is, is this a bad idea.  Are arrays like this appropriate for this situation?

If this would work, how should I go about populating it?  My initial thought was shallow to deep, but the more I work on this, the more I realize that it'd be very difficult to abstract out the conditionals that determine where each item goes in the array.  So it seems that starting from the most deeply nested data may be the approach I should take.

If this is array abuse, what alternatives exist?

Edit

I went ahead with this approach, learning and changing things as I went.  But I ended up with a similar end array.  What I learned in regards to the shallow to deep conundrum was this.

I went into the process thinking of the outer arrays as the largest of a set of cups, containing multitudes of smaller cups which in turn contained another multitude of smaller cup until the last set which in my mind was water (this being the indexed array of database values).  Arrays are not cups...

The idea fell apart when I started legitimately hand drawing out the array structures and found that the base of these arrays, the water filled tiny cups I had envisioned, represented a heck of a lot more data than those big cups.  This lead me to see these deeply nested arrays as towers, with the indexed data representing a base of sorts, tapering up to the tip, which was the containing array.

From there, I figured out that the best way for me to process the data was to gather the bottom data, plug it into it's next layer and then go up the tower plugging each layer into it's next layer.

I'm not sure if I'm right, but I do feel like I understand arrays more now than I did before.

And I'm definitely still not sure if this is the best solution.

答:
I'm not sure I understand the problem you're trying to solve.  Can you give us a sample SQL query?

Are you joining five different tables using 4+ relations in order to render a single query?  If so I'd recommend trying an ORM.  Any good MVC solution for your language (e.g. CodeIgniter) should have something for you.

Are you trying to load the full contents of five tables into memory (either at the PHP server or on the client) so that you can join them at will once the user selects something that describes the necessary join?  If so (and assuming there's not all that much data) then you  might want to try a Javascript-based frontend ORM, maybe using something as simple as Backbone.js.

I must admit that I'm not entirely certain either of the above suggestions is appropriate for your problem as described.  I'd love a bit more detail.


问:
Am I allowed to rename a package for a library under Apache V2?
I have developed a library at my former employer.
After my employment ended, I got to take the library with me.

Does the Apache v2 prohibit renaming packages as long as I keep the license header intact?

答:
You should be fine.

Here's a copy of the (Apache v2 license](http://www.apache.org/licenses/LICENSE-2.0.html)

And this is the relevant section:

```
2. Grant of Copyright License. Subject to the terms and conditions of this License, each
Contributor hereby grants to You a perpetual, worldwide, non-exclusive, no-charge,
royalty-free, irrevocable copyright license to reproduce, prepare Derivative Works of,
publicly display, publicly perform, sublicense, and distribute the Work and such Derivative
Works in Source or Object form.
```

So the Apache v2 license explicitly grants recipients of the license copyright to the work, including the ability to create and distribute derivative works.  It also grants the right to reproduce the work.

Renaming a package is closest to simply reproducing the work, so you should be fine.

If you wanted to go to an extreme, you could call renaming a package the creation of a derivative work.  Which you have also been granted license to do.

Keep the notices intact, as the license instructs in Section 4.

Body:
You should be fine.

Here's a copy of the (Apache v2 license](http://www.apache.org/licenses/LICENSE-2.0.html)

And this is the relevant section:

2. Grant of Copyright License. Subject to the terms and conditions of this License, each
Contributor hereby grants to You a perpetual, worldwide, non-exclusive, no-charge,
royalty-free, irrevocable copyright license to reproduce, prepare Derivative Works of,
publicly display, publicly perform, sublicense, and distribute the Work and such Derivative
Works in Source or Object form.

So the Apache v2 license explicitly grants recipients of the license copyright to the work, including the ability to create and distribute derivative works.  It also grants the right to reproduce the work.

Renaming a package is closest to simply reproducing the work, so you should be fine.

If you wanted to go to an extreme, you could call renaming a package the creation of a derivative work.  Which you have also been granted license to do.

Keep the notices intact, as the license instructs in Section 4.


问:
Is it appropriate to try to control the order of finalization?
I'm writing a class which is roughly analogous to a CancellationToken, except it has a third state for "never going to be cancelled". At the moment I'm trying to decide what to do if the 'source' of the token is garbage collected without ever being set.

It seems that, intuitively, the source should transition the associated token to the 'never cancelled' state when it is about to be collected. However, this could trigger callbacks who were only kept alive by their linkage from the token. That means what those callbacks reference might now in the process of finalization. Calling them would be bad.

In order to "fix" this, I wrote this class:

```<code>public sealed class GCRoot {
    private static readonly GCRoot MainRoot = new GCRoot();
    private GCRoot _next;
    private GCRoot _prev;
    private object _value;
    private GCRoot() {
        this._next = this._prev = this;
    }
    private GCRoot(GCRoot prev, object value) {
        this._value = value;
        this._prev = prev;
        this._next = prev._next;
        _prev._next = this;
        _next._prev = this;
    }
    public static GCRoot Root(object value) {
        return new GCRoot(MainRoot, value);
    }
    public void Unroot() {
        lock (MainRoot) {
            _next._prev = _prev;
            _prev._next = _next;
            this._next = this._prev = this;
        }
    }
}
</code>```

intending to use it like this:

```<code>Source() {
    ...
    _root = GCRoot.Root(callbacks);
}
void TransitionToNeverCancelled() {
    _root.Unlink();
    ...
}
~Source() {
    TransitionToNeverCancelled();
}
</code>```

but now I'm troubled. This seems to open the possibility for memory leaks, without actually fixing all cases of sources in limbo. Like, if a source is closed over in one of its own callbacks, then it is rooted by the callback root and so can never be collected.

Presumably I should just let my sources be collected without a peep. Or maybe not? Is it ever appropriate to try to control the order of finalization, or is it a giant warning sign?

答:
Is it appropriate to try to control the order of finalization?

No, it's not. That you're thinking about finalizers at all is a giant warning sign. If you need to dispose of unmanaged resources, use Dispose. If you want scoped release of some resource, reconsider; then use Dispose if you really benefit from it.

I also would be skeptical about some of your concerns regarding callbacks being in some finalizer state. If you can trigger them, the classes they call can't by definition be collected.


答:
It sounds like you are looking for a JavaScript boilerplate project. A boilerplate project gives you all the tools you need to be instantly productive. Since you are looking to use Test Driven Development (TDD) you'll need a unit testing framework included. Here are some recommendations (the ones I like towards the top):

Yeoman is a robust and opinionated set of tools, libraries, and a workflow that can help developers quickly build beautiful, compelling web apps.

Backbone Boilerplate - This is a great starting place if you want to build a single page app with Backbone.

Foundation 3 - The most advanced responsive front-end framework in the world.

Search google for "JavaScript boilerplate" to find your own perfect fit.

Title: TDD in JavaScript


问:
How to experience gradual improvement of knowledge while a newbie does .NET maintenance programming?
I started my career as a software developer about 6 months ago. This is my first job, and I am the only developer in this company. I gained .NET knowledge by self study and also by doing some university projects.  Our systems have old foundations based on an earlier version of .NET, and I'm starting to feel that I am not improving since I am a maintenance programmer here. Everything is old and my manager is not really taking any chances on gradually improving the software.

What is your opinion? What should I do? I am newbie and also work hard to find my way through. There is no other developer, not even a senior one to help me here.
I need your advice on my situation. And one last thing, can I get a new job with doing maintenance programming? I mean don't managers say that you do not have the experience of developing a new software from scratch? I feel redundant, what do I do?

答:
Well. Maintaining applications are a great way to learn. Having to work with a .NET 1.1 application would be terrible. But .NET 2.0 has most of the foundations that .NET developers use every day. Take this opportunity to learn .NET will before going on with things like LINQ, WCF etc. Learn from the mistakes that the previous developer made and how you solved them. If something looks wierd, study the code and come up with a better solution.

When you are fed up go looking for a new job.

As for your CV. Open source projects are great. Join one. It will also show that you can work on a remote team (better than solo coding but not as good as working in a real team). The most important thing with joining an open source project is that you show ambition and effort to learn and get better.


问:
How to avoid big and clumsy UITableViewController on iOS?
I have a problem when implementing the MVC-pattern on iOS. I have searched the Internet but seems not to find any nice solution to this problem.

Many UITableViewController implementations seems to be rather big. Most examples I have seen lets the UITableViewController implement <UITableViewDelegate> and <UITableViewDataSource>. These implementations are a big reason why UITableViewControlleris getting big. One solution would be to create separate classes that implements <UITableViewDelegate> and <UITableViewDataSource>. Of course these classes would have to have a reference to the UITableViewController. Are there any drawbacks using this solution? In general I think you should delegate the functionality to other "Helper" classes or similar, using the delegate pattern. Are there any well established ways of solving this problem?

I do not want the model to contain too much functionality, nor the view. I believe that the logic should really be in the controller class, since this is one of the cornerstones of the MVC-pattern. But the big question is:

How should you divide the controller of a MVC-implementation into smaller manageable pieces? (Applies to MVC in iOS in this case)

There might be a general pattern for solving this, although I am specifically looking for a solution for iOS. Please give an example of a good pattern for solving this issue. Please provide an argument why your solution is awesome.

答:
I avoid using UITableViewController, as it puts lots of responsibilities into a single object. Therefore I separate the UIViewController subclass from the data source and delegate. The view controller's responsibility is to prepare the table view, create a data source with data, and hook those things together. Changing the way the tableview is represented can be done without changing the view controller, and indeed the same view controller can be used for multiple data sources that all follow this pattern. Similarly, changing the app workflow means changes to the view controller without worrying about what happens to the table.

I've tried separating the UITableViewDataSource and UITableViewDelegate protocols into different objects, but that usually ends up being a false split as almost every method on the delegate needs to dig into the datasource (e.g. on selection, the delegate needs to know what object is represented by the selected row). So I end up with a single object that's both the datasource and delegate. This object always provides a method -(id)tableView: (UITableView *)tableView representedObjectAtIndexPath: (NSIndexPath *)indexPath which both the data source and delegate aspects need to know what they're working on.

That's my "level 0" separation of concerns. Level 1 gets engaged if I have to represent objects of different kinds in the same table view. As an example, imagine that you had to write the Contacts app—for a single contact, you might have rows representing phone numbers, other rows representing addresses, others representing email addresses, and so on. I want to avoid this approach:

```<code>- (UITableViewCell *)tableView: (UITableView *)tableView cellForRowAtIndexPath: (NSIndexPath *)indexPath {
  id object = [self tableView: tableView representedObjectAtIndexPath: indexPath];
  if ([object isKindOfClass: [PhoneNumber class]]) {
    //configure phone number cell
  }
  else if …
}
</code>```

Two solutions have presented themselves so far. One is to dynamically construct a selector:

```<code>- (UITableViewCell *)tableView: (UITableView *)tableView cellForRowAtIndexPath: (NSIndexPath *)indexPath {
  id object = [self tableView: tableView representedObjectAtIndexPath: indexPath];
  NSString *cellSelectorName = [NSString stringWithFormat: @"tableView:cellFor%@AtIndexPath:", [object class]];
  SEL cellSelector = NSSelectorFromString(cellSelectorName);
  return [self performSelector: cellSelector withObject: tableView withObject: object];
}

- (UITableViewCell *)tableView: (UITableView *)tableView cellForPhoneNumberAtIndexPath: (NSIndexPath *)indexPath {
  // configure phone number cell
}
</code>```

In this approach, you don't need to edit the epic if() tree to support a new type - just add the method that supports the new class. This is a great approach if this table view is the only one that needs to represent these objects, or needs to present them in a special way. If the same objects will be represented in different tables with different data sources, this approach breaks down as the cell creation methods need sharing across the data sources—you could define a common superclass that provides these methods, or you could do this:

```<code>@interface PhoneNumber (TableViewRepresentation)

- (UITableViewCell *)tableView: (UITableView *)tableView representationAsCellForRowAtIndexPath: (NSIndexPath *)indexPath;

@end

@interface Address (TableViewRepresentation)

//more of the same…

@end
</code>```

Then in your data source class:

```<code>- (UITableViewCell *)tableView: (UITableView *)tableView cellForRowAtIndexPath: (NSIndexPath *)indexPath {
  id object = [self tableView: tableView representedObjectAtIndexPath: indexPath];
  return [object tableView: tableView representationAsCellForRowAtIndexPath: indexPath];
}
</code>```

This means that any data source that needs to display phone numbers, addresses etc. can just ask whatever object is represented for a table view cell. The data source itself no longer needs to know anything about the object being displayed.

"But wait," I hear a hypothetical interlocutor interject, "doesn't that break MVC? Aren't you putting view details into a model class?"

No, it doesn't break MVC. You can think of the categories in this case as being an implementation of Decorator; so PhoneNumber is a model class but PhoneNumber(TableViewRepresentation) is a view category. The data source (a controller object) mediates between the model and the view, so the MVC architecture still holds.

You can see this use of categories as decoration in Apple's frameworks, too. NSAttributedString is a model class, holding some text and attributes. AppKit provides NSAttributedString(AppKitAdditions) and UIKit provides NSAttributedString(NSStringDrawing), decorator categories that add drawing behaviour to these model classes.

Body:
I avoid using UITableViewController, as it puts lots of responsibilities into a single object. Therefore I separate the UIViewController subclass from the data source and delegate. The view controller's responsibility is to prepare the table view, create a data source with data, and hook those things together. Changing the way the tableview is represented can be done without changing the view controller, and indeed the same view controller can be used for multiple data sources that all follow this pattern. Similarly, changing the app workflow means changes to the view controller without worrying about what happens to the table.

I've tried separating the UITableViewDataSource and UITableViewDelegate protocols into different objects, but that usually ends up being a false split as almost every method on the delegate needs to dig into the datasource (e.g. on selection, the delegate needs to know what object is represented by the selected row). So I end up with a single object that's both the datasource and delegate. This object always provides a method -(id)tableView: (UITableView *)tableView representedObjectAtIndexPath: (NSIndexPath *)indexPath which both the data source and delegate aspects need to know what they're working on.

That's my "level 0" separation of concerns. Level 1 gets engaged if I have to represent objects of different kinds in the same table view. As an example, imagine that you had to write the Contacts app—for a single contact, you might have rows representing phone numbers, other rows representing addresses, others representing email addresses, and so on. I want to avoid this approach:

- (UITableViewCell *)tableView: (UITableView *)tableView cellForRowAtIndexPath: (NSIndexPath *)indexPath {
  id object = [self tableView: tableView representedObjectAtIndexPath: indexPath];
  if ([object isKindOfClass: [PhoneNumber class]]) {
    //configure phone number cell
  }
  else if …
}

Two solutions have presented themselves so far. One is to dynamically construct a selector:

- (UITableViewCell *)tableView: (UITableView *)tableView cellForRowAtIndexPath: (NSIndexPath *)indexPath {
  id object = [self tableView: tableView representedObjectAtIndexPath: indexPath];
  NSString *cellSelectorName = [NSString stringWithFormat: @"tableView:cellFor%@AtIndexPath:", [object class]];
  SEL cellSelector = NSSelectorFromString(cellSelectorName);
  return [self performSelector: cellSelector withObject: tableView withObject: object];
}

- (UITableViewCell *)tableView: (UITableView *)tableView cellForPhoneNumberAtIndexPath: (NSIndexPath *)indexPath {
  // configure phone number cell
}

In this approach, you don't need to edit the epic if() tree to support a new type - just add the method that supports the new class. This is a great approach if this table view is the only one that needs to represent these objects, or needs to present them in a special way. If the same objects will be represented in different tables with different data sources, this approach breaks down as the cell creation methods need sharing across the data sources—you could define a common superclass that provides these methods, or you could do this:

@interface PhoneNumber (TableViewRepresentation)

- (UITableViewCell *)tableView: (UITableView *)tableView representationAsCellForRowAtIndexPath: (NSIndexPath *)indexPath;

@end

@interface Address (TableViewRepresentation)

//more of the same…

@end

Then in your data source class:

- (UITableViewCell *)tableView: (UITableView *)tableView cellForRowAtIndexPath: (NSIndexPath *)indexPath {
  id object = [self tableView: tableView representedObjectAtIndexPath: indexPath];
  return [object tableView: tableView representationAsCellForRowAtIndexPath: indexPath];
}

This means that any data source that needs to display phone numbers, addresses etc. can just ask whatever object is represented for a table view cell. The data source itself no longer needs to know anything about the object being displayed.

"But wait," I hear a hypothetical interlocutor interject, "doesn't that break MVC? Aren't you putting view details into a model class?"

No, it doesn't break MVC. You can think of the categories in this case as being an implementation of Decorator; so PhoneNumber is a model class but PhoneNumber(TableViewRepresentation) is a view category. The data source (a controller object) mediates between the model and the view, so the MVC architecture still holds.

You can see this use of categories as decoration in Apple's frameworks, too. NSAttributedString is a model class, holding some text and attributes. AppKit provides NSAttributedString(AppKitAdditions) and UIKit provides NSAttributedString(NSStringDrawing), decorator categories that add drawing behaviour to these model classes.


问:
for vs. foreach vs. LINQ
When I write code in Visual Studio, ReSharper (God bless it!) often suggests me to change my old-school for loop in the more compact foreach form.

And often, when I accept this change, ReSharper goes a step forward, and suggests me to change it again, in a shiny LINQ form.

So, I wonder: are there some real advantages, in these improvements? In pretty simple code execution, I cannot see any speed boost (obviously), but I can see the code becoming less and less readable... So I wonder: is it worth it?

答:
but I can see the code becoming less and less readable

Readability is in the eye of the beholder. Some people might say

```<code>var common = list1.Intersect(list2);
</code>```

is perfectly readable; others might say that this is opaque, and would prefer

```<code>List<int> common = new List<int>();
for(int i1 = 0; i1 < list1.Count; i1++)
{
    for(int i2 = 0; i2 < list2.Count; i2++)
    {
        if (list1[i1] == list2[i2])
        {
            common.Add(i1);
            break;
        }
    }
}
</code>```

as making it clearer what's being done. We can't tell you what you find more readable. But you might be able to detect some of my own bias in the example I have constructed here...

Title: for vs. foreach vs. LINQ

Body:
but I can see the code becoming less and less readable

Readability is in the eye of the beholder. Some people might say

var common = list1.Intersect(list2);

is perfectly readable; others might say that this is opaque, and would prefer

List<int> common = new List<int>();
for(int i1 = 0; i1 < list1.Count; i1++)
{
    for(int i2 = 0; i2 < list2.Count; i2++)
    {
        if (list1[i1] == list2[i2])
        {
            common.Add(i1);
            break;
        }
    }
}

as making it clearer what's being done. We can't tell you what you find more readable. But you might be able to detect some of my own bias in the example I have constructed here...


问:
What are your thoughts on Periods/Full Stops in code comments?
I saw this asked in the SO Tavern, so I'm posting the question here. I thought it an interesting question. (Of course it doesn't belong on SO, but I think it's OK here.)

Do you add periods (or, as the OP wrote, "full stops") in your code comments?

To keep it relevant, why?

答: If you write comments one would hope they are written in English. That being case case, one should punctuate properly. Doing otherwise would be lazy.</p>