答:
Arguing with your bosses is much easier when you have some numbers, or at least some pros and cons at hand, so my suggestion is trying to make a cost vs. benfit analysis. The rough idea goes like this:

how much development effort do you expect for writing a device simulator? (Note that a device simulator cannot replace the original hardware 100%, especially when the hardware has some unexpected quirks).

how much testing / debugging effort do you expect without such a tool? Include the costs for your lab workers because you have to block the hardware for testing purposes. Include also the costs for the time the system cannot be used because of bugs and you have trouble to find the root cause.

how much will additional hardware for testing cost?

how much time do you expect you will need blocking the hardware for testing purposes?

Of course, reality might not be so simple, and there are a lot of unknown variable in this equation, but try to make some estimations and where you are unsure, ask other people from your environment.

Present the results to your management, discuss the alternatives and then let them decide.


问:
Upcoming Google interview, looking for some preparation advice
Well I've been hitting the books wherever I can. I have an interview coming up, first one via phone, for a software engineer position. I've read all the blog posts, I've read all the accounts of interviews (some pretty old), and Google itself even suggested a reading list of books, none of which would surprise anyone here. Still, after some time preparing, I can't shake that feeling that there is such a large ground to cover, and I'm never sure whether to go with depth or breadth. I've found myself re-learning a whole area of compsci, only to forget most of the nitty details as I move on to another.

So, I don't know that there's a good answer to this question, but I'm looking for any practical advice on how to tackle the remaining weeks in advance of the interview. Part of my brain is tired from cramming, and of course the rest of it has to be utilized for some tough problems at my current place of employment.

答:
Things you should know

Google wants to hire you!

The life-blood of any software company is its employees and Google is no different. It's looking to hire the best and the brightest and the people conducting the interview(s) want you to succede just as much as you do.

Google will do it's best to evaluate you as accurately as possible. It's their job.

Google is a data-driven company. Hiring decisions are not decided by manager fiat. Instead, each interviewer takes extensive notes during the interview which gets combined into a packet. That packet will then get reviewed by a separate committee, which will ultimately make the decision. So if you just weren't 'gelling' with one of your interviewers don't worry! What matters is how well you perform on the interview.

Skills you should have

Be sure to brush up on the following skills/techniques before your interview. Even if you don't get asked a question on these directly, reviewing them can certainly get your head into the right mindset.

Data structures

What is the difference between an Array and a Linked List? A Tree and a Graph? When would you use one over the other? How would that impact speed/memory tradeoffs?

An interview question doesn't end at a working solution. Be able to explain the runtime of your approach and what sorts of trade offs you could make. For example, "if I cached everything it would take X gigs of RAM but would perform faster because...". Or, "if I kept the binary tree sorted while I performed the operations X would be slower, Y would be faster, etc."

Algorithms

Basic graph traversal algorithms, tree traversal algorithms, and two good approaches for sorting numbers.

Make sure to practice solving a non-trivial problem using Dynamic Programming. That is your ace in the hole when it comes to tough interview questions!

Hash tables

This is huge. Know everything there is to know about hash tables, from being able to implement one yourself, to knowing about hashing functions, to why the number of buckets should be a prime number. The concepts involved with hash tables are relevant to just about every area of Computer Science.

Talking points about yourself

That first few minutes of chit-chat with the interviewer is an important time to explain any sort of experience which sets you apart. Relevant projects, significant technical accomplishments, and the like. Remember, the person conducting the interview has interviewed dozens if not hundreds of smart people just like you.  So what can you say that would surprise them?

For example, in an interview I spoke to the interviewer about a program I wrote to play the game of Go in college. It is very difficult to write an AI for the game of Go, and I have a horrible Go-bot to prove it! The bottom line is be yourself, and not just some smart person who knows how to program.

Don't stress out too much, it's just an interview like any other. Rest assured that nobody will ask you stupid questions about manhole covers or Mt. Fuji.

ContentLicense: CC BY-SA 2.5


问:
How to efficiently troubleshoot or test new code when hardware setup to reproduce bugs is difficult or impossible to obtain?
I work at a mid-sized company (150ish employees, ~10 size engineering team), and most of my projects involve interfacing with lab equipment (oscilloscopes, optical spectrum analyzers, etc) for the purpose of semi-automated test applications.  I have run into a few different scenarios where I am unable to efficiently troubleshoot or test new code because I no longer or never had the hardware setup available to me.

Example 1: A setup where 10-20 "burn-in" processes are run independently using a bench top type sensor - I was able to obtain one such sensor for testing and could occasionally steal a second for simulating all of the facets of interfacing to multiple devices (searching, connecting, streaming, etc).

Eventually a bug showed up (and ultimately ended up being in the device firmware & drivers) that was very difficult to reproduce accurately with only one unit, but hit near "show stopper" levels when 10-20 of these devices were in use simultaneously.  This is still unsolved and is ongoing.

Example 2: A test requiring an expensive optical spectrum analyzer as its core component.  The device is pretty old, legacy according to the manufacturer who was acquired by a larger company and basically dissolved, and its only documentation was a long winded (and uninformative) document that seems poorly translated.  During initial development I was able to keep the device at my desk, but now its tied up, both physically and in schedule during its 24/7 multi-week tests.

When bugs show up related or unrelated to the device, I often need to go through the trouble of testing code external to the application and fitting it in, or writing code blindly and attempting to squeeze in some testing time in between runs, as much of the program logic requires the OSA and the rest of the test hardware to be in place.

I guess my question is how should I approach this? I could potentially spend time developing device simulators, but figuring that into the development estimate will balloon it more than most would probably appreciate.  It may not accurately reproduce all issues either, and it's pretty rare to see the same equipment used twice around here.  I could get better at unit testing...etc...I could also be loud about the issue and make others understand that temporary delays will be required, not much more than a headache for Research and Development but usually a perceived as a joke when pitched to manufacturing.

答:
Management understands it will take longer to develop and maintain software when you don't have full access to test hardware.  You need to take this into account when doing your estimates.  Part of the acceptance criteria for putting your software into production should be that you have a way to maintain the software under most circumstances without stopping manufacturing.  If you're practicing TDD, this should happen pretty much naturally.

I used to write software for $60 million aircraft.  Obviously, there's a high degree of reliability required, and they are reluctant to give every developer one for their desk.  We basically had 5 levels of test environments, with more of the real hardware at each level, up to a full aircraft.  I estimate 95% of our software could be developed and debugged only with emulators and unit tests.  95% of the remaining features could be worked on the next level up, and so on.

Try to set up similar levels of test environments for yourself.  You can't expect to never need access to the real hardware, but if you've set it up so you can't work on your software's GUI without the hardware available, you're wasting valuable time on an expensive resource (not to mention you have some coupling issues with your architecture).  Consider that other developers likely have the same issues as you.  I would ask the hardware vendor if they already have emulators or other test resources available.

You also need to change your mindset somewhat if you only have limited access to hardware.  Rather than trying to debug your application in the normal serial manner, you often need to write code specifically for the purpose of gathering information as quickly as possible.

For example, perhaps you have a bug and you can think of 10 possible causes.  If the only time you can get on a machine is the 15 minutes while the operator is on break, write a Short, Self Contained, Correct (Compilable), Example that triggers the bug and write 10 automated tests using that SSCCE to test your theories and log a bunch of data.  Afterward back at your desk you can take as long as you need to sift through the data for your next attempt.  The idea is to maximize the utility of your limited time with the hardware.

ContentLicense: CC BY-SA 3.0


问:
Should I assert in packages?
I have read a few asserts vs exception questions already; I ask specifically about package visible classes though.

When you write a package, the classes marked with "public" are exposed to the outside world, thus exceptions are used to let users of the package's interface know they're using the package wrong.

The classes that are left unmarked are only exposed to the internals of the package, no?  So I'm inclined to say that when something goes awry in a package visible class, assertions would be used stop the classes I have built from sending one another bad data.

Is this a fine thing to do?

I have adopted the idea that objects hold their own data as private to them and methods are public/private as needed to work internally or with other classes.  Once the class is identified as doing too much, the class is split into simpler objects meant to work together.

At this point, many classes exist, but only some should be exposed to the outside world.  So I have reached the conclusion that packages are like super objects, exposing just enough so that the entire "community" of classes can work together to solve the problem.  This way implementation is hidden but a service is still provided.

Is that understanding correct?  That is what the question is based on, since the community of classes is created in a "private to the package" manner, it is not exposed to the outside, and so, should assertions be used instead?

答:
That is what the question is based on, since the community of classes is created in a "private to the package" manner, it is not exposed to the outside, and so, should assertions be used instead?

No.  While it's true that assertions should not be part of your public contract, that doesn't mean that all non-public contracts should be enforced through assertions!

Assertions are not (solely) a matter of visibility.  They are a different type of mechanism, used to signal a different type of problem.

Assertions signal logic errors inherent to the code.  They are checkpoints that a programmer introduces to catch bugs early, and triggering them means that a program is no longer operating normally or predictably.  Exceptions cover usage errors and unforeseen circumstances that may arise during otherwise normal execution of a program.

Here is an example that clarifies this.  It's part of an implementation of java.util.Iterator:

```<code>public Object next() {
    if ( !hasNext() ) {
        // usage error: there is no next object
        throw new NoSuchElementException();
    }

    // logic error: hasNext() says okay, but there is no next element!
    assert next != null : "hasNext() but not found!";
    Object retval = next;
    next = null;
    return retval;
}
</code>```

Another example that could be in a public implementation of java.util.Set:

