问:
How to deal with exceptions to business rules?
I have been given a file with several records. I have also been given business rules that determine how to process those records and produce an output file. The business rules are relatively simple:

If record is of type A, use methodology A.

If record is of type B, use methodology B.

However my client emailed me with a problem: There is one "special" record in the file. It's a type A record, but it needs to be processed with methodology B.

How does one deal with these exceptions to business rules? Some options I have thought of so far:

Hard-code the exception into the software: if record.id == "some_id" && record.value == 123.45 then methodology B.

Manipulate the file by hand, run the program, and then correct the output by hand.

My coworker is astonished that I would even consider option 1. It's messy, and next year (when I have to run this process again) the file could be different. It will turn out to a nice hidden "gotcha" that could cause problems long after I forgot about the exception.

However option 1 is easier than option 2, and if the exception to the rule stays the same for next year, I won't have to even think about it. It's already been handled. Besides, it's easy to change if I need to change it later.

How do I deal with random exceptions to business rules?

EDIT:

This is very targeted software - written to specifically do one job for one client.

答: 3. Build an override option into the program, where you can (optionally) explicitly specify a rule set for a certain processing job instead of having the program decide automatically.


问:
Is there a faster way to work out this logic?
The purpose of this assignment was the find the smallest and largest of the integer(User inputs 5 entries)

I am a beginner Java programmer with no prior experience. Is there an easier way to do this without a ton of if/else statements?

Forgive for the dirty code.

```<code>    //Scanner Object
    Scanner input = new Scanner(System.in);

    int num1, num2, num3, num4, num5;
    int large;
    int small;

    System.out.print("Enter Num1: ");
    num1 = input.nextInt();

    System.out.print("Enter Num2: ");
    num2 = input.nextInt();

    System.out.print("Enter Num3: ");
    num3 = input.nextInt();

    System.out.print("Enter Num4: ");
    num4 = input.nextInt();

    System.out.print("Enter Num5: ");
    num5 = input.nextInt();

    //If/Else statements (SMALL)
    if (num1<num2 && num1<num3 && num1<num4 && num1<num5) {
        small = num1;

        }

    else if (num2<num1 && num2<num3 && num2<num4 && num2<num5) {
                small = num2;

                        }

    else if (num3<num1 && num3<num2 && num3<num4 && num3<num5) {
                small = num3;

    }

    else if (num4<num1 && num4<num2 && num4<num3 && num4<num5) {
                small = num4;

    }

    else {
        small = num5;

    }

    //Large

    if (num1>num2 && num1>num3 && num1>num4 && num1>num5) {
        large = num1;
    }

    else if (num2>num1 && num2>num3 && num2>num4 && num2>num5) {
                                        large = num2;
    }

    else if (num3>num1 && num3>num2 && num3>num4 && num3>num5) {
                large = num3;
    }

    else if (num4>num1 && num4>num2 && num4>num3 && num4>num5) {
                    large = num4;
    }

    else {
                large = num5;

            }

    //Display: Use printf when using a format limiter (%)

    System.out.printf("The smallest integer: %d\n", small);
    System.out.printf("The largest integer: %d\n", large);

    }// end of main

}
</code>```

答:
There are definitely better ways to do that. Put the values in an array and then scan through the array looking keeping track of the smallest and largest values you find:

```<code>for (i in valueArray) {
    if (i < min)
        min = i;
    if (i > max)
        max = i;
}
</code>```

I'll leave that into real code up to you.

ContentLicense: CC BY-SA 3.0

Body:
There are definitely better ways to do that. Put the values in an array and then scan through the array looking keeping track of the smallest and largest values you find:

for (i in valueArray) {
    if (i < min)
        min = i;
    if (i > max)
        max = i;
}

I'll leave that into real code up to you.


问:
What is the point of having every service class have an interface?
At the company I work at, every service class has a corresponding interface.

Is this necessary?

Notes:

Most of these interfaces are only used by a single class

We are not creating any sort of public API

With modern mocking libraries able to mock concrete classes and IDEs able to extract an interface from a class with two or so clicks, is this just a holdover from earlier times?

答:
Given your question I assume that the reasons for this kind design are not documented.

Unjustified usage of an interface with single implementation is plain wrong since this violates YAGNI. In my experience, this also has been pretty damaging maintenance-wise, mostly because methods implementing interface are forced to be unnecessarily public. After you gather more refactoring experience, you'll probably learn to appreciate modest charm of private and package private access modifiers allowing one to focus attention within a single class / package.

As for undocumented justified usage of this idiom, it is in my eyes about as bad - first of all because it doesn't allow a maintainer to "tell good from bad". As a result, this leaves one between not quite appealing options. Options are, either you keep the questionable public stuff as-is, thus repeatedly decreasing productivity every time you need to change the code, or you make risky changes by blindly "collapsing" the single-implementation into easier to maintain POJO - exposing self to the risk to painfully discover that this is wrong way, that some other (God forbid, remote) module out of your sight expects the interface.

I've been through "revelations" caused by erroneous collapse of single-implementation-interface few times. Each time it has been quite an educative experience but I would not really want to get there again. Thing is, this happens at late testing, at integration or even at user acceptance and rolling back / fixing the mistake made long time ago at this stage is quite cumbersome.

An option that shouldn't be left without mentioning is to investigate whether the undocumented use is justified (and, after that, collapse or document respectively) right at the moment you find it.

To me, this one has been quite counter-productive. This approach essentially forces one to go full-round integration testing which is probably one of the most efficient ways to break a flow in the middle of some complicated fix / refactoring.

I just couldn't see the practicality... the interfaces are used one-to-one like com.company.service.foo and com.company.service.foo.impl

Well below is about how I typically handle cases like that.

Create a ticket in issue tracker, like "PRJ-123 Undocumented questionable use of interface with single implementation in Foo / FooImpl".

Add to ticket description or to comment an explanation that this hurts maintainability and point out that without documentation this looks like overengineering. Add a comment suggesting to fix the issue by "collapsing" this into a POJO, for easier maintainability.

Wait for some time just in case if someone comes to explain things. I'd wait a week or two at least

If someone explains the purpose, a) put that to the ticket, b) add to Foo javadocs something like purpose of interface explained in ticket PRJ-123, c) close the ticket, d) skip next three steps.

Otherwise, ...

Come to team lead or manager to ask what would they think if I fix the ticket as suggested.

Pick an adviser having sufficient authority to stand the "scream test" in case if suggested fix turns out wrong.

Collapse to POJO as per suggested fix, arrange code review if that's possible (in slippery cases like that it won't hurt to cover your back).

Wait until the change passes the full testing and update the ticket depending on its outcome - add the information on whether the change passed testing or not.

Create and handle a new issue tracker ticket to deal with remaining similar cases based on the outcome of your pilot ticket (PRJ-123): either document the purpose, or collapse to POJO.

ContentLicense: CC BY-SA 4.0


问:
Good workflow for software development with scrum and continuous integration
I'm studying an approach to understand better how the continuous integration workflow fits better in a software development company with the scrum method.

I'm thinking something like this:

Would that be a nice workflow?

答:
There is a good series of posts on continuous integration up on asp.net that you may find useful, it covers quite a bit of ground and workflows that fit with what it looks like you're after doing.

Your diagram doesn't make mention of the work done by the CI server (unit testing, code coverage and other metrics, integration testing or nightly builds), but I assume that's all covered in the "Continuous Integration server" stage. I'm not clear on why the CI box would be pushing back to the central repository though? Obviously it needs to get the code but why would it ever need to send it back?

CI is one of those practices recommended by various disciplines, it isn't unique to scrum (or XP) but in fact I would say it's benefits are available to any flow even the non-agile such as waterfall (maybe wet-agile?). For me the key benefits are the tight feedback loop, you know pretty quickly whether the code you just committed works with the rest of the code base. If you're working in sprints and having your daily stand-ups then being able to refer to the status, or metrics from last nights build in the CI server is definitely a plus and helps focus people. If your product owner can see the status of the build - a big monitor in a shared area showing the status of your build projects - then you've really tightened up that feedback loop. If your development team are committing frequently (more than once a day and ideally more than once an hour) then the chances that you'll run into an integration issue that takes a long time to resolve are reduced, but if they do it's clear to all and you can take whatever measures you need, everyone stopping to deal with the broken build for example. In practice you'll probably not hit many failed builds that take more than a few minutes to figure out if you're integrating often.

Depending on your resources / network you may want to consider adding different end servers. We have a CI build that's triggered by a commit to the repo and assuming that builds and passes all it's tests then it's deployed to the the development server so devs can make sure that it plays nicely (you could include selenium or other UI testing here?). Not every commit is a stable build though, so to trigger a build to the staging server we have to tag the revision (we use mercurial) we want to be built and deployed, again this is all automated and triggered simply by committing with a particular tag.
To go to production is a manual process; you can leave it as simple as forcing a build the trick is knowing which revision / build you want to use, but if you were to tag the revision appropriately then the CI server can checkout the correct version and do whatever is needed. You could be using MS Deploy to sync the changes to the production server(s), or to package it up and put the zip somewhere ready for an admin to deploy manually... it depends on how comfortable you are with that.

