答:
According to the God Object wikipedia entry, "A god object is the object-oriented analogue of failing to use subroutines in procedural programming languages, or of using far too many global variables to store state information."  In other words, it's a tightly coupled mess that's been wrapped in an object.

According to you, the hardware class is "is a very thin container for components".  I don't believe there's any way for a very thin container to be a tightly coupled mess, unless it were tightly coupled to the components it contains.  You describe the components as "composed at runtime based on what capabilities/configuration are available", which implies that there are multiple possible components that could fit in a slot in the container, so your container must be decoupled from its components.

So, unless I've misunderstood your description, your hardware class is not a God Object.  It might be very large at runtime, but I can't see how being large at runtime could be a problem, as long as both the individual pieces and the ways of putting them together are not tightly coupled messes.

Title: If an entity is composed, is it still a god object?

Body:
I am working on a system to configure hardware. Unfortunately, there is tons of variety in the hardware, which means there's a wide variety of capabilities and configurations depending on what specific hardware the software connects to.

To deal with this, we're using a Component Based Entity design where the "hardware" class itself is a very thin container for components that are composed at runtime based on what capabilities/configuration are available. This works great, and the design itself has worked well elsewhere (particularly in games).

The problem is that all this software does is configure the hardware. As such, almost all of the code is a component of the hardware instance. While the consumer only ever works against the strongly typed interfaces for the components, it could be argued that the class that represents an instance of the hardware is a God Object.

If you want to do anything to/with the hardware, you query an interface and work with it.

So, even if the components of an object are modular and decoupled well, is their container a God Object and the downsides associated with the anti-pattern?


问:
How you return to a code when you don't remember what you were doing?
Well, I have some problems with procrastination and whatnot, but those get infinitely worse, when I cannot remember what I should be doing.

I mean, I know my project, I wrote 100% of the code so far, and I knew more or less what I was doing, but I don't remember exactly what, I don't remember what file I was editing and why.

How I get back on track? (because right now my technique of opening the source code and staring at it is not working)

答:
Well, besides whatever disease interupted you, it sounds like you have basically two problems.

```<code>1. A lack of version control and bug tracking.  Get one of the many free
   VCS/bug trackers/project managment.  TFS from Microsoft, git and Jira or
   or even FogBugz from Fog Creek.  There's a bunch out there, pick one or
   just try a bunch.
2. Having lost track of what you were doing, you're now in something like
   analysis paralysis -- and the solution is the same.  Do something.  It
   doesn't matter what you were working on, it will come back to you if it's
   important, and you can work on something else important until then.
</code>```

This is where the project managment tool of your choice can shine -- you have bugs that need to be fixed and features to add.  You can prioritize them and record which one you are currently working on.  Start doing that.  Good chance that while you are entering all of your known bugs and desired features, that you will recall what you were doing.

ContentLicense: CC BY-SA 3.0

Body:
Well, besides whatever disease interupted you, it sounds like you have basically two problems.

1. A lack of version control and bug tracking.  Get one of the many free
   VCS/bug trackers/project managment.  TFS from Microsoft, git and Jira or
   or even FogBugz from Fog Creek.  There's a bunch out there, pick one or
   just try a bunch.
2. Having lost track of what you were doing, you're now in something like
   analysis paralysis -- and the solution is the same.  Do something.  It
   doesn't matter what you were working on, it will come back to you if it's
   important, and you can work on something else important until then.

This is where the project managment tool of your choice can shine -- you have bugs that need to be fixed and features to add.  You can prioritize them and record which one you are currently working on.  Start doing that.  Good chance that while you are entering all of your known bugs and desired features, that you will recall what you were doing.


问:
What is the best way to handle dynamic content?
So we run a site where there are elements of the interface that could potentially be changed at any moment in the backend. Specifically we run a web service where certain functions are loaded dynamically. However, there are times where we remove certian functions and we want the experience to be as seamless for the user as possible. Now we've considered a few methods of solving this

Ping the server every few seconds. If the functions are outdated/no longer available refresh the users page. While this would work the best, I feel like having that much IO can't be too good

When the user clicks a function, if it's outdated/no longer available, alert them in the response and refresh the page. This would also work fairly well.

I guess I'm more wondering how web apps like Google Docs work where you have content that has to be synced up across multiple users and that isn't more than a few seconds outdated

Sorry if this isn't the best place to ask this. I figured this was more of a site architecture question and that this might be the place to ask it over SO.

答:
I generally dislike the notion of making things disappear suddenly. Makes me paranoid.
So I would stick to the second option.

However, if you still want it to be somewhat like the first one, you should do pushing instead of polling. Check out this page.


答: All I do is I keep a notebook/TODO file, and before I go on a long (>hour) break, I write down what remains to be done. My mind then extrapolates what I was doing before. I always do this, and it never disappoints.</p>

Title: How you return to a code when you don't remember what you were doing?

Body:
Well, I have some problems with procrastination and whatnot, but those get infinitely worse, when I cannot remember what I should be doing.

I mean, I know my project, I wrote 100% of the code so far, and I knew more or less what I was doing, but I don't remember exactly what, I don't remember what file I was editing and why.

How I get back on track? (because right now my technique of opening the source code and staring at it is not working)


问:
what is the task of a coach in acm programming contests?
In the university that I am working they have decided to participate in the ACM regionals for the first time, they would like to appoint me like a coach. I have never been into that situation before and have not found so much information about it, so what is the real work of a coach in those contests?

Sometimes I have found experienced programmers like coaches, but others are just people with no so good programming skills; so what is all about?

答:
At my alma mater we distinguished between organisers and coaches for the ACM contests. Organisers could easily be non-programmers and were responsible for communication with ACM /on-site organizers, team registration, travel bookings, etc.

Our coach(es), however, were usually recruited from past team members who were no longer eligible to compete themselves. They had a) strong algorithmic skills and b) experience with the contest minutiae. Their responsibilities included the following:

Organize a learning regimen for newcomers: We competed with multiple teams at the regional, and hence, our university focused on getting fresh blood in. Downside of that was that first year students have next to no idea about the required algorithms. So the coach prepared them with learning material, sample contest questions, etc. in a manner that quickly brought them up to speed on all basic algorithms.

Organize a work-out regimen for the participating teams: The participating teams were constantly practicing. It was the task of the coach to schedule the practice sessions, in particular with regard to various online contests. While it is possible to practice based on old ACM contests, one should also practice the real deal, i.e. against real opponents with a limited time setting and as a team.

Recap of practice sessions: The coach typically monitored the practice sessions (usually keeping himself busy by teaching newcomers as mentioned above, whilst the real teams were left to participate in their training contest on their own). During the practice, however, the coach monitored the team's performance and gave a recap in the end (or on the next day). For newer teams, the recap may involve algorithmic issues (f.ex. bad implementations, wrong algorithm choices, etc.). For technically more experienced teams, coaches usually had little to add in that respect, but instead added value based on their contest experience. They gave tips on how to deal with the team's overall performance (who solves which problems and when, whose turn is it at the computer, how to deal with debugging, etc etc).

Basically, our coach was accompanying newcomers into the world of algorithms, then showing them how a real contest is run, supported them in gaining more experience, and finally helped them form a real team that was able to compete at a high-level (most years we won the regional contest and often had 3 of our teams in the top 10).

That being said, contest rules have changed all the time and maybe there's now something like an on-site coach during regional. In that case, note that the above considers a coach as being located at your university and there was no need for a coach to be present during the regionals (sometimes they came along, sometimes they didn't).


答:
First, learn the lesson.

From now on, write code easy to understand:

Document it. Tools like Doxygen are very helpful. Actually, Doxygen is helpful even with undocumented code with its capability to draw call tree, caller tree and dependency tree.

Don't try to look smart when you write code. Don't use advanced features just to show that you know about them.

Remember that documentation and simple code are read not only by other maintainers but mainly by your future self.


问:
Is it okay to just add a page or two PHP page to add some functionality to a Drupal site?
I'm not familiar with Drupal, really.  I can dig around the admin interface and navigate the directories and find the files that I need to just fine as well.

What I'm really not familiar with is adding modules or extending modules.  The site currently takes an order and sets up recurring payments through Ubercart and uses Authorize.net as a gateway.  Right now, when a payment fails, a single e-mail gets sent out to the admin.  We'd like to extend it to send an e-mail to the user and let them change their payment information through another page on the site.

Authorize has a service called Silent Post URL that basically just posts a carbon copy in XML to whatever URL you give it.  We'd like to accept that XML, deserialize it, parse the data, send a notice to the user and give them the page for updating their information.

So, I guess it'll be two PHP pages.  One for the XML API call from Authorize.net, and then one for the page for the users' to update their payment information.

Could I just create two simple pages each handling their own tasks, or should I check out properly extending a module?  If it's appropriate for me to write up the pages and not have to hook them into the module, what would be the best way to handle setting up what needs to get done?