```<code>public boolean add(Object o) {
    if ( o == null ) throw new IllegalArgumentException("does not accept null");

    added = // adding magic here

    // either it was added, or it was already in: either way, must contain now
    assert contains(o) : "added but does not contain?";
    return added;
}
</code>```

Both asserts are in public methods of classes that could likewise be public.  But their presence is basically there to assure me, the programmer, that my assumptions/assertions about the code that I wrote are valid.  If users of my code see AssertionErrors, that means my code has a problem.

The following are bad examples of assertions:

```<code>public boolean add(Object o) {
    // disabling asserts makes the code below possibly take nulls
    assert o != null : "does not accept null";
}

public Object next() {
    // this is a usage error
    assert hasNext();
}
</code>```

Title: Should I assert in packages?

Body:
That is what the question is based on, since the community of classes is created in a "private to the package" manner, it is not exposed to the outside, and so, should assertions be used instead?

No.  While it's true that assertions should not be part of your public contract, that doesn't mean that all non-public contracts should be enforced through assertions!

Assertions are not (solely) a matter of visibility.  They are a different type of mechanism, used to signal a different type of problem.

Assertions signal logic errors inherent to the code.  They are checkpoints that a programmer introduces to catch bugs early, and triggering them means that a program is no longer operating normally or predictably.  Exceptions cover usage errors and unforeseen circumstances that may arise during otherwise normal execution of a program.

Here is an example that clarifies this.  It's part of an implementation of java.util.Iterator:

public Object next() {
    if ( !hasNext() ) {
        // usage error: there is no next object
        throw new NoSuchElementException();
    }

    // logic error: hasNext() says okay, but there is no next element!
    assert next != null : "hasNext() but not found!";
    Object retval = next;
    next = null;
    return retval;
}

Another example that could be in a public implementation of java.util.Set:

public boolean add(Object o) {
    if ( o == null ) throw new IllegalArgumentException("does not accept null");

    added = // adding magic here

    // either it was added, or it was already in: either way, must contain now
    assert contains(o) : "added but does not contain?";
    return added;
}

Both asserts are in public methods of classes that could likewise be public.  But their presence is basically there to assure me, the programmer, that my assumptions/assertions about the code that I wrote are valid.  If users of my code see AssertionErrors, that means my code has a problem.

The following are bad examples of assertions:

public boolean add(Object o) {
    // disabling asserts makes the code below possibly take nulls
    assert o != null : "does not accept null";
}

public Object next() {
    // this is a usage error
    assert hasNext();
}


问:
Javascript based application controller in Javascript-less environments
I just got done watching an informative Box tech talk by Nicholas Zakas on a javascript architecture for web development:

https://www.youtube.com/watch?v=mKouqShWI4o&feature=youtu.be

This image, which I acquired from http://alanlindsay.me/kerneljs/index.html#nav-what , will give you an overview of the architecture:

However, to give you a brief summary and help you avoid mundane stuff, the Kernel is basically an Application Controller which makes up the C in the MVC.

Now I obviously have to take care of the possibility of an environment where Javascript is disabled. I was wondering if that effectively meant developing an application controller in a language such as PHP and maintaining it in parallel to the one written in Javascript along with the ensuing commands/modules? There's something smelly about that, is there a better way to do this?

答:
If you have to account for browsers with JavaScript disabled, then you don't want a Web Application. Instead, you want a classic client-server web site with some JavaScript usability enhancements. Forget MVC on the client, and go with the normal GET/POST HTTP life cycle. After that, use some unobtrusive JavaScript to AJAX-ify portions of the page that just POST back to the server, which returns some HTML that JavaScript plunks into a
.

If business really wants something so complex in the browser it requires an MVC architecture on the front end, then you need to tell them that JavaScript is required.

If your main reason for having a server side fallback is because of accessibility concerns, check out the Accessible Rich Internet Applications Spec at the W3C. A List Apart has a recent article with a good introduction to this.

Body:
If you have to account for browsers with JavaScript disabled, then you don't want a Web Application. Instead, you want a classic client-server web site with some JavaScript usability enhancements. Forget MVC on the client, and go with the normal GET/POST HTTP life cycle. After that, use some unobtrusive JavaScript to AJAX-ify portions of the page that just POST back to the server, which returns some HTML that JavaScript plunks into a <div>.

If business really wants something so complex in the browser it requires an MVC architecture on the front end, then you need to tell them that JavaScript is required.

If your main reason for having a server side fallback is because of accessibility concerns, check out the Accessible Rich Internet Applications Spec at the W3C. A List Apart has a recent article with a good introduction to this.


问:
Help me catch up on what I've missed since Java 1.4.2
I am about to start my first professional career position as a software developer, and I'm likely going to be writing a lot of Java code.  I don't know that much about what specifically I'll be writing, and besides, I have fairly broad interests when it comes to code anyway.

For reasons not worth discussing, my last internship had me coding only for the Java 1.3 and 1.4 SDK's.  Also, my university education has focused mainly on algorithms, data structures, and other theory, not language features or libraries.

So, with the above in mind, what features, classes, etc. in the current version of Java (what number are we on now, anyway?) would be worth my time to read up on and why?  What have I missed since 1.4.2 that makes your life as a programmer easier?

Examples and stories of how you discovered a particular package or some such and put it to use would also be great.

答:
The single most important change in your day to day programming life is the introduction of generics which will most likely be used in every new module you will be asked to write, and it is a confusing new syntax.

Generics is the mechanism allowing e.g. a List to contain strings instead of naked objects, where the compiler enforces that an item to be put into the the list is a String, and it knows that when you get an item out of a list it is a String.

This makes for better programs as you avoid the explicit runtime cast to the target type (which is a frequent source of errors if you get it wrong) and the IDE can help you doing all the dirty work as it knows much more about your code than it did when it was just list of objects.

Joshua Bloch has written a good introduction to Generics, which is available as the sample chapter at http://java.sun.com/docs/books/effective/


问:
Direct database manipulation an anti-pattern?
Recently I learned that some teams have moved all their database manipulation to the actual database through the use of stored procedures. I thought that was pretty clever, since the database becomes a black box and any change to how the data is stored and manipulated won't affect application code. Is it accurate to conclude that manipulating the database in application code is an anti-pattern, since it unnecessarily couples application and storage code, or are there circumstances that would make decoupling sql queries from the application a disadvantage?</p>

答:
Using the approach of requiring 100% of the database interaction to be done through stored procedures is actually a bad idea, I would say. The database should be for storing "data" (among the usual CRUD functionality and ACID properties), not for storing procedures to encapsulate the entire database. A few reasons why this is a bad idea include:

slow tests (assuming you are writing tests)

possibly harder to test (assuming you are writing tests)

potentially large effort required if switching DBMSs, or in other words perhaps being tied to a single DBMS vendor

effort or even possibility of switching to some non-SQL-based vendor or mechanism to store data

However, you should also consider how "likely" or not that the above things may happen during the lifecycle of your project when making your decision.


答:
The answer to this question is "It Depends".

If the stored procedures aren't doing anything fancier than UPDATE, INSERT, DELETE or SELECT with no special logic around them, then using Stored Procedures is an Anti Pattern because most ORMs will do this for you.

If you have half a dozen applications written in several different languages saving data to a particular table, and each application duplicates some business logic around the INSERTs and UPDATEs, then not using stored procedures is an anti pattern.

The general rule I use is Don't Repeat Yourself. If there is common business logic that multiple applications must use, and those applications cannot use shared libraries or using shared libraries becomes a maintenance headache, then by all means use a Stored Procedure.

If the Stored Procedure is not doing anything more than an ORM would do, then a Stored Procedure is like hitting a thumbtack with a sledge hammer. You are creating more work for the Programmer than is necessary.

Title: Direct database manipulation an anti-pattern?

Body: Recently I learned that some teams have moved all their database manipulation to the actual database through the use of stored procedures. I thought that was pretty clever, since the database becomes a black box and any change to how the data is stored and manipulated won't affect application code. Is it accurate to conclude that manipulating the database in application code is an anti-pattern, since it unnecessarily couples application and storage code, or are there circumstances that would make decoupling sql queries from the application a disadvantage?</p>


问:
Correct way to inject dependencies in Business logic service?
Currently the structure of my application is as below
Web App --> WCF Service (just a facade) --> Business Logic Services --> Repository -> Entity Framework Datacontext

Now each of my Business logic service is dependent on more than 5 repositories ( I have interfaces defined for all the repos) and I am doing a Constructor injection right now(poor mans DI instead of using a proper IOC as it was determined that it would be a overkill for our project). Repositories have references to EF datacontexts. Now some of the methods in the Business logic service require only one of the 5 repositories, so If I need to call that method I would end up instantiating a Service which will instatiate all 5 repositories which is a waste. An example:

```<code>public class SomeService : ISomeService
{
   public(IFirstRepository repo1, ISecondRepository repo2, IThirdRepository repo3)
   {}

   // My DoSomething method depends only on repo1 and doesn't use repo2 and repo3
   public DoSomething()
   {
        //uses repo1 to do some stuff, doesn't use repo2 and repo3
   }

   public DoSomething2()
   {
     //uses repo2 and repo3 to do something, doesn't require repo1
   }

   public DoSomething3()
   {
     //uses repo3 to do something, doesn't require repo1 and repo2
   }
}
</code>```

Now if my I have to use DoSomething method on SomeService I end up creating both IFirstRepository,ISecondRepository and IThirdRepository but using only IFirstRepository, now this is bugging me, I can seem to accept that I am un-necessarily creating repositories and not using them.

Is this a correct design? Are there any better alternatives? Should I be looking at Lazy instantiation Lazy<T> ?

答:
ISP states:

no client should be forced to depend on methods it does not use