As well as going up a version you should also consider how you might deal with failure and go down a version. Hopefully it wont happen but there could be some change made to your servers that means that what works on UAT doesn't work on production, so you release your approved version and it fails... you can always take the approach that you identify the bug, add some code, commit, test, deploy to production to fix it... or you could wrap some further tests around your automated release to production and if it fails those then it automatically rolls back.

CruiseControl.Net uses xml to configure the builds, TeamCity uses wizards, if you're aiming to avoid specialists in your team then the complexity of the xml configs can be something else to bear in mind.


答:
You can use not only arrays like Caleb suggested, but also lists and sorting.

It is not the most efficient way, but it is, in my opinion, the fastest one to implement.

```<code>public static void main(String[] args) {
    Scanner input = new Scanner(System.in);
    List numbers = new ArrayList<Integer>();

    int currentNumber;

    for(int i=0; i<5; i++){
        System.out.print("Enter Num"+(i+1)+": ");
        currentNumber=input.nextInt();
        numbers.add(currentNumber);
    }

    Collections.sort(numbers);

    System.out.printf("The smallest integer: %d\n", numbers.get(0));
    System.out.printf("The largest integer: %d\n", numbers.get(4));

}// end of main
</code>```

Edit:

An alternative for millions of elements, improved with jk.'s proposal:

```<code>public static void main(String[] args) {
    Scanner input = new Scanner(System.in);

    Integer min = Integer.MAX_VALUE;
    Integer max = Integer.MIN_VALUE;

    int currentNumber;

    for(int i=0; i<5; i++){
        System.out.print("Enter Num"+(i+1)+": ");
        currentNumber=input.nextInt();

        max = Math.max(max, currentNumber);
        min = Math.min(min, currentNumber);
    }

    System.out.printf("The smallest integer: %d\n", min);
    System.out.printf("The largest integer: %d\n", max);

}// end of main
</code>```

Title: Is there a faster way to work out this logic?

Body:
The purpose of this assignment was the find the smallest and largest of the integer(User inputs 5 entries)

I am a beginner Java programmer with no prior experience. Is there an easier way to do this without a ton of if/else statements?

Forgive for the dirty code.

```<code>    //Scanner Object
    Scanner input = new Scanner(System.in);

    int num1, num2, num3, num4, num5;
    int large;
    int small;

    System.out.print("Enter Num1: ");
    num1 = input.nextInt();

    System.out.print("Enter Num2: ");
    num2 = input.nextInt();

    System.out.print("Enter Num3: ");
    num3 = input.nextInt();

    System.out.print("Enter Num4: ");
    num4 = input.nextInt();

    System.out.print("Enter Num5: ");
    num5 = input.nextInt();

    //If/Else statements (SMALL)
    if (num1<num2 && num1<num3 && num1<num4 && num1<num5) {
        small = num1;

        }

    else if (num2<num1 && num2<num3 && num2<num4 && num2<num5) {
                small = num2;

                        }

    else if (num3<num1 && num3<num2 && num3<num4 && num3<num5) {
                small = num3;

    }

    else if (num4<num1 && num4<num2 && num4<num3 && num4<num5) {
                small = num4;

    }

    else {
        small = num5;

    }

    //Large

    if (num1>num2 && num1>num3 && num1>num4 && num1>num5) {
        large = num1;
    }

    else if (num2>num1 && num2>num3 && num2>num4 && num2>num5) {
                                        large = num2;
    }

    else if (num3>num1 && num3>num2 && num3>num4 && num3>num5) {
                large = num3;
    }

    else if (num4>num1 && num4>num2 && num4>num3 && num4>num5) {
                    large = num4;
    }

    else {
                large = num5;

            }

    //Display: Use printf when using a format limiter (%)

    System.out.printf("The smallest integer: %d\n", small);
    System.out.printf("The largest integer: %d\n", large);

    }// end of main

}
</code>```

Body:
You can use not only arrays like Caleb suggested, but also lists and sorting.

It is not the most efficient way, but it is, in my opinion, the fastest one to implement.

public static void main(String[] args) {
    Scanner input = new Scanner(System.in);
    List numbers = new ArrayList<Integer>();

    int currentNumber;

    for(int i=0; i<5; i++){
        System.out.print("Enter Num"+(i+1)+": ");
        currentNumber=input.nextInt();
        numbers.add(currentNumber);
    }

    Collections.sort(numbers);

    System.out.printf("The smallest integer: %d\n", numbers.get(0));
    System.out.printf("The largest integer: %d\n", numbers.get(4));

}// end of main

Edit:

An alternative for millions of elements, improved with jk.'s proposal:

public static void main(String[] args) {
    Scanner input = new Scanner(System.in);

    Integer min = Integer.MAX_VALUE;
    Integer max = Integer.MIN_VALUE;

    int currentNumber;

    for(int i=0; i<5; i++){
        System.out.print("Enter Num"+(i+1)+": ");
        currentNumber=input.nextInt();

        max = Math.max(max, currentNumber);
        min = Math.min(min, currentNumber);
    }

    System.out.printf("The smallest integer: %d\n", min);
    System.out.printf("The largest integer: %d\n", max);

}// end of main


答:
If you are guaranteed that there will be exactly one of of the "special" records and that it can be identified easily (i.e., by its id in your example), option 1 is just fine.  Don't hard-code the record ID into the program; accept an optional value from the command line or whatever way your environment lets you specify these things:

```<code>% process-records --special-id 12345 < infile > outfile
</code>```

This means your client can change its behavior by the way it's invoked and you don't have to maintain multiple versions across years.

Title: How to deal with exceptions to business rules?

Body:
I have been given a file with several records. I have also been given business rules that determine how to process those records and produce an output file. The business rules are relatively simple:

If record is of type A, use methodology A.

If record is of type B, use methodology B.

However my client emailed me with a problem: There is one "special" record in the file. It's a type A record, but it needs to be processed with methodology B.

How does one deal with these exceptions to business rules? Some options I have thought of so far:

Hard-code the exception into the software: if record.id == "some_id" && record.value == 123.45 then methodology B.

Manipulate the file by hand, run the program, and then correct the output by hand.

My coworker is astonished that I would even consider option 1. It's messy, and next year (when I have to run this process again) the file could be different. It will turn out to a nice hidden "gotcha" that could cause problems long after I forgot about the exception.

However option 1 is easier than option 2, and if the exception to the rule stays the same for next year, I won't have to even think about it. It's already been handled. Besides, it's easy to change if I need to change it later.

How do I deal with random exceptions to business rules?

EDIT:

This is very targeted software - written to specifically do one job for one client.

Body:
If you are guaranteed that there will be exactly one of of the "special" records and that it can be identified easily (i.e., by its id in your example), option 1 is just fine.  Don't hard-code the record ID into the program; accept an optional value from the command line or whatever way your environment lets you specify these things:

% process-records --special-id 12345 < infile > outfile

This means your client can change its behavior by the way it's invoked and you don't have to maintain multiple versions across years.


问:
Should you fix preexisting defects while working on something else?
Conundrum:  During the course of working on a new feature or fixing a defect, you find a legacy problem in code.  What should you do?  Fix it and risk altering the behavior of the code. It has either been working up until now by some fluke, or else the defect has not been detected or worth anyone's time to report.  Should you leave it alone and allow the problem to make the code harder to work with later?  Fixing the problem will only add to the time of your original task and force you to regression test. Few will appreciate the work. Fixing it, however, seems right somehow. Code with fewer problems is easier to refactor and build upon.

I've been finding myself in this situation time and time again as we work to modernize a web application. I can't tell if I'm being obsessive or honorable when I go off-tangent working on these old bugs.  How do you handle these situations?

Thanks,
Corey

答:
I'll buck the trend here.  Unless you are in the very early prototype phase of development, you should never fix it immediately, you should file a bug report.   This has several advantages:

the team gets to evaluate it. Is it a real bug, what are the risks of fixing it.

management gets to decide if is important enough to take the schedule impact of including it in this release

a method for detecting it can be added to the test suite, hopefully in a general enough way to also find similar errors.

it provides valuable metrics about how many bugs are slipping through the previous  phases

ContentLicense: CC BY-SA 2.5


问:
Dependency injection: How to sell it
Let it be known that I am a big fan of dependency injection (DI) and automated testing. I could talk all day about it.

Background

Recently, our team just got this big project that is to built from scratch. It is a strategic application with complex business requirements. Of course, I wanted it to be nice and clean, which for me meant: maintainable and testable. So I wanted to use DI.

Resistance

The problem was in our team, DI is taboo. It has been brought up a few times, but the gods do not approve. But that did not discourage me.

My Move

This may sound weird but third-party libraries are usually not approved by our architect team (think: "thou shalt not speak of Unity, Ninject, NHibernate, Moq or NUnit, lest I cut your finger"). So instead of using an established DI container, I wrote an extremely simple container. It basically wired up all your dependencies on startup, injects any dependencies (constructor/property) and disposed any disposable objects at the end of the web request. It was extremely lightweight and just did what we needed. And then I asked them to review it.

The Response

