问:
Performing data operations that involve separate applications and data sources
I'm designing an enterprise application that produces output based on some input data from another application.  In this case, I happen to have also built and thus do control the source application and data, database structure, etc., but this question also applies to cases where I am using input data from a third-party application, so I'll assume that going forward.

The new application should only produce output once for a given set of input data; it will pull data from the source, produce output, and maintain state so that the same input data is not processed the next time it runs.

What I'm wondering about is what is a good design approach to take in cases where I need to store state so that I'm not pulling the entire universe of source data when I only need to operate on a small subset of that data.

Three options I can think of are:

Modify the schema of the third-party source database so I can store my state there.

Query the data via a join between the third-party database and my new database and filter the results within that query based on state that is stored in the new database.

Warehouse the source data within my new database and perform all queries against the warehoused data.

I have worked with commercial enterprise applications that use all of these approaches, but each of them has its downsides:

With option 1, one obvious downside is that modifying a third-party database is, at best, discouraged by most vendors and, at worst, explicitly forbidden in license agreements.  Furthermore, future vendor updates to the schema could wipe out data or fail due to conflicts caused by your modifications.  The bottom line for me, though, is that I just don't want to store data for a "destination" application in a "source" application's database, regardless of whether I "own" both databases or not, but especially if the source is a third-party application.  If the data is not used by the application itself, it doesn't belong in its database.

With option 2, one downside is that the databases may be migrated to different servers, and if joins are not constructed properly with fully-qualified object names -- including dynamically-provided DB server names (because of the aforementioned possibility of them being migrated to different servers) -- then the application will break.  Another downside is that the source data might not even be stored in the same format as the new database (e.g. a different DBMS) thus precluding the possibility of a join.  Most importantly for me, though, is the fact that this approach violates Separation of Concerns because either the data layer has to perform some awkward and arguably-inefficient surgery to rend the two entities into separate domain objects or the domain layer has to have some gnarly beast hybrid of the two disparate entities.  Either way, it smells.

Option 3 sounds the best to me, but it still has the downside that there is overhead involved in populating and maintaining the warehouse.  Some "process" has to do this.  Where does that process run...from some middle-tier server?  How often does it run, and what happens if your application wants data that hasn't been updated yet?  Who administers it?

Does anyone know of another approach I haven't considered, or can anyone offer any insight into any of the above approaches I have considered (for instance, suggest modifications to the approaches that preclude the downsides or explain to me why one approach is best despite its downsides)?

答:
I came up with a "hybrid" solution. And you may give it a thought. I understand it's not desireable to modify 3rd party database, or, sometime it is not even possible because you don't have access to client sources, right?

In my case, source data did not have anything I can "reference" like "updatedOn" or any reliable timestamps or logs.. I also needed to track CRUD. Not just additions.

So, what I ended up doing - I placed triggers on those tables that you need to monitor and all this triggers do - they populate MY INFO TABLES with what happened to which record. I monitor those tables every 30 seconds, but in your case it's daily. Point is - you know exactly what was changed and don't process any extra data. After processing - wipe data you processed from your INFO tables..

In my case the only "foreign" objects on 3rd party database is triggers and additional table for change logging. This approach survived upgrades from 3rd party, just run your script to re-create triggers if needed after upgrade.


问:
In what case would indexedDB be useful
I have been over-viewing indexedDB recently, and I cannot seem to find a suitable use case that would not be better done using a server side database. Since the little hackathon competition I'm doing with my friends is creating an agenda web-app, I'll put my examples in that contest.

Just to make sure, I read that indexedDB is stored per site per browser. If this is so, the following ideas make no sense:

Storing user preferences. Since a user will most likely want his preferences saved across devices, it would seem better to save this on the server side.

Storing items / date that were recently viewed. Since this data is not structured and not data that will need to persist for a long time, wouldn't be easier to use localStorage.

I could go on with ideas that would fit better with a server side DB, localStorage or sessionStorage, so to cut to the chase, what are some example use cases that would fix indexedDB well?

答:
Server side relational databases are great for being a normalised primary data store. However, in many cases:

Persistent data storage isn't required because the data can easily be recalculated or retrieved again

It adds too much latency to make a minimum ~50ms HTTP request every time you want to access the data

Making frequent requests to data which is unlikely to have changed on the server side would place excessive strain on the database.

In these cases indexedDB can be suitable, which is most often in the context of a sophisticated web application.

A clearer example might be to look at the tables created by something like Google Docs/Drive:

I assume in that scenario indexedDB might be used in several cases such as:

Storing edits without having to sync every single character change back to the server immediately

Ensuring edits can be synced to the server the next time the page is opened even if the user closed their browser instantly after making the edits originally

Avoiding having to reload things that don't change very often, such as a list of fonts or image resources every time the page is reloaded.

indexedDB is particularly useful if you want a client which can be used without an internet connection, which is becoming increasingly important as browser based applications replace more and more desktop applications.

ContentLicense: CC BY-SA 3.0

Title: In what case would indexedDB be useful


问:
Why does the TRACE level exist, and when should I use it rather than DEBUG?
In Log4J, Slf4J and a couple other logging frameworks in Java, you have two "developper" level for logging:

DEBUG

TRACE

I understand what DEBUG does, because the explanation is clear:

The DEBUG Level designates fine-grained informational events that are most useful to debug an application.

But the TRACE level is not very specific about its use case:

The TRACE Level designates finer-grained informational events than the DEBUG

(Source: the log4J JavaDoc)

This does not tell me how or when to use TRACE. Interestingly, this is not a severity level defined in the syslog standard. Googling for the difference between TRACE and DEBUG only seem to return "use DEBUG, oh, and there is TRACE too". I couldn't find a specific use case for the TRACE level. The best I could find was this old wiki page debating the merit of the existence of the level.

This, as an architect, raises a lot of flags and questions in my head. If a young developer asked me to add TRACE to my architecture, I would bombard him with questions:

What are some examples of information that should be logged with TRACE and not with DEBUG?

What specific problem do I solve by logging that information?

In those examples, what are the properties of the logged information that clearly discriminate between logging at the TRACE level rather than the DEBUG level?

Why must that information go through the log infrastructure?

What are the benefits of persisting that information in a logs journals rather than just using System.out.println ?

Why is it better to use log for this rather than a debugger?

What would be a canonical example of logging at the TRACE level?

What are the specific gains that have been made by logging at the TRACE level instead of DEBUG in the example?

Why are those gains important?

In reverse: What problems did I avoid by logging it at TRACE instead of DEBUG?

How else could I solve those problems? Why is logging at the TRACE level better than those other solutions?

Should TRACE level log statement be left in the production code? Why?

But given that it is present in most major framework, I am guessing it is useful for something? So... what is TRACE for, and what distinguishes it from DEBUG?

答:
I think Telastyn's excellent answer can be summarized to my short rule of thumb:

DEBUG logging must be able to be used in production (but tends to still be off normally)

TRACE logging is allowed to be such that using it in production (other than for a specific / short session) is infeasible


问:
Test and deployment environment design for small team
Question is about organizing dev environment for the web development.

There is 2 things to deploy: web site and database schema

We use SVN to keep track of source code

We use RedGate tools to generate migration SQL and to version-control database schema.

It is important to have fresh copy of data in our dev environment.

At first, we just worked each in personal databases. Now our team getting bigger so we have dev server with shared database.

For customer, we created "test" website that we run on our server. And it points to our dev database.

For data - we bring fresh copy of database weekly, so it's just another PITA because we do it by backup/restore and obviously schema different when we bring it back.

Where we have problem now is when we release something for customer to test. They check, it may take some time. By the time they check we might already have some other new features added to TEST site. Now, let's say production missing A, B, and C features. Customer tested A, but B and C need to be tested or changed. A need to go to release.

In big companies were I worked there was DEV, TEST and PROD environments. Pretty much DEV->TEST didn't go unless TEST->PROD happened. This caused just wasted time (realistically). Now we can't afford just sitting, so how do we work fast-paced like this with minimum hickups.

Now because we still waiting from a customer on feedback on "A" - we already "forgot" what else we added. With many people it just get's more complex.

So, I guess question is: How to manage DB/Code version control and separate features publishing in such environment? With minimal bureaucracy.

答:
As you also said, the efficiency of the team is not likely to get improved if you only have a TEST environment, where all developers work. I think this is the main bottleneck in you development process.

Every developer should have his own DEV environment in his local machine, with its own database (perhaps a recent clone from TEST environment). So, each developer could work on its own feature independently. When each feature has passed the DEV stage with local testing by the DEV team, it should be commited in the Versioning Control System you use and then it should be deployed in TEST environment to be seen by the client.

In aspects of Versioning, the best practice is that each developer creates a new branch for each new feature and when the feature is to be deployed in TEST, the branch is merged in the trunk. So, all conflicts between different features will be easily observable and by looking the Versioning history, the features added at each step will also be easily noticed, since you will just have to look for merged branches


问:
Approach to encouraging organizational adoption of new web dev tools
I'm attending the O'Reilly Fluent conference, and a clear theme I've seen is the widespread adoption of tools to improve effectiveness of efficiency in web development workflows.

I readily recognize the value of these tools, but I am concerned that some of my coworkers may feel like my suggestion to adopt them would be seen as "one more chunk of overhead - one more thing adding complexity and standing between me and getting code written".

What are approaches you've successfully used in similar cultures or situations to help your organization be open to considering the possibility of adopting new tools?