Although you are using all the methods from the 5 repositories, you are probably using them in different contexts and probably from different instances of the service (it's hard to figure out the usage scenario from the generic code sample you provided).

Also, your services seem to be doing more than one thing and should be broken down into smaller components (having 4 or more dependencies is often an indication of breaking SRP).

Advice: you should give DI a try. It's definitely not an overkill and you'll have some benefits out of it.


问:
When should you use Local Classes in Java?
I learned about local classes on the Oracle Java Tutorial page. Not nested classes.

I don't see myself using local classes. It makes the code look messy and you can easily do what local classes do with having a class declared separately.

But maybe I'm missing some use cases for it. Are there situations where you would prefer using local classes over other approaches or are local classes just an antiquated feature no one really uses?

答:
Local classes are just a way to encapsulate some state and behavior locally.

But I think you're right; if it's worth doing, it's worth doing in a way that is reusable, and that means public classes, not local ones. Local classes seem to me to be a bit of a code smell because they are indicative of an outer class definition that is too broad; that is, it is being asked to do too much.


答:
Autoboxing is a nice feature introduced with Java 5. Just like in C# the compiler now makes an automatic conversion between the primitive (basic) types and their corresponding object wrapper classes (int to Integer etc) and back again. That makes working with Java Collections much less pain.

For-each looping was new in Java 5, too, I think. It makes iterating over arrays (and collections) easier, because it eliminates much of the usual clutter involving the setup and management of an index variable or iterators. At example:

```<code>void myMethod(Collection<myObjectType> c) {
    for (myObjectType o : c)
        o.foo();
}
</code>```

Title: Help me catch up on what I've missed since Java 1.4.2

Body:
I am about to start my first professional career position as a software developer, and I'm likely going to be writing a lot of Java code.  I don't know that much about what specifically I'll be writing, and besides, I have fairly broad interests when it comes to code anyway.

For reasons not worth discussing, my last internship had me coding only for the Java 1.3 and 1.4 SDK's.  Also, my university education has focused mainly on algorithms, data structures, and other theory, not language features or libraries.

So, with the above in mind, what features, classes, etc. in the current version of Java (what number are we on now, anyway?) would be worth my time to read up on and why?  What have I missed since 1.4.2 that makes your life as a programmer easier?

Examples and stories of how you discovered a particular package or some such and put it to use would also be great.

Body:
Autoboxing is a nice feature introduced with Java 5. Just like in C# the compiler now makes an automatic conversion between the primitive (basic) types and their corresponding object wrapper classes (int to Integer etc) and back again. That makes working with Java Collections much less pain.

For-each looping was new in Java 5, too, I think. It makes iterating over arrays (and collections) easier, because it eliminates much of the usual clutter involving the setup and management of an index variable or iterators. At example:

void myMethod(Collection<myObjectType> c) {
    for (myObjectType o : c)
        o.foo();
}


问:
I am making 4-5x more story points than average, but producing bugs at half the rate. Graphs say it's 2x more bugs, how to deal with that?
So it is generally accepted that top tier programmers can produce an order of magnitude more/better code than their more average peers.

It's also generally accepted that the rate of errors made in code is relatively constant for programmers.

Instead, it tends to be impacted by the processes used when writing the code and after the code is written. (As I understand it) Humans tend to make mistakes at a fairly constant rate - better programmers just notice more of them and are quicker to fix them.

Note that both of above assertions come from Code Complete by Steve McConnell - so it's not a matter of differing perspectives.

So I've started to see this recently in my code. I can hammer out about 4-5x the amount of code as many of my peers (measured by story points estimated by the team), with higher quality (based on performance metrics and number of changes made after check-in). But I still make mistakes. Between better unit tests, a better understanding of what the code is doing, and a better eye for issues when doing code reviews I'm not producing 4-5x the number of bugs.

But I'm still producing about twice as many bugs found by QA as other developers on my team. As you might imagine, this causes some problems with non-technical folks doing metric measurements (read: my boss).

I've tried to point out that I'm producing bugs at half the rate of my peers (and fix twice as many), but it's a hard sell when there's graphs saying I produce twice as many bugs.

So, how to deal with the fact that increased productivity will lead to an increased number of bugs?

答:
You should tell your boss that the metrics he is using is quite flawed.  If you take a look at turnovers by guards in the NBA, you will find that they tend to have higher numbers than forwards.  But, that is because they are handling the ball more.  If a non-starting guard plays 1/5 as much as a starting guard and turns the ball over 3 times on average .vs. a starting guard that turns the ball over 7 times per game - at first glance it might look like the starting guard is worse.  But, if you divide the number of turnovers by the number of minutes played, then clearly the starting guard has much better numbers based upon minutes played.

Likewise, you have much better numbers if the number of bugs is divided by the number of story points completed.  So, that is what I would propose to your manager.  Change the metric to be the number of bugs divided by story points completed, or at least add a new metric for this if the total number of bugs per developer is needed.  But, since some story points are much harder and more complex than other story points, there can and will be quite a bit of variance and this needs to be taken into account by the manager as well.

What I don't think you should do is to slow down.


问:
Strategies to manage multiple clients able to simultaneously edit same data
How can I deal with situations when multiple clients might edit same object at the same time?

For example, I have a web app with admin console, which lets you edit profile data. Several users want to open the same profile and edit it.

If I just let the things go as they do, I`ll get "the last who saves wins" situation and all the other users will lose their changes.

Blocking object for edit on client, when someone enters edit page, seems relatively easy and overall acceptable for simple objects. However, for complex objects, when different users may want to change different parts of object, merging would be much better. I've read a paper on Conflict-free Replicated Data Types and it seems to be pretty complex and does not cover conflict situations.

Are there any other ways to merge objects? Or maybe there are totally different strategies to deal with the situation?

答:
There is a technique that can be employed to handle this.  There are some assumptions first.  You (or your team) must to be in control of all software that can update the data.  Based upon this, here is what you can do:

Do not lock the data upon original download and while the user is editing it.  The reason for this is because locks in general are very bad for performance - for example what happens if a user decides to take a break while an exclusive lock is held?

When the user tries to save the data, then acquire an exclusive lock and download the data again.  Compare the original downloaded data with the data just downloaded.  If the data includes a timestamp for the last update, then just compare the timestamps.  You might consider adding a last-update timestamp column for this purpose.  If the data is the same, which indicates that no intervening updates have taken place, then update the database and release the lock.  If the data is not the same, then release the lock and show the updated data and prompt the user to enter his updates again.  You can save his original updates in another tab or window to make this easier.  Another possibility is to have the software do a merge and highlight any conflicts.


答:
I can think of one use case for local classes - creating a structure for an object that will be returned to a mechanism that uses reflection to access it. I don't know though if anyone uses it for this purpose...

For example, lets say you have an AJAX web framework. The server side has a routing mechanism that routes a requests to Java methods, and those methods should return objects that the mechanism will convert to some serialization format(XML/JSON/whatever) and send back to the client.

The client does not need the Java class, because it runs JavaScript and only care about the class's bean structure. The framework doesn't need that class either not at compile time anyways. The only place that class will be used is the method that creates an object of it and returns it to the framework's routing system.

Now, you can't use anonymous classes for this because you won't be able to populate their properties(unless you use an ugly hack and create a single method that sets all the properties and return this as Object...), but if you use a local class it can have a constructor and setter properties you can call more than once.

Like you said, you could also use separate class definitions for this, and I know the widely preached dogma says that class declarations should be placed in the most visible and accessible place possible, but I'm gonna risk being burned at the stake and claim that not every single piece of code needs to be widely reusable!

There are disadvantages to code reuse. One of them is that you can't change reusable code easily, because you don't know where else it's being used. A large portion of the design patterns that run around are dedicated to solve this disadvantage, but sometimes it's just not worth it, and it's better to simply limit the code to a be only usable in a single point so you could easily change it when you need to.

For example, let's say method foo returns to our framework a Result object that has 3 fields - a, b and c. Another method, bar, also needs to return those 3 fields, and since you don't want to copy 28 lines of code ((1 line of for declaration + 3 lines for setter + 3 lines for getter) * 3 fields + 2 lines for the class + 5 lines for constructor = 28 lines of code. Java is that freaking verbose...) you use Result in bar.

Now, what if you want to return from foo another field - d? You can't just add it to Result, because bar uses Result as well and you can't just have it returning a d, because bar doesn't return d, and there might be other methods that use Result for other things. So, you apply the open-close principle and subclass Result into Result2 that adds the d field.

Repeat 10 times, and you get a weird hierarchy of classes used solely to create data objects that will be handled by reflection...

Wouldn't it be better if each method had it's own Result local class that you could alter freely because it's local and there is no risk other methods will use it?

Title: When should you use Local Classes in Java?

Body:
I learned about local classes on the Oracle Java Tutorial page. Not nested classes.

I don't see myself using local classes. It makes the code look messy and you can easily do what local classes do with having a class declared separately.

But maybe I'm missing some use cases for it. Are there situations where you would prefer using local classes over other approaches or are local classes just an antiquated feature no one really uses?


答:
Change your objective from producing the most code to helping the company move forward the most.

Since it seems you have many colleagues plus extra time available, the most effect you can have on a quicker delivery of features and bug fixes is to help your colleagues.

Help your colleagues by

using code reviews to improve code quality and education.

creating process automation to make their work faster and their lives easier.

writing better tests with them

attacking technical code to improving the code base

being the go-to guy that is always available to help others.

writing / improving tools that help with developer productivity

making the case with management for better tools /equipment / working conditions for your co-workers if you have more clout.

preparing for and leading educational sessions on writing better code.

practising humility

Title: I am making 4-5x more story points than average, but producing bugs at half the rate. Graphs say it's 2x more bugs, how to deal with that?

Body:
So it is generally accepted that top tier programmers can produce an order of magnitude more/better code than their more average peers.

It's also generally accepted that the rate of errors made in code is relatively constant for programmers.

Instead, it tends to be impacted by the processes used when writing the code and after the code is written. (As I understand it) Humans tend to make mistakes at a fairly constant rate - better programmers just notice more of them and are quicker to fix them.

Note that both of above assertions come from Code Complete by Steve McConnell - so it's not a matter of differing perspectives.

So I've started to see this recently in my code. I can hammer out about 4-5x the amount of code as many of my peers (measured by story points estimated by the team), with higher quality (based on performance metrics and number of changes made after check-in). But I still make mistakes. Between better unit tests, a better understanding of what the code is doing, and a better eye for issues when doing code reviews I'm not producing 4-5x the number of bugs.

But I'm still producing about twice as many bugs found by QA as other developers on my team. As you might imagine, this causes some problems with non-technical folks doing metric measurements (read: my boss).

I've tried to point out that I'm producing bugs at half the rate of my peers (and fix twice as many), but it's a hard sell when there's graphs saying I produce twice as many bugs.

So, how to deal with the fact that increased productivity will lead to an increased number of bugs?


问:
Is there a difference in resource allocation & efficiency between a web app and a compiled one?
I'm a web developer. I feel like I develop less resource-intensive functionality often times, because I have this feeling that if I ask too much of the web app (animation, calculation, connections, etc), it will get lagged for users with slower computers.

I've been curious for a while now about just how much difference there is in the capability (resource allocation) of a web (interpreted) app vs a compiled one.

Also, I've heard that interpreted (JS, for example) programs are very inefficient and resource-hungry in comparison to compiled ones (C++, for example). Google's V8 JS Engine is said to make JS  faster, but I still see people talk about JS being much less efficient than C++.

The reason that I ask this question is to separate fact from biased opinion.

Is there a difference in available CPU & RAM between a web app and a compiled one?

Is there a large efficiency difference between a program written in (an interpreted language) JS versus one written in (a compiled language) C++?

Edit: I realize that we are comparing apples and oranges here. There are some really well-defined aspects of choosing between C++ (anything compiled) and JavaScript (web) when developing a client application, and this is one side aspect of that decision that I would not want to be misinformed about if it were to come up at any point in my career.

答:
The current crop of Javascript interpreters are very, very fast as interpreters go.
Not many "good" benchmarks available this one seems to be the least dubious -javascript vs C++ showing Javascript taking only twice as long as C++ on the same compute intensive benchmark compared which is astonishingly good for an interpreted language.

While nothing will beat well coded C as far as performance goes the down sides are enormous:-

much longer development cycles

poor built in text handling

no built in "collections" (C++ has boost/templates etc.)

build (and often code changes) required for each platform supported.

you need to distribute and install before you can run

you need to support old versions forever or find some way of forcing users to upgrade

you app will run natively inviting a whole raft of security issues


答:
Is there a difference in available CPU & RAM between a web app and a compiled one?

You web app is running in the context of the browser and it's extensions, the browser requires some memory and CPU cycles for its housekeeping chores. That memory and those cycles are therefore unavailable to your application. On a fully loaded desktop the fraction of the CPU cycles or memory needed for browser housekeeping is tiny relative to the available cycles and memory. On a low-end smart phone it may have a more significant impact.

Is there a large efficiency difference between a program written in (an interpreted language) JS versus one written in (a compiled language) C++?

A program running in a JavaScript interpreter or in some other VM is going to have some overhead that a compiled language is not going to have. In some cases this overhead is significant, in other cases it may allow for optimizations that actually make the interpreted program faster than the compiled program. It depends on what problem you are trying to solve.

Ask yourself these questions:

Do I needed unconstrained access to the machine's hardware?

Do I need to replace functionality of the OS's or the language's runtime libraries
with custom behavior of my own design? For example, do I need to turn off the standard memory allocation system and implement my own?

Am I running a computation so involved that it will be difficult to complete it in a timely fashion without using every last jot and title of the system's capacity? Think about Bitcoin mining, protein folding simulations, or real-time process control.

If you answer yes to any of these questions you may need to use assembly, C, C++, or some other system programming language.

Some tasks, say rendering streaming video, are computationally very complex, but everybody needs them, so the C and C++ programmers writing the browser wrapped them as libraries that get invoked by HTML5 or JavaScript. It's no less efficient to call these libraries from JavaScript or via an HTML5 tag than it is from a C++ program.

Computers don't get bored or tired, so it doesn't make sense to worry about efficiency for its own sake. It only becomes a concern when it becomes so inefficient that the performance constraints of your program can't be met. Back in 1987 just putting up a few windows, buttons, and scalable fonts required almost every cycle a CPU could provide, so compiled languages were the only game in town. Nowadays, if the main job of your program is to interact with a human dragging windows and clicking buttons, your computer is going to spend most of its time twiddling its figurative thumbs, and other concerns, like development time, become more important.

Title: Is there a difference in resource allocation & efficiency between a web app and a compiled one?

Body:
I'm a web developer. I feel like I develop less resource-intensive functionality often times, because I have this feeling that if I ask too much of the web app (animation, calculation, connections, etc), it will get lagged for users with slower computers.

I've been curious for a while now about just how much difference there is in the capability (resource allocation) of a web (interpreted) app vs a compiled one.

Also, I've heard that interpreted (JS, for example) programs are very inefficient and resource-hungry in comparison to compiled ones (C++, for example). Google's V8 JS Engine is said to make JS  faster, but I still see people talk about JS being much less efficient than C++.

The reason that I ask this question is to separate fact from biased opinion.

Is there a difference in available CPU & RAM between a web app and a compiled one?

Is there a large efficiency difference between a program written in (an interpreted language) JS versus one written in (a compiled language) C++?

Edit: I realize that we are comparing apples and oranges here. There are some really well-defined aspects of choosing between C++ (anything compiled) and JavaScript (web) when developing a client application, and this is one side aspect of that decision that I would not want to be misinformed about if it were to come up at any point in my career.


问:
license and copyright assignment
I'm currently working on a wordpress plugin. My client gives me a specs doc (a powerpoint presentation, if you can call that a specs doc), and I code the requested functionality.

Every time I send him code every file containing code starts with these lines:

```<code>Author: My Name
Copyright: The_client's_company.com
License: MIT Expat (http://en.wikipedia.org/wiki/Expat_License)
</code>```

My intention being giving my client complete right to relicense and distribute the code under any other license (as the TOS of the freelancing website requires, plus I know he intends to sell it under a proprietary license), but at the same time giving myself the right to expand and redistribute the plugin under MIT license if I wish to (not that I do).

The reason is I am paid only 10USD/hour (this is my first gig) so I want to at least keep the right to reuse parts of the code in other projects or expand it if I want to start a similar project myself when I finish the contract (unlikely, but who knows...) or show it to potential employers. The contract we agreed upon doesn't include any licensing specifications but I've informed him on the emails we've interchanged that although all my work is licensed by default as MIT I'm giving my clients the copyright of the code I produce so they can relicense it at will before distribution.

Is this the correct way of achieving that?

答:
Your license that you provide to your clients should specify their redistribution rights; that is, it should specify:

Whether they can redistribute,

How they can redistribute (via source and/or binary copies),

Whether or not they can be compelled to provide source code, and

Whether they must license any changes they make to the code.

You don't need to assign copyright to do this.

Generally, redistribution means that the client provides the program and/or code to a third party, meaning someone outside of their organization.

Title: license and copyright assignment


问:
When calling for a random integer from 1-6, how can I make it gradually get less likely to pick a number the bigger it is?
Like having 1 be the most common number and 6 be the least common number. And everything else just leveling out.</p>

答:
You could set up an array of say 42 integers with numbers :

```<code> 1,1,1,1,1,1,1,1,1,1,1,1,2,2,2,2,2,2,2,2,2,2,3,3,3,3,3,3,3,3,4,4,4,4,4,4,5,5,5,5,6,6
</code>```

You then get a true random number between 0 and 41 and the appropriate number from the array.

In the above setup a 1 is 6 times more likely to occur than a 6, and twice as likely as a three. You can play with the contents of the array to get the distribution you require.

Body:
You could set up an array of say 42 integers with numbers :

 1,1,1,1,1,1,1,1,1,1,1,1,2,2,2,2,2,2,2,2,2,2,3,3,3,3,3,3,3,3,4,4,4,4,4,4,5,5,5,5,6,6

You then get a true random number between 0 and 41 and the appropriate number from the array.

In the above setup a 1 is 6 times more likely to occur than a 6, and twice as likely as a three. You can play with the contents of the array to get the distribution you require.


答: If you have spent the last couple of months at careercup you can afford to relax. What happens at that moment in the interview can not be planned but better be relaxed and have the energy to last the rounds.</p>

Title: Upcoming Google interview, looking for some preparation advice

Body:
Well I've been hitting the books wherever I can. I have an interview coming up, first one via phone, for a software engineer position. I've read all the blog posts, I've read all the accounts of interviews (some pretty old), and Google itself even suggested a reading list of books, none of which would surprise anyone here. Still, after some time preparing, I can't shake that feeling that there is such a large ground to cover, and I'm never sure whether to go with depth or breadth. I've found myself re-learning a whole area of compsci, only to forget most of the nitty details as I move on to another.

So, I don't know that there's a good answer to this question, but I'm looking for any practical advice on how to tackle the remaining weeks in advance of the interview. Part of my brain is tired from cramming, and of course the rest of it has to be utilized for some tough problems at my current place of employment.


问:
Should I follow the normal path or fail early?
From the Code Complete book comes the following quote:

"Put the normal case after the if rather than after the else"

Which means that exceptions/deviations from the standard path should be put in the else case.

But The Pragmatic Programmer teaches us to "crash early" (p. 120).

Which rule should I follow?

答:
"Crash early" is not about which line of code comes earlier textually. It tells you to detect errors in the earliest possible step of processing, so that you don't inadvertently make decisions and computations based on already faulty state.

In an if/else construct, only one of the blocks is executed, so neither can be said to constitute an "earlier" or "later" step. How to order them is therefore a question of readability, and "fail early" doesn't enter into the decision.


答:
You should follow both of them.

The "Crash early"/fail early advice means that you should test your inputs for possible errors as soon as possible.

For example, if your method accepts a size or count that is supposed to be positive (> 0), then the fail early advice means that you test for that condition right at the beginning of your method rather than waiting for the algorithm to produce nonsense results.

The advice for putting the normal case first means that if you test for a condition, then the most likely path should come first. This helps in performance (as the branch prediction of the processor will be right more often) and readability, because you don't have to skip over blocks of code when trying to figure out what the function is doing in the normal case.

This advice doesn't really apply when you test for a precondition and immediately bail out (by using asserts or if (!precondition) throw constructs), because there is no error handling to skip while reading the code.

Title: Should I follow the normal path or fail early?

Body:
From the Code Complete book comes the following quote:

"Put the normal case after the if rather than after the else"

Which means that exceptions/deviations from the standard path should be put in the else case.

But The Pragmatic Programmer teaches us to "crash early" (p. 120).

Which rule should I follow?


答: Another approach could be to apply some function to the random numbers. This works nicely for floating point random numbers, which usually come between 0 and 1 subjected to functions like square(x) or square_root(x), which distort the distribution while staying within the original interval.

Title: When calling for a random integer from 1-6, how can I make it gradually get less likely to pick a number the bigger it is?

Body: Like having 1 be the most common number and 6 be the least common number. And everything else just leveling out.</p>


问:
Java Singleton fields implementation
I have singleton in Java and I have realized, that I could make its fields static and it would work same way as regular instance fields.

Would there be a performance / optimization difference? If so, what would turned out better? Is there a preferred way to implement singleton fields? (again, I am talking fields, not methods)

答:
Keep in mind that static does not mean unique in the entire application. It is just unique for the classloader. If you are working with multiple classloaders in an application server for example there will be multiple values for the same field.

Instead of the static approach you should take a look into dependency injection which would give you what you need without the problems of singletons and static attributes.

Title: Java Singleton fields implementation


答:
What you're looking for is Fitness proportionate selection.

The way to imagine this is to visualise a game where we spin a wheel to win prizes.

The best prizes have smaller segments (and are less likely to be won) and the rubbish prizes have huge segments (and are more likely to be won).

Here's how I would implement this:

Assign (or calculate) the likelihood of each of your items occurring.

```<code>1 60%
2 30%
3 4%
4 3%
5 2%
6 1%
</code>```

We'll turn these into decimals because this will be easier to work with now.  The only important thing is that these values add up to one:

```<code>1 60%   .6
2 30%   .3
3 4%    .04
4 3%    .03
5 2%    .02
6 1%    .01
</code>```

Next calculate the cumulative values for each item in your array:

```<code>1 60%   .6
2 30%   .9
3 4%    .94
4 3%    .97
5 2%    .99
6 1%    1.00
</code>```

Then generate a random number between 0 and 1.

Find the position in your cumulative array where this random number would be inserted.  The value at this position is the value that has been selected.

For example - if we generate 0.5 that would be inserted at the first element of your array, so we select 1.

If we generate 0.7 that would fit into the next position so we select 2, and so on.

Body:
What you're looking for is Fitness proportionate selection.

The way to imagine this is to visualise a game where we spin a wheel to win prizes.

The best prizes have smaller segments (and are less likely to be won) and the rubbish prizes have huge segments (and are more likely to be won).

Here's how I would implement this:

Assign (or calculate) the likelihood of each of your items occurring.

1 60%
2 30%
3 4%
4 3%
5 2%
6 1%

We'll turn these into decimals because this will be easier to work with now.  The only important thing is that these values add up to one:

1 60%   .6
2 30%   .3
3 4%    .04
4 3%    .03
5 2%    .02
6 1%    .01

Next calculate the cumulative values for each item in your array:

1 60%   .6
2 30%   .9
3 4%    .94
4 3%    .97
5 2%    .99
6 1%    1.00

Then generate a random number between 0 and 1.

Find the position in your cumulative array where this random number would be inserted.  The value at this position is the value that has been selected.

For example - if we generate 0.5 that would be inserted at the first element of your array, so we select 1.

If we generate 0.7 that would fit into the next position so we select 2, and so on.


问:
Program license : Open-Source and commercial?
Currently programming a new software, I'm searching for information about protecting my concept and my source-code. I precise I'm quite new in licensing.

As I'm feeling very concerned by Open-source and sharing with the community, I'm puzzled on the other hand because I want to make some profit of my work (around 1 year of free-time, you can imagine the amount of missed beers in pub!). So I'm looking for a double license, that is compatible, and allows software source-code distributing, but force companies to get a commercial license, or to negotiate directly with me. But I think it is totally contradictory with GPL like licenses.

What are you thinking about that?

答:
Just adding to Brian's answer:

"force companies to get a commercial license": As you guessed, you won't be able to do that with any open source license. Sell support, integration, services, and enterprise plugins.

If you use any third-party library, check that these libraries can be re-distributed in proprietary software. LGPL: OK GPL: not OK.

If you want to make money out of it, I would recommend making your dual license proprietary+GPL. While some opt for a dual-license proprietary+LGPL, it makes it easier for bigger companies to extend/repackage/resell your product with no compensation to you.


答:
Perhaps the easiest way to describe the difference ot a web developer is to highlight asm.js and Google's Native client.

If javascript web apps were almost as fast as compiled languages like C++ then nobody would be working on making web apps attempt to be as fast, the fact they are shows that there is a performance and efficiency difference between the two systems .

Javascript JIT compilers are very good now, but they still lag native code. Part of the problem is the "expressive" syntax of javascript which is why asm.js is invented - its a very specific subset of javascript that is much more constrained, but that makes it much easier to compile into efficient code, and therefore allows it to perform much better. Its still slower than native code however, some benchmarks say "only "twice as slow, but then other benchmarks say normal javascript is only twice as slow. Benchmarks, huh!

Native client went a different tack, providing a sandboxed environment to run real natively compiled code. It doesn't integrate as well into the browser environment as javascript does, but that's mainly due to uptake and how the established environments are, not what they could be.


问:
Should we push for more JavaScript on the JVM, alongside Java and Scala? Or, if not, why?
With JavaScript becoming one of the most widely used languages around, I began asking myself why people do not find ways to use it extensively on the JVM. As a programmer who spends half day writing Java, and the other half, writing JavaScript, I do see a lot of potential in this.

Was it just the timing that shot Scala up straight? Or the nature of the language itself. Although JavaScript and Java are fundamentally different languages, it is certainly not a problem to compile JS to Java bytecode. That's what Rhino has been doing for many years, right? Or the maybe the problem lies in the performance?

Whatever it is, I would be interested to know.

答: Scala had a considerable head start over the recent popularity of JavaScript, but that is not the only reason. Scala is intimately connected to the specification and implementation of Java. It was written by the principal author of javac specifically to fix all the perceived flaws in Java that he wasn't able to overcome during the earlier project. To M. Odersky, Scala is the perfect language for competent programmers that can run on the JVM without requiring incompatible changes. It is hard to imagine another alternative language that was better poised to win the "alternative" crown, and it didn't happen.


问:
How can I group commits in a version control system such as git
Instead of a one long flat commit history, why isn't there a hierarchy, so at the top level you might have pull requests, then you could go down a level and look at the commits in that PR. I realise that PR's are specific to github, but you get the idea. I just mean grouping a number of commits as a feature or bug-fix, for example.

Surely it would make the commit history a lot easier to navigate.

I'm sure there is an obvious answer this question, but I can't seem to find it.

答:
There is one long flat commit history because the changes are sequential.  Each one build on the 'before' state and leaves an 'after' state.  It would be hard to have changes not reflect this.

One option for grouping related changes is to use tags - http://git-scm.com/book/en/Git-Basics-Tagging though they are used more for tagging a point in history rather than grouping disparate commits.

To group together commits into larger ones you can also do interactive rebasing.

Branches are one option,  You can create a branch and do a bunch of commits that are logically related.  You can merge those commits back into master as desired - probably using the --no-ff option.

The relationship between branches can also be seen in visual tools such as gitg/gitx


问:
What is better to return from the DataService: Status or Exceptions?
I have a MVVM app with DataServices (using mvvmlight).

Right now, i'm using it like

```<code>var answer = await myDataService.PullList(categoryId);
if (answer.Status == Ok)
    ObservableListOfItems.ReplaceWith(answer.Collection); // Show results
if (answer.Status == ConnectionLost)
    // Handle connection lost state, show msg window or something
if (answer.Status == ParsingError)
    // Handle parsing problem
</code>```

where

```<code>async Task<MyAnswer> PullList(int id)
{
    // Just a wrapper around HttpWebRequest, returns String.Empty if something happened
    var resultString = await NetworkManager.GetAsync(UrlGenerator.GenerateCategoryRequest(id));

    if (String.IsNullOrEmpty(resultString))
        return new MyAnswer {Status = ConnectionLost);

    try
    {
        var parsedResult = JsonConvert.DeserializeObject<PocoProducts>();

        return new MyAnswer {Status = Ok, Collection = parsedResult.List);
    }
    catch (Exception)
    {
         return new MyAnswer {Status = ParsingError; }
    }
</code>```

and

```<code>public class MyAnswer()
{
    public List<Items> {get; set;}
    public EnumStatuses Statuc {get; set;}
}

public enum EnumStatuses
{
    Ok = 0,
    ConnectionLost,
    ParsingError
}
</code>```

So I'm curious, did i just re-invented an exceptions, didn't i?

PS: wrote a code just here, typos are possible, but general idea should be clear

答:
I guess my main issue with this is

What happens if an exception occurs during parsing.  How will you
  diagnose it or know what has occurred?

The reason I ask this is that the exception itself is ignored and you are simply returning a new MyAnswer.  I don't necessarily have any issues with this if you are logging the exception however this does not appear to be the case here.

Included in this, you are catching a general Exception?  Does DeserializeObject
throw specific exceptions?  I'm not 100% on that but where possible catch the most specific exception you know about and leave the rest to bubble up.  A reason for this is that your code is then easier to follow as you know exactly what you are dealing with in the method and can code accordingly.

So in summary.  In general I like to at the very least do something with the exception whether it's re-throwing, including it in the response or logging it.  I also like to catch the most specific exception I can at the point of interest to ensure the code is easier to follow and in the long term help provide a more robust solution.

OwnerDisplayName: Vitalii Vasylenko

OwnerDisplayName: dreza


答:
I have a some apps which use code like your code.  I use HttpClient and have a few types errors. For example MyWebException.

It is enough to keep the user informed. For example, if the Web server is not available, we will get response.StatusCode != HttpStatusCode.OK and throw the MyWebException. And if we got json but could not parse it, then throw Exception.

If we get MyWebException then we show message "Sorry, we have troubles with web server or bad signal". If Exception then "Sorry, something wrong".

You can even specify the error, if it is necessary.

Here's how it works:

API:

```<code> public async static Task<CPParkingZones> GetZones()
        {
            return await CPRequestService.Get<CPParkingZones>(string.Format("objects?types=zone"));
        }
</code>```

RequestService:

```<code>public async static Task<T> Get<T>(string url) where T : CPBase, new()
        {
            try
            {
                using (var httpClient = new HttpClient())
                {
                    var response = await httpClient.GetAsync(CPConfig.APIServer + url);
                    var responseObject = new T();
                    if (response.StatusCode != HttpStatusCode.OK)
                    {
                        responseObject.Error = new MyWebException();
                        return responseObject;
                    }
                    response.EnsureSuccessStatusCode();
                    string jsonResponse = await response.Content.ReadAsStringAsync();
                    responseObject = JsonConvert.DeserializeObject<T>(jsonResponse);
                    responseObject.Status = response.StatusCode;
                    return responseObject;
                }
            }
            catch (Exception ex)
            {
                var responseObject = new T();
                responseObject.Error = ex;
                return responseObject;
            }
        }
</code>```

Base class

```<code>public class CPBase
{
        public Exception Error { get; set; }
}
</code>```

Using

```<code>var zones = await CPMapObjectsAPI.GetZones();

if (zones.Error != null)
{
    if (zones.Error is WebException)
    {
       DialogService.ShowMessage("Sorry, we have troubles with web server or bad signal");
    }
    else
    {
       DialogService.ShowMessage("Sorry, something wrong");
    }
}
</code>```

This is just an example, "IF constructs" design looks awkward, especially If you need many types of errors, you can use many options to write this code better.

Title: What is better to return from the DataService: Status or Exceptions?

Body:
I have a MVVM app with DataServices (using mvvmlight).

Right now, i'm using it like

```<code>var answer = await myDataService.PullList(categoryId);
if (answer.Status == Ok)
    ObservableListOfItems.ReplaceWith(answer.Collection); // Show results
if (answer.Status == ConnectionLost)
    // Handle connection lost state, show msg window or something
if (answer.Status == ParsingError)
    // Handle parsing problem
</code>```

where

```<code>async Task<MyAnswer> PullList(int id)
{
    // Just a wrapper around HttpWebRequest, returns String.Empty if something happened
    var resultString = await NetworkManager.GetAsync(UrlGenerator.GenerateCategoryRequest(id));

    if (String.IsNullOrEmpty(resultString))
        return new MyAnswer {Status = ConnectionLost);

    try
    {
        var parsedResult = JsonConvert.DeserializeObject<PocoProducts>();

        return new MyAnswer {Status = Ok, Collection = parsedResult.List);
    }
    catch (Exception)
    {
         return new MyAnswer {Status = ParsingError; }
    }
</code>```

and

```<code>public class MyAnswer()
{
    public List<Items> {get; set;}
    public EnumStatuses Statuc {get; set;}
}

public enum EnumStatuses
{
    Ok = 0,
    ConnectionLost,
    ParsingError
}
</code>```

So I'm curious, did i just re-invented an exceptions, didn't i?

PS: wrote a code just here, typos are possible, but general idea should be clear

Body:
I have a some apps which use code like your code.  I use HttpClient and have a few types errors. For example MyWebException.

It is enough to keep the user informed. For example, if the Web server is not available, we will get response.StatusCode != HttpStatusCode.OK and throw the MyWebException. And if we got json but could not parse it, then throw Exception.

If we get MyWebException then we show message "Sorry, we have troubles with web server or bad signal". If Exception then "Sorry, something wrong".

You can even specify the error, if it is necessary.

Here's how it works:

API:

 public async static Task<CPParkingZones> GetZones()
        {
            return await CPRequestService.Get<CPParkingZones>(string.Format("objects?types=zone"));
        }

RequestService:

public async static Task<T> Get<T>(string url) where T : CPBase, new()
        {
            try
            {
                using (var httpClient = new HttpClient())
                {
                    var response = await httpClient.GetAsync(CPConfig.APIServer + url);
                    var responseObject = new T();
                    if (response.StatusCode != HttpStatusCode.OK)
                    {
                        responseObject.Error = new MyWebException();
                        return responseObject;
                    }
                    response.EnsureSuccessStatusCode();
                    string jsonResponse = await response.Content.ReadAsStringAsync();
                    responseObject = JsonConvert.DeserializeObject<T>(jsonResponse);
                    responseObject.Status = response.StatusCode;
                    return responseObject;
                }
            }
            catch (Exception ex)
            {
                var responseObject = new T();
                responseObject.Error = ex;
                return responseObject;
            }
        }

Base class

public class CPBase
{
        public Exception Error { get; set; }
}

Using

var zones = await CPMapObjectsAPI.GetZones();

if (zones.Error != null)
{
    if (zones.Error is WebException)
    {
       DialogService.ShowMessage("Sorry, we have troubles with web server or bad signal");
    }
    else
    {
       DialogService.ShowMessage("Sorry, something wrong");
    }
}

This is just an example, "IF constructs" design looks awkward, especially If you need many types of errors, you can use many options to write this code better.

OwnerDisplayName: Alexandr


问:
sizeof style: sizeof(type) or sizeof variable?
I've seen two styles of using sizeof for memory-related operations (such as in memset or malloc):

sizeof(type), and

sizeof variable or sizeof(variable)

Which one would you prefer, or would you use a mix of the two styles, and when would you use each style? What are the pros and cons of each style and when you use them?

As an example, I can see the following pair of situations where one style helps and the other doesn't:

When you get the pointer indirection wrong:

```<code>type *var;
...
memset(var, 0, sizeof var);    /* oops */
</code>```

When the type changes:

```<code>new_type var;    /* changed from old_type to new_type */
...
memset(&var, 0, sizeof(old_type));    /* oops */
</code>```

答:
Business logic defines your choice.

If your code refers to a particular variable and without this variable your code makes no sense - choose sizeof(var)

If you code deals with a set of variables with particular type - choose sizeof(type). Usually you need this if you have a typedef which defines many variables which you process differently based on their type (e.g. serialization). You may not know which of these variables will remain in future code versions so choosing type as an argument is logically correct. Even changing of such typedef will not affect your sizeof line.


问:
Is it possible for business logic not to creep into the view?
I've developed for several web application projects for the last 3 years, both personal and at work, and I can't seem to figure out whether it's possible for at least some business logic not ending up in the view layer of the application.

In most cases there will be problems like "If the user has selected option x then the application must enable him to supply info for y, if not then s/he should supply info z".
Or do some AJAX operation which should apply some changes to the model but NOT commit them until the user has explicitly requested so. These are some of the simplest problems I've encountered and I can't figure out how it's possible to avoid complex logic in the view.

Most of the books I've read describing MVC usually showcase some very trivial examples, like CRUD operations that just update data on the server and display them, but CRUD is not the case on most rich applications.

Is it possible to achieve having a view with no business logic at all?

答:
I usually do this: if the user has selected option x, the view calls

```<code>controller->OptionXChanged()
</code>```

Then controller enable y on the view:

```<code>view->SetEnableInfoY(True) // suppose False=SetDisable
</code>```

The view notifies the controller of what happens without deciding anything.

Body:
I usually do this: if the user has selected option x, the view calls

controller->OptionXChanged()

Then controller enable y on the view:

view->SetEnableInfoY(True) // suppose False=SetDisable

The view notifies the controller of what happens without deciding anything.


答:
A business logic is more like If X then return InfoType.Y, then the UI will display fields based on result returned by the domain.

```<code>// Controller method pseudocode
option changed routine

    get selected option

    get required info type from domain routine based on selected option

    display fields based on required info type
</code>```

If the UI requires a business logic, then delegate the choice to the domain. The UI will simply act upon the decision.

Title: Is it possible for business logic not to creep into the view?

Body:
I've developed for several web application projects for the last 3 years, both personal and at work, and I can't seem to figure out whether it's possible for at least some business logic not ending up in the view layer of the application.

In most cases there will be problems like "If the user has selected option x then the application must enable him to supply info for y, if not then s/he should supply info z".
Or do some AJAX operation which should apply some changes to the model but NOT commit them until the user has explicitly requested so. These are some of the simplest problems I've encountered and I can't figure out how it's possible to avoid complex logic in the view.

Most of the books I've read describing MVC usually showcase some very trivial examples, like CRUD operations that just update data on the server and display them, but CRUD is not the case on most rich applications.

Is it possible to achieve having a view with no business logic at all?

Body:
A business logic is more like If X then return InfoType.Y, then the UI will display fields based on result returned by the domain.

// Controller method pseudocode
option changed routine

    get selected option

    get required info type from domain routine based on selected option

    display fields based on required info type

If the UI requires a business logic, then delegate the choice to the domain. The UI will simply act upon the decision.


问:
Spring JDBC Template without DAO?
I am rather new to writing applications that interact with databases, and I'm curious about a project I'm working on. I have to write a very simple web app which is going to be displaying metric data based off a handful of various queries (probably not over 15) to various database tables. Based on my own research, Spring JDBC Template seemed like a good technology to go with based on the rather simplistic nature of my project. Every example I see for using it though seems to involve the use of the DAO pattern. I was under the assumption that usage of the DAO pattern wouldn't be necessary for what I'm doing, but it seems extremely pervasive in the examples, so perhaps I'm mistaken.

What criteria would be used to evaluate whether I should be implementing a DAO pattern with Spring JDBC Template for my project?

答: No matter how small your project, maybe it is advisable to use DAOs and when it comes to a database query it is a good idea to use Hibernate to access the database contents. Then all you would need is to autowire the sessionfactory so that you can use it on your controller.</p>

Title: Spring JDBC Template without DAO?


答:
Is it possible to achieve having a view with no business logic at all?

I find this a deceptively hard question to answer.  (Thought-provoking question!)

Theoretically, yes, depending on what we define as business logic.  In practice, strict separation becomes a lot harder, and maybe even undesirable.

Separation of concerns is a great way to think about building software: it provides you with ideas about where to place code, and it gives maintainers a good idea about where to look for the code.  I'll argue that it's basically impossible for humans to build working software without separation of concerns.  We need this.

But, as with all things, there are trade-offs.  The best conceptual location may not be the best location for other reasons.  Maybe there's too much load on your web server, so you add some javascript to your web pages to catch easy input errors before they hit your server; now you have some business logic in your view.

The view itself, on its own, has no value without the business logic.  And to be effective in use and display, implicitly or explicitly, the view will have some knowledge of the business processes going on behind it.  We can limit that amount of knowledge, and we can cordon off parts of it, but practical considerations will often force us to 'break' separation of concerns.


问:
Specification languages vs automated tests
I recently listened to an episode of Software Engineering Radio in which Leslie Lamport was interviewed. One thing he discussed was his specification language, TLA+.

Essentially, he seemed to be arguing that, for programs where correctness is very important, we need to think carefully and specify carefully before writing code, and TLA+ is meant to be a tool to do that. He said a team at Amazon has recently had success using it.

Personally, I write executable tests for my code. I see the tests as a specification, which has the huge benefit of proving whether the code conforms to it.

I assume that Mr. Lamport, being a brilliant and accomplished computer scientist, has long known about this, and still sees a need for his language. But why?

Are formal specification languages and automated tests complementary approaches, or at odds? Do they lend themselves to different kinds of code?

答:
Your tests can show that the system reacts correctly to those inputs that the tests actually exercise. That is very valuable, but it is nigh-impossible to exercise all inputs that a program might receive.

A judiciously chosen formal proof or specification language document can prove mathematically that your program will respond correctly to all inputs it could possibly receive, even if that is an infinite set. That is certainly better, although whether or not the extra effort is worth the improvement in reliability varies from case to case.

ContentLicense: CC BY-SA 4.0


答:
Mr. Lamport, ... still sees a need for his language. But why?

With a formal specification language, you can run a verifier - that proves the design/algorithm mathematically. This is not the same as a set of unit/integration/bdd tests.

Are formal specification languages and automated tests complementary approaches, or at odds?

These are complementary, certainly. Nothing stops you from using both, if needed.

Title: Specification languages vs automated tests

Body:
I recently listened to an episode of Software Engineering Radio in which Leslie Lamport was interviewed. One thing he discussed was his specification language, TLA+.

Essentially, he seemed to be arguing that, for programs where correctness is very important, we need to think carefully and specify carefully before writing code, and TLA+ is meant to be a tool to do that. He said a team at Amazon has recently had success using it.

Personally, I write executable tests for my code. I see the tests as a specification, which has the huge benefit of proving whether the code conforms to it.

I assume that Mr. Lamport, being a brilliant and accomplished computer scientist, has long known about this, and still sees a need for his language. But why?

Are formal specification languages and automated tests complementary approaches, or at odds? Do they lend themselves to different kinds of code?


问:
Direct database manipulation an anti-pattern?
Recently I learned that some teams have moved all their database manipulation to the actual database through the use of stored procedures. I thought that was pretty clever, since the database becomes a black box and any change to how the data is stored and manipulated won't affect application code. Is it accurate to conclude that manipulating the database in application code is an anti-pattern, since it unnecessarily couples application and storage code, or are there circumstances that would make decoupling sql queries from the application a disadvantage?</p>

答:
unnecessarily couples application and storage code

Is this better than coupling your app to a particular database? I think the big question is do I want to couple my developers to the database?

If you're going to work with a database, I think you should understand how the code works, but that doesn't mean the developer has to directly write every single statement. Using the language of choice is hard enough without the additional labor of writing sql. Most programmers would separate the concerns by putting the domain logic (what the app really does) and the storage within the application. There are frameworks that take care of a lot of the "database stuff" for the programmer and can even use the same code and switch from one RDBMS to another. Add a property to a data model and let the ORM create a place in the database.

Stored Procedure Benefits They contain the text for a script. Yes it has been checked by the db to see if it will run (notice I didn't say it works). Like all queries sent to many databases it will try to cache some execution plan for performance (store procedure not required). Table and other object access can be blocked and controlled in the sproc for users/groups. I agree, what a great feature. Why would a programmer want to have to worry about all this stuff in app code. Get it from the database similar to some web service or other api.

Here's why this is a bad idea for many developers. They don't want to write the sql and having an amiable DBA 24/7 is hard to come by. Database development can become a bottle-neck. When a requirement is needed or a bug to be found, the name of the movie would be "Dude! Where's My Code?" It's all in the domain section.

RDBMS Doesn't Like Surprises: which is why some types of coding are not suitable for most database scripting languages  If only this worked:

Select @ListOfFields FROM @TheTableOfYourChoice WHERE @TheColumnYouWant = @OnlyParameterValueWhichWouldActuallyWork;

As much as this stored procedure doing all the database stuff sounds so great, there are limitations. Good luck writing the sql statement for the 8 part filter option your client wants. "But what if I NEED to search on the full name or just the abbreviation and possibly phone number? It could happen."


问:
Should a user story be shared between developers?
I commonly see stories that have back-end and front-end development.  For example, consider a large dialog with a few tables and some dynamic controls.  We'll make several stories (maybe one for each table and another for the dynamic control system).

The dev team will then split with one person on the back-end and another on the front-end.  This makes it easy for the back-end person to just worry about the structure of the SQL layer while the front-end person focuses on stuff like layout.  After the initial interface between back- and front-end is agreed, the two developers can focus their attention to get their part done by the end of the sprint.

Then comes the chaos.  Who "owns" which story?  What does "in progress" mean or "done"?  Should we make two separate stories for back-end and front-end?  If so, doesn't that break the idea of user stories based on feature?  Our system has a notion of "sub-tasks", which eases some of these problems.  But sub-tasks add an extra complexity.  Is there a better way?  Is this a "bad" way to use Scrum?

I have been using some form of Agile over the past few years at a couple places.  I have no official training yet, so please forgive any wrong terminology or ideology.  I'm just trying to learn practical ways to improve our process.

答:
Where we have implemented Scrum models, it is perfectly expected that multiple developers may be involved in a single user story. There may be work for data layer, integration, front-end CSS, infrastructure, etc. The team can band together on the various sub-tasks for a story to get it done.

That being said, one person owns the story and is responsible for updating on the progress of it and ensuring everybody's done their piece and that it is working together. This is the person for us who reports that a story is "done".


问:
Can a layer consist of multiple projects / dlls?
I am working on the architecture for a new web application and I am pretty much a complete newbie when it comes to architecture. Working my way through .NET Application Architecture Guide, 2nd Edition and learning a lot. I have decided to go for the "standard" 3-layer architecture: Presentation layer, Business layer, Data layer. Will be using ASP.NET MVC and Entity Framework.

Currently the business layer contains the logic and business entities (anemic models). I am planning to use the business entities as EF entities. That would, however, cause the data layer to have a depency on the business layer. This "problem" can be solved by moving the business entities into its own project and have the layers that have dependencies on the business entities reference that project.

Is that an ok / good way of doing things?

Will / can / should
the business entities project be considered part of the business
layer?

Can a layer consist of multiple projects, that is, the
layer only acts as a "logical container"? In the above mentioned
book they talk about how the business layer can consist of "Business
Workflow", "Business Components", "Business Entities", and I assume
that each of those are a separate project (maybe even multiple
projects)?

答:
1. Is that an ok / good way of doing things?

Sure, there's nothing within that guidance that says you can only use one project per layer.  For anything beyond a small application, you're going to want to separate things out into their own projects.

2. Will / can / should the business entities project be considered part of the business layer?

Absolutely.  Even though you'll have multiple projects per layer, you still need to organize the projects by their logical role.  So all business layer projects should be named and organized in a similar way.

3. Can a layer consist of multiple projects, that is, the layer only acts as a "logical container"?

Yes again.

You will likely end up with some "core" projects within your layers.  These are the projects you create in order to avoid the circular dependencies you mentioned in your question.  And it's okay to have a "business layer core" as well as "business layer application function" type projects.  All of them belong to the business layer.  Repeat as necessary for the other layers.

The important thing to keep in mind is to continue to observe the separation between layers that this architecture introduces.  Each project within each layer needs to obey the separation of concerns rules you put in place regarding what the project is allowed to reference.

For example, don't allow a Presentation layer project access a Data layer project.  It's a little harder because now you have more projects to apply that governance to, but if you use a consistent naming convention or project structure it's pretty easy to do.


问:
Doing Integration Testing, what would be a good way to provide test values from external sources?
I am building an Integration Testing Solution using Selenium in VS2012, which will be run on a CI server in the near future. I need to provide some way to vary the values being used for testing. The easiest would be to provide the QA testers with a few template spreadsheets, which they can fill in to run tests with those values (for example Log-In, Create new user, Create new Booking, Update Reservation etc).

At this moment I have a Test project using NUnit, and another project that contains the test execution code using Selenium, with sample values hardcoded in workflows for each test.

I have done some searching, but came up with no relevant results. I am either using incorrect terminology, or this has never been done (improbable, I know).

Have you done this, or heard/read about someone who has? I'd like to not reinvent this particular wheel.

答:
It sounds like you are describing Cucumber.

What you're really looking for is Acceptance Test and Behavior Driven Development (ATDD and BDD) tools.  If Cucumber is not what you are looking for, I hope those terms help you in your search.


问:
Forking BSD-Project and changing license
Is it possible to fork a project (which I don't own) and change the license from BSD to for example LGPL / GPL / AGPL?

I read it would be possible to change fork's license to something compatible to BSD - is this just a rumor / urban legend?

答:
From wikipedia (http://en.wikipedia.org/wiki/Fork_(software_development)) "The BSD licenses permit forks to become proprietary software".
Since "proprietary software" is more restrictive then other open source licenses, you should not have any problem: since the fork can be your "proprietary software", you can release with any license you like. (Btw, I'm not a lawer :P ).</p>


答:
Is it possible to fork a project (which I don't own) and change the license from BSD to for example LGPL / GPL / AGPL?

It depends upon which BSD license is used.

The BSD 2-clause license is compatible with the GPL, but the BSD 3-clause license is not.

The FSF has declared the BSD 2-clause license to be compatible with the GPL.  And by "compatible" they mean:

you can combine code released under the other license with code released under the GNU GPL in one larger program.

It's important to keep in mind that "compatible" is really just a euphemism for a re-licensing of the resulting project under the GPL.

The BSD 3-clause is not compatible with the GPL as explained here

Because it imposes a specific requirement that is not in the GPL; namely, the requirement on advertisements of the program. Section 6 of GPLv2 states:

      You may not impose any further restrictions on the recipients' exercise of the rights granted herein.
  GPLv3 says something similar in section 10. The advertising clause provides just such a further restriction, and thus is GPL-incompatible.

To address the specifics of forking.  The BSD 2-clause license states:

Redistribution and use in source and binary forms, with or without modification, are permitted provided that the following conditions are met:

That first clause that I have emphasized means you are permitted to do what you want with the BSD licensed project.  So you're free to fork the project.

Remember to keep the original copyright notices and disclaimer of liability in place in order to honor the terms of the BSD license.  But other than that, you're free to do what you want.

Title: Forking BSD-Project and changing license

Body:
Is it possible to fork a project (which I don't own) and change the license from BSD to for example LGPL / GPL / AGPL?

I read it would be possible to change fork's license to something compatible to BSD - is this just a rumor / urban legend?


问:
Does anybody recognize this scheduling problem? Is there an algorithm for it?
Consider the following problem:

Description:

There are n jobs J1...Jn with cycle times C1....Cn. Find a time quantum and a scheduling table considering that:

any element of the table contains at most one job

the job handler will process an element at a time, i.e. execute the job (if any) then, after a time quantum passes, moves to the next element.

the job handler will loop-back, i.e. after the last element it will continue with the first.

the ciclicity must be maintained, i.e. the distance between any two consecutive (including loop-back) occurances of job Jk (k = 1,n) must be equal to Ck / time quantum.

the table must be as short as possible.

Example:

J1 - 4 seconds ciclicity

J2 - 6 seconds ciclicity

J3 - 8 seconds ciclicity

Example solution:

time quantum = 1s

```<code>0  1  2  3  4  5  6  7  8  9  10 11 12 13 14 15 16 17 18 19 20 21 22 23 24 seconds
+--+--+--+--+--+--+--+--+--+--+--+--+--+--+--+--+--+--+--+--+--+--+--+--+
|J1|J2|J3|  |J1|  |  |J2|J1|  |J3|  |J1|J2|  |  |J1|  |J3|J2|J1|  |  |  |
+--+--+--+--+--+--+--+--+--+--+--+--+--+--+--+--+--+--+--+--+--+--+--+--+
</code>```

My feeling is that this belongs to the family of scheduling problems and that it may be a special case of a more general problem. Is this so?
 I tried to search for it online but didn't find anything that looks similar.
 Since I don't have any experience with scheduling problems I'm not even sure what to search for.

From what I see:

the total duration of the schedluing table should be the smallest common multiple of C1...Cn.

the time quantum should be at least GCD(C1,...,Cn) / n. - This is not necessarly the optimal solution.

This leads me to believe that there is a straight forward solution and not one involving dynamic programming. Is this so?

Can somebody point me to some resources, maybe even an algorithm, for this problem?

I'm also curious about variations where there the jobs can be distributed between more than one scheduling tables.

GCD = Greatest Common Divider

Edit: I'm not asking how to schedule N jobs with given cycle times; I'm sure there are more dynamic ways to do this as some suggested. My problem is "Find a time quantum and a scheduling table considering that:[...]". It's even possible that it may have it's roots in some parts of mathematics.

答:
You could determine the best schedule using a priority queue.  Where are the decision moments in scheduling?  It is when you have more than one cycle to start on any given second.

You'll need to have a "schedule" data type representing a possible schedule (the data you've written above is a perfect example of the data you'd represent here).

Therefore the pseudo algorithm should be the following:

Add each cycle type to its own schedule and push each schedule onto a priority queue, prioritizing by smallest GCD*(C1,...,Cn) / n value.

Then, starting with the schedule with the smallest GCD*(C1,...,Cn) / n value, create new schedules from the old by appending new cycles to launch.

Continue for as much as you like.

You decide when the schedule should end, and since it is a priority queue, you're guaranteed that the first element is the optimal in terms of GCD*(C1,...,Cn) / n at any given point.

Hope that helps.


答:
You can license your new changes under a license compatible with the old license and relicense the entirety of the new project with the new license (as it is now a derivative work of the changes you have made under the GPL).

However the original code does not change its license.  If the code is licensed under the BSD license, it is licensed under the BSD license.  You may not change that.  You may not remove the BSD license from the code that you received (forked).

Only the entity that controls the copyright for the code has the legal authority to change the license of the existing code to something else.


问:
Retried Operation with generic Exception
I am looking for a way to get the logic of retrying an operation in a single method while keeping the exception types of the operation.

I.e., the implementation to retry an operation could look like this:

```<code>public void retriedOperation(Operable operable, int maxAttempts) throws Exception {
    for (int attempt = 0; attempt < maxAttempts; attempt++) {
        try {
            operable.doOperation();
            break;
        } catch (Exception e) {
            if (attempt + 1 > maxAttempts) {
                throw e;
            }
        }
    }
}
</code>```

This implementation is however only capable of throwing an unspecified Exception and thereby looses lots of information.

Unfortunately, generic Exceptions can neither be caught nor thrown not be caught in Java, thus something like

```<code>public void <ExceptionType extends Exception> retriedOperation(...) throws ExceptionType { ... }
</code>```

would only allow to catch an unspecific Exception, check if it is of the right type and then cast it. But if it is of another type, it cannot be thrown with this method header.

Is there a way to implement a generic retry function that preserves specific exceptions?

答:
I'm not a java developer, but this might work for you anyway.

You can try using the instanceof operator.

```<code>public void retriedOperation<T>(Operable operable, int maxAttempts) throws Exception {
    for (int attempt = 0; attempt < maxAttempts; attempt++) {
        try {
            operable.doOperation();
            break;
        } catch (Exception e) {
            if (!(e instanceof T) || attempt + 1 > maxAttempts) {
                throw e;
            }
        }
    }
}
</code>```

Where T is the type of the exception you want to allow.

Body:
I'm not a java developer, but this might work for you anyway.

You can try using the instanceof operator.

public void retriedOperation<T>(Operable operable, int maxAttempts) throws Exception {
    for (int attempt = 0; attempt < maxAttempts; attempt++) {
        try {
            operable.doOperation();
            break;
        } catch (Exception e) {
            if (!(e instanceof T) || attempt + 1 > maxAttempts) {
                throw e;
            }
        }
    }
}

Where T is the type of the exception you want to allow.