Well, to make it short. I was met with heavy resistance. The main argument was, "We don't need to add this layer of complexity to an already complex project". Also, "It's not like we will be plugging in different implementations of components". And "We want to keep it simple, if possible just stuff everything into one assembly. DI is an uneeded complexity with no benefit".

Finally, My Question

How would you handle my situation? I am not good in presenting my ideas, and I would like to know how people would present their argument.

Of course, I am assuming that like me, you prefer to use DI. If you don't agree, please do say why so I can see the other side of the coin. It would be really interesting to see the point of view of someone who disagrees.

Update

Thank you for everyone's answers. It really puts things into perspective. It's nice enough to have another set of eyes to give you feedback, fifteen is really awesome! This are really great answers and helped me see the issue from different sides, but I can only choose one answer, so I will just pick the top voted one. Thanks everyone for taking the time to answer.

I have decided that it is probably not the best time to implement DI, and we are not ready for it. Instead, I will concentrate my efforts on making the design testable and attempt to present automated unit testing. I am aware that writing tests is additional overhead and if ever it is decided that the additional overhead is not worth it, personally I would still see it as a win situation since the design is still testable. And if ever testing or DI is a choice in future, the design can easily handle it.

答:
I am hearing some big no-nos from your team here:

"No third-party libraries" - AKA "Not Invented Here" or "NIH". The fear is that, by implementing a third-party library and thus making the codebase dependent on it, should the library have a bug, or a security hole, or even just a limitation that you need to overcome, you become dependent on this third party to fix their library in order for your code to work. In the meantime, because its "your" program that failed spectacularly, or was hacked, or doesn't do what they asked for, you still carry the liability (and the third-party devs will say that their tool is "as-is", use at your own risk).