Some of the tools I have in mind (as examples, though the question isn't limited to or even specifically about these) are Grunt, Travis CI, ReactJS, Hubot, Browserify, PhantomJS, ES6 (with Babel, currently), etc.

答:
I've been in situations like this before. One thing to avoid is to jump right into saying "We should adopt tool X, because of reason Y." This would likely trigger the response you're woried about.

One of the approaches that have worked for me in the past is to actually identify a point of improvement. For example, you could point out something in your processes that takes a lot of time. If you can then identify a tool that helps improving on that point, and you can demonstrate, that could allow for a more open aproach.

Something that is always very important in these situations is to listen to your coworkers. They may come up with some valuable feedback. Or they might come up with a better solution.
There might alsow be cases where they are just trying to block you with irrelivant arguments, in which case you should be ready to reply to them accordingly.

Another approach is to casually demonstrate a tool to a coworker. The way you could do that is to have the tool open on your computer with a demo scenario ready and when a coworker looks on your screen, show him or her what you're playing with. Lines like "I've been playing with this to see if it's any good. Look, it does this which is cool." can help.

Another thing to keep in mind is to be honest about any tools, including drawbacks. This would enhance the feeling you're trying to solve a problem, not introduce more overhead.


问:
Can a the kind of load Uber handles be served from just one server?
http://techcrunch.com/2013/12/04/leaked-uber-numbers-which-weve-confirmed-point-to-over-1b-gross-revenue-213m-revenue/

This article says that Uber does about 1M requests a week. Which is about 1.65 reqs a sec.

So does this mean Uber can probably do with just one machine serving their requests? Or am I missing something here?

I realize traffic will be bursty but still doesn't seem like they'd need too many servers even at max load.

Edit: Let's assume we're building a bare bones version of uber where you don't do the realtime GPS locations of drivers & you don't have georeplication.

Say, the app has only this functionality: open the app, and order a cab. The phone triangulates your location and sends a request to the server who then responds with whether a driver was found or not

答:
Yes, of course it could. Whether they do is another matter as even Uber will not be running all their business off a single server - they'll have web servers to receive requests, application servers to process the data, and a (clustered?) database server to store the data. (well, I assume they do, chances are they are running it all off a single websever running PHP for all I know).

Servers are very powerful nowadays, for £20,000 you can have a 32-quad-core-cpu with gigabytes of RAM and several network cards. The server processing game changed about ten years ago and made practically unlimited computing available, hence the rise in cloud services as providers had more power than they knew what to do with!

I do know that I used to work for a financial services company that had a trio of servers that was rated for 400,000 transactions per hour. The solitary performance test server could handle way more than 2 requests per second, and this was quite complicated transactions involving a lot of data transfer, aggregation and checking. I also worked for a company making emergency service control systems, thousands of vehicles sending in location data isn't as heavy a load as you'd think, its very easy to handle large amounts of data packets like this, storing them was more of an issue (and you simply cache them in RAM until you have a block to persist together - assuming Uber has the same audit requirements, they could just be keeping the last-known location and throwing away the rest)


问:
provability of while loop vs for loop
I have this teacher, he's quite smart (sometimes, haha) he said good programmers try to use while loops instead of for loops. the reason he gave for this is because while loops can be proven, as in, one can completely explain what happens in a while loop whereas you can't do that for a for loop. he also said something about NASA programmers only using while loops and not allowed to do for loops because of this.

I have quite a hard time understand this, for both loops one can explain how they work in detail right? for both you would always know what is going to happen?

can someone explain to me why while loops can be proven (And because of it, might be better than for loops, in some cases at least).

EDIT:

maybe he was reffering to:

2: All loops must have a fixed upper bound. It must be trivially possible for a checking tool to statically prove that a preset upper bound on the number of iterations of a loop cannot be exceeded. If the loop-bound cannot be proven statically, the rule is considered violated.

Though this still doesn't say anything about the difference between while and for loops.

答:
Actually, in some sense, the exact opposite is true.

A language with only for-loops is not Turing-complete, it can only compute the primitive-recursive functions, not all Turing-computable functions. Since all computation in a language with only for-loops always terminates, the Halting Problem and all the other Decidability Problems based upon it, simply don't arise, so it is possible to mechanically decide many more static properties of programs than in a language with while-loops.

OTOH, a language with only natural numbers, a single variable, and while-loops is Turing-complete, and so it is not possible to decide even the simplest of properties: will this program return a result?

Title: provability of while loop vs for loop


问:
How to name complex DAL/repository methods?
I'm beginning working with repository pattern. When it comes to simple queries I don't have problems with names.

GetById

GetByDay

UpdateById

If a method retrieves data filtered by two values also I can name it properly.

GetByNameAndSurname

Also when there are very advanced filters I just name it as follows.

GetByFilter

(and pass search criteria object)

But I have a problem with naming methods like that:

Get data filtered by three or four values (GetByNameAndSurnameAndDayAndCountry)

Get data using comparison (GetByDateGreatherThan)

Mixed (GetByCreateDateGreatherThanAndNameAndSurname)

Is there any good pattern I can use to name such methods?

答:
Use the entire method signature to specify your intent, not just its name. Method names should represent verbs not phrases. Your method signatures can be written as:

```<code>Get(object id)
Get(Date day)
Update(object id)

Get(string name, string surname)
Get(Filter filter)

Get(string name, string surname, Date day, string country)
Get(Date greaterThan);
Get(Date greaterThan, string name, string surname)
</code>```

A case where it could be needed to be more specific in a method name should be when the parameter part of the signature is identical. For example:

```<code>Get(object id); // GetById
Get(object name); // GetByName
</code>```

Body:
Use the entire method signature to specify your intent, not just its name. Method names should represent verbs not phrases. Your method signatures can be written as:

Get(object id)
Get(Date day)
Update(object id)

Get(string name, string surname)
Get(Filter filter)

Get(string name, string surname, Date day, string country)
Get(Date greaterThan);
Get(Date greaterThan, string name, string surname)

A case where it could be needed to be more specific in a method name should be when the parameter part of the signature is identical. For example:

Get(object id); // GetById
Get(object name); // GetByName


问:
Is it appropriate to use the unordered list (ul) element for composite content
I recently had a thought of utilizing the unordered list element to represent a list of composite content (such as a product list with details or an image list with captions).

For example:

```<code><ul>
    <li>
        <img src="awesometoaster.png" alt="toaster">
        <p>Awesome Toaster<p>
        <p>This is an available product</p>
        Buy Now
    </li>
</ul>
</code>```

I have looked into example usages of the element, however many provide very basic one level examples.

```<code><ul>
    <li>Red</li>
    <li>Blue</li>
    <li>Green</li>
</ul>
</code>```

To me, the first example is a logical list of products and would make sense to utilize an unordered list. Would this be a semantic choice to represent this type of content or is there a more appropriate element choice?

答:
First of all : yes, using unordered list makes sense. But you might want to style it a bit with css in order to get a better visual than bullet lists.

So, my real advice is to use bootstrap and its grid system, which is responsive and easy to use. Bootstrap has a lot of html classes that will style your content in a classical and pretty way. You can then add your own css to get exactly what you want, but bootstrap gives you quick and easy basics.

Body:
I recently had a thought of utilizing the unordered list element to represent a list of composite content (such as a product list with details or an image list with captions).

For example:

```<code><ul>
    <li>
        <img src="awesometoaster.png" alt="toaster">
        <p>Awesome Toaster<p>
        <p>This is an available product</p>
        <a href="#">Buy Now</a>
    </li>
</ul>
</code>```

I have looked into example usages of the element, however many provide very basic one level examples.

```<code><ul>
    <li>Red</li>
    <li>Blue</li>
    <li>Green</li>
</ul>
</code>```

To me, the first example is a logical list of products and would make sense to utilize an unordered list. Would this be a semantic choice to represent this type of content or is there a more appropriate element choice?


答:
A lot of it is about communication skills. You should also know that being skeptical about new tools is common in software industry. More on this later.

First: Your Mindset

You are not selling so don't feel like it. You are kindly presenting a solution to a common problem so be confident. (Actually if you were marketing a product, you would also be advised to have the latter mindset.)

Be prepared to be rejected. You can never be sure to convince everyone every time. Furthermore, it is common in software development teams to be (wrongly) skeptical or even lazy about:

Reusing code which needs learning about it.

Using proper new advanced tools to solve new advanced types of problems.

Writing unit tests.

Second: Your Presentation

Dale Carnegie in his classic book, "How To Win Friends And Influence People" has a lot of things to say about this subject. One of those things is that you have to point out their problems and your solutions for them rather than stating your desires and emotions. Following that lead:

- Find The Problems You Can Solve

Try to find the main common concerns in your organization that the tools can somehow solve. Start with them (e.g. Remeber the other day when we were talking about how running our tests regularly puts too much on our plates? ... and then lead to Contiuous Integration tools.)

Find and list the problems that your team beleive they exist too. This way you won't have to convince them that a problem exists prior to presenting the solution. Winning an argument is really hard. Winning two arguments in one session is really really hard.

The problems you mention do not have to be directly related to the solution you are providing. You just have to be able to start from the problem and lead to your solution. of course, the solutions should be practical enough or you would look like preeching. Do not preech. never.

- Answer Before They Ask

Try to answer the arguments you really guess people would start before the start it. This makes your argument more solid and convincing.

Do not be obvious in this. Blend those answers in the context of your presentation. E.g. in the first part of this answer I pointed out 3 common skepticisms in software development. I put our subject in the second item! See what I did there?!

Finally I have to emphasize again that you should avoid at all cost preeching. always keep an open mind.

Title: Approach to encouraging organizational adoption of new web dev tools

Body:
I'm attending the O'Reilly Fluent conference, and a clear theme I've seen is the widespread adoption of tools to improve effectiveness of efficiency in web development workflows.

I readily recognize the value of these tools, but I am concerned that some of my coworkers may feel like my suggestion to adopt them would be seen as "one more chunk of overhead - one more thing adding complexity and standing between me and getting code written".

What are approaches you've successfully used in similar cultures or situations to help your organization be open to considering the possibility of adopting new tools?

Some of the tools I have in mind (as examples, though the question isn't limited to or even specifically about these) are Grunt, Travis CI, ReactJS, Hubot, Browserify, PhantomJS, ES6 (with Babel, currently), etc.


问:
How to explain a project for a potential employer
I went to an interview last week for a junior programmer and mentioned that I have been working on a project with a buddy of mine. Tomorrow they would like to see this project in order to decide if they should hire me or not. So I was wondering:

What parts of a project are of interest to someone who has not seen the project before?

What could I show that would change their perspective of me as a programmer and what I know?

The project is in C# and have been a hobby project for 6 months now. Without going into to much details:

it's a networked program

it's server / client based where clients end up connecting to each others

there is synchronization of data between clients

we are using files to store information about the different clients, which is also being synchronized

the program in whole is divided into some different projects (some which go into .dll's)

the project will later handle multiple layers of displaying the data to the user (meaning cmd, a window etc..)

I have green lighted this with my buddy as well and it is ok to show. My idea was to show the shell (cmd) that we have which is working and the top layers of the hierarchy, the ones that the shell communicates directly with. These are three classes in particular, one that connects and communicates with the server, one that handles the synchronization and one that handles the objects that are being synchronized. I'll try to go into some details about how we store the objects and how this is communicated to the synchronizer class. Then discuss on a higher level of how we synchronize the data, ending with going into some detail about how this is done.

Basically, start from an abstract layer and go into detail where the magic happends.

But I wonder how this will be understandable for someone who has never seen our project before. How will this show that I am a better or worse programmer than my next? They are programmers so I guess they will understand the basics and be able to follow the functions and what the code do. But I know that I have trouble with understanding the overall picture of a project, much less in 1-2 hours. Also, I wouldn't know how to decide if it was a good programmer or bad unless I saw some bad code. So my question is:

Is the above idea something to work on? (top > bottom)

Should I concentrate more on algorithms?

Should I try to build a UML diagram or some other visual representation of the project?

Any other ideas?

答:
To be honest if you are applying for a programming position do not be at all worried about how 'technical' you get. If the interviewer does not understand to the same level or a higher level than you despite you knowing your project inside out, you should have their job!

"How will this show that I am a better or worse programmer than my next? "

Your app will speak for itself. If it's an illegible mess, providing the interviewer is NOT of the breed above, then it will appear as an illegible mess.

It might be beneficial to produce a brief UML diagram (and I mean brief). Up to now though this only covers application design. I imagine they are going to want to get dirty and see the actual code. For that reason have source code ready (print out the entire app if you have to or have it handy on a laptop).

ContentLicense: CC BY-SA 2.5


答:
In Floyd-Hoare logic, the most common formal system for reasoning about the correctness of computer programs, there is the while rule.

In words, if you have a guard clause (the expression in brackets in the while()), a variant function (an expression with discrete values that can be shown to decrease monotonically each time the loop runs, and always be positive), and a loop invariant (a logic statement that is always true before and after every time the loop runs), you can prove that the while loop will finish (because the variant function can't keep decreasing) and that eventually the guard clause will be false and the loop invariant be true.

Floyd-Hoare logic doesn't have rules for for loops or whatever constructs actual languages may have.

However, as other answers explain, for loops can always be written in terms of while loops. That means that they can be reasoned about, it just takes a little more work.

If your teacher had courses at university where he had to provide correctness proofs of his programs, he probably wrote programs using only while loops. I know I did. And once you are used to thinking in terms of guards and variant functions and loop invariants, they seem very natural. Overusing while loops is a habit you see with CS graduates, I had to learn to stop doing that in my first months as a professional developer.

Somewhere down the line, your teacher misremembered all this as "good programmers use while loops", whereas what really happens is more like "some CS graduates turn their correctness proof habits into practical programming habits".

Title: provability of while loop vs for loop

Body:
I have this teacher, he's quite smart (sometimes, haha) he said good programmers try to use while loops instead of for loops. the reason he gave for this is because while loops can be proven, as in, one can completely explain what happens in a while loop whereas you can't do that for a for loop. he also said something about NASA programmers only using while loops and not allowed to do for loops because of this.

I have quite a hard time understand this, for both loops one can explain how they work in detail right? for both you would always know what is going to happen?

can someone explain to me why while loops can be proven (And because of it, might be better than for loops, in some cases at least).

EDIT:

maybe he was reffering to:

2: All loops must have a fixed upper bound. It must be trivially possible for a checking tool to statically prove that a preset upper bound on the number of iterations of a loop cannot be exceeded. If the loop-bound cannot be proven statically, the rule is considered violated.

Though this still doesn't say anything about the difference between while and for loops.


问:
Generics in C# Test Class
I'm learning about unit testing in C#. Languages_Service and PlaceOfWork_Service are classes for SOAP services which Microsoft Navision generated for me. There are several methods that are very similar (see the two examples below).

```<code>[TestMethod]
public void Languages()
{
    string serviceUrl = Helper.GetBaseUrl() + "Languages";
    Languages_Service service = new Languages_Service();
    service.Credentials = Helper.GetCredentials();
    service.Url = serviceUrl;
    Languages_Filter[] filter = { new Languages_Filter() };
    service.ReadMultiple(filter, null, 0);
}
[TestMethod]
public void PlaceOfWork()
{
    string serviceUrl = Helper.GetBaseUrl() + "PlaceOfWork";
    PlaceOfWork_Service service = new PlaceOfWork_Service();
    service.Credentials = Helper.GetCredentials();
    service.Url = serviceUrl;
    PlaceOfWork_Filter[] filter = { new PlaceOfWork_Filter() };
    service.ReadMultiple(filter, null, 0);
}
</code>```

Method ReadMultiple of Language_Service looks like so:

```<code>public Languages[] ReadMultiple([System.Xml.Serialization.XmlElementAttribute("filter")] Languages_Filter[] filter, string bookmarkKey, int setSize)
    {
        object[] results = this.Invoke("ReadMultiple", new object[] {
        filter,
        bookmarkKey,
        setSize});
     return ((Languages[])(results[0]));}
</code>```

Method ReadMultiple of PlaceOfWork_Service looks like so:

```<code>public PlaceOfWork[] ReadMultiple([System.Xml.Serialization.XmlElementAttribute("filter")] PlaceOfWork_Filter[] filter, string bookmarkKey, int setSize) {
        object[] results = this.Invoke("ReadMultiple", new object[] {
                    filter,
                    bookmarkKey,
                    setSize});
        return ((PlaceOfWork[])(results[0]));
    }
</code>```

How could one write something like the (pseudo) code below?

```<code>[TestMethod]
public void GunAndSmokeTestAllSerivces()
{
    Dictionary<String, List<Type>> servicesToTest = new Dictionary<String, List<Type>>();
    servicesToTest.Add("Languages", new List<Type>(new Type[] { typeof(Languages_Service), typeof(Languages_Filter) }));
    servicesToTest.Add("PlaceOfWork", new List<Type>(new Type[] { typeof(PlaceOfWork_Service), typeof(PlaceOfWork_Filter) }));
    foreach (KeyValuePair<String, List<Type>> entry in servicesToTest)
    {
        var t1 = entry.Value.ToArray()[0];
        var t2 = entry.Value.ToArray()[1];
        SoapHttpClientProtocol service = (SoapHttpClientProtocol)Activator.CreateInstance(t1);
        service.Credentials = Helper.GetCredentials();
        service.Url = Helper.GetBaseUrl() + entry.Key;
        object[] filter = { (object)Activator.CreateInstance(t2) };
        service.ReadMultiple(filter, null, 0);
    }
}
</code>```

Languages_Service and PlaceOfWork_Service are subclasses of System.Web.Services.Protocols.SoapHttpClientProtocol.

答:
You probably don't want to do exactly what you describe because then you'd have a single test method covering multiple test cases. This isn't great because it means your tests lose granularity, so:-

It becomes unclear when a test fails where exactly the bug may lie, e.g. which `Service.

There's a greater risk of one reason for failure masking another. i.e. there are actually multiple bugs, but because the test fails after the first one, you're not aware of the rest.

A simpler and probably more applicable solution is just to do what you normally do when there's repeated code like this- pull it out into a parameterized method:

```<code>private void Test<TService,TFilter>(string urlSuffix)
    where TService : SoapHttpClientProtocol, new()
    where TFilter : new()
{
    string serviceUrl = Helper.GetBaseUrl() + urlSuffix;
    TService service = new TService();
    service.Credentials = Helper.GetCredentials();
    service.Url = serviceUrl;
    TFilter[] filter = { new TFilter() };
    service.ReadMultiple(filter, null, 0);
}

[TestMethod]
public void PlaceOfWork()
{
    Test<PlaceOfWork_Service,PlaceOfWork_Filter>("PlaceOfWork");
}
</code>```

That's the basic version, just to give you a rough idea. As the comments said this seems incomplete without assertions, and there may be better ways to split this into multiple methods. You should also come up with better names based on your understanding of what exactly these tests are for.

A few issues to take note of:

This won't work out of the box because ReadMultiple isn't a method on SoapHttpClientProtocol. You'll need a superclass or interface with this method, and have that as a constraint on your TService generic parameter.

Likewise, TFilter may need some similar constraint

If the above two prove to be a problem, you could leave your individual test methods in charge of calling that ReadMultiple line, or they could provide an Action<TService,TFilter[]> or similar

If you can't actually keep to that new() constraint, you'll instead want to remove it and have a TService parameter on the method, and leave the individual test in charge of doing the construction.

Title: Generics in C# Test Class

Body:
You probably don't want to do exactly what you describe because then you'd have a single test method covering multiple test cases. This isn't great because it means your tests lose granularity, so:-

It becomes unclear when a test fails where exactly the bug may lie, e.g. which `Service.

There's a greater risk of one reason for failure masking another. i.e. there are actually multiple bugs, but because the test fails after the first one, you're not aware of the rest.

A simpler and probably more applicable solution is just to do what you normally do when there's repeated code like this- pull it out into a parameterized method:

private void Test<TService,TFilter>(string urlSuffix)
    where TService : SoapHttpClientProtocol, new()
    where TFilter : new()
{
    string serviceUrl = Helper.GetBaseUrl() + urlSuffix;
    TService service = new TService();
    service.Credentials = Helper.GetCredentials();
    service.Url = serviceUrl;
    TFilter[] filter = { new TFilter() };
    service.ReadMultiple(filter, null, 0);
}

[TestMethod]
public void PlaceOfWork()
{
    Test<PlaceOfWork_Service,PlaceOfWork_Filter>("PlaceOfWork");
}

That's the basic version, just to give you a rough idea. As the comments said this seems incomplete without assertions, and there may be better ways to split this into multiple methods. You should also come up with better names based on your understanding of what exactly these tests are for.

A few issues to take note of:

This won't work out of the box because ReadMultiple isn't a method on SoapHttpClientProtocol. You'll need a superclass or interface with this method, and have that as a constraint on your TService generic parameter.

Likewise, TFilter may need some similar constraint

If the above two prove to be a problem, you could leave your individual test methods in charge of calling that ReadMultiple line, or they could provide an Action<TService,TFilter[]> or similar

If you can't actually keep to that new() constraint, you'll instead want to remove it and have a TService parameter on the method, and leave the individual test in charge of doing the construction.


问:
Is it a good idea to format the code in eclipse using auto format
I use eclipse for coding, and the language which we use is Java.
Once it was suggested by someone that to properly format the code,
using the auto formatter(CTRL+SHIFT+F)
While this command does format the code, but sometimes I feel that overall
look becomes weird, and it is not actually very readable.

So is this a recommended thing to do?
If not what is the better of formatting our code in eclipse ?

答:
Although I do like having the code formatted automatically on save (in fact I enabled it on my personal projects).  I found that I couldn't fully recommend this practice in project teams using Eclipse based products as the Eclipse formatter has some critical bugs that prevent me from recommending it.

Specifically if you have "code cleanup" + "formatter" enabled the indents get fixed/unfixed on every save.

Each new version of Eclipse may change the formatter (for the better) but would introduce significant changes such as JavaDocs finally removing that extra space after the * but that got introduced sometime after Helios and a lot of enterprises are using the older Rational Software version of eclipse that uses Helios as the base.

The code formatter that is provided by Eclipse is not extensible per their API in fact it explicitly states CodeFormatter javadoc

This class is not intended to be subclassed by clients.

Granted, I haven't found any viable non-commercial alternative as of yet.  Jalopy hasn't been updated for years now and the forks in github are not organized as of yet to make me recommend any of them.  Nor does it have any update site for Eclipse to have it integrated.  I was actually planning to make the code formatting as part of the build much like I did cleanpom-maven-plugin using Jalopy but that idea fell by the wayside due to the lack up updates for Jalopy.


问:
Should I edit a codebase's whitespace to conform to a coding style?
We have a large Java project (1m+ SLOC) with mixed whitespace - some files have tabs and some have spaces.  It's tricky to make my editor work with whichever file I happen to be editing.

We are going to choose a convention and enforce it in future.  The question is whether I should make one commit to correct the whitespace in the whole project after the decision is made.

Git can ignore changes in whitespace, so in future to compare with older revisions we would have to use git diff -w.  However, if and when we update a file in a piecemeal way we would still have to use git diff -w.

For the record, this is an Eclipse RCP project, so using an IDE other than Eclipse is not really sensible.

Edit: There are some good answers here, but they tend to discuss how I should go about this rather than whether this is a good idea or whether I should just leave well alone, which is what I'm really interested in.

答:
What do you mean by "my editor"?  And what do you mean by "git -w"?  Are you using an editor and command line tools instead of an IDE?  May I recommend IntelliJ IDEA?  It is the best java IDE ever, and it has no problem with either kind of whitespace, or even with mixed whitespace within the same file.

Generally, if a massive change has to be made to the code base, like changing the formatting, it should be done all at once and as early as possible.

If you don't do that, then files will keep being committed in the future for no reason other than whitespace changes, unnecessarily bloating the history lists, and forcing you to often request diffs of files only to be told "files differ only in whitespace".

Also, it will never be obvious whether a file was committed due to actual changes or only due to whitespace changes, so if two or more developers happen to have different whitespace and/or formatting settings by mistake, it will take you some time and several commits where one developer is undoing the whitespace changes of another until you realize that this discrepancy exists.

By reformatting and committing everything at once, the revision number of that commit (which will from that day on be known as "The Great Big Reformatting") will be memorized by everyone, so whenever you see that revision number you will know to not even request a diff.

Plus, from that moment on, everyone will know that subsequent commits due to whitespace changes only should not be made, because they are obviously the result of a configuration mismatch between developers.

Amendment

Now, on the question of whether you should convert the entire code base to conform to a particular coding style, this is not an easy thing to answer without knowing the particulars of your situation.  The obvious answer, which anyone out there will tell you, is that a consistent coding style is important, and that even a bad (by whatever standard) but consistent style is better than an inconsistent style. However, there are some practical questions to be asked first:

Do most of the important contributors at your workplace agree?

Are there any contributors who, despite being a minority, might rage-quit if you proceed with this?  And how important are they?

How big of a variety of styles do you have?  Is it only tabs vs. spaces, or does it include other major aspects of coding style like Allman vs. Egyptian braces?  People should be flexible enough to not mind a small variety.

But mostly: Is it really necessary?

I mean, in my current job, each developer is working on a specific, clearly delineated subset of the code base, so I don't delve (much) into other people's code, and nobody delves into my code, so it does not really matter that we have vastly different styles.  It neither picks my pocket nor breaks my leg that a colleague wraps his lines at column 80. (Ssssh, he probably does not know how to change the relevant setting.) The situation would be quite different if we had developers whose job involved frequently dealing with other people's code. If you do have such a situation, and if the coding styles vary so much as to make it hard for them to do their job, then you probably should enforce a single coding style for everyone.  Otherwise, perhaps not.

One more final note:

In theory, it should be possible to resolve this issue with technical means so that a) different developers can work on the same code, and yet b) each developer gets to enjoy whatever coding style he or she prefers. The way this would (in theory) be accomplished would be by having code formatted to your preferred style when updating from the version control system, and re-formatted to the "project style" right before committing.  Unfortunately, as of today, there are no tools that will do this as far as I know.  IntelliJ IDEA gets close by supporting multiple styles, including a "personal style" and a "project style", but it is not fully automated: you still get to browse unmodified code in "project style", if you re-format any files to your "personal style" they will unfortunately appear as modified with respect to the pristine copies, (which is probably a shortcoming of the version control system and not of IDEA,) and the (optional of course) step which re-formats files back to "project style" when committing leaves all of your local copies in "project style" again.  If anyone knows of anything that achieves more than that, please do say.


答:
Before you even start the Big Format, put the proper processes, procedures, and tools in place to ensure consistent formatting in the future. There's no point going through that pain, if the same mess is going to pop up a year from now anyway.

In order to minimize merge hell, coordinate with everybody using the source tree, and set a specific date when the Big Format is taking place, giving everybody a chance to merge their changes back into the mainline. Record and publicize that date, as well as the name/number/hash/whatever of the commit. It would probably be a good idea to tag is as well.

Do not, under any circumstance mix non-formatting and formatting changes.

Use a well-known, well-reviewed, well-tested, well-trusted automated tool (a small sed script, indent, Eclipse's formatting engine, …) to perform the Big Format, and do not do any manual changes to the output of that tool; the output of the tool should be committed as-is, and the commit message should specify the exact name, version, configuration, and command-line (if applicable) for the tool, so that everybody can reproduce the results.

That last point has two advantages:

Being able to reproduce the diff means that you can shift having to trust the diff that nobody was trying to sneak a change into that 1m line diff to having to trust the Eclipse Foundation (for example) that they are not trying to sneak a change into your code via their formatting engine (which is extremely unlikely, and could further be mitigated by using multiple different tools to end up with the same diff, if possible).

Being able to reproduce the diff means that developers on non-mainline branches can perform the "merge" by reproducing the effects of the commit mechanically rather than having to actually merge their changes into the newly formatted mainline code.

Title: Should I edit a codebase's whitespace to conform to a coding style?

Body:
We have a large Java project (1m+ SLOC) with mixed whitespace - some files have tabs and some have spaces.  It's tricky to make my editor work with whichever file I happen to be editing.

We are going to choose a convention and enforce it in future.  The question is whether I should make one commit to correct the whitespace in the whole project after the decision is made.

Git can ignore changes in whitespace, so in future to compare with older revisions we would have to use git diff -w.  However, if and when we update a file in a piecemeal way we would still have to use git diff -w.

For the record, this is an Eclipse RCP project, so using an IDE other than Eclipse is not really sensible.

Edit: There are some good answers here, but they tend to discuss how I should go about this rather than whether this is a good idea or whether I should just leave well alone, which is what I'm really interested in.


答:
Give a general description of the problem you're trying to solve and how you went about it. A diagram of the main pieces and how they interact will be helpful with this type of application. They're buying you and not the application. It may be something they have absolutely no use for, but want to see how well it is constructed.

Once you start showing them your code, they should have a lot of questions and start directing what they want to see. Be prepared to identify areas that have been coded well and those that may be a work in progress. They'll probably ask how long it took to write certain sections of code.

Hope your work looks as good or better than your buddy's ;)

Title: How to explain a project for a potential employer

Body:
I went to an interview last week for a junior programmer and mentioned that I have been working on a project with a buddy of mine. Tomorrow they would like to see this project in order to decide if they should hire me or not. So I was wondering:

What parts of a project are of interest to someone who has not seen the project before?

What could I show that would change their perspective of me as a programmer and what I know?

The project is in C# and have been a hobby project for 6 months now. Without going into to much details:

it's a networked program

it's server / client based where clients end up connecting to each others

there is synchronization of data between clients

we are using files to store information about the different clients, which is also being synchronized

the program in whole is divided into some different projects (some which go into .dll's)

the project will later handle multiple layers of displaying the data to the user (meaning cmd, a window etc..)

I have green lighted this with my buddy as well and it is ok to show. My idea was to show the shell (cmd) that we have which is working and the top layers of the hierarchy, the ones that the shell communicates directly with. These are three classes in particular, one that connects and communicates with the server, one that handles the synchronization and one that handles the objects that are being synchronized. I'll try to go into some details about how we store the objects and how this is communicated to the synchronizer class. Then discuss on a higher level of how we synchronize the data, ending with going into some detail about how this is done.

Basically, start from an abstract layer and go into detail where the magic happends.

But I wonder how this will be understandable for someone who has never seen our project before. How will this show that I am a better or worse programmer than my next? They are programmers so I guess they will understand the basics and be able to follow the functions and what the code do. But I know that I have trouble with understanding the overall picture of a project, much less in 1-2 hours. Also, I wouldn't know how to decide if it was a good programmer or bad unless I saw some bad code. So my question is:

Is the above idea something to work on? (top > bottom)

Should I concentrate more on algorithms?

Should I try to build a UML diagram or some other visual representation of the project?

Any other ideas?


问:
Explanation of how server-side programming languages are accessed
It is my understanding that any general-purpose programming language can be used for server-side development of a website.

Am I right in thinking that a server just needs some kind of interface such as CGI to make the server and the programming language work together? If so then why are some programming languages (such as php) more popular than others?

答:
You can use some HTTP server library, e.g. libonion, even in your program coded in C (or C++, see also Wt). There also some HTTP client library (e.g. libcurl)

You can use other HTTP libraries, e.g. ocsigen & ocamlnet for OCaml.

There are several Web dedicated languages (outside of PHP), e.g. Opa, HOP, Kaya, etc...  (both HOP & Opa can easily mix server-side and browser-side computations, but you have to do that painfully and manually in PHP, explicitly using AJAX techniques and hand-coding some Javascript for the browser. In contrast, HOP, Opa, Ocsigen are able to generate that Javascript).

You can also use FASTCGI technology to add some dynamic service to some web server ... FASTCGI is better than plain old CGI which starts a new process for every incoming HTTP request, while a FASTCGI application can serve many HTTP requests in the same process. BTW, PHP can be configured to work as a FASTCGI application.

C.Queinnec observed that web browsing and continuations are significantly related.

PS. I don't like PHP, and I believe that its popularity has historical and social reasons (not mainly technical ones). Indeed PHP was widespread well before AJAX became widely used, and is older than HOP or Opa (or Ocsigen).


答:
Yes, any general programming language can serve to write the server-side part of a web site.

However, the qualities of a programming language, in this subject as in other things, are usually only one of many factors that contribute to its popularity.

For example, I reckon that PHP became popular for websites because:

It is extremely easy to upgrade from a static website to a PHP dynamic website - simply replace the file extension of your HTML file, place the <?php tag at the beginning, and, provided PHP is installed, you have a dynamic web site! The rest of the workflow is exactly the same as for a static website;

Because of that ease of deployment, web hosts that were looking to propose dynamic web sites chose PHP, making it pretty quickly the most widely deployed server-side platform;

It got into that market at the right time;

And once PHP was widely deployed, it became interesting to write more serious web applications in PHP in order to benefit from that wideness of deployment.

To say it in a more generic way: language adoption is often about the answers to these questions:

How easy is it to do what I want to do?

How widely supported is the language for what I want to do?

Title: Explanation of how server-side programming languages are accessed

Body:
It is my understanding that any general-purpose programming language can be used for server-side development of a website.

Am I right in thinking that a server just needs some kind of interface such as CGI to make the server and the programming language work together? If so then why are some programming languages (such as php) more popular than others?


答:
In the early days of the web, CGI was indeed the only (practical) way to have dynamic content (you could do named pipes of files -- and those were used in days before cgi, but that wasn't practical at all).

CGI works by sticking a bunch of information in the environment of the process that is forked and then exec'ed (and possibly some in stdin) and then takes what comes out of stdout and spits that back to the requestor.

This doesn't care one bit about what the implementation language is. Indeed, I wrote my early CGIs back in the day in C or C++. It was kind of painful. I later learned some perl in the early 90s and that was much less painful.

This works, up to a point. The problem is scale. Each CGI request is a fork and exec of a process. Thousands of requests means thousands of processes. That really doesn't work well.

The solution to this is to remove forking and execing by either moving it into a thread in the web server itself, or dispatching the request to another process that handles the request without needing to fork and exec. mod_perl is one such tool to do this (a plugin moving perl into apache). Php (late 90s) also did this with implementing the language as a plugin in the web server itself rather than something that was forked and exceed.  This became quite popular as it was perl-like (which was the early dominant web programming language) and could outperform perl cgis. There is still quite a bit of momentum from this period of time in the mid-90s -- before the more enterprise-grade application servers started to take hold with more formalized languages behind them.  If you dig around, you can find a lot of failed attempts in the late 90s to early 2000s too -- languages and frameworks that just didn't stick.

This brings us to the application servers where internal threads are spawned (or other approaches -- this isn't the case for everything) to handle requests rather than entire new processes -- which can help with scale. As an external process this could be seen with FastCGI and then later became prevalent with other application servers. Note that with this the line between application server and web server got a bit blurry -- many application servers could double as web servers, though weren't optimized for handling static file IO in the way that traditional web servers are.

The generic application server has also paved the way to solutions where instead of a generic application server, you have the application itself either running an embedded web server or otherwise being the entire deployment. In such situations one doesn't deploy a web application on an application server - it just is running itself and handling requests.  Again, the goal of this model is to avoid the heavy price of launching new instances of the application and instead handle the requests inside the application with much lighter weight threads or similar approaches.

Here's the thing though -- all the solutions are deficient in some way, shape, or form. CGI, while easy has serious problems with scale.  Plugins in the web servers get bound into the web server itself (apache vs nginx vs IIS vs ...) and lose the common functionality of the language. Microsoft has its own parade of technologies it would like to promote. And if you know one language, wouldn't you rather keep programming in it rather than have different languages in different parts of the stack (javascript in the client and Node.js)?

And so, you've got today. Some people work in a Java stack (with scala and clojure becoming not uncommon). Others in a C# stack. Others in a JavaScript stack. There's quite a bit of php stacks out there. Lots of python. You can still find some perl stacks out there (and if you look at some low volume sites, you'll still find CGIs). With cloud computing, Google has also promoted Go as a viable server side web language.

Each has its advantages, disadvantages, its frameworks and its servers. The relative popularity of these ebbs and flows as technologies around them change. They do different things well.


问:
Partitioning REST API resources into areas based on business domains
In a major application REST API that covers several related domains, does it make more sense to split resources into 'areas' based on the business domain they belong to or is it better to to maintain a single model?

For example, there are 'Sales' and 'Inventory' sub-domains. Users of the system typically only care about one domain at a time, but exceptions are possible.
There is an 'Item' concept that exists in both domains so we could implement the 'item' resource in two different ways.

have different resources to represent the concept in each domain, each resource holding only the relevant data:

/sales/items/:id

/inventory/items/:id

have a single resource with all the data to be used in all contexts:

/items/:id

There are also plenty of resources that only belong to one of the domains.

pros of 'areas'

easier to understand the API for users who only care about a single domain

easier to implement resources (less stuff to read/update at a time)

resources can be more specialized/optimized for each particular domain

ability to control access to resources at more granular level

pros of a single unified model

no duplicated resources for concepts that belong to more than one domain

if a user needs to work with multiple domains, he will only have to use a single API that covers all his needs

Is API partitioning as described above a valid way to reduce complexity of both API contract and implementation? I haven't seen it mentioned much anywhere.

Are there any more things that need to be considered to make a decision in favor of either approach?

答:
I think the rule of thumb should be the following.

If an item itself is unthinkable without being related to sales or inventory, you should go for option 1.

If an item can exist without any relation to sales/inventory or this relation is not really strong in your architecture, you could go for option 2.


答:
Am I right in thinking that a server just needs some kind of interface
  such as CGI to make the server and the programming language work
  together?

Almost. You need a web server that has some kind of software to allow it to respond to HTTP requests as well.

Think about how a static page is served.  The server retrieves the HTTP request, finds the requested document from the filesystem based on the HTTP server's configuration, and returns the static page.

CGI extends this concept by allowing you to designate a cgi-bin folder on the filesystem where executables or scripts can be stored.  When you access a program via CGI, the HTTP server runs the process or script and passes the standard output back to the client rather than simply serving up the static document.

```<code> If so then why are some programming languages (such as php) more popular than others?
</code>```

The old CGI structure does not scale well over a large volume of requests.  Different programming languages and frameworks for the web exist for different reasons, and each one does different things well.  PHP is as popular as it is for historical reasons, as it was one of the first easy and cheap solutions for serving dynamic pages without resorting to CGI and had widespread hosting support.  ASP was popular among Microsoft circles because it allowed VB developers to shift their skills to the web.  ASP.NET (Web Forms) made it very easy for Windows Forms developers, many of whom were VB coders, to switch over to the web.

Body:
Am I right in thinking that a server just needs some kind of interface
  such as CGI to make the server and the programming language work
  together?

Almost. You need a web server that has some kind of software to allow it to respond to HTTP requests as well.

Think about how a static page is served.  The server retrieves the HTTP request, finds the requested document from the filesystem based on the HTTP server's configuration, and returns the static page.

CGI extends this concept by allowing you to designate a cgi-bin folder on the filesystem where executables or scripts can be stored.  When you access a program via CGI, the HTTP server runs the process or script and passes the standard output back to the client rather than simply serving up the static document.

 If so then why are some programming languages (such as php) more popular than others?

The old CGI structure does not scale well over a large volume of requests.  Different programming languages and frameworks for the web exist for different reasons, and each one does different things well.  PHP is as popular as it is for historical reasons, as it was one of the first easy and cheap solutions for serving dynamic pages without resorting to CGI and had widespread hosting support.  ASP was popular among Microsoft circles because it allowed VB developers to shift their skills to the web.  ASP.NET (Web Forms) made it very easy for Windows Forms developers, many of whom were VB coders, to switch over to the web.


问:
What do you do when you have to work on a project using a language that you hate?
I've recently been assigned to work on a project written in PHP. I can't change that, and have no intention of really trying.

However, this can't be an uncommon scenario. How do you motivate yourself to work on the project when the code you're looking at and producing constantly makes you want to cry?

EDIT:

It should be noted that this is pretty much the only on-campus job doing anything software related available at the moment, so "just change jobs" isn't really an option :(

答: How long is the project? If is it short just grin and bear it and think if it as good resume filler. If long term I would look for another job. </p>


问:
How/when to "build" a Singleton that stores configuration data
I am a junior developer (think "intern-level" experience) working at a small shop more or less alone on a project that consumes data from a database, processes it, and inserts the results into another database. The solution is a Windows service written in C#.

A previous version of the solution used App.config for things like connection strings, time intervals for checking the db for new data, etc. The project manager wants for this information to be stored in a table in the db, and then have a singleton keep that data rather than needing to access the config file. The configuration data needs to be loaded at startup.

My current implementation has the singleton's constructor make a single call to getConfig(), a method that encapsulates the work of getting all the data from the db. We are now in the process of writing code that will check the db at startup to make sure those configuration tables are there and will build them if they aren't.

I have several uncertainties about the design:

1) Is building the config in the constructor the best place so the work is implicit:

```<code>protected override void OnStart(string[] args)
{
    // The first call for an instance, so the object is created & data is loaded
    ConfigSingleton MyConfig = ConfigSingleton.GetInstance;

    // Create object that checks db for data to process; relies on config
    Poller = new Poller();
    Poller.Start();
}
</code>```

or should I make an explicit public call to getConfig() during startup for the sake of clarity:

```<code>protected override void OnStart(string[] args)
{
    ConfigSingleton MyConfig = ConfigSingleton.GetInstance;
    MyConfig.getConfig(); // Explicit call to get config from db

    // Create object that checks db for data to process; relies on config
    Poller = new Poller();
    Poller.Start();
}
</code>```

2) Should the work to check for the config tables be done by a separate, presumably static, class:

```<code>protected override void OnStart(string[] args)
{
    if (!DBChecker.isTableReady())
    {
        DBChecker.BuildTables();
    }

    ConfigSingleton MyConfig = ConfigSingleton.GetInstance;
    MyConfig.getConfig();

    // Create object that checks db for data to process; relies on config
    Poller = new Poller();
    Poller.Start();
}
</code>```

or should it be handled internally by the configuration singleton, so the code would look like one of the variations above?

A somewhat unrelated example that helps clarify the spirit of my question comes from a previous version of the solution (which I've paraphrased):

```<code>// Inside this function, a call is made to BusinessLayer.GetList1()
MyController = new Controller(FirstParam);
MyController.Start();

// Yet here, a similar version is called first and then the result is passed as a parameter
List<Objects> MyList2 = BusinessLayer.GetList2();
MySender = new Sender(SecondParam, MyList2);
MySender.Start();
</code>```

Are there basic rules of thumb that govern when work should be done inside some other work, or outside, passed as parameter, etc, other than the obvious fact that it should at least be consistent?

答:
I actually just solved this issue.  I wanted to store configuration data in the database while having the program consume the data.  I created a configuration retrieval class (non singleton) that when ever a part of the program needed a configuration value they instantiated the class and called the GetConfigValue(ConfigPropertyEnum item) method.  Behind the class was a cache that was only accessed from the configuration retrieval class and a Repository class for interfacing with the database (using Entity Framework).

When I first implemented the configuration retrieval class it was just accessing the database through the repository any time a config value was needed so that I could start writing the rest of the program.  After I had validated that the general design would work I implemented the cache with a way to time out cache values so that periodically I would reload an item from the database in case things changed.

This structure got me a loosely coupled configuration.  Since the rest of the program does not care how the configuration retrieval class got the value, I can swap out the actual data store from config file to database and back with out any code changes except in the configuration retrieval class.  Also since I have an interface I can swap out my cache implementation with out having to change the rest of the program as long as the interface remains the same.

Overall it has provided a robust and extendable config class.  When I want to add a new configuration variable I can add to the enum and table and have the value available any where in the program.

As to how to get configuration values to other parts of your program?  I tend to like dependency injection with my classes taking an instance of IConfiguration so I can use different implementations if I am testing.

ContentLicense: CC BY-SA 4.0


答:
No, wait until a decision is made.

Before the reformat I suggest to create a Eclipse formatting profile and distribute it to all developers and start using it. Make Eclipse use the save action to format automatically with every file save.

Then do a complete reformat and commit it as a single refactoring.

The code is now consistent and will remain that way.

But add some analysis tool to the build to check for correct formatting. This to catch mistakes.


答:
There's one big piece of the puzzle you're missing: response time.  Even if the load were light and manageable by one server, and I can't really comment on whether it is or not, you'd have potential latency issues from having Uber in the US served by a single server residing in Australia or Belarus.

If you look at news reports of Uber going down, you'll notice that Uber tends to go down regionally with rare global outages.  My thought would thus be that Uber relies on cloud-based or perhaps managed hosting solutions in regional data centers across areas where they do business.  It's also possible that they have required pieces of the application sitting locally with some very core functionality hosted out of a single data center.  That doesn't even begin to touch on details of storage or SANs, database clusters, CDNs, etc.

With cloud-based hosting becoming more prevalent, the idea of something running on n number of servers becomes less relevant while  ideas like request volume and compute time become more relevant.  Look at the pricing models for services like Amazon EC2.  Billing is expressed in hours of compute time, not quantity of infrastructure.

Title: Can a the kind of load Uber handles be served from just one server?

Body:
http://techcrunch.com/2013/12/04/leaked-uber-numbers-which-weve-confirmed-point-to-over-1b-gross-revenue-213m-revenue/

This article says that Uber does about 1M requests a week. Which is about 1.65 reqs a sec.

So does this mean Uber can probably do with just one machine serving their requests? Or am I missing something here?

I realize traffic will be bursty but still doesn't seem like they'd need too many servers even at max load.

Edit: Let's assume we're building a bare bones version of uber where you don't do the realtime GPS locations of drivers & you don't have georeplication.

Say, the app has only this functionality: open the app, and order a cab. The phone triangulates your location and sends a request to the server who then responds with whether a driver was found or not


问:
Does dealing with legacy code help one evolve as a programmer?
I'm a Java developer with a bit more than a year of experience which places me somewhere above a junior, but not among mid-level developers yet. Recently I was offered a long-term project which is about studying an existing banking application code for 4 months and then introducing changes when needed. As a not-so-experienced programmer I'm looking for ways to develop and I wonder what such a project might give.

Would you consider dealing with a big and probably not-so-well written application a good practice for a beginner?

答:
Legacy can mean anything but based on your 'not so well written' comment I'm going to assume that Legacy means 'bad' or at least 'out of date' technologies and patterns. If the legacy code is good, do not hold back and learn every line of it.

I don't think there are clear enough warnings against the kind of jobs and projects that divert your career and get you stuck in valueless sink holes on this thread to date.

Sports analogy alert: Do you think a line backer in the NFL learns more and becomes more valuable by playing on the team with the worst record or the best? My answer: Not only are they more valuable having played for the best teams, but they probably picked up best practices and knowledge and avoided picking up career ending practices and attitudes.

There is a lot of terrible anti pattern code out there that actually works for the business and pays a lot of dev salaries. I propose that a developer that hasn't seen enough code done the 'right' way might mistake anti pattern code for a legitimate solution to a problem. The business may say that the solution works, but it's not one you want on your resume or one that you would brag about to other developers. This is also only relevant if your personal growth path includes gaining the respect of your engineering peers and not just temporarily increasing the income of whatever company you work for (Sounds bad, but in the end, the best engineering absolutely makes the most money IMO).

Unfortunately there is a lot of code and a lot of time that can pass before tech debt is revealed. And that tech debt is usually recognized exactly when it is too late. Whomever may have tried to stop tech debt or anti patterns before,  could have been sidelined because of the perceived extra expense or lack of understanding of scalability ect. It is our duty as engineers to expose tech debt right away. Projects without experienced engineers are in jeopardy of hitting a brick wall at some point, actually all projects even with talented devs. Most businesses view 'some point' as plenty of time to fix it later. This makes job choices for up and coming developers a very complicated matter. It also points out the entirely different goals and mindsets between developers and businesses and how complicated it is to bridge the gap.

It is the goal of engineers to 'include' real scientific work and design consideration while it is the goal of business to 'exclude' unnecessary cost and time. Since engineers often don't know what the level of effort and time is until the end state is actually done, software development plays out like any good drama with characters like agile, scrum, and kanban playing leading roles.

One take away might be to stay away from bad code until you have seen enough good code to not be 'corrupted'. I love the saying that senior developers create simple solutions to complex problems. Like wise, junior mid level developers create complex solutions for simple and complex problems.

Another take away could be that you need to work on good AND bad code at different points in order to gain understanding. If you have done neither then go for it and be prepared to unlearn it all when you come across a better system. I think this is probably a more common trajectory for most developers.

I'm biased this year because I'm feeling like I'm climbing an extremely complicated 'secret sauce' mountain. While I will increase my ability to decipher some of the worst patterns I have ever seen, it is so 'custom' and 'one off' that I don't believe my struggle will increase my marketability or my usable skill set in my future.

In order to keep my sanity, I'm just chugging along at a steady pace and embracing every road block as par for the course. Having just reviewed my yearly goals with my boss that include digging out of this legacy hole, I'm kind of thinking it might be a sacrificial climb. I could survive the process with bad reviews and perceived slowness. This is a realistic and foreboding warning to those of you wondering what job to take.

Disclaimer: This post will live much longer than my opinions so take it with a grain of salt. Tomorrow I might love legacy code! (Doubt it).


问:
Why is a architecture with anemic models the JavaEE standard?
I took a JavaEE course today and I was presented to the "default" JavaEE architecture, which consists mainly of Entities, Services and DTOs.
The guy presenting the course explained that it was indeed a case of anemic models, but however this was the "in facto standard JavaEE architecture".

I am new to JavaEE, but I've head some experience with other languages. The first time I read about beans as components, I thought they would be great to create a DDD-like architecture.

It sounds strange to me that a "standard architecture" has a anemic domain (I, until now, thought it was a "bad smell").

Is there any technical reason or big advantage of using this architecture? Why an architecture that defines its models to be anemic is the current standard?

I asked him and he talked about transaction context, but I have to admit I didn't understood exactly what he meant.

答:
Typically you domain objects would cross layers and also process boundaries. So your Domain objects which are typically POJOs are essentially the contract between layers and processes. Contracts should define the expected structure of inputs, outputs (and exceptions) not the business logic. This is true weather you are writing enterprise code or otherwise.

Keeping the domains light weight and bare-bones ensures that the conversion (serializations in various forms) takes place easily. Here is an example - your domain gets spitted out by Jersy Clients as a JSON object - now if you object has a lot of BL and dependencies - the conversion or serialization to JSON will be complicated and unwanted knowledge will be passed on to the client which only cares for the data.

That is not to say your objects have to be dumb! If you can reduce redundancy in the object by providing one field with some additional getter methods for convenience by all means go ahead and do it - example if you have unit cost and quantity fields in your POJO but for display you typically need the total price go ahead and add it as a getter without introducing a new fields (redundant) - make sure you provide no setter method for it only getter. this kind of border lines with BL but it isn't if the role of your services is a lot more involved than computing price.


答:
Really? You do what you do when you HAVE to work on ANYTHING you hate. You grit your teeth, dig in and get the job done.

..or you learn to be a little more easy going!

Title: What do you do when you have to work on a project using a language that you hate?

Body:
I've recently been assigned to work on a project written in PHP. I can't change that, and have no intention of really trying.

However, this can't be an uncommon scenario. How do you motivate yourself to work on the project when the code you're looking at and producing constantly makes you want to cry?

EDIT:

It should be noted that this is pretty much the only on-campus job doing anything software related available at the moment, so "just change jobs" isn't really an option :(


答:
Yes, fixing all the existing files immediately before starting to enforce whitespace rules for new commits is a good idea.  If you have mixed whitespace, there is no such thing as "leaving well enough alone". Your codebase is not well.

If you do not fix it, it becomes nearly impossible to enforce a 'whitespace only' vs 'code change only' policy.  And that means

Small extraneous diffs every time a minor edit is made to an old file.

Large whitespace changes in random feature commits, whenever someone gets  frustrated enough to fix the file they are working in.

Just do it.


问:
Explanation of two of Lehman's Laws of Software Evolution
I have a hard time understanding #3 and #8 of Lehman's Laws of Software Evolution.

The laws are:

(1974) "Self Regulation" — E-type system evolution processes are self-regulating with the distribution of product and process measures close to normal

and

(1996) "Feedback System" (first stated 1974, formalised as law 1996) — E-type evolution processes constitute multi-level, multi-loop, multi-agent feedback systems and must be treated as such to achieve significant improvement over any reasonable base

The rest of the laws are clear to me.

Could someone explain these two laws?

答:
Not sure about law 3 yet, but here's my take on law 8:

Law 8 would be a perfect example of a successful agile project. The system is adapted to the changing requirements of users, product owners and other stakeholders. By using the system, users find out what they really want to do with the system. Product owners and management prioritize new features according to a changing environment and the team discovers better ways of doing things by gaining domain knowledge and experience. That sounds a lot like a multi-level, multi-loop, multi-agent feedback system.


答: If I'm building something that someone wants with a language that I feel is capable of delivering the project without too many problems, I can get over it. What worries me is when they want functionality that may not be possible/practical or it takes longer than normal. </p>


问:
Advantages of having numeric data types as classes rather than primitives
I was wondering about why some languages choose to implement numeric types (boolean, integers, floats, characters etc.) as classes/objects (eg. Kotlin) and some as primitive types (eg. Java). I am specifically considering interpreted languages rather than compiled languages.

Below are the differences that I was able to come up with:

As a class:

The type could then be extended, so that new classes could be treated as numeric types as well (i.e. being applicable to arithmetic operators).

No need for wrapper classes, as the type's relevant functionality could be encapsulated within the numeric type's class itself.

As a primitive:

Less memory usage, as only the primive's value would be stored,
rather than the extra bulk needed for an object.

What could any other reasons be?

Edit: This is not a duplicate of this question, as this question is purely about language-design, rather than what should be chosen for a specific practical and real-world problem.

答:
One of the most important characteristics that make a programming language efficient is the closeness of the supported data types to the native data types of the underlying hardware.  An int primitive directly corresponds to a machine word; it does not get any better than that.  The moment you turn the int primitive into an Integer object you have degraded performance of integer operations by an order of magnitude.

Now, modern applications are mostly GUIs which don't do much other than sitting waiting for user input, so in many cases efficiency does not really matter, and ease of use considerations take precedence.

It is very useful and it keeps many things simple to be able to treat numeric types as objects because then you can apply uniform operations on them without having to write special code for each one of them separately.

For example, by implementing the Comparable interface, Integer objects know how to compare themselves against other Integer objects, and Double objects know how to compare themselves against other Double objects, so essentially the quicksort routine and the binary search routine only need to be implemented once, to simply work with any kind of comparable object.

That having been said, let me repeat that if you write an application that has any number-crunching whatsoever to do, primitives are definitely the way to go.

Also it might be worth noting that one of the most beautiful things about C# is that it has managed to achieve the best of both worlds in this respect: it has structs, which are value types that map (perhaps not perfectly, but fairly well) to native machine types, and at the same time are capable of implementing interfaces the way objects do.


问:
Is embedding URLs as query parameters in URLs an acceptable REST API design pattern?
We are designing some resource oriented web services.

Service B needs to be able to make calls to Service A passing in a reference to a resource in service B that service A will use when formulating it's response. Maybe service A already has some knowledge about service B's resource from a previous interaction.

e.g.

```<code>GET http://serviceA.com/resource/123?widget=http://serviceB.com/widget/456
</code>```

(obviously the query parameter 'widget' would need to be appropriately encoded)

I see very few examples of this kind of thing in practice. You sometimes see it on the web e.g. an example would be redirect URIs in Google OAuth (https://developers.google.com/identity/protocols/OAuth2WebServer#formingtheurl)

It seems like it's more common to build in some knowledge of service B's resources into service A so you would instead make a call like:

```<code>GET http://serviceA.com/resource/123?widget=456
</code>```

This this seems to break resource oriented design principles.

Is embedding URLs as query parameters an appropriate design approach or are there issues with it?

Clearly it could lead to issues with URL length with any user agents that have limitations on URL length.  And it looks kind of ugly.  But other than are there other downsides? Why isn't it used more?  Or maybe it is?  Is it because most REST based API designs are not truly RESTful (resource oriented) - which isn't to say they are bad either (http://www.intridea.com/blog/2010/4/29/rest-isnt-what-you-think-it-is)

答:
This, to my mind, depends on the way you use the URL parameters. Passing URLs as actual data you have to manipulate is fine.

Imagine a REST service to handle Web bookmarks. Let's assume it associates some metadata with bookmarks (e.g. date added, icon, etc). By the REST canon a request that asks for such data for a particular bookmark will be a GET request and will have to pass the bookmark's URL as parameter.

On the other hand, it's probably not a good idea to use URL-carrying parameters to control other aspects. E.g. I can't expect to see something like &redirect=http://... among parameters of a well-designed REST API. (Please note that OAuth is not a REST API at all.)


问:
How do I make a JavaScript promise return something other than a promise?
I have a spec from a client for an implementation of a method in a module:

```<code> // getGenres():
 //  Returns a promise. When it resolves, it returns an array.
</code>```

If given an array of genres,

```<code>['comedy', 'drama', 'action']
</code>```

Here is a skeleton method with a promise:

```<code>MovieLibrary.getGenres = function() {
  var promise = new Promise(function(resolve, reject) {
    /* missing implementation */
  });

  return promise;
};
</code>```

Can the promise be made to return the data found in the genres? Is there a better way to achieve the spec description?

答:
It sounds like you aren't understanding how promises are used.  You return a promise.  Then, later when your code resolves the promise, it resolves it with a result and that result is passed to the .then() handler attached to the promise:

```<code>MovieLibrary.getGenres = function() {
  var promise = new Promise(function(resolve, reject) {
    /* missing implementation */
    resolve(result);
  });

  return promise;
};

MovieLibrary.getGenres().then(function(result) {
    // you can access the result from the promise here
});
</code>```

Body:
It sounds like you aren't understanding how promises are used.  You return a promise.  Then, later when your code resolves the promise, it resolves it with a result and that result is passed to the .then() handler attached to the promise:

MovieLibrary.getGenres = function() {
  var promise = new Promise(function(resolve, reject) {
    /* missing implementation */
    resolve(result);
  });

  return promise;
};

MovieLibrary.getGenres().then(function(result) {
    // you can access the result from the promise here
});


问:
What's the worst question you were ever asked at interview?
It doesn't have to be programming or software development related, but just asked during an interview for an IT related job.

I know some "left field" questions are meant to see how the candidate copes with unexpected and novel situations, but here I'm looking for a question that appeared to be completely unrelated to the job they were interviewing you for, or something that made you think "what useful information could they possibly get from my answer to that question?".

答:
Having been on both sides of the table on this one, the reaction to the odd and stereotypically lame questions can be more informative than the "good" ones.

The worst of that sort I was ever asked was if I would take a doughnut.

They had one on a plate on the table, but it was sitting in front of an empty chair next to the 4th coffee cup on the table (only three interviewers) giving the appearance that it was a 4th person's doughnut.  The job dealt with a fair number of uncomfortable situations and they wanted to see how gracefully the interviewee could deal with it.

The one I later asked as an interviewer was to go 3rd in a team interview, and when it was my turn to ask I would put one of those aluminum briefcases that movies always show cash in on the table and ask the interviewee to name something inside. I actually carried the briefcase regularly so there was mostly normal things inside, but in dozens of interviews I only ever got two good answers: "air" which is almost impossible to be wrong, and "pencil" which we actually had to look to see because I couldn't remember (their wasn't).  The point of this one was to see how quickly the person could deal with the random context change and how logically they approached the issue.

The point is that sometimes the answer itself doesn't matter in the least, the interviewer is interested in how you handle yourself or how you arrive at the answer.


答:
I am a freelance developer and I think I lately have found the ideal way to "talk" to customers: BPMN.

Generally after the requirements gathering I model their whole business process and add my $0.02 with what I intend to implement. In a second session to clear up doubts I present the BPMN process (and subprocesses) and open with: "this is your business process, it is modeled with a specialized notation called Business Process Modelling Notation, it is like a flow-chart but here are only two symbols you must know, circles are events (stuff that happens instantly) and squares are tasks (stuff that takes time)".

And I totally have them there; then I start explaining them how I understood it and how it will reflect in the implementation, and what are the future possibilities, and then the magic happens: customers are totally engaged in a proactive discussion.

If you ask me why I'd tell you that this way you can show the client/employer that you actually understood the problem, and where you didn't, he/she will have an actual opportunity to know how to tell you why, where and what is missing.

Try http://www.bizagi.com/ as a BPMN editor, its free and the diagrams just look gorgeous. The tool actually explains you BPMN on the fly (mouse-over the pallette). Tip: make a general process and use "Reusable SubProcesses" in it, so that each reusable subprocess refers each other diagram you create. When you finish, export in HTML, it just looks awesome.

Remember, BPMN is meant to describe mainly business logic, not program logic (e.g. don't diagram "ifs" and "loops" if they are not relevant to the business logic), and this makes possible to show only the relevant parts of the problem and how your software solves it.

Give it a try, and good luck.

P.S.: Check the wikipedia page on BPMN.


问:
Dynamic Programming Problem - To find smallest integer number 'x' which contains only digits 1's and 0's such that x mod n = 0
To design an algorithm that will output the smallest integer number 'x' which contains only digits 1's and 0's such that x mod n = 0 and x > 0.....
For example:

2   divides 10

3   divides 111

4   divides 100

5   divides 10

6   divides 1110

7   divides 1001
and so on.

The 1's and 0's are in base 10 representation.

I know that we can solve this using the pigeon hole principle but in this problem we are interested in the smallest number.

I was thinking of using a DP approach similar to a subset sum problem where the set contains 1, 10, 100, 1000 and so on. I am not completely clear about how to formulate the recurrence relation for this problem. Can someone give some insight?

答:
Dynamic programming is much better than brute force plus a few heuristics.

Try to determine the minimum number of digits so that some 0-1 integer is a mod n.

For example, you could make a dictionary whose keys will be integers mod n, and whose values are the least number of digits so that there is some 0-1 integer equal to the key mod n. Start with (0,0). For each k, compute 10^(k-1) mod n, and go through every key a to see whether b=a+10^(k-1) mod n is a key yet. If not, add (b,k) to the dictionary. If b is 0, then we have found the number of digits needed.

Once you have the number of digits needed for each reduction of a number with at most k digits, you can determine the least number recursively. If you reach a mod n with k digits, then the least 0-1 number congruent to a mod n is 10^(k-1) plus the least 0-1 number congruent to a-10^(k-1) mod n.

This takes O(n^2) time, since for each k, you generate at least one new congruence class mod n while adding 10^(k-1) to at most n old congruence classes. Perhaps there is some memoization that would speed up the cases where a small number of congruence classes are generated at a time, such as when a small power of 10 is 1 mod n.


答:
This seems to me to be a straightforward case of the Granovetter introduction operator as applied by the client in a request - the resource receiving the request needs no prior knowledge of the specific external resource referenced (only that it have compatible behavior), and so long as the external resource being referenced is treated as a subject or object of the request you haven't departed from RESTful style.

Here Alice is the client, Bob is the resource receiving the request, and Carol is the external resource referenced in the request.  Bob has no prior specific knowledge of Carol as evidenced by the lack of an edge connecting them.  foo is simply the default metasyntactic variable for an arbitrary message.

Title: Is embedding URLs as query parameters in URLs an acceptable REST API design pattern?

Body:
We are designing some resource oriented web services.

Service B needs to be able to make calls to Service A passing in a reference to a resource in service B that service A will use when formulating it's response. Maybe service A already has some knowledge about service B's resource from a previous interaction.

e.g.

```<code>GET http://serviceA.com/resource/123?widget=http://serviceB.com/widget/456
</code>```

(obviously the query parameter 'widget' would need to be appropriately encoded)

I see very few examples of this kind of thing in practice. You sometimes see it on the web e.g. an example would be redirect URIs in Google OAuth (https://developers.google.com/identity/protocols/OAuth2WebServer#formingtheurl)

It seems like it's more common to build in some knowledge of service B's resources into service A so you would instead make a call like:

```<code>GET http://serviceA.com/resource/123?widget=456
</code>```

This this seems to break resource oriented design principles.

Is embedding URLs as query parameters an appropriate design approach or are there issues with it?

Clearly it could lead to issues with URL length with any user agents that have limitations on URL length.  And it looks kind of ugly.  But other than are there other downsides? Why isn't it used more?  Or maybe it is?  Is it because most REST based API designs are not truly RESTful (resource oriented) - which isn't to say they are bad either (http://www.intridea.com/blog/2010/4/29/rest-isnt-what-you-think-it-is)


问:
Why have many programmers moved to using exception handling for input or output?
Why have many programmers moved to using exception handling for input or output? For these programmers, what is the motivation behind this decision?</p>

答:
Because input and output are unreliable.

Exceptions are, in part, an acknowledgement that there are going to be conditions which the software cannot reasonably recover from.

Premature end-of-line termination, syntax error or any number of validation error conditions,

Inputs are too long or large to reasonably accomodate,

Keyboard gets unplugged,

Hard disk runs out of space, etc.

Exceptions are the programmer's way of saying "I can't continue under the present conditions."  In essence, when you throw an exception, you're giving up and asking for a do-over.

You can do this without gracefully exiting your input/output subroutine or even worrying about memory management, because the orderly disposal of the relevant objects is already built into the exception-handling mechanism.

You can control where in your code the exception gets handled without elaborate if structures, intricate state mechanisms or call tree tracking.