(The most experience I've had with extending a PHP site has been hacking away at someone else' poorly constructed, custom framework, so if anyone has any good resources perhaps on PHP best practices that they could share through a PM or a comment, I'd appreciate It)

(Also, I'm still getting the hang of Stack Exchange, so if this isn't appropriate please let me know.  I'll delete it.)

答:
I am not too familiar with drupal either but from my experience so far many modules are built with flexibility in mind. I don't know how your site is setup but my approach would be to research and setup a test implementing a automated emailing system that links up to the admin's payment warning.There should be a module for each step.

Not sure if clear:-> I would try and fit in modules that have been shown to work before you modify or make your own. Many modules can work together (think Legos). I don't want to link to specific modules with a simple plan as I am not confident in my knowlege.

Vague Plan: use (module) Parsing API + (module) Email API + (module) Payment API though you should have it reroute to your current payment system.

So Three modules with some customization and you could have a decent solution without code.

Hope that isn't to convoluted.


答: What has been already suggested is probably useful but in general I would use a separate issue tracking or task management system (such as Jira) for planning and managing your work. There are also additional tools (such as Mylyn for Eclipse) that integrate your IDE to the task management system.</p>


问:
Is there a representation for mixins or traits on UML?
Is there a representation for modern programming constructs that are becoming common in modern OOP/hybrid languages like mixins/traits/categories/partial classes ?</p>

答:
Yes and no. Generally, UML allows the usage of multiple inheritance, which allows you to model something like traits. In a sense, traits in Scala are a way to allow multiple inheritance, whilst trying to reduce its negative effect (namely, the diamond inheritance problem).

As for the Yes part of the answer: you can show traits/mixins as normal classes in UML, or even add a corresponding stereotype to them (either make them abstract, or if you want to be more precise define your own profile with a proper trait-stereotype). A class that mixes multiple traits is then visualized as a class that inherits from these traits (via generalization associations).

However, the UML has no proper semantic concept of this inheritance. Other than a vague description that the generalization means that the subclass gets the features from its superclasses, you will not get a clean semantics. In particular, language-specific semantics like Scala's trait linearization are not directly supported in UML.

If you want to make a very precise model of your Scala traits/classes, you would need to define a custom UML profile and assign stereotypes to your generalizations to document their linearization order. However, that's limited as well, because the order may be different for different classes that share some of their traits.

So it depends on what you want to use UML for. If you want to use it as documentation, you may well be able to live with these shortcomings. If you want to use UML models as a base for code generation or some such, then newer language features spell trouble. While the UML offers semantic variation points it is as a whole based on the traditional OO languages and falls short as soon, as you leave these standard feature sets. While traits/mixins still relate closely to classes/objects, and hence, can be visualized with some trade-offs, you'll be even more at a loss, when you try to use UML for non-OO language aspects (think, functional or logic programming).


问:
How long should I wait to autosave user input?
I have a table where a User can edit data by simply choose a field, then edit its value. I want to fire an update function to automatically save the data to a MySQL database.

However, I think that it would be inefficient to fire that function on literally every change, e.g every single keypress.

How long should I wait to save my input?

答:
I would monitor the type frequencies of users while using your program.
You can analyze that and than determine which time interval of nothing done indicates that an input was finished and saving would be appropriate.</p>


答:
If the data or change of the information is nondestructive then I would first check and see how much of an impact each update has. If it's not much then just make it update/change gracefully.

If not then my first guess without knowing the kind of data table you have is to them about twice the length of time they had to type their current valid value then after the update make sure to clearly prompt the update so they can fix a typo.

Title: How long should I wait to autosave user input?

Body:
I have a table where a User can edit data by simply choose a field, then edit its value. I want to fire an update function to automatically save the data to a MySQL database.

However, I think that it would be inefficient to fire that function on literally every change, e.g every single keypress.

How long should I wait to save my input?


问:
How to handle fine grained field-based ACL permissions in a RESTful service?
I've been trying to design a RESTful API and have had most of my questions answered, but there is one aspect of permissions that I'm struggling with.

Different roles may have different permissions and different representations of a resource. For example, an Admin or the user himself may see more fields in his own User representation vs another less-privileged user. This is achieved simply by changing the representation on the backend, ie: deciding whether or not to include those fields.

Additionally, some actions may be taken on a resource by some users and not by others. This is achieved by deciding whether or not to include those action items as links, eg: edit and delete links. A user who does not have edit permissions will not have an edit link.

That covers nearly all of my permission use cases, but there is one that I've not quite figured out. There are some scenarios whereby for a given representation of an object, all fields are visible for two or more roles, but only a subset of those roles my edit certain fields.

An example:

```<code>{
    "person": {
        "id": 1,
        "name": "Bob",
        "age": 25,
        "occupation": "software developer",
        "phone": "555-555-5555",
        "description": "Could use some sunlight.."
    }
}
</code>```

Given 3 users: an Admin, a regular User, and Bob himself (also a regular User), I need to be able to convey to the front end that:

Admins may edit all fields, Bob himself may edit all fields, but a regular User, while they can view all fields, can only edit the description field. I certainly don't want the client to have to make the determination (or even, for that matter, to have any notion of the roles involved) but I do need a way for the backend to convey to the client which fields are editable.

I can't simply use a combination of representation (the fields returned for viewing) and links (whether or not an edit link is availble) in this scenario since it's more finely grained.

Has anyone solved this elegantly without adding the logic directly to the client?

答:
How about adding specific permissions as 'links' in your resource representation. Basically, letting the client know what attributes are available to the updated (by regular users). Both Admin and Self are non-regular users which are allowed to edit everything. Based on your example that regular users can edit only the 'description' field, here are my thoughts:</p>

```<code>{
    "person": {
        "id": 1,
        "name": "Bob",
        "age": 25,
        "occupation": "software developer",
        "phone": "555-555-5555",
        "description": "Could use some sunlight.."
        "_links": {
           "href": "/person/1",
           "method": "PUT",
           "attributes": ["description"]
        }
    }
}
</code>```

Body:
How about adding specific permissions as 'links' in your resource representation. Basically, letting the client know what attributes are available to the updated (by regular users). Both Admin and Self are non-regular users which are allowed to edit everything. Based on your example that regular users can edit only the 'description' field, here are my thoughts:

{
    "person": {
        "id": 1,
        "name": "Bob",
        "age": 25,
        "occupation": "software developer",
        "phone": "555-555-5555",
        "description": "Could use some sunlight.."
        "_links": {
           "href": "/person/1",
           "method": "PUT",
           "attributes": ["description"]
        }
    }
}


问:
Display large amount of data to client through pagination
I have a web application in which i need to show a big number of data or records for clients. Now i 'll use pagination but i was wondering should I:

Load all the data once then pagination, sorting and sarching 'll be easy..But it 'll takes big time(using local DB it takes up to 9 sec.)

Or each time i show new page(from the pagination) i make a new request to server and then new request to DB to get the next records..But then what if the client click on Prev button, i 'll make a new request to get data that I had previously..Should i cach data that are loaded before and how if that's good technique?

So load all data once or make a new request every time i need data that maybe have been loaded before.

I'm using ASP.NET MVC SPA with durandaljs and knockoutjs

答:
You can use caching pagination, i.e. generate the first few pages, and as the user scrolls through the pages, load more pages in the background.

This should give you a good trade-off between initial respond speed and lag between pages.


问:
What are some interesting but not too difficult projects for a beginner kernel hacker?
Having taken a course in Operating Systems I'm interested in expanding my knowledge of the Linux kernel and practice working with a big system. What are some interesting but not overly difficult projects I can try my hand at?

EDIT: a bit of background on what I did do with the kernel.

Implemented a new scheduling policy

Implemented User Threads and a corresponding mutex library (not really kernel hacking but contained kernel related theory)

答: It depends on your existing background. If you are an embedded developer, you can write or improve some device driver. There aren't many other task to do in the kernel, unless you want to write a new process scheduler of course. I would suggest instead to study the existing source, it is a boring task but for a beginner it is almost the only thing to do.</p>

ContentLicense: CC BY-SA 2.5


问:
"Bad apple" algorithm, or process crashes shared sandbox
I'm looking for an algorithm to handle the following problem, which I'm (for now) calling the "bad apple" algorithm.

The problem

I've got N processes running in M sandboxes, where N >> M.

It's impractical to give each process its own sandbox.

At least one of those processes is badly-behaved, and is bringing down the entire sandbox, thus killing all of the other processes in the same sandbox.

If it was a single badly-behaved process, then I could use a simple bisection to put half of the processes in one sandbox, and half in another sandbox, until I found the miscreant.

The question

If more than one process is badly-behaved -- including the possibility that they're all badly-behaved -- does this naive algorithm "work"? Is it guaranteed to work within some sensible bounds?

Simplifications

For the sake of argument, let's assume that a bad process brings down its sandbox instantaneously, and a good process never does.

答:
If you were finding one bad apple, then you could apply the algorithm:

Divide N into M groups

Perform the test on each group.

If group size greater than 1, return to step 1, replacing N with number of items in bad group.

Likewise, if you were finding the one "good" apple, then the same algorithm applies, but rather finding the good group.

This algorithm has a O(log_M (N)) performance rate but it depends on the fact that there is only one bad apple.

If you don't know how many good/bad apples there are, then you could use the following algorithm:

```<code>For each M processes in N
  Test M processes
</code>```

This is the worst case scenario, but it runs in O(N/M) time (or O(N) depending on if you consider a single pass as a single test or as a collection of tests performed in parallel).  All things considered, this is not a bad approach by any means.

There may be algorithms which perform better than this, but it requires that you know how many bad apples/good apples there are in the batch.  Not knowing this factor, while I can't prove it, I'd be willing to bet that you cannot do better than the latter algorithm listed above.

Hope that helps!

Edit:  From a practical perspective, I understand that some of these operations are not easily performed.  That's true, however, the unfortunate reality is that you cannot determine the bad apple strictly from which processes were running on the sandbox that was running at that moment without being to at least activate or disactivate processes.  If the question pertains to the algorithm, I think I have answered that.  If the question pertains to how to deal with a situation like this, then perhaps the question would be better suited for superuser SE.

Body:
If you were finding one bad apple, then you could apply the algorithm:

Divide N into M groups

Perform the test on each group.

If group size greater than 1, return to step 1, replacing N with number of items in bad group.

Likewise, if you were finding the one "good" apple, then the same algorithm applies, but rather finding the good group.

This algorithm has a O(log_M (N)) performance rate but it depends on the fact that there is only one bad apple.

If you don't know how many good/bad apples there are, then you could use the following algorithm:

For each M processes in N
  Test M processes

This is the worst case scenario, but it runs in O(N/M) time (or O(N) depending on if you consider a single pass as a single test or as a collection of tests performed in parallel).  All things considered, this is not a bad approach by any means.

There may be algorithms which perform better than this, but it requires that you know how many bad apples/good apples there are in the batch.  Not knowing this factor, while I can't prove it, I'd be willing to bet that you cannot do better than the latter algorithm listed above.

Hope that helps!

Edit:  From a practical perspective, I understand that some of these operations are not easily performed.  That's true, however, the unfortunate reality is that you cannot determine the bad apple strictly from which processes were running on the sandbox that was running at that moment without being to at least activate or disactivate processes.  If the question pertains to the algorithm, I think I have answered that.  If the question pertains to how to deal with a situation like this, then perhaps the question would be better suited for superuser SE.


问:
When should method overloads be refactored?
When should code that looks like:

```<code>DoThing(string foo, string bar);

DoThing(string foo, string bar, int baz, bool qux);

...

DoThing(string foo, string bar, int baz, bool qux, string more, string andMore);
</code>```

Be refactored into something that can be called like so:

```<code>var doThing = new DoThing(foo, bar);

doThing.more = value;
doThing.andMore = otherValue;

doThing.Go();
</code>```

Or should it be refactored into something else entirely?

In the particular case that inspired this question, it's a public interface for an XSLT templating DLL where we've had to add various flags (of various types) that can't be embedded into the string XML input.

答:
What you are facing here is the telescoping constructor anti-pattern.

IMHO you should refactor to public members only if it's a simple class used to store data. Otherwise, your class looks like a good candidate for the Builder pattern. You can use it to:

encapsulate default member-values logic - set those values from inside the builder instead of setting them for each object you construct using it's members public access

gain the ability to respond to inappropriate initialization - when the object is constructed from the builder you determine inside the builder what to do when not all required values were set


问:
"Do it right, against customer's wishes" - how is it called?
We know the optimal situation of negotiating corrections of specifications with the customer, getting the specs to do what the client wanted, not what they said or thought they wanted. That's negotiating, explaining.

Sometimes, we're unable to convince the client. We're forced to produce broken as designed. This, called "demonology" by merit of mages summoning demons and demons fulfilling their wishes very literally, causing the mage's demise as result, is another approach that will leave the customer very dissatisfied once they realize their error, and of course try to pin the blame on the developer.

Now I just faced a very different approach: the customer created simple specs that fail to account for some critical caveat, and is completely unwilling to fix them, admit the obvious errors and accept suggested corrections. The product made to these specs will be critically broken, and possibly might cost human lives. Still, it's too late to drop the contract entirely. The contract has punitive clauses for that, ones we can't really accept.

The boss' decision? We do the work right and lie to the customer that we did it according to the specs. The algorithms in question are hidden deep enough under the surface, the product will do the work just fine, won't fail in the caveat situation, and unless someone digs too deep, they will never discover we didn't break it as requested.

Is there some common name for this tactics of execution of specs?

答:
I am not a lawyer.  You should neither act nor refrain from acting on any opinions I provide.

Releasing a product that could put lives at risk due to a design flaw (rather than as a necessary part of its operation) that you are aware of is likely to put you the wrong side of health and safety legislation as well as expose your organisation to legal claims and costs.  In most territories and situations the law of the land overrules any contract you may have so that should be your priority.

In other words:  Clarify your specific legal position before continuing.


答:
It's a tradeoff between speed, memory requirements in the cache, and programming required to keep the cache fresh. A lot depends on your use cases. For example

If, like Google search results, most users only ever read page 1, just a few carrying on down to page 2 and beyond, then cacheing may not even be necessary.

If users tend to repeatedly sort, search etc. then you can't cache individual pages because the number of combinations will overwhelm your storage. But if you have huge datasets, cacheing whole resultsets will do the same.

If the data in the background is liable to change a lot even during reading one page, and that is critical to the business, then the risk of displaying stale data may turn you against cacheing.

Personally, it might be a better investment of time to look at refactoring your db to squeeze more life out of it. If your queries are taking 9s it may be because the data model is too complex, you are missing important indexes, or you're keeping hold of old data in your main tables that should be archived away instead.

Title: Display large amount of data to client through pagination

Body:
I have a web application in which i need to show a big number of data or records for clients. Now i 'll use pagination but i was wondering should I:

Load all the data once then pagination, sorting and sarching 'll be easy..But it 'll takes big time(using local DB it takes up to 9 sec.)

Or each time i show new page(from the pagination) i make a new request to server and then new request to DB to get the next records..But then what if the client click on Prev button, i 'll make a new request to get data that I had previously..Should i cach data that are loaded before and how if that's good technique?

So load all data once or make a new request every time i need data that maybe have been loaded before.

I'm using ASP.NET MVC SPA with durandaljs and knockoutjs


问:
Explanation of the definition of interface inheritance as described in GoF book
I am reading the first chapter of the Gof book. Section 1.6 discusses about class vs interface inheritance:

Class versus Interface Inheritance

It's important to understand the difference between an object's class
  and its type. An object's class defines how the object is
  implemented.The class defines the object's internal state and the
  implementation of its operations.In contrast,an object's type only
  refers to its interface--the set of requests on which it can respond. An
  object can have many types, and objects of different classes can have
  the same type.

Of course, there's a close relationship between class and type. Because
  a class defines the operations an object can perform, it also defines
  the object's type . When we say that an object is an instance of a
  class, we imply that the object supports the interface defined by the
  class.

Languages like c++ and Eiffel use classes to specify both an object's
  type and its implementation. Smalltalk programs do not declare the
  types of variables; consequently,the compiler does not check that the
  types of objects assigned to a variable are subtypes of the variable's
  type. Sending a message requires checking that the class of the
  receiver implements the message, but it doesn't require checking that
  the receiver is an instance of a particular class.

It's also important to understand the difference between class
  inheritance and interface inheritance (or subtyping). Class inheritance
  defines an object's implementation in terms of another object's
  implementation. In short, it's a mechanism for code and representation
  sharing. In contrast,interface inheritance(or subtyping) describes when
  an object can be used in place of another.

I am familiar with the Java and JavaScript programming language and not really familiar with either C++ or Smalltalk or Eiffel as mentioned here. So I am trying to map the concepts discussed here to Java's way of doing  classes, inheritance and interfaces.

This is how I think of of these concepts in Java:

In Java a class is always a blueprint for the objects it produces and what interface(as in "set of all possible requests that the object can respond to") an object of that class possess is defined during compilation stage only because the class of the object would have implemented those interfaces. The requests that an object of that class can respond to is the set of all the methods that are in the class(including those implemented for the interfaces that this class implements).

My specific questions are:

Am I right in saying that Java's way  is more similar to C++ as described in the third paragraph.

I do not understand what is meant by interface inheritance in the last paragraph. In Java interface inheritance is one interface extending from another interface. But I think the word interface has some other overloaded meaning here. Can some one provide an example in Java of what is meant by interface inheritance here so that I understand it better?

答:
@Euphoric has already answered both of your questions. I just wanted to extend his explanation with some further clarification.

It is possible to perform "Class inheritance" without interface being inherited completely. It has been more than 5 years that I have touched Java, but, if I remember correctly, "protected" methods becomes "private" for a class when inherited outside the package. Now, in Java "protected" member will be part of interface of an object but "private" member isn't (anything which you can access using an instance of class is part of it's interface, which in the case of Java is "public" and "protected", I believe). In this scenario the method is inherited (that is -- can be used within subclass as it's own) but you cannot call the method on instance of a subclass. Thus, you get class inheritance without interface being inherited.


答:
Loading all the data at once is not necessarily all-bad in the sense that it has a lot of performance advantages.  However, I would only use this method if:

I was 100% certain that this list would not grow to large amounts

I would store data not currently shown in javascript objects (in other words, don't put the burden on the browser other than the actual memory required to hold it).

Most often than not, I can't guarantee that the list would not grow, so I usually have to stick with the second solution you mentioned.  Load by page on demand.  This also means you cannot search using the items you have available unless searching for items on the current page only is acceptable.  Searching must perform its own query on the database separate from the cache you have.

I would not bother to cache pages you've already loaded, since how often do you return to previous pages after you've seen them?  It is not worth the loss of memory in my humble opinion.  Rather, I would advise you to load several pages at once rather than just one at a time.  When the user clicks next and nothing is loaded, you fetch the next 4 pages.  This way, nothing must be fetched for the following 3.  This is already a solution that would meet most of your requirements and still be 4 times as efficient than fetching one page at a time.

If you want to get even more sophisticated, you would use AJAX to load the next page once the user has loaded the current page.  You only have to perform a check that the next page has already been loaded before showing the next page, which hopefully enough time will elapse that it will have already been loaded.  And in the case in which it has not yet been loaded, you can show some sort of load animation to provide feedback to the user that you're currently working on it.  This has the best performance of all solutions, however it is also the most difficult to implement.

Hope that helps!


答:
Generally I prefer the number 2 solution, with regards of mixed approach

Paged queries:

Using a paged query when showing a list of data to end user is the normal way.

Following the approach of creating paged queries with the template query bellow:

```<code>SELECT TOP pageSize columns
  FROM Table
  WHERE IDColumn NOT IN ( SELECT TOP pageSize*(pageNumber-1) IDColumn
  FROM Table
  ORDER BY uniqueOrPrimaryKey)
  ORDER BY uniqueOrPrimaryKey;
</code>```

The key points will be:

Designing efficient Data Transfer-er Objects.

Choosing effective page size, based on entity
size, bandwidth limitation, none functional testing ...

About cashing:

Using cashing strategy depends on the specification and business logic of you application.

Some data can be cashed and cashing some data will case inconsistency.

Think about an Internet-Banking software, where the user will see his accounts listed data, It will be a good approach to cash the accounts data when the user is logging in (as account creating is not normally done from internet-bank application).

Now the user can do some debit and credit actions and the balance of his accounts will be modified, we need to update the balance field and update the cash.

In any case using cashed data will confront you with application design questions like
when to clear or update cashed data, using client side or server side cashing, data security on client side cashing, etc.

Conclusion

I will use paging when ever possible, that will optimize the performance.

Will use cashing on static data that are less update-able.

Will not use cashing on concurrent data and scenario.

Caveat-> Will not try to alter stateless nature of HTTP protocol by cashing.

Body:
Generally I prefer the number 2 solution, with regards of mixed approach

Paged queries:

Using a paged query when showing a list of data to end user is the normal way.

Following the approach of creating paged queries with the template query bellow:

SELECT TOP pageSize columns
  FROM Table
  WHERE IDColumn NOT IN ( SELECT TOP pageSize*(pageNumber-1) IDColumn
  FROM Table
  ORDER BY uniqueOrPrimaryKey)
  ORDER BY uniqueOrPrimaryKey;

The key points will be:

Designing efficient Data Transfer-er Objects.

Choosing effective page size, based on entity
size, bandwidth limitation, none functional testing ...

About cashing:

Using cashing strategy depends on the specification and business logic of you application.

Some data can be cashed and cashing some data will case inconsistency.

Think about an Internet-Banking software, where the user will see his accounts listed data, It will be a good approach to cash the accounts data when the user is logging in (as account creating is not normally done from internet-bank application).

Now the user can do some debit and credit actions and the balance of his accounts will be modified, we need to update the balance field and update the cash.

In any case using cashed data will confront you with application design questions like
when to clear or update cashed data, using client side or server side cashing, data security on client side cashing, etc.

Conclusion

I will use paging when ever possible, that will optimize the performance.

Will use cashing on static data that are less update-able.

Will not use cashing on concurrent data and scenario.

Caveat-> Will not try to alter stateless nature of HTTP protocol by cashing.


问:
Where should the database and mail parameters be stored in a Symfony2 app?
In the default folder structure for a Symfony2 project the database and mail server credentials are stored in parameters.yml file inside ProjectRoot/app/config/parameters.yml with these default values:

```<code>parameters:
    database_driver: pdo_mysql
    database_host: 127.0.0.1
    database_port: null
    database_name: symfony
    database_user: root
    database_password: null
    mailer_transport: smtp
    mailer_host: 127.0.0.1
    mailer_user: null
    mailer_password: null
    locale: en
    secret: ThisTokenIsNotSoSecretChangeIt
</code>```

During development we change these parameters to the development database and mail servers. This file is checked into the source code repository.

The problem is when we want to deploy to the production server. We are thinking about automating the deployment process by checking out the project from git and deploy it to the production server.

The thing is that our project manager has to manually update these parameters after each update. The production database and mail servers parameters are confidential and only our project manager knows them.

I need a way to automate this step and suggestion on where to store the production parameters until they are applied?

答:
Rename parameters.yml to parameters.yml.sample, and ignore parameters.yml in your version control.

For each installation of the app, copy .sample back to the proper location and edit the details as needed.

That way you have a sample file that says what kind of details (mailer, DB, API keys, etc.) each installation needs, and the secrets are never in version control.


问:
Restful WebAPI VS Regular Controllers
I'm doing some R&D on what seems like a very confusing topic, I've also read quite a few of the other SO questions, but I feel my question might be unique enough to warrant me asking. We've never developed an app using pure WebAPI.

We're trying to write a SPA style app, where the back end is fully decoupled from the front end code

Assuming our service does not know anything about who is accessing/consuming it:

WebAPI seems like the logical route to serve data, as opposed to using the standard MVC controllers, and serving our data via an action result and converting it to JSON. This to me at least seems like an MC design... which seems odd, and not what MVC was meant for.
(look mom... no view)

What would be considered normal convention in terms of performing action(y) calls?

My sense is that my understanding of WebAPI is incorrect.

The way I perceive WebAPI, is that its meant to be used in a CRUD sense, but what if I want to do something like: "InitialiseMonthEndPayment".... Would I need to create a WebAPI controller, called InitialiseMonthEndPaymentController, and then perform a POST... Seems a bit weird, as opposed to a MVC controller where i can just add a new action on the MonthEnd controller called InitialisePayment.

Or does this require a mindset shift in terms of design?

Any further links on this topic will be really useful, as my fear is we implement something that might be weird an could turn into a coding/maintenance concern later on?

答:
The way I perceive WebAPI, is that its meant to be used in a CRUD
  sense

wrong.

I don't know about that "WebAPI" style, but any web service is way more than CRUD.

Most of the 'classic' services (SOAP, XMLRPC, etc) are an implementation of the RPC (remote procedure call) style, in effect, you make function calls from the client to a server.  What each call does is up to you, but it's better if you make sure that each call leaves the system in a complete, consistent state.  It's better to include more data in a single call and not to require two calls to make what is conceptually a single operation.

A different proposal is REST style, which puts emphasis in the things that are handled and not on the procedures.  That's why so many simplistic libraries just make a remote-accessible CRUD and call it a day.

But a real RESTfull API is not CRUD, because a "resource" is not a database record.  Resources are the conceptual entities of your system, the "representations" (typically JSON data) embody the state of those entities.  The PUT, POST and DELETE verbs modify that state, maybe via some sub-resources.  (adding a comment to a forum thread, deleting a user from the list of who can access something, etc).  The HATEOAS principle lets you 'browse' the state of the system, and the relationships and lists give you more URL endpoints to handle all that.

In your example, adding an 'month end payment' to a list of payments (or maybe the list of payments of a specific payee?) is simply a POST with the payment data to the URL that represents the payment 'container'.  The server should do all the needed creation, initialization and relationships to make sure that in the end the system is in a new complete state, no 'in betweens'.

Title: Restful WebAPI VS Regular Controllers


答:
Is the requirement(s) in question a flawed, missing or derived requirement? It matters. If the requirement is missing or can be derived from another requirement then it is a simple matter to say it is a derived requirement and you are meeting the terms of the contract. And there is no reason to hide it.

If the requirement contradicts a requirement then how are you going to validate the system without a change in requirements? The most likely reason for the government to not want to change requirements is "you will charge them more". If you are already going to implement with no extra cost then there is little reason for them to object.

Finally, because this is a government job, there will be a paper trail for all these types of decisions, if you want one. If those government employees responsible for your project won't agree verbally to the requirements change then you can formally file a requirements variance. I'm sure any variance request using terms such as "endangering life" will have ZERO possibility of being rejected. In any event, there is no reason to "hide" that you aren't meeting requirements as that could actually result in punitive damages to your company, even though you are trying to do the right thing. In this case, the right thing is to formally escalate the issue and make sure your company is protected. It is not to hide what your are doing from the customer because that is also wrong, although not as wrong as delivering a known safety hazard.

Title: "Do it right, against customer's wishes" - how is it called?

Body:
We know the optimal situation of negotiating corrections of specifications with the customer, getting the specs to do what the client wanted, not what they said or thought they wanted. That's negotiating, explaining.

Sometimes, we're unable to convince the client. We're forced to produce broken as designed. This, called "demonology" by merit of mages summoning demons and demons fulfilling their wishes very literally, causing the mage's demise as result, is another approach that will leave the customer very dissatisfied once they realize their error, and of course try to pin the blame on the developer.

Now I just faced a very different approach: the customer created simple specs that fail to account for some critical caveat, and is completely unwilling to fix them, admit the obvious errors and accept suggested corrections. The product made to these specs will be critically broken, and possibly might cost human lives. Still, it's too late to drop the contract entirely. The contract has punitive clauses for that, ones we can't really accept.

The boss' decision? We do the work right and lie to the customer that we did it according to the specs. The algorithms in question are hidden deep enough under the surface, the product will do the work just fine, won't fail in the caveat situation, and unless someone digs too deep, they will never discover we didn't break it as requested.

Is there some common name for this tactics of execution of specs?


问:
How should I start with Lisp?
I've been programming for years now, working my way through various iterations of Blub (BASIC, Assembler, C, C++, Visual Basic, Java, Ruby in no particular order of "Blub-ness") and I'd like to learn Lisp. However, I have a lot of intertia what with limited time (family, full time job etc) and a comfortable happiness with my current Blub (Java).

So my question is this, given that I'm someone who would really like to learn Lisp, what would be the initial steps to get a good result that demonstrates the superiority of Lisp in web development? Maybe I'm missing the point, but that's how I would initially see the application of my Lisp knowledge.

I'm thinking "use dialect A, use IDE B, follow instructions on page C, question your sanity after monads using counsellor D". I'd just like to know what people here consider to be an optimal set of values for A, B, C and perhaps D. Also some discussion on the relative merit of learning such a powerful language as opposed to, say, becoming a Rails expert.

Just to add some more detail, I'll be developing on MacOS (or a Linux VM) - no Windows based approaches will be necessary, thanks.

Notes for those just browsing by

I'm going to keep this question open for a while so that I can offer feedback on the suggestions after I've been able to explore them. If you happen to be browsing by and feel you have something to add, please do. I would really welcome your feedback.

Interesting links

Assuming you're coming at Lisp from a Java background, this set of links will get you started quickly.

Using Intellij's La Clojure plugin to integrate Lisp (videocast)

Lisp for the Web

Online version of Practical Common Lisp (c/o Frank Shearar)

Land of Lisp a (+ (+ very quirky) game based) way in but makes it all so straightforward

Install Clojure and Sublime 2 on MacOS an excellent getting started guide

Look at the Clojure in Action book. Worked for me.

答:
This is probably counter to most peoples' recommendations, but steer clear of Emacs to start with, unless you already know it. Especially if you're used to modern IDEs/editors.

I'm speaking from experience; I tried to start with Emacs, but having to learn the language AND the editor at the same time really frustrated me (especially since Emacs is so different from other tools). I ended up chucking it, getting started with PLT Scheme (now Racket) which comes with a comparatively simple cross-platform IDE, a centralized package repository and fabulous docs (including an intermediate tutorial specifically aimed at web development). After I got a clean grip on Lisp, I ended up going back to Emacs, picking up EL/CL by way of Practical Common Lisp and Xah's Elisp Guide. Basically, as I see it, you need to know a Lisp before you can use Emacs effectively, and you need to know Emacs in order to be very effective with CL/Elisp. This means that you can either pick up Scheme, or learn Common Lisp through some other editor first (LispWorks personal, probably).

If you already know Emacs, then yeah Elisp is the natural step (though how you would enjoy Emacs use without knowing Elisp first is beyond me).

YMMV of course, this is just what I found helped.

Since your current blub is Java, you could probably get a lot of mileage out of Clojure, Armed Bear or Kawa. I haven't tried any of them myself, not being a Java guy, but Clojure specifically comes highly recommended from other Lispers I know. It seems like the ability to keep your current VM and IDE might help with the learning process.

Title: How should I start with Lisp?

ContentLicense: CC BY-SA 4.0


问:
Why is Internet Explorer the only browser to be referred to by version when talking about compatibility?
Whenever I read something or hear someone talking about HTML5, CSS and JavaScript support, they always refer to Internet Explorer with the version number such as Internet Explorer 6, and Internet Explorer 9. But they only refer to Google Chrome, Firefox, Safari and others without version numbers.

Shouldn't they also specify the version number in which certain web technologies are incompatible for other browsers instead of just Internet Explorer?

答:
The Internet Explorer is not made available on all Windows platforms. For example, the latest Internet Explorer version cannot be used on Windows XP. Therefore there is a user base (Windows XP users) who cannot update to the most recent Internet Explorer version, which means that Web developers will get reports from these people about incompatibilities.

In contrast, other browsers like Firefox are compiled for all major platforms with the most recent release. With auto updating, most users are quite up to date with the browser version which reduces the need to separate between different browser versions, most of the time people talk about the "current" release.


问:
How to charge in agile iterative approach?
I have a doubt about budgeting when working with agile iterative approach. If I understood well, in agile at the end of each iteration we have usable product, so we have some of the requirements met and then some part of the software will be already working.

How do we charge for our work in this methodology? Do we charge per iteration, i.e. charge per major requirements being met, or just charge the customer when the software is indeed finished and then receive for everything at once?

答:
Dr. Jeff Sutherland (original signatory of the Agile Manifesto and co-creator of Scrum) proposed a contract format for Agile based projects that he calls “Money for Nothing, and Your Change for Free”.

The fundamental approach, is that the parties agree that they are working together, and building trust in each other’s expertise.

To do this, the contract requires active customer participation, including:

Prioritizing features according to business value

Mutually agreed estimates for all work

Active participation in each Sprint Planning

Active participation in writing the acceptance criteria for each
feature (for a shared definition of done)

Active participation in each Sprint Review, and providing timely
feedback for work (both completed and in-progress)

The value of the contract is agreed on, along with time & materials, and the scope. These are based off of the mutually agreed estimates for the work (usually produced using relative estimation by the team and the team’s historical velocity).

With this contract comes a couple of additional clauses:

Change for free -  If the customer actively participates with the team as above during the process, the customer can change the scope without any additional cost, as long as the total scope is not changed (e.g. they could pull out a 13 point story further ahead in the backlog that is no longer needed, and replace it with other stories so long as they total to 13 or less points).

Guarantee of Work -  If the customer actively participates with the team as above during the process, the customer can terminate the contract at any point at which they feel the implementation of the next feature costs more than the business value of the next feature, for 20% of the remaining contract value.

Further Reading:

Blog posts:
http://scrum.jeffsutherland.com/2008/10/agile-contracts-money-for-nothing-and.html

PDF of slide deck:
http://jeffsutherland.com/Agile2008MoneyforNothing.pdf

(I would include more links - but my reputation will not allow more than two - however if you search for "Money for nothing and you change for free" you should find further reading)


问:
Is COM truly dead?
I have previously worked on COM, however I have observed for quite sometime that hardly any company asks for COM exp.

Is COM dead or reports of its demise are highly exaggerated?

答:
To quote Don Box:

Is COM dead? It's not dead - it's
  done.

Because you can add a "COM Reference" to a lot of the Windows goodies that are presented as COM rather than flat APIs, a lot of managed code devs can ignore it. There are still scenarios where more detailed knowledge (controlling lifetimes or marshalling, implementing specific COM interfaces in managed code for the OS to call, etc) is needed, but they aren't day-to-day.

Title: Is COM truly dead?


问:
Why can't Java/C# implement RAII?
Question:
Why can't Java/C# implement RAII?

Clarification:
I am aware the garbage collector is not deterministic. So with the current language features it is not possible for an object's Dispose() method to be called automatically on scope exit. But could such a deterministic feature be added?

My understanding:

I feel an implementation of RAII must satisfy two requirements:

1. The lifetime of a resource must be bound to a scope.

2. Implicit. The freeing of the resource must happen without an explicit statement by the programmer. Analogous to a garbage collector freeing memory without an explicit statement. The "implicitness" only needs to occur at point of use of the class. The class library creator must of course explicitly implement a destructor or Dispose() method.

Java/C# satisfy point 1. In C# a resource implementing IDisposable can be bound to a "using" scope:

```<code>void test()
{
    using(Resource r = new Resource())
    {
        r.foo();
    }//resource released on scope exit
}
</code>```

This does not satisfy point 2. The programmer must explicitly tie the object to a special "using" scope. Programmers can (and do) forget to explicitly tie the resource to a scope, creating a leak.

In fact the "using" blocks are converted to try-finally-dispose() code by the compiler. It has the same explicit nature of the try-finally-dispose() pattern. Without an implicit release, the hook to a scope is syntactic sugar.

```<code>void test()
{
    //Programmer forgot (or was not aware of the need) to explicitly
    //bind Resource to a scope.
    Resource r = new Resource();
    r.foo();
}//resource leaked!!!
</code>```

I think it is worth creating a language feature in Java/C# allowing special objects that are hooked to the stack via a smart-pointer. The feature would allow you to flag a class as scope-bound, so that it always is created with a hook to the stack. There could be options for different types of smart pointers.

```<code>class Resource - ScopeBound
{
    /* class details */

    void Dispose()
    {
        //free resource
    }
}

void test()
{
    //class Resource was flagged as ScopeBound so the tie to the stack is implicit.
    Resource r = new Resource(); //r is a smart-pointer
    r.foo();
}//resource released on scope exit.
</code>```

I think implicitness is "worth it". Just as the implicitness of garbage collection is "worth it". Explicit using blocks are refreshing on the eyes, but offer no semantic advantage over try-finally-dispose().

Is it impractical to implement such a feature into the Java/C# languages? Could it be introduced without breaking old code?

答:
The biggest difficulty in implementing something like this for Java or C# would be defining how resource transfer works. You would need some way to extend the life of the resource beyond the scope. Consider:

```<code>class IWrapAResource
{
    private readonly Resource resource;
    public IWrapAResource()
    {
        // Where Resource is scope bound
        Resource builder = new Resource(args, args, args);

        this.resource = builder;
    } // Uh oh, resource is destroyed
} // Crap, there's no scope for IWrapAResource we can bind to!
</code>```

What's worse is that this may not be obvious to the implementer of IWrapAResource:

```<code>class IWrapSomething<T>
{
    private readonly T resource; // What happens if T is Resource?
    public IWrapSomething(T input)
    {
        this.resource = input;
    }
}
</code>```

Something like C#'s using statement is probably as close as you're going to come to having RAII semantics without resorting to reference counting resources or forcing value semantics everywhere like C or C++. Because Java and C# have implicit sharing of resources managed by a garbage collector, the minimum a programmer would need to be able to do is choose the scope to which a resource is bound, which is exactly what using already does.

Title: Why can't Java/C# implement RAII?

Body:
The biggest difficulty in implementing something like this for Java or C# would be defining how resource transfer works. You would need some way to extend the life of the resource beyond the scope. Consider:

class IWrapAResource
{
    private readonly Resource resource;
    public IWrapAResource()
    {
        // Where Resource is scope bound
        Resource builder = new Resource(args, args, args);

        this.resource = builder;
    } // Uh oh, resource is destroyed
} // Crap, there's no scope for IWrapAResource we can bind to!

What's worse is that this may not be obvious to the implementer of IWrapAResource:

class IWrapSomething<T>
{
    private readonly T resource; // What happens if T is Resource?
    public IWrapSomething(T input)
    {
        this.resource = input;
    }
}

Something like C#'s using statement is probably as close as you're going to come to having RAII semantics without resorting to reference counting resources or forcing value semantics everywhere like C or C++. Because Java and C# have implicit sharing of resources managed by a garbage collector, the minimum a programmer would need to be able to do is choose the scope to which a resource is bound, which is exactly what using already does.


答:
The reason why RAII can't work in a language like C#, but it works in C++, is because in C++ you can decide whether an object is truly temporary (by allocating it on the stack) or whether it is long-lived (by allocating it on the heap using new and using pointers).

So, in C++, you can do something like this:

```<code>void f()
{
    Foo f1;
    Foo* f2 = new Foo();
    Foo::someStaticField = f2;

    // f1 is destroyed here, the object pointed to by f2 isn't
}
</code>```

In C#, you can't differentiate between the two cases, so the compiler would have no idea whether to finalize the object or not.

What you could do is to introduce some kind of special local variable kind, that you can't put into fields etc.* and that would be automatically disposed when it goes out of scope. Which is exactly what C++/CLI does. In C++/CLI, you write code like this:

```<code>void f()
{
    Foo f1;
    Foo^ f2 = gcnew Foo();
    Foo::someStaticField = f2;

    // f1 is disposed here, the object pointed to by f2 isn't
}
</code>```

This compiles to basically the same IL as the following C#:

```<code>void f()
{
    using (Foo f1 = new Foo())
    {
        Foo f2 = new Foo();
        Foo.someStaticField = f2;
    }
    // f1 is disposed here, the object pointed to by f2 isn't
}
</code>```

To conclude, if I were to guess why the designers of C# didn't add RAII, it's because they thought that having two different types of local variables is not worth it, mostly because in a language with GC, deterministic finalization is not useful that often.

* Not without the equivalent of the & operator, which in C++/CLI is %. Though doing so is “unsafe” in the sense that after the method ends, the field will reference a disposed object.

Title: Why can't Java/C# implement RAII?

Body:
Question:
Why can't Java/C# implement RAII?

Clarification:
I am aware the garbage collector is not deterministic. So with the current language features it is not possible for an object's Dispose() method to be called automatically on scope exit. But could such a deterministic feature be added?

My understanding:

I feel an implementation of RAII must satisfy two requirements:

1. The lifetime of a resource must be bound to a scope.

2. Implicit. The freeing of the resource must happen without an explicit statement by the programmer. Analogous to a garbage collector freeing memory without an explicit statement. The "implicitness" only needs to occur at point of use of the class. The class library creator must of course explicitly implement a destructor or Dispose() method.

Java/C# satisfy point 1. In C# a resource implementing IDisposable can be bound to a "using" scope:

```<code>void test()
{
    using(Resource r = new Resource())
    {
        r.foo();
    }//resource released on scope exit
}
</code>```

This does not satisfy point 2. The programmer must explicitly tie the object to a special "using" scope. Programmers can (and do) forget to explicitly tie the resource to a scope, creating a leak.

In fact the "using" blocks are converted to try-finally-dispose() code by the compiler. It has the same explicit nature of the try-finally-dispose() pattern. Without an implicit release, the hook to a scope is syntactic sugar.

```<code>void test()
{
    //Programmer forgot (or was not aware of the need) to explicitly
    //bind Resource to a scope.
    Resource r = new Resource();
    r.foo();
}//resource leaked!!!
</code>```

I think it is worth creating a language feature in Java/C# allowing special objects that are hooked to the stack via a smart-pointer. The feature would allow you to flag a class as scope-bound, so that it always is created with a hook to the stack. There could be options for different types of smart pointers.

```<code>class Resource - ScopeBound
{
    /* class details */

    void Dispose()
    {
        //free resource
    }
}

void test()
{
    //class Resource was flagged as ScopeBound so the tie to the stack is implicit.
    Resource r = new Resource(); //r is a smart-pointer
    r.foo();
}//resource released on scope exit.
</code>```

I think implicitness is "worth it". Just as the implicitness of garbage collection is "worth it". Explicit using blocks are refreshing on the eyes, but offer no semantic advantage over try-finally-dispose().

Is it impractical to implement such a feature into the Java/C# languages? Could it be introduced without breaking old code?

Body:
The reason why RAII can't work in a language like C#, but it works in C++, is because in C++ you can decide whether an object is truly temporary (by allocating it on the stack) or whether it is long-lived (by allocating it on the heap using new and using pointers).

So, in C++, you can do something like this:

void f()
{
    Foo f1;
    Foo* f2 = new Foo();
    Foo::someStaticField = f2;

    // f1 is destroyed here, the object pointed to by f2 isn't
}

In C#, you can't differentiate between the two cases, so the compiler would have no idea whether to finalize the object or not.

What you could do is to introduce some kind of special local variable kind, that you can't put into fields etc.* and that would be automatically disposed when it goes out of scope. Which is exactly what C++/CLI does. In C++/CLI, you write code like this:

void f()
{
    Foo f1;
    Foo^ f2 = gcnew Foo();
    Foo::someStaticField = f2;

    // f1 is disposed here, the object pointed to by f2 isn't
}

This compiles to basically the same IL as the following C#:

void f()
{
    using (Foo f1 = new Foo())
    {
        Foo f2 = new Foo();
        Foo.someStaticField = f2;
    }
    // f1 is disposed here, the object pointed to by f2 isn't
}

To conclude, if I were to guess why the designers of C# didn't add RAII, it's because they thought that having two different types of local variables is not worth it, mostly because in a language with GC, deterministic finalization is not useful that often.

* Not without the equivalent of the & operator, which in C++/CLI is %. Though doing so is “unsafe” in the sense that after the method ends, the field will reference a disposed object.


答:
Such a language extension would be significantly more complicated and invasive than you seem to think. You can't just add

if the life-time of a variable of a stack-bound type ends, call Dispose on the object it refers to

to the relevant section of the language spec and be done. I'll ignore the problem of temporary values (new Resource().doSomething()) which can be solved by slightly more general wording, this is not the most serious issue. For example, this code would be broken (and this sort of thing probably becomes impossible to do in general):

```<code>File openSavegame(string id) {
    string path = ... id ...;
    File f = new File(path);
    // do something, perhaps logging
    return f;
} // f goes out of scope, caller receives a closed file
</code>```

Now you need user-defined copy constructors (or move constructors) and start invoking them everywhere. Not only does this carry performance implications, it also makes these things effectively value types, whereas almost all other objects are reference types. In Java's case, this is a radical deviation from how objects work. In C# less so (already has structs, but no user-defined copy constructors for them AFAIK), but it still makes these RAII objects more special. Alternatively, a limited version of linear types (cf. Rust) may also solve the problem, at the cost of prohibiting aliasing including parameter passing (unless you want to introduce even more complexity by adopting Rust-like borrowed references and a borrow checker).

It can be done technically, but you end up with a category of things which are very different from everything else in the language. This is almost always a bad idea, with consequences for implementers (more edge cases, more time/cost in every department) and users (more concepts to learn, more possibility of bugs). It's not worth the added convenience.

Title: Why can't Java/C# implement RAII?

Body:
Such a language extension would be significantly more complicated and invasive than you seem to think. You can't just add

if the life-time of a variable of a stack-bound type ends, call Dispose on the object it refers to

to the relevant section of the language spec and be done. I'll ignore the problem of temporary values (new Resource().doSomething()) which can be solved by slightly more general wording, this is not the most serious issue. For example, this code would be broken (and this sort of thing probably becomes impossible to do in general):

File openSavegame(string id) {
    string path = ... id ...;
    File f = new File(path);
    // do something, perhaps logging
    return f;
} // f goes out of scope, caller receives a closed file

Now you need user-defined copy constructors (or move constructors) and start invoking them everywhere. Not only does this carry performance implications, it also makes these things effectively value types, whereas almost all other objects are reference types. In Java's case, this is a radical deviation from how objects work. In C# less so (already has structs, but no user-defined copy constructors for them AFAIK), but it still makes these RAII objects more special. Alternatively, a limited version of linear types (cf. Rust) may also solve the problem, at the cost of prohibiting aliasing including parameter passing (unless you want to introduce even more complexity by adopting Rust-like borrowed references and a borrow checker).

It can be done technically, but you end up with a category of things which are very different from everything else in the language. This is almost always a bad idea, with consequences for implementers (more edge cases, more time/cost in every department) and users (more concepts to learn, more possibility of bugs). It's not worth the added convenience.


问:
Found a better solution to a problem at work - should I deter from posting the code snippet online?
I think most of us, programmers, used Stack Overflow to solve every day problems: looked for an efficient algorithm to do something.

Now imagine a situation: you have a problem to solve. Googled a bit, found a StackOverflow question but you are not really satisfied with the answers so far. So you have to do your own research: you need to do it because you want it in the company's app.

Eventually after some hours you have found the better solution. You're happy, you added it to the company's code base, then you want to submit your answer with a code snippet (just several lines) to the question you've found before to help others too.

But wait: the company's software is closed source, and you worked on it on the clock.

So does this mean I shouldn't post the answer neither at work nor at home to that question in the rest of my life, because I solved it at work, and the company owns that piece of code?

答:
Exposing proprietary company information is something you should never do.  Most code snippets on Stack Overflow are far more mundane than that, however.  Consider this example:

```<code>public static unsafe void SwapX4(Byte[] Source)
{
    fixed (Byte* pSource = &Source[0])
    {
        Byte* bp = pSource;
        Byte* bp_stop = bp + Source.Length;

        while (bp < bp_stop)
        {
            *(UInt32*)bp = (UInt32)(
                (*bp       << 24) |
                (*(bp + 1) << 16) |
                (*(bp + 2) <<  8) |
                (*(bp + 3)      ));
            bp += 4;
        }
    }
}
</code>```

This method inverts the endianness of a 32 bit number, by swapping the bytes around.  The difference between this implementation and a naive one is that this one runs twice as fast, but you can only run it on a little endian machine.  It's being used in a proprietary program, but it describes a general technique, and does not expose anything confidential.

Body:
Exposing proprietary company information is something you should never do.  Most code snippets on Stack Overflow are far more mundane than that, however.  Consider this example:

public static unsafe void SwapX4(Byte[] Source)
{
    fixed (Byte* pSource = &Source[0])
    {
        Byte* bp = pSource;
        Byte* bp_stop = bp + Source.Length;

        while (bp < bp_stop)
        {
            *(UInt32*)bp = (UInt32)(
                (*bp       << 24) |
                (*(bp + 1) << 16) |
                (*(bp + 2) <<  8) |
                (*(bp + 3)      ));
            bp += 4;
        }
    }
}

This method inverts the endianness of a 32 bit number, by swapping the bytes around.  The difference between this implementation and a naive one is that this one runs twice as fast, but you can only run it on a little endian machine.  It's being used in a proprietary program, but it describes a general technique, and does not expose anything confidential.


答:
I frequently post problems and solutions I run into at work, on company time with company code*.  I've spoken to my manager directly about this, and he feels that the value the company gets from my time spent here far outweighs any concern about my time spent here in general.

*I'm cautious to obfuscate anything I think could be proprietary.  Our in-house code is very proprietary, but would largely be useless to anyone without our proprietary hardware (which we don't sell).

I look at my questions & answers as helping myself as well as someone else down the road when they run into similar problems as I have.

Title: Found a better solution to a problem at work - should I deter from posting the code snippet online?

Body:
I think most of us, programmers, used Stack Overflow to solve every day problems: looked for an efficient algorithm to do something.

Now imagine a situation: you have a problem to solve. Googled a bit, found a StackOverflow question but you are not really satisfied with the answers so far. So you have to do your own research: you need to do it because you want it in the company's app.

Eventually after some hours you have found the better solution. You're happy, you added it to the company's code base, then you want to submit your answer with a code snippet (just several lines) to the question you've found before to help others too.

But wait: the company's software is closed source, and you worked on it on the clock.

So does this mean I shouldn't post the answer neither at work nor at home to that question in the rest of my life, because I solved it at work, and the company owns that piece of code?


答:
For an example of how RAII does work in a garbage-collected language, check the with keyword in Python.  Instead of relying on deterministically-destroyed objects, it let's you associate __enter__() and __exit__() methods to a given lexical scope.  A common example is:

```<code>with open('output.txt', 'w') as f:
    f.write('Hi there!')
</code>```

As with C++'s RAII style, the file would be closed when exiting that block, no matter if it's a 'normal' exit, a break, an immediate return or an exception.

Note that the open() call is the usual file opening function.  to make this work, the returned file object includes two methods:

```<code>def __enter__(self):
  return self
def __exit__(self):
  self.close()
</code>```

This is a common idiom in Python: objects that are associated with a resource typically include these two methods.

Note that the file object could still remain allocated after the __exit__() call, the important thing is that it is closed.

Title: Why can't Java/C# implement RAII?

Body:
For an example of how RAII does work in a garbage-collected language, check the with keyword in Python.  Instead of relying on deterministically-destroyed objects, it let's you associate __enter__() and __exit__() methods to a given lexical scope.  A common example is:

with open('output.txt', 'w') as f:
    f.write('Hi there!')

As with C++'s RAII style, the file would be closed when exiting that block, no matter if it's a 'normal' exit, a break, an immediate return or an exception.

Note that the open() call is the usual file opening function.  to make this work, the returned file object includes two methods:

def __enter__(self):
  return self
def __exit__(self):
  self.close()

This is a common idiom in Python: objects that are associated with a resource typically include these two methods.

Note that the file object could still remain allocated after the __exit__() call, the important thing is that it is closed.


答:
If what bothers you with using blocks is their explicitness, perhaps we can take a small baby-step towards less explicitness, rather than changing the C# spec itself. Consider this code:

```<code>public void ReadFile ()
{
  string filename = "myFile.dat";
  local Stream file = File.Open(filename);
  file.Read(blah blah blah);
}
</code>```

See the local keyword I added? All it does is add a bit more syntactic sugar, just like using, telling the compiler to call Dispose in a finally block at the end of the variable's scope. That is all. It's totally equivalent to:

```<code>public void ReadFile ()
{
  string filename = "myFile.dat";
  using (Stream file = File.Open(filename))
  {
      file.Read(blah blah blah);
  }
}
</code>```

but with an implicit scope, rather than an explicit one. It's simpler than the other suggestions since I don't have to have the class defined as scope-bound. Just cleaner, more implicit syntactic sugar.

There might be issues here with hard-to-resolve scopes, though I can't see it right now, and I'd appreciate anyone who can find it.

Update: Since the initial writing of this, C# has gotten this feature with C#8. Only instead of local as suggested here the keyword is simply using, as it replaces a using-block.

Title: Why can't Java/C# implement RAII?

Body:
If what bothers you with using blocks is their explicitness, perhaps we can take a small baby-step towards less explicitness, rather than changing the C# spec itself. Consider this code:

public void ReadFile ()
{
  string filename = "myFile.dat";
  local Stream file = File.Open(filename);
  file.Read(blah blah blah);
}

See the local keyword I added? All it does is add a bit more syntactic sugar, just like using, telling the compiler to call Dispose in a finally block at the end of the variable's scope. That is all. It's totally equivalent to:

public void ReadFile ()
{
  string filename = "myFile.dat";
  using (Stream file = File.Open(filename))
  {
      file.Read(blah blah blah);
  }
}

but with an implicit scope, rather than an explicit one. It's simpler than the other suggestions since I don't have to have the class defined as scope-bound. Just cleaner, more implicit syntactic sugar.

There might be issues here with hard-to-resolve scopes, though I can't see it right now, and I'd appreciate anyone who can find it.

Update: Since the initial writing of this, C# has gotten this feature with C#8. Only instead of local as suggested here the keyword is simply using, as it replaces a using-block.


答:
I would say about two seconds - but make sure that those are two seconds with no change, rather than two seconds from the first unsaved change!

1/2 letters-per-seconds is a very slow speed, so you won't send the update when they type - only when they stop to think. And while it's true that among the one-finger typists there are users who type slower than that - an update every 2 seconds(or longer!) is not that bad, and the users shouldn't even feel it(because they are too busy looking at the keyboard).

If two seconds are too much a burden on your server, you can try longer times, but not too much(you don't want to sacrifice usability). You can also try to measure the user's typing speed on the fly, and update the interval dynamically.


问:
Layering Design Pattern in Java clean code style
As a Java developer, I am developing trying to use the clean code rules. But in my team we are facing a concrete problem:

We have a business layer offering a service called "createObject", this service makes a lot of operation which can result to problem. E.g: parentObjectDontExist, objectAlreadyExist, dontHaveAuthorizationToCreate, operationFailed...

and we want the UI using this service to display different information messages depending which error occurred.

In old java dev, we should have create all signed exception type and throw it in createObject.

As Clean code says, it is forbidden to use Exception for business logic AND signed exceptions are evil...
Why not...But i don't know how to solved this problem and i don't want to use return code.

How do you do?
Thanks for youre experience return.

答:
Checked exceptions are not evil: sometimes they can be handy e.g. while writing a critical library. But in fact Runtime Exceptions are prefered in most scenarios.

Define exceptions in terms of caller's needs. Does the caller need to know about all the specific exceptions you mention here: parentObjectDontExist, objectAlreadyExist, dontHaveAuthorizationToCreate, operationFailed? If not, then it will be just enough to have one common exception type (e.g. CreatingObjectException) to be thrown by the service with a relevant information for the UI.


问:
Is it just me or is this a baffling tech interview question?

Background

I was just asked in a tech interview to write an algorithm to traverse an "object" (notice the quotes) where A is equal to B and B is equal to C and A is equal to C.

That's it.  That is all the information I was given.

I asked the interviewer what the goal was but apparently there wasn't one, just "traverse" the "object".

I don't know about anyone else, but this seems like a silly question to me.  I asked again, "am I searching for a value?".  Nope.  Just "traverse" it.

Why would I ever want to endlessly loop through this "object"??  To melt my processor maybe??

The answer according to the interviewer was that I should have written a recursive function.

OK, so why not simply ask me to write a recursive function?  And who would write a recursive function that never ends?

My question:

Is this a valid question to the rest of you and, if so, can you provide a hint as to what I might be missing?  Perhaps I am thinking too hard about solving real world problems.  I have been successfully coding for a long time but this tech interview process makes me feel like I don't know anything.

答:
Coming very late to this party, but I think the interviewer incorrectly asked this question:

Write an algorithm to traverse an array and determine that A is equal to B and B is equal to C and A is equal to C, in that order.

Then the correct answer would be a recursive algorithm.


问:
Should selenium tests be written in imperative style?
Is an automation tester supposed to know concepts of OOPS and design patterns to write Tests in a way where changes & code re-use are possible?

For example, I pick up Java to write cucumber step definitions that instruct a selenium webdriver.

Should I be using a lot of inheritance, interfaces, delegation etc. to make life easier or would that be overly complicated for something that should just line by line instructions?

答: This decision depends on the kind of testing you would want to do , for instance you will test the project once and forget about it .In such scenarios , using a design pattern such as Page Objects does not make a sense. But if the aim is to build a regression library that would need maintenance and a need for adding additional tests that project then it makes perfect sense to use a solid design. A good design is also useful when you want to test continious integration builds.</p>


问:
More elegant way to avoid hard coding the format of a a CSV file?
I know this is trivial issue, but I just feel this can be more elegant.

So I need to write/read data files for my program, lets say they are CSV for now.  I can implement the format as I see fit, but I may have need to change that format later.  The simply thing to do is something like

```<code>out.write(For.getValue()+","+bar.getMinValue()+","+fi.toString());
</code>```

This is easy to write, but obviously is guilty of hard coding and the general 'magic number' issue.  The format is hard-coded, requires parsing of the code to figure out the file format, and changing the format requires changing multiple methods.

I could instead have my constants specifying the location that I want each variable to be saved in the CSV file to remove some of the 'magic numbers'; then save/load into the an array at the location specified by the constants:

```<code>int FOO_LOCATION=0;
int BAR_MIN_VAL_LOCATION=1;
int FI_LOCATION=2
int NUM_ARGUMENTS=3;

String[] outputArguments=new String[NUM_ARGUMENTS];
outputArguments[FOO_LOCATION] = foo.getValue();
outputArgumetns[BAR_MIN_VAL_LOCATION] = bar.getMinValue();
outptArguments[FI_LOCATOIN==fi.toString();

writeAsCSV(outputArguments);
</code>```

But this is...extremely verbose and still a bit ugly.  It makes it easy to see the format of existing CSV and to swap the location of variables within the file easily.  However, if I decide to add an extra value to the csv I need to not only add a new constant, but also modify the read and write methods to add the logic that actually saves/reads the argument from the array; I still have to hunt down every method using these variables and change them by hand!

If I use Java enums I can clean this up slightly, but the real issue is still present.  Short of some sort of functional programming (and java's inner classes are too ugly to be considered functional) I still have no obvious way of clearly expressing what variable is associated with each constant short of writing (and maintaining) it in the read/write methods.  For instance I still need to write somewhere that the FOO_LOCATION specifies the location of foo.getValue().

It seems as if there should be a prettier, easier to maintain, manner for approaching this?

Incidentally, I'm working in java at the moment, however, I am interested conceptually about the design approach regardless of language.  Some library in java that does all the work for me is definitely welcome (though it may prove more hassle to get permission to add it to the codebase then to just write something by hand quickly), but what I'm really asking is more about how to write elegant code if you had to do this by hand.

答:
Use varargs...

```<code>public void write(Object... args);
</code>```

... and call it like this:

```<code>out.write(new Object { For.getValue(), bar.getMinValue(), fi.toString() });
</code>```

Body:
Use varargs...

public void write(Object... args);

... and call it like this:

out.write(new Object { For.getValue(), bar.getMinValue(), fi.toString() });


问:
Is it possible to learn maths via programming, or you should learn maths for programming?
I am not the best in maths, not very horrid either, but lower than the average, I've always been thinking to improve my maths, but schools and books didn't do the job because I get bored too fast. The only thing I don't get bored with is coding and gaming, so I thought what if coding a program that solves mathematical problems will help me understand maths better, most of these problems are limits (calculus), functions, Differential calculus, and some other subjects (I already said am not that good) similar to the previous noted.

My question is: Am I able to achieve a better knowledge in maths if I do some specific program coding, and if possible, is physics possible that way too? Or am I wrong and Maths should be learned before programming to help improve my coding?

P.S : C++ is the preferred language.

答:
I couldn't find the blog entry but I recall a designer "type" from the late pre first bubble-burst era (before '01-ish) who blogged about discovering a love of math through becoming a web developer and realizing that he was actually quite good at it even though he'd always failed miserably in high school and had assumed he just wasn't somebody who would ever be any good at math and then pegged himself as an artsy type.

No not me. I was just lazy. I have to relearn trig occasionally but that's about it.

IMO, you can write a lot of decent code without heavy math knowledge until you can't, basically.

What programming CAN do for anybody with a reasonable amount of interest in it, however, is help you get over the idea of whether you're this sort of person or that sort of person, and give you the tools you need to just try stuff out and discover on your own how far your interests will take you in a given field of study.

And of course everything we're doing is linked at the hip with math so you may discover you've already learned more than you realized when you do stuff like learn about what that backwards-e summation thingy is all about.


答:
If you dont need csv, please look into using JAX-B to write them as XML instead of writing them as CSV, if it is for local file storage. It's clutterless: just annotate the classes that will contain the information, and use a Marshaller. It's what I'd do anyway. In case you're interested: http://www.oracle.com/technetwork/articles/javase/index-140168.html

On the other hand, you could have a generic method to marshall into csv, like this:

```<code>public String marshallCsv(String[][] data,boolean includeFirstLine){
    String delimeter = "\"";
    String separator = ",";
    StringBuilder csv = new StringBuilder("");
    int i =0;
    if(!includeFirstLine){
        i=1;
    }
    for(;i<data.length;i++){//if includeFirstLine is true, start from index 1
         for(j=0;j<data[i].length;j++){
             csv.append(delimeter+data[i][j]+delimeter);
             if(j<data[i].length){
                  csv.append(separator);
             }
             csv.append("\n");
         }
    }
    return csv.toString();
}
</code>```

If a certain field is omitted, fill it with a blank string. You can then have your objects implement a method, say "toContentStringArray()" which returns the relevant fields as Strings of an array.

For finer grained control, there are many things you can do, but I like crazy: you can have an overload of toContentStringArray which received an array of Strings naming the fields you want to output, then use reflections to get those fields and omit the others as blank strings.

For better results, make sure you have a sanitizeString(String cleanable,String[] forbiddenStrings), so that you escape the strings you dont want in the csv. For instance, you want to escape all the "," so your fields aren't broken in half.

But trust me, this gets messy. I'd definitely go to JAX-B.

Title: More elegant way to avoid hard coding the format of a a CSV file?

Body:
I know this is trivial issue, but I just feel this can be more elegant.

So I need to write/read data files for my program, lets say they are CSV for now.  I can implement the format as I see fit, but I may have need to change that format later.  The simply thing to do is something like

```<code>out.write(For.getValue()+","+bar.getMinValue()+","+fi.toString());
</code>```

This is easy to write, but obviously is guilty of hard coding and the general 'magic number' issue.  The format is hard-coded, requires parsing of the code to figure out the file format, and changing the format requires changing multiple methods.

I could instead have my constants specifying the location that I want each variable to be saved in the CSV file to remove some of the 'magic numbers'; then save/load into the an array at the location specified by the constants:

```<code>int FOO_LOCATION=0;
int BAR_MIN_VAL_LOCATION=1;
int FI_LOCATION=2
int NUM_ARGUMENTS=3;

String[] outputArguments=new String[NUM_ARGUMENTS];
outputArguments[FOO_LOCATION] = foo.getValue();
outputArgumetns[BAR_MIN_VAL_LOCATION] = bar.getMinValue();
outptArguments[FI_LOCATOIN==fi.toString();

writeAsCSV(outputArguments);
</code>```

But this is...extremely verbose and still a bit ugly.  It makes it easy to see the format of existing CSV and to swap the location of variables within the file easily.  However, if I decide to add an extra value to the csv I need to not only add a new constant, but also modify the read and write methods to add the logic that actually saves/reads the argument from the array; I still have to hunt down every method using these variables and change them by hand!

If I use Java enums I can clean this up slightly, but the real issue is still present.  Short of some sort of functional programming (and java's inner classes are too ugly to be considered functional) I still have no obvious way of clearly expressing what variable is associated with each constant short of writing (and maintaining) it in the read/write methods.  For instance I still need to write somewhere that the FOO_LOCATION specifies the location of foo.getValue().

It seems as if there should be a prettier, easier to maintain, manner for approaching this?

Incidentally, I'm working in java at the moment, however, I am interested conceptually about the design approach regardless of language.  Some library in java that does all the work for me is definitely welcome (though it may prove more hassle to get permission to add it to the codebase then to just write something by hand quickly), but what I'm really asking is more about how to write elegant code if you had to do this by hand.

Body:
If you dont need csv, please look into using JAX-B to write them as XML instead of writing them as CSV, if it is for local file storage. It's clutterless: just annotate the classes that will contain the information, and use a Marshaller. It's what I'd do anyway. In case you're interested: http://www.oracle.com/technetwork/articles/javase/index-140168.html

On the other hand, you could have a generic method to marshall into csv, like this:

public String marshallCsv(String[][] data,boolean includeFirstLine){
    String delimeter = "\"";
    String separator = ",";
    StringBuilder csv = new StringBuilder("");
    int i =0;
    if(!includeFirstLine){
        i=1;
    }
    for(;i<data.length;i++){//if includeFirstLine is true, start from index 1
         for(j=0;j<data[i].length;j++){
             csv.append(delimeter+data[i][j]+delimeter);
             if(j<data[i].length){
                  csv.append(separator);
             }
             csv.append("\n");
         }
    }
    return csv.toString();
}

If a certain field is omitted, fill it with a blank string. You can then have your objects implement a method, say "toContentStringArray()" which returns the relevant fields as Strings of an array.

For finer grained control, there are many things you can do, but I like crazy: you can have an overload of toContentStringArray which received an array of Strings naming the fields you want to output, then use reflections to get those fields and omit the others as blank strings.

For better results, make sure you have a sanitizeString(String cleanable,String[] forbiddenStrings), so that you escape the strings you dont want in the csv. For instance, you want to escape all the "," so your fields aren't broken in half.

But trust me, this gets messy. I'd definitely go to JAX-B.


答:
I am interested conceptually about the design approach regardless of language

For low-level problems like this one, there is no "design approach regardless of language".  For Java, one answer is to use annotations to mark the fields that should be written to the CSV.  Then a single write function can use reflection to find the annotated fields and write them to the CSV.  Alternatively, you could work with the existing Java serialization facilities and write all the fields that are not transient.

For deeper understanding, read the code for an existing serialization library.  You might want to start with a simple one like openCSV.