The counter-argument is that the code that solves the problem already exists in the third-party library. Are you building your computers from scratch? Did you write Visual Studio? Are you eschewing the built-in libraries in .NET? No. You have a level of trust in Intel/AMD and Microsoft, and they find bugs all the time (and don't always fix them quickly). Adding a third-party library allows you to quickly get a maintainable codebase working, without having to reinvent the wheel. And Microsoft's army of lawyers will laugh in your face when you tell them that a bug in the .NET cryptography libraries makes them liable for the incident of hacking your client suffered when using your .NET program. While Microsoft will certainly jump to fix "zero-hour" security holes in any of its products, they make it very clear that they are only liable for very specific damages in very specific cases.

"We want to stuff everything into one assembly" - actually, you don't. In .NET at least, if you make a change to one line of code the entire assembly containing that line of code must be rebuilt. Good code design is based on multiple assemblies that you can rebuild as independently as possible (or at least only have to rebuild dependencies, not dependents). If they REALLY want to release an EXE that is just the EXE (which does have value in certain circumstances), there's an app for that; ILMerge.

"DI is taboo" - WTF? DI is an accepted best practice in any O/O language with an "interface" code construct. How does your team adhere to the GRASP or SOLID design methodologies if they're not loosely-coupling the dependencies between objects? If they don't bother, then they're perpetuating the spaghetti factory that makes the product the complicated morass it is. Now, DI does increase complexity by increasing object count, and while it makes substituting a different implementation easier, it makes changing the interface itself harder (by adding an extra layer of code object that has to change).

"We don't need to add this layer of complexity to an already complex project" - They may have a point. A crucial thing to consider in any code development is YAGNI; "You Ain't Gonna Need It". A design that is SOLIDly engineered from the beginning is a design that is made SOLID "on faith"; you don't know if you'll need the ease of change that SOLID designs provide, but you have a hunch. While you may be right, you may also be very wrong; a very SOLID design could end up being viewed as "lasagna code" or "ravioli code", having so many layers or bite-size chunks that making seemingly trivial changes become difficult because you have to dig through so many layers and/or trace through such a convoluted call stack.

I support a three-strikes rule: Make it work, make it clean, make it SOLID. When you first write a line of code it just has to work, and you don't get points for ivory-tower designs. Assume it's a one-off and do what you gotta do. The second time you look at that code, you're probably looking to expand or reuse it, and it's not the one-off you thought it'd be. At this point, make it more elegant and understandable by refactoring it; simplify convoluted logic, extract repeated code into loops and/or method calls, add a few comments here and there for any kludge you have to leave in place, etc. The third time you look at that code it's probably kind of a big deal. Now you should adhere to the SOLID rules; inject dependencies instead of constructing them, extract classes to hold methods that are less cohesive with the "meat" of the code, make sure class hierarchies are logical and that derived classes "look" like their parents if you were to substitute one for the other, etc.

"It's not like we'll be plugging in different implementations" - You, sir, have a team that doesn't believe in unit tests on your hands. I posit that it is impossible to write a unit test, which runs in isolation and has no side effects, without being able to "mock" the objects that have those side effects. Any non-trivial program has side effects; if your program reads or writes to a DB, opens or saves files, communicates over a network or peripheral socket, launches another program, draws windows, outputs to the console, or otherwise uses memory or resources outside its process's "sandbox", it has a side effect. If it does none of these things, what DOES it do, and why should I buy it?

To be fair, unit testing is not the only way to prove a program works; you can write integration tests, code to mathematically-proven algorithms, etc. However, unit testing does show, very quickly, that given inputs A, B and C, this piece of code outputs the expected X (or not), and thus that the code works properly (or doesn't) in a given case. Suites of unit tests can demonstrate with a high degree of confidence that the code works as expected in all cases, and they also provide something that a mathematical proof cannot; a demonstration that the program STILL works the way it was intended. A mathematical proof of the algorithm doesn't prove it was implemented correctly, nor does it prove any changes made were implemented correctly and didn't break it.

The short of it is that, if this team doesn't see any value in what DI would do, then they won't support it, and everybody (at least all the senior guys) has to buy into something in order for real change to happen. They're putting a lot of emphasis on YAGNI. You're putting a lot of emphasis on SOLID and automated testing. Somewhere in the middle lies the truth.

Title: Dependency injection: How to sell it


问:
How to become a super user (programming)?
You try a new tool and it does not work. You google the problem and if you are lucky a random answer says you need to edit some weird configuration file and place it in a specific directory you don't know. You try but during the process things go wrong. Either because you don't understand the steps listed in the answer or because the solution is not exactly the same situation as yours.

I can't be the only who is puzzled/annoyed when I am in these kind of situations. I find these problems a lot more scarier than when I don't understand a particularly algorithm. Often I can end up using 10 hours trying to get something to work without getting anything done. After that I just give up.

I like programming but I really hate these moments when you need to integrate with a tool and you end up in situations as described. Often I don't even want to try new tools because I am afraid of this happening.

My question is: Is there a way to get better at this? Is there a faster way to learn all this without just practicing? I have thought about getting books about unix and begin using the shell for every day use but I am not sure it is worth it.

答:
As you beat your way through each problem, you become better at solving problems in general, and eventually, you may become really good at it.

Eg, trade in your club for a nice circular saw.

Time Doing Something + Paying Attention = Experience

I've been programming for 24 years now, and have gotten quite proficient at diving into new areas that are confusing or hard at first.  Be encouraged, and keep working at it!


答:
There are a few different ideas you could explore here:

Deliberate practice would be one idea to explore in terms of which skills are you honing when you learn something from scratch.

In a similar way, you may want to consider how you frame learning something new.  Is it exciting to do what you didn't previously do?  Which mindset do you have going into this, a fixed mindset or a growth mindset?

If you look over at the "Related" list you may find similar questions that have already been covered here a few times on how to be great at programming.

Maybe I don't relate well to the challenge you have as I know I learn quite a bit when I get something working that I didn't know how to do when I started.  While there can be the challenge of how much tenacity one has to handle the various setbacks, this seems to be quite normal to my mind.

The idea of deliberate practice could be applied by looking into logic problems, studying various heuristics behind algorithms such as being greedy, divide and conquer, or dynamic programming, though I imagine for each person it could be difficult to identify what skills are the key ones to use.  Another point in here is to consider what kinds of practices do you have that have brought you to this point?  Part of working with technology is that it does tend to change quite regularly, at least that is my experience mostly in a web development capacity.

My understanding of your question is that you have a frustration or annoyance in acquiring proficiency with new tools.  I can relate to have issues understanding how to use something new and making more than a few mistakes in the process.  My tenacity and desire to see something through to completion is where I get my drive to keep in the game and eventually overcome the problems I was facing.

Title: How to become a super user (programming)?

Body:
You try a new tool and it does not work. You google the problem and if you are lucky a random answer says you need to edit some weird configuration file and place it in a specific directory you don't know. You try but during the process things go wrong. Either because you don't understand the steps listed in the answer or because the solution is not exactly the same situation as yours.

I can't be the only who is puzzled/annoyed when I am in these kind of situations. I find these problems a lot more scarier than when I don't understand a particularly algorithm. Often I can end up using 10 hours trying to get something to work without getting anything done. After that I just give up.

I like programming but I really hate these moments when you need to integrate with a tool and you end up in situations as described. Often I don't even want to try new tools because I am afraid of this happening.

My question is: Is there a way to get better at this? Is there a faster way to learn all this without just practicing? I have thought about getting books about unix and begin using the shell for every day use but I am not sure it is worth it.


问:
Test Driven Development, has it reduced stress for developers?
I understand the benefits of test driven development, but have there been any studies that reveal the level of satisfaction with the product or stress levels of the authoring developers with the introduction of unit testing?

I'm looking for case studies, or preferably research papers.

答:
I don't personally know of any papers that focus on TDD vs Programmer Stress. I can really only offer you anecdotal evidence based on my own experience.

One of the more difficult things when I first tried TDD was to refocus my thinking so that it made more sense to write the test before the code. Often it simply felt easier to get my ideas into code, then follow up with tests. Over time I noticed that the number of noticeable bugs in my code didn't really seem to change and testing seemed to make me to appear to be working more slowly. In a sense, this contributed to additional stress at the time, as it felt like a failure in terms my ability to deliver quality work on time, and all of my scheduling estimates seemed to be way off of what I would have expected.

Fast forward several years with greater experience and the determination to see if I could actually make this approach work.  I have changed my approach to using BDD as it seems to fit my mind set better, and to me feels like a better way to do TDD. Not only have I found that I work better this way, but that I can more easily keep myself focused on meeting only the specified requirements.  I'm not wasting time with gold-plating, and I'm able to churn out code faster than I used to, simply because my efforts are more focused which ensures I am able to use my time more efficiently. This has had the effect of making even the more mundane tasks enjoyable when my test runner shows me all of my tests passing. I see my code quality improving also, and the code has become easier to maintain over time. All of this has made it much less stressful doing my work.

The thing is, that while I do see that things are better working this way, I can't really draw a direct correlation between TDD and less stress, because there are many other factors that have impacted on the quality of my work life. I have learned other skills over time that have also contributed to an overall reduction of stress levels.  Some of those skills are interpersonal, some are simple mindfulness exercises, while other skills have been acquired as a result of reading lots of books about code quality and design which have all had their influence on the way that I go about my work. All of these elements contribute to the amount of stress that I perceive, but no one thing stands out as having had a significant impact by itself.

So while I can't really say that TDD itself reduces stress, I can offer the observation that TDD has helped to improve the way I write software. By helping to make my working life easier, I could argue that TDD has contributed in some way to helping me to maintain a less stressful working situation, but that it is difficult to directly measure the specific amount that TDD has contributed.


问:
Why does adding more people to a late project make it later?
It's a fairly common adage that adding more programmers to a late project will make matters worse. Why is this?</p>

答:
The problem cited in the book the originally promulgated this law, The Mythical Man-Month, is communication. He starts off by saying:

Men and months are interchangeable commodities only when a task can be partitioned among many workers with no communication among them. This is true of reaping wheat or picking cotton; it is not even approximately true of systems programming.

He does mention training as part of the problem:

The added burden of communication is made up of two parts: training and intercommunication. Each worker must be trained in the technology, the goals of the effort, the overall strategy, and the plan of work. This training cannot be partitioned, so this part of the work varies linearly with the number of workers.

...but notes that intercommunication is by far the larger factor:

Since software construction is inherently a systems effort -- an exercise in complex interrelationships--communication effort is great, and it quickly dominates the decrease in individual task time brought about by partitioning. Adding more men lengthens, not shortens, the schedule.

It's also worth noting that Fred Brooks (the author) does have the background to know what he's talking about. Most of the book is based on his experience managing IBM's OS/360 project. Despite decades of adherents preaching all manner of "improved" management methods, and some even coming up with cool names (eXtreme, Agile, Scrum, etc.) when you get down to it, little of essence1 seems to have changed since.

1For the definition of "essence", see the same author's "No Silver Bullet: Essence and Accident in Software Engineering", included in the 20th Anniversary Edition of The Mythical Man-Month.


答:
Your specific question: "is there a way to get better at this"?  By 'this' I infer, the random stab-in-the-dark methodology you claim to use when approcaching a new problem.

I would encourage you particularly to take notes on the issues you face each time you begin a new task. Upon greeting your second task, check your notes to see if you've done any of these things before.  If so, use that experience to your own benefit.  You have stated in comments "I don't think I learn anything when I try to get [things] to work".  It could be, and no offence intended, that you have poor task memory. that you really don't learn anything and hence have an overly difficult time with a new task.  Again I would advice meticulous note-taking because in that way, your own problem solving abilities will be the best resource for you to prevent "flailing".

As for learning faster, sorry. I can only advocate learning better.  Eat right, get plenty of rest (a tired mind is a slow and stubborn one), and stay calm.

I've been computing for 22 years and I too have been known to colour the air around me blue with frustration. I just take a deep breath and "check my settings".


答:
Unfortunately, it's difficult to blame you. Quite a few tools are fairly arbitrary about how they do certain things. In some cases, you simply need to collect more data points to start to see a pattern, so the eventually you don't have as much difficulty with these sorts of configuration problems. Unfortunately, that's not necessarily the case -- in a lot of cases you're dealing with the result of people who have a number of reasonable possibilities, among which they choose at least somewhat arbitrarily. That being the case, there often just isn't much in the way of a pattern to find -- at best you can hope to find some meta-patterns, such as better ways to search for solutions.

That said, I'd say that yes, if you're going to (even try to) program on Unix (or anything similar) much, you pretty much need to learn how to use the shell to at least some degree. It has been a core tool in Unix programming for long enough that trying to program on Unix without knowing how to use the shell at least reasonably well will leave you hamstrung. At least in my opinion, it's worthwhile learning vi to at least some degree as well -- even if you don't like it or plan to use it, you'll almost inevitably end having to do something on a machine without the text editor of your choice, and if it's at all Unix-like, it'll almost certainly have vi, vim, or something similar available.

I should also add that in some cases, giving up is the right reaction. You haven't said much about how you're selecting the tools/libraries you're trying to use, but in some cases getting them installed and working just isn't worth the trouble. The big thing here is to look around pretty carefully before you jump in. I've certainly had a few that I did get to work just because I was too stubborn to quit -- and the result definitely was not worth the trouble.

You also need to be honest about your capabilities and current level of expertise. In some cases, you need to know a lot just to get something installed an operating in a reasonable length of time (or to be entirely sure when it is installed and operating correctly). If you don't have that level of expertise yet, then yes about all you can do is spend the time and effort necessary to gain expertise before you can do it.

One question to keep in mind is whether this is happening all the time with everything you try to use, or once in a while. If it's all the time, it may indicate that you're giving up a bit too easily. If it's happening once in a great while, it's likely to be perfectly normal.


问:
mysql, one connection vs multiple
On nodejs with node-mysql, should I create one connection for the service like this:

```<code>var client = mysql.createClient({
    user: 'user',
    password: 'pass'
}); // Create a new mysql Client
io.sockets.on("connection", function (user)) // when a user enters
{
    result = client.query('check user'); //check for user on DB
    if (result) {
        user.on('do stuff', function (data) // set to do something on ask
        {
            client.query('some stuff'); //run the mysql client to work
        });
    } else {
        user.disconnect();
    }
});
}
</code>```

or or for each user like this:

```<code>io.sockets.on("connection", function (user)) // when a user enters
{
    var client = mysql.createClient({
        user: 'user',
        password: 'pass'
    }); // Create a new mysql Client when the users enters
    result = client.query('check user'); //check for user on DB
    if (result) {
        user.on('do stuff', function (data) // set to do something on ask
        {
            client.query('some stuff'); //run the mysql client to work
        });
        user.on('disconnect', function (data) {
            client.close();
        });
    } else {
        user.disconnect();
        client.close();
    }
}
</code>```

What I'm asking is:

is the first one faster because the connection is always open and on
the second one it needs to create every time a user connects?

is the first one slower because if many users are asking for queries
he only does one at the time, and on the second one each one have his
own client and can make multiple connections at the same time?

is the second one heavier for the node server and for the mysql
because it needs to have 1 client for each user?

is the first one heavier because it never closes the mysql connection, and after some queries may have some memory leaks?

or should I create and close a mysql connection for every query?

PS: the application connected to the node server will have a big number of users, connected during a long period of time, but will have a very low number of queries, but the users probably will ask for queries at about the same time.

答:
Node is a single-process, single-threaded, asynchronous, event-driven application. So only one request/event is handled concurrently.

Since node-mysql looks like its API is synchronous, you should be fine with a single connection. This assumes that your application doesn't rely on SQL session variables, temporary tables, or transactions that might span multiple Node events.

Title: mysql, one connection vs multiple


答:
To become a super user, you need to become accustom to understanding the problems and the pieces that you don't understand. Key to this is understanding differences in environments.

Practice and experience are huge keys to becoming more proficient overall, but they must be coupled with a desire to understand the problems. If you edited a configuration file and it didn't behave the way you expected it to, you need to dig into why it didn't work. Simply shooting in the dark and tweaking it until it magically works will not improve your ability to understand things in the future.

The other key is to understand that computers behave differently based on their environment. Environment in this case means the OS, the OS version, and even the applications installed on that OS and their versions.

If you're using Ubuntu 12.04, for example, then you'll want to search for solutions to your problem on Ubuntu 12.04. If you find a solution to a problem but it's being described on Fedora 16, then you'll probably run into problems related to differences in the environment. Finding a solution described on an earlier version of Ubuntu or even Debian (on which Ubuntu was originally built) would yield better luck.

The beautiful thing about working with computers is that 99.9% of of the time, the problem, no matter how much it doesn't make sense, actually has a logical and sensible solution behind it (as opposed to understanding humans, which can actually make no sense at times).

Computers are systems a lot like humans, minus all the illogical emotional stuff (although I'm convinced that even computers very occasionally experience unexplainable emotional issues). Humans that speak the same language work well together (identical operating systems running on the same network, applications built for a specific OS, etc.). Friends that know each other well can operate nicely together (mature applications built for a specific OS generally run more smoothly than ported apps).

The key to becoming a super user lies in understanding all these differences and in being able to identify differences in environments while intuitively knowing which areas you don't understand.

When something doesn't work the way you expect it to, you'll know which areas to investigate based on what you don't know and you'll save time by ignoring the areas you already understand.


答:
Exceptions to business rules are generally not exceptions -- they are almost always simply more rules.  So, the first thing I'd do in this case is ask WHY this particular record is an A but gets treated as a B.  Where and how is that decision recorded?

If the answer is that it's recorded outside of the data that your process has access to, then the question is how best to add it to the data that your process has access.

What's the best way to give your process access to the decision will depend upon your particular situation.  Others have suggested having it done as a command line argument, that will work, I generally prefer config files myself, but that's going to be up to you and your circumstances, you may just be able to query a database or webservice...


答:
Your coworker is absolutely correct. Choosing Option 1 is a sign of a programmer that has not spend one minute maintaining someone else code and does not care about the likes of technical debt and future maintenance of the code base.

Its just a simple program that is needed to process the input data and create correct data for input into your main program. As the "exception" changes (as it will), your simple program that deals with is can just be updated.  This could be a person with Excel, a Perl script or real program, depending how often it is done and and how complex it is.  As @jmoreno points out - it is unlikely to be an exception, so as the business rules become clear, the main program can be modified to accommodate them.

(Warning - the 2 four letter words "just" and "simple" - might be worth exploring further)


问:
Why would one ever want to use a synchronized method in Enum?
I stumbled upon this question and a couple of other along the same lines.

While we know creation of enum is thread safe and enums are by birth singletons .

It kind of confuses me that why would any one want to have a synchronized method with in an enum. Yes I am fully aware that methods in an enum are not thread safe but then what?

They must not try to change the state of an enum any way . If we are not concerned about change of state of an enum then why would we ever like a method in an enum to be thread safe.

答: Consider this example: let's say you want to provide a description of your enum in a language associated with a Locale passed into your method. If the language is English, you provide a "canned" response hardcoded with your class; if it is a different language, you query Google Translate, pass English description, get back a response, cache it in a by-locale map inside your enum, and return the response back to the user. Accessing and modifying a cache should definitely be synchronized.


答:
If you design your enum so that the methods don't change its state, then they are by definition thread safe.  It is, however, possible to introduce state into an enum so that concurrent modification does become a problem.

Should you? Probably not. However, since Java has the flexibility to allow concurrent access to members of an enum, synchronization tools are needed to ensure that behavior occurs correctly.

Contrived example

Let's say you want to enumerate recent decades, and query them for phrases that people said when they wanted to say it was "cool."  Since you don't want to favor any one of these phrases  more than another, you want to make sure that they get used evenly, even across threads.  You might try something like this:

```<code>enum Decades {

    NINETIES( "dope", "fly", "bomb", "tight" ),
    EIGHTIES( "bad", "righteous", "sick", "gnarly" ),
    SEVENTIES( "boss", "choice", "funky" );

    final String[] phrases;
    volatile int currentPhrase = 0;
    Decades( String... phrases ){
        this.phrases = phrases;
    }

    synchronized String getCoolPhrase(){
        final String result = phrases[currentPhrase];
        currentPhrase = (currentPhrase + 1) % phrases.length;
        return result;
    }

}
</code>```

If you're familiar with classic problems in concurrency (counting to 100 with multiple threads comes to mind), you'll know that without synchronization, two threads could see the value of currentPhrase, retrieve the phrase, and increment at the same time.  This could result in repeated uses of the same phrase, since one thread didn't know that a phrase had already been used when it read the counter.

Cool phrases inspired by http://www.thebestpageintheuniverse.net/c.cgi?u=epic

Title: Why would one ever want to use a synchronized method in Enum?

Body:
I stumbled upon this question and a couple of other along the same lines.

While we know creation of enum is thread safe and enums are by birth singletons .

It kind of confuses me that why would any one want to have a synchronized method with in an enum. Yes I am fully aware that methods in an enum are not thread safe but then what?

They must not try to change the state of an enum any way . If we are not concerned about change of state of an enum then why would we ever like a method in an enum to be thread safe.

Body:
If you design your enum so that the methods don't change its state, then they are by definition thread safe.  It is, however, possible to introduce state into an enum so that concurrent modification does become a problem.

Should you? Probably not. However, since Java has the flexibility to allow concurrent access to members of an enum, synchronization tools are needed to ensure that behavior occurs correctly.

Contrived example

Let's say you want to enumerate recent decades, and query them for phrases that people said when they wanted to say it was "cool."  Since you don't want to favor any one of these phrases  more than another, you want to make sure that they get used evenly, even across threads.  You might try something like this:

enum Decades {

    NINETIES( "dope", "fly", "bomb", "tight" ),
    EIGHTIES( "bad", "righteous", "sick", "gnarly" ),
    SEVENTIES( "boss", "choice", "funky" );

    final String[] phrases;
    volatile int currentPhrase = 0;
    Decades( String... phrases ){
        this.phrases = phrases;
    }

    synchronized String getCoolPhrase(){
        final String result = phrases[currentPhrase];
        currentPhrase = (currentPhrase + 1) % phrases.length;
        return result;
    }

}

If you're familiar with classic problems in concurrency (counting to 100 with multiple threads comes to mind), you'll know that without synchronization, two threads could see the value of currentPhrase, retrieve the phrase, and increment at the same time.  This could result in repeated uses of the same phrase, since one thread didn't know that a phrase had already been used when it read the counter.

Cool phrases inspired by http://www.thebestpageintheuniverse.net/c.cgi?u=epic


问:
Which is best for learning how to do a certain thing: writing your own or looking at someone else's?
Often when I'm writing code to do a certain thing, I'm faced with either writing my own or using someone else's code. Assume here that this "thing" is something that I've never done before and am interested in learning how it's done.

Which would you say is better from a learning perspective: try writing your own solution; or looking at code by someone else? I've always written my own code if I have an idea on how to do it, but resorted to looking at someone else's when I don't have a clue. I believe that the best is probably a combination of both: make your own attempt and then look at how someone else did.

答:
Something closely related that I just realised today....

Things that I learn by writing my own program for a real life solution to something stick with me a lot more than doing samples/tutorial/exercises just for the sake of learning.

Walking through a tutorial or sample of something new is good as a basic learning exercise, but if I then walk away from it and have to apply it three weeks later (without looking at that technology at all since), I'll tend to have to Google things, revisit, look up, etc, a lot more than if I did a real program in it. It's only when I actually create something from scratch for myself in a given programming language or technology that it really sticks, and that I internalize the knowledge.


问:
Definition of "state"
What is a good way to define "state", as in state variable or state machine, to a new (previously non) programmer?  What are some good ways to explain why this concept is useful for writing software?  Is the concept of state explicitly taught in beginning programming courses or books commonly?</p>

答:
From Wikipedia:

State commonly refers to either the present condition of a system or entity...

That's pretty much what it means in a computing context: the data that defines the condition of some object or system.

The meaning of 'state' isn't specific to programming. There are examples of 'state' literally everywhere you look. The television is off. The coffee is hot. The sneakers are a) blue; b) smelly; c) not put away; d) quite worn out. 'state' in a programming sense is just the same as 'state' in a non-programming sense, except we apply it to the objects that we deal with: variables, objects, threads, databases, file systems, etc. If you have to explain it, explain it in terms that are familiar -- there's no need to make it into a foreign, technical concept.

A clock is a good example of a simple system that has some state: a clock can be running or not running, and it indicates a time which may or may not correspond to the actual time of day. It's pretty easy to see how those things are like variables and how changing the state of the clock might impact other things.

Compare that to something stateless, like a statement: "The door is red." The statement itself doesn't have state. It may or may not be true that the door is red, but the statement itself doesn't contain any state. Painting the door can change the truth of the statement, but the statement itself never changes. Similarly, a number like 42 doesn't have any state: 42 is 42 and there's nothing you can change about it.

Variables have state, values don't.

Title: Definition of "state"


答:
State is information your program manipulates to accomplish some task. It is data or information that gets changed or manipulated throughout the runtime of a program. The "state" of a program at a given time refers to a snapshot of all the data the program is currently looking at or analyzing to get to the next step in it's execution.

My university started with Scheme, so we started programming with a state-less model. We then switched to C and were very explicit about what state is, why it's useful, and why it makes things potentially very complicated. So some universities certainly talk about state, but not necessarily all of them

Title: Definition of "state"

Body: What is a good way to define "state", as in state variable or state machine, to a new (previously non) programmer?  What are some good ways to explain why this concept is useful for writing software?  Is the concept of state explicitly taught in beginning programming courses or books commonly?</p>


问:
Which hashing algorithm is best for uniqueness and speed?
Which hashing algorithm is best for uniqueness and speed? Example (good) uses include hash dictionaries.

I know there are things like SHA-256 and such, but these algorithms are designed to be secure, which usually means they are slower than algorithms that are less unique. I want a hash algorithm designed to be fast, yet remain fairly unique to avoid collisions.

答: If you are wanting to create a hash map from an unchanging dictionary, you might want to consider perfect hashing https://en.wikipedia.org/wiki/Perfect_hash_function - during the construction of the hash function and hash table, you can guarantee, for a given dataset, that there will be no collisions.</p>


答:
Fred Brooks wrote an entire book "The Mythical Man-Month" answering this question.

Here's the quick-n-dirty version:

There is a limit to how much you can break a project out into distinct pieces to assign to more programmers.

Splitting a project out to more people increases the amount of communication required to coordinate all the parts of the application. More communication = More Work.

For every person you add to the project you add more than one communication channel that must be navigated to the team. This number grows geometrically and increases the amount of communication that must happen. More communication = More work.

There is a "J-Curve" when you add each team member. That is, the existing productive resources have to spend time getting the new people up to speed that they otherwise could have spent working on the project. Ultimately you may increase capacity, but it temporarily slows down the project. The later in the project the more that must be learned, thus the more pronounced the effect. Also, there is less time remaining in the project to reap the benefits of the newly trained resources.

Title: Why does adding more people to a late project make it later?

Body: It's a fairly common adage that adding more programmers to a late project will make matters worse. Why is this?</p>


答:
You can use the analogy of a traffic light which can be in one of three states: [GREEN], [YELLOW] or [RED]. It must only be in one state at a time. The traffic light is the actual state machine being modelled. It will normally transition its state from [GREEN to YELLOW], then [YELLOW to RED], then [RED to GREEN].

An alternative state transition (which is in effect in some countries like UK, has two transitions of [RED to YELLOW, then YELLOW to GREEN] in place of the [RED to GREEN] transition.

Title: Definition of "state"


问:
Securing client->database game
OK, I am creating a game using JavaScript and HTML5. The variables such as map, x, y, level, exp, etc are stored in JavaScript to keep track. On my client page, the JavaScript variables are stored to play along with the game. Every 5 seconds, the client page sends a POST AJAX call to the MySQL database and it successfully updates it.

However a user can easily modify the JavaScript variables and cheat their way in the game. Then once they edit the JavaScript variables, the POST grabs that and updates it even though they edited it unethically.

So, how do I prevent this from happening?

答: To be completely secure, you have your HTML5/JS be a dumb client.  It only gives the user options, but those options are executed on the server itself.  This way the server can validate that every option is true, what options were taken and the state everything is in.  With no logic happening on the front end and the state of the game being stored on the back end, there really is no way to cheat.</p>

Title: Securing client->database game


答:
Game are really hard to develop, because you'll never be sure that no one will find the way to cheat. But there is some tips you can put in place to try to prevent cheat, in every type of game, whether it's written in Flash, JavaScript ...

The more important thing to think of is : You must never rely on client.

The server must

NEVER :

rely on datas sent by the client (ids, coordinates, power, prices won.. ).

save datas that it has not calculated and checked itself

ALWAYS

has an up-to-date version of the client's properties. the server must always rely on that properties to allow/disallow any action, calculate new properties, store properties in databases, send to clients

check the concordence between clients actions

allow or disallow the client to do any action (you want to move left ? I check if you can... Yes you can, your x is now lastx-1 / No you can not, you're at the map limit, your x is now lastx )

check if the elapsed time between two actions is possible. ( You asked me to jump. I replied you could, but that would take you 5 seconds before next action. You're asking me, two seconds after, to move right. It's not possible, you're jumping right now !).

The client must

ALWAYS

verify itself if it can perform an action before asking the server to do it =» less server calls, more security because there is two checks, by the client and by the server

rely on server datas. (You sometimes can animate things - like counter - and calculate the animation client-side AND server side. BUT you can have latency client side that makes client datas a little different than server datas.)

Other cheat controls in case of step-by-step game

Server must

validate every steps ( you try to do the second step, does your session says that you already performed the first one ? )

has a validation datas for every steps ( You sent me that your score for this step was 1200, but the max score is 500, bug or cheat ? redo step please )

keep traces of every step to validate/calculate datas at the end ( you send me this score at the first step, this one for the second, this one for the third... )

check if the validation of a step is possible in the elapsed time ( you try to send me step 2 result. Step 2 takes at least 18 seconds to perform, you sent me step 1 result 4 secondes ago. Houston, we've got a problem )

re-create a validation token for each calls ( ok, next time you call me, send me this token with your message, I want to be sure that we are at the same point )

(re)-create the session when the client download the game ( when you send a flash/javascript game file, when the client download the file from your server, make it go through a script that initialize the session, by making the file not cachable by the browser. If a client try to go to step 1 and the session does not exists, either the session is expired, or he tried to modify the flash/javascript file )

Very simple example case :

You have a real-time game with 2 players on the same map

Map properties : 3x3 -  Coords {x : 0, y : 0} = corner top left

Server » players : player1 : { x : 0, y : 0, life : 5 }, player2 : { x : 3, y : 3, life : 2 }

Player1 » Server : move right

Server » players : player1 : { x : 1, y : 0, life : 5 }, player2 : { x : 3, y : 3, life : 2 }

Player2 » Server : move left

Server » players : player1 : { x : 1, y : 0, life : 5 }, player2 : { x : 2, y : 3, life : 2 }

Player2 » Server : move left

Server » players : player1 : { x : 1, y : 0, life : 5 }, player2 : { x : 1, y : 3, life : 2 }

Player1 » Server : move up

Server » player1 : you can not move

Server » players : player1 : { x : 1, y : 0, life : 5 }, player2 : { x : 1, y : 3, life : 2 }

Player1 » Server : move down

Server » players : player1 : { x : 1, y : 1, life : 5 }, player2 : { x : 1, y : 3, life : 2 }

Player2 » Server : hit

Server » Player2 : no one to hit

Server » players : player1 : { x : 1, y : 1, life : 5 }, player2 : { x : 1, y : 3, life : 2 }

Player2 » Server : move up

Server » players : player1 : { x : 1, y : 1, life : 5 }, player2 : { x : 1, y : 2, life : 2 }

Player2 » Server : hit

Server » players : player1 : { x : 1, y : 1, life : 3 }, player2 : { x : 1, y : 2, life : 2 }

Player1 » Server : hit

Server » players : player1 : { x : 1, y : 1, life : 3 }, player2 : { x : 1, y : 2, life : 1 }

Player2 » Server : hit

Server » players : fatal, player1 : { x : 1, y : 1, life : 0 }, player2 : { x : 1, y : 2, life : 1 }, player2 win

I'm sure I forgot some tips, and I'll update if it comes back to me, but I think you'll be able to manage your game with these and maybe think by yourself at securities to add.

The more important thing to think of is : You must never rely on client.

Title: Securing client->database game

Body:
OK, I am creating a game using JavaScript and HTML5. The variables such as map, x, y, level, exp, etc are stored in JavaScript to keep track. On my client page, the JavaScript variables are stored to play along with the game. Every 5 seconds, the client page sends a POST AJAX call to the MySQL database and it successfully updates it.

However a user can easily modify the JavaScript variables and cheat their way in the game. Then once they edit the JavaScript variables, the POST grabs that and updates it even though they edited it unethically.

So, how do I prevent this from happening?


问:
Software Optimization vs. Hardware Optimization - what has the bigger impact?
I was wondering how software optimization and hardware optimization compare when it comes to the impact they have on speed and performance gains of computers.

I have heard that improving software efficiency and algorithms over the years has made huge performance gains. Obviously both are extremely important, but what has made the bigger impact in the last 10, 20 or 30 years?

And how do hardware changes affect the software changes? How much of software optimization is a direct result of hardware improvements and how much is independent of the hardware?

To be clear, I am asking about software optimizations at the level of compilers and operating systems. Obviously using better high level-algorithms will result in the largest speed ups (think: quick-sort vs. bubble-sort), but this question is about the underlying reason why computers are faster today, in general.

答:
30 years ago, a PC computer had a Z80 Micro running at maybe 1 Meg, and if you were lucky, another Z80 running the display.

Today, a Typical PC computer has a CPU with 2 or 4 cores running at 2-3 Gig Hz. They also have GPU's with 100's of parrallel processes, again measured in the GhZ range.

Then we have 8 bit vs 64 bit bus widths.

Will all that, why are computers not running 10 thousand times faster than there 30 yo counterparts. The hardware is.  I would argue computer software optimizations are not as good as your questions supposes.


问:
From where do financial firms obtain the stock data to analyze
I've been thinking about the subject and I've always wondered, from where do they obtain the data that is analized in applications, I've looked at Nasdaq's website and they do not seem to have any sort of APIs, do the firms parse yahoo's finance section, or are there special contracts, agreements in places with the different stock markets?</p>

答: There are firms that specialize in providing Market Data for most asset classes.  Reuters, Bloomberg and Markit are three of many.  The data is sold, so there likely won't be public APIs for most of it.  Academics use CRSP to track stock returns - most of the data on efficient markets is from that data set.</p>


问:
At which point do you "know" a technology enough to list it on a resume
I recently had a programmer in for an interview, who listed Python, PHP, Rails and ASP as a few of their skills. In the interview however, they interviewee didn't enough know what control structures and basic logic were, they had only followed a few demo tutorials.

So my question is this: At which point can you add a technology to your resume accurately. Is it when you can demonstrate all basic concepts, write a useful program in it, or are just comfortable using it without having to refer to the documentation every 30 seconds.

I don't believe this is overly subjective, a baseline should easily be established based on feedback.

答:
This is a problem I've run into a bit.  I eventually ditched the "Skills" section of my resume entirely, and just focused on what I'd done with those languages, specifically in my projects and employment section.  I highlight/bold specific technologies as part of the description.

Example:

Web Developer @ Company X (3/3/03 to 5/5/05) Primary developer on a database-driven website to help film students organize their projects. Used PHP and MySQL. Worked on it through development and release leading to a successful roll-out to students in early 2009, and maintenance thereafter.

This method gives your skills actual context that you can discuss in an interview.


答:
Yahoo does have a simple API for obtaining current data for individual stocks. Details here:

http://www.gummy-stuff.org/Yahoo-data.htm

But it's not a way to get historic data. For that, you'll probably have to subscribe to a service.

Title: From where do financial firms obtain the stock data to analyze

Body: I've been thinking about the subject and I've always wondered, from where do they obtain the data that is analized in applications, I've looked at Nasdaq's website and they do not seem to have any sort of APIs, do the firms parse yahoo's finance section, or are there special contracts, agreements in places with the different stock markets?</p>


答:
Assuming no gross software algorithmic inefficiency, it can still be unclear where the biggest gains are. Most recent hardware improvements are useless without the software optimization side of things anyways. Is task parallelization and vectorization a software or hardware optimization? It is both.

Furthermore, speed is sometimes realized through a sea change in hardware capability and software philosophy. For example, due to an explosion of both memory capacity and disk sequential throughput, many software engineers are ditching the concept of seek-heavy relational databases in favor of slamming all the data into memory.

The general point is that hardware optimizations without the corresponding software optimizations often buy you only incremental gains. Same vice versa.

Title: Software Optimization vs. Hardware Optimization - what has the bigger impact?

Body:
I was wondering how software optimization and hardware optimization compare when it comes to the impact they have on speed and performance gains of computers.

I have heard that improving software efficiency and algorithms over the years has made huge performance gains. Obviously both are extremely important, but what has made the bigger impact in the last 10, 20 or 30 years?

And how do hardware changes affect the software changes? How much of software optimization is a direct result of hardware improvements and how much is independent of the hardware?

To be clear, I am asking about software optimizations at the level of compilers and operating systems. Obviously using better high level-algorithms will result in the largest speed ups (think: quick-sort vs. bubble-sort), but this question is about the underlying reason why computers are faster today, in general.


问:
Is it legal to use icons from some other application while developing?
On my machine while developing I'm using icons from other application (in particular MS Paint and Paint.NET) as sign for the user that if he chooses to open that file (with our own internal command) it would open in those applications.

Is it legal to extract the icons from those applications and use them? Commit them to repository and then use on all developers' machines (even those that do not have Paint.NET installed)?

Let me make it clear once more. I'm not talking about including those icons in release version. Providing proper icons is up to graphics/skin designer. I'm talking just about the developing process.

Would extracting the icons in run-time either directly or based on file types change anything?

Recently there was a similar question: Can I legally use the icon of a different software? Yet mine differs in that I do not want to release those icons along my application.

EDIT

Let me emphasis an issue which (judging by answers so far) was missed.

If using the icons in above described circumstances was against the license/law (again judging from answers) then how about asking operating system for an icon of the application or an icon associated with the file. This will likely end in showing the very same icon...

How about file browsing apps for which showing those icons is crucial part of their working rather than a nice but minor feature?

How (from license/law point of view) is operating system/file browser/... different from my own developed application that they are (as I assume they are) allowed to query those icons and show them while I'm not. After all one could claim that looking at his beautiful icons in file browser aided my development like unit tests do and so I should pay extra like I do for using those unit tests...

(Also if icon would be queried at run-time from operating system it might be irrelevant whether it is on my development machine or on a released version at client machine...)

答: You are using somebody else's work to develop your own product. It might be an intermediate step but so is e.g. unit testing. And you have to get a license for your unit testing tool as well even though you are not releasing the unit tests with your product. I guess a lawyer would not hesitate to sue you for it. </p>


答:
Depends on the licensing terms applied to the icons.  If they've come from the creative commons or other free license then yes.  If you can't verify that the icons came from a third party source that's ok to use, or that the assets of the program itself are free to use then you should assume they're covered by copyright.

There's plenty of icon packs out there that don't have any copyright or are released under an open source/creative commons license, and they're already out there as graphic files with no extracting required.  Why not just use one of those?

Title: Is it legal to use icons from some other application while developing?

Body:
On my machine while developing I'm using icons from other application (in particular MS Paint and Paint.NET) as sign for the user that if he chooses to open that file (with our own internal command) it would open in those applications.

Is it legal to extract the icons from those applications and use them? Commit them to repository and then use on all developers' machines (even those that do not have Paint.NET installed)?

Let me make it clear once more. I'm not talking about including those icons in release version. Providing proper icons is up to graphics/skin designer. I'm talking just about the developing process.

Would extracting the icons in run-time either directly or based on file types change anything?

Recently there was a similar question: Can I legally use the icon of a different software? Yet mine differs in that I do not want to release those icons along my application.

EDIT

Let me emphasis an issue which (judging by answers so far) was missed.

If using the icons in above described circumstances was against the license/law (again judging from answers) then how about asking operating system for an icon of the application or an icon associated with the file. This will likely end in showing the very same icon...

How about file browsing apps for which showing those icons is crucial part of their working rather than a nice but minor feature?

How (from license/law point of view) is operating system/file browser/... different from my own developed application that they are (as I assume they are) allowed to query those icons and show them while I'm not. After all one could claim that looking at his beautiful icons in file browser aided my development like unit tests do and so I should pay extra like I do for using those unit tests...

(Also if icon would be queried at run-time from operating system it might be irrelevant whether it is on my development machine or on a released version at client machine...)


问:
Security of logging people in automatically from another app?
I have 2 apps. They both have accounts, and each account has users.

These apps are going to share the same users and accounts and they will always be in sync.

I want to be able to login automatically from one app to the other.

So my solution is to generate a login_key, for example: 2sa7439e-a570-ac21-a2ao-z1qia9ca6g25 once a day. And provide a automated login link to the other app... for example if the user clicks on:

https://account_name.securityhole.io/login/2sa7439e-a570-ac21-a2ao-z1qia9ca6g25/user/123

They are logged in automatically, session created.

So here we have 3 things that a intruder has to get right in order to gain access; account name, login key, and the user id.

Bad idea? Or should I can down the path of making one app an oauth provider? Or is there a better way?

答:
Better to use SSO(single sign on) software like LDAP.
your idea is fine too. but my suggestion is to use apps for what they are made not for user authentication.
and if your one app got crash that is authenticating user, the other will got effect too.</p>


答: Even for release - Using their logo to actually use their product would be like using their trademarked name. They would have an interest in it being so, not oppose it.</p>


答:
With silicon compilation, any piece of software can be implemented in hardware.

The performance gain is basically in the conversion of a sequential Von Neuman architecture into a parallel data flow one.

Therefore, any software optimization is possible in hardware with the same leverage.

Nowadays, software is mainly used for moving data from one place to another, while hardware processes it: FPU, DSP, GPU...

AVCHD cams and YouTube would not exist without hardware implemented video encoders and decoders (they exist on devices as constrained as smartphones!).

These hardware optimizations impact compilers and OSes in the sense that graphics, audio and video processing now belong to the OS and its provided libraries.


问:
With entity framework - who needs a DAL
On EF4 actions on entities are actually done via the Business Element layer (BE).

Why do I need the Data Access (DAL) on another layer?

答:
It's usefull to wrap entity functions with a service/ DAL layer.

This helps to define a clear distinction between business logic(in a backing bean), and data operations(in a DAL).

So the bean purely deals with business logic, and the data operations as simply called.  This means if you later change the data operations, you don't affect the business logic layer(as much).
Much like the division that should be between the view and business layer.  The view layer should not be doing any business logic(with the exception of validation, and you could argue that could still be a call to the business logic).

You'll also find you will probably use the same data operation repeately throughout your application, so if you have it wrapped in a service class, it's easy to reuse.

My own rule of thumb is, if you have a entity manager in a backing bean, then your doing it wrong.

Title: With entity framework - who needs a DAL


问:
Fear of releasing a hobby project - how to overcome?
I don't know if this question is strictly related to software development, but still I'll give it a try:

Like a lot of programmers, I love to work on hobby projects. Sometimes, seemingly good ideas turn out to be not so good, so I drop the project. But sometimes, something useful comes out of the project. So, I could release it, present it to the world, right?

Wrong. Somehow, I don't seem to be able to make this step. I fear that my code is not good enough, I can always think of things which are suboptimal, of features which could be added. So, I don't release anything, I lose interest, and at one point abandon the project.

Is this normal? How do you overcome such a situation?

答:
First of all, remember: shipping is a feature. It's better to release something imperfect than to release nothing at all.

The other thing to note is that these are Hobby projects.  If you don't meet deadlines or lose interest it's not a big deal. You're doing the project for fun after all.


答:
Put it out there.

It is not that difficult to do this with a social coding site such as GitHub or Bitbucket. Most of the stuff of what you'll put out probably won't be used a lot, but that is ok. That is pretty much normal in these social coding sites, and a lot of projects get abandoned (even some useful ones). But the greatest thing is that others can pick off what you've left (given you have a permissive license).

Even though your stuff probably won't be used by anyone else there are several benefits of why you still should put it out:

You learn to use version control which is something that a lot of programmers don't know how, making you more hirable

People may point out problems for you; all opportunities for you to learn how to do things differently

You will have an online portfolio of stuff that you've done, great to have as a complement to your resumé

Title: Fear of releasing a hobby project - how to overcome?

Body:
I don't know if this question is strictly related to software development, but still I'll give it a try:

Like a lot of programmers, I love to work on hobby projects. Sometimes, seemingly good ideas turn out to be not so good, so I drop the project. But sometimes, something useful comes out of the project. So, I could release it, present it to the world, right?

Wrong. Somehow, I don't seem to be able to make this step. I fear that my code is not good enough, I can always think of things which are suboptimal, of features which could be added. So, I don't release anything, I lose interest, and at one point abandon the project.

Is this normal? How do you overcome such a situation?


答: Basically, I wouldn't worry about if people like my code or not. Release it under a free license, if it's useful for people, but they find bugs, suboptimal solutions and require more features, they are free to fix it themselves. Using GPL or LGPL will also make it possible for you to find these fixes, and you can apply them yourself if you find them useful/fitting.</p>


问:
Plagued by multithreaded bugs
On my new team that I manage, the majority of our code is platform, TCP socket, and http networking code. All C++.  Most of it originated from other developers that have left the team. The current developers on the team are very smart, but mostly junior in terms of experience.

Our biggest problem: multi-threaded concurrency bugs. Most of our class libraries are written to be asynchronous by use of some thread pool classes. Methods on the class libraries often enqueue long running taks onto the thread pool from one thread and then the callback methods of that class get invoked on a different thread. As a result, we have a lot of edge case bugs involving incorrect threading assumptions.  This results in subtle bugs that go beyond just having critical sections and locks to guard against concurrency issues.

What makes these problems even harder is that the attempts to fix are often incorrect. Some mistakes I've observed the team attempting (or within the legacy code itself) includes something like the following:

Common mistake #1 - Fixing concurrency issue by just put a lock around the shared data, but forgetting about what happens when methods don't get called in an expected order.  Here's a very simple example:

```<code>void Foo::OnHttpRequestComplete(statuscode status)
{
    m_pBar->DoSomethingImportant(status);
}

void Foo::Shutdown()
{
    m_pBar->Cleanup();
    delete m_pBar;
    m_pBar=nullptr;
}
</code>```

So now we have a bug in which Shutdown could get called while OnHttpNetworkRequestComplete is occuring on. A tester finds the bug, captures the crash dump, and assigns the bug to a developer. He in turn fixes the bug like this.

```<code>void Foo::OnHttpRequestComplete(statuscode status)
{
    AutoLock lock(m_cs);
    m_pBar->DoSomethingImportant(status);
}

void Foo::Shutdown()
{
    AutoLock lock(m_cs);
    m_pBar->Cleanup();
    delete m_pBar;
    m_pBar=nullptr;
}
</code>```

The above fix looks good until you realize there's an even more subtle edge case. What happens if Shutdown gets called before OnHttpRequestComplete gets called back? The real world examples my team has are even more complex, and the edge cases are even harder to spot during the code review process.

Common Mistake #2 - fixing deadlock issues by blindly exiting the lock, wait for the other thread to finish, then re-enter the lock - but without handling the case that the object just got updated by the other thread!

Common Mistake #3 - Even though the objects are reference counted, the shutdown sequence "releases" it's pointer. But forgets to wait for the thread that is still running to release it's instance. As such, components are shutdown cleanly, then spurious or late callbacks are invoked on an object in an state not expecting any more calls.

There are other edge cases, but the bottom line is this:

Multithreaded programming is just plain hard, even for smart people.

As I catch these mistakes, I spend time discussing the errors with each developer on developing a more appropriate fix. But I suspect they are often confused on how to solve each issue because of the enormous amount of legacy code that the "right" fix will involve touching.

We're going to be shipping soon, and I'm sure the patches we're applying will hold for the upcoming release. Afterwards, we're going to have some time to improve the code base and refactor where needed. We won't have time to just re-write everything. And the majority of the code isn't all that bad. But I'm looking to refactor code such that threading issues can be avoided altogether.

One approach I am considering is this. For each significant platform feature, have a dedicated single thread where all events and network callbacks get marshalled onto. Similar to COM apartment threading in Windows with use of a message loop. Long blocking operations could still get dispatched to a work pool thread, but the completion callback is invoked on on the component's thread. Components could possibly even share the same thread. Then all the class libraries running inside the thread can be written under the assumption of a single threaded world.

Before I go down that path, I am also very interested if there are other standard techniques or design patterns for dealing with multithreaded issues.  And I have to emphasize - something beyond a book that describes the basics of mutexes and semaphores. What do you think?

I am also interested in any other approaches to take towards a refactoring process.  Including any of the following:

Literature or papers on design patterns around threads. Something beyond an introduction to mutexes and semaphores. We don't need massive parallelism either, just ways to design an object model so as to handle asynchronous events from other threads correctly.

Ways to diagram the threading of various components, so that it will be easy to study and evolve solutions for. (That is, a UML equivalent for discussing threads across objects and classes)

Educating your development team on the issues with multithreaded code.

What would you do?

答:
Literature or papers on design patterns around threads. Something
  beyond an introduction to mutexes and semaphores. We don't need
  massive parallelism either, just ways to design an object model so as
  to handle asynchronous events from other threads correctly.

I'm currently reading this and it explain all the problems you can get and how to avoid them, in C++ (using the new threading library but I think the global explainations are valid for your case):
http://www.amazon.com/C-Concurrency-Action-Practical-Multithreading/dp/1933988770/ref=sr_1_1?ie=UTF8&qid=1337934534&sr=8-1

Ways to diagram the threading of various components, so that it will
  be easy to study and evolve solutions for. (That is, a UML equivalent
  for discussing threads across objects and classes)

I personally use a simplified UML and just assume that messages are done asynchronously.
Also, this is true between "modules" but inside modules I don't want to have to know.

Educating your development team on the issues with multithreaded code.

The book would help, but I think exercices/prototyping and experienced mentor would be beter.

What would you do?

I would totally avoid having people not understanding concurrency problems work on the project. But I guess you cannot do that, so in your specific case, other than try to make sure the team gets more educated, I have no idea.

Title: Plagued by multithreaded bugs


答: It's still good idea to have a separate DAL. In the future, you might want to implement something else (other than Entity Framework). Will you go on looking for all the data access code lying all over the place? nah, I don't think so.</p>

Title: With entity framework - who needs a DAL

Body:
On EF4 actions on entities are actually done via the Business Element layer (BE).

Why do I need the Data Access (DAL) on another layer?


问:
Google Analytics with multiple environments
We are planning to use Google Analytics in our organization and I am in charge for setting it up. I was wondering how to deal with multiple environments. We sure do not want to collect data during development and QA (or maybe collect data to a different analytics account), but we want to when the site goes to production (obviously).

How do you deal with multiple environments and Google Analytics ?

Do you setup multiple accounts for Google Analytics and use either one depending on the environement ?

We're using ASP.NET 2.0, if that matters.

答:
Another option would be Google Analytics profiles. Use the same account in all environments, but add a hostname filter in each profile to only include traffic from the respective environment.

For example, if your internal QA environment is qa.example.com, create a "QA" profile in Google Analytics with a custom filter to only include hostnames matching ^qa\.example\.com$. In your "Production" profile, do the opposite and exclude traffic from internal hostnames.


答:
"state" is needed, when you need to remember something. Functions (not "methods" or whatever) ideally only depend on their inputs. If you ask a question where the answer can change over time, even if the inputs are the same, you need something to remember that difference in the answer, correct? Otherwise, you are unable to give a different answer because no other factors have changed (let's assume the answer does not depend on time directly).

That "thing/information" that you need to remember is called "state".

(it is not requiered that this "state" changes over time, it's basically just a way to say "remembering/knowing something")

Title: Definition of "state"