问:
What are some of the major differences in process management between CGI and newer (better) technologies?
I know CGI spawns a new process for every HTTP request that it serves, while servlets use one Java process to serve many requests. What do other technologies (rails, WSGI/django, mod_php, asp.net etc.) do so that web servers do not have to spawn a new process new HTTP request?</p>

答:
Servers generally either

1) Use a thread pool with a thread per client connection request, potentially with a separate pool of separate thread/processes to handle "application" code (as opposed to the basics of handling a HTTP request. A thread handles each request from beginning to end; often thread pooling is used to reduce the amount of startup and teardown required with each connection.

Or, 2) they will use an event-based model which allows a single thread / process to handle many connections. In this case, each of the "events" such as new connection or new received packet will go into a queue of sorts to be worked through by one or a small number of threads. This is a highly efficient way to scale if you can limit the amount of work to be done processing each event (otherwise small quick requests will be queued behind larger requests).

The major difference as far as outcomes are concerned is that both of these models avoid or minimise the overheads of process startup time and inter-process communication and handoffs.


问:
Logging asynchronously - how should it be done?
In many of the services I work on there are a lot of logging being done.
The services are WCF services (mostly) which use the .NET EventLogger class.

I'm in the process of improving these services' performance, and I got to think that logging asynchronously would benefit performance.

I'm unaware of what happens when multiple threads ask to log, and if it creates a bottleneck, but even if it doesn't I still think that it shouldn't interfere with the actual process being executed.

My thoughts are that I should invoke the same log method I call now but do so using a new thread, while continuing with the actual process.

Some questions about that:

Is it ok?

Are there any downsides?

Should it be done in a different way?

Maybe its so fast that it doesn't even worth the effort?

答:
Key factors to consider are your need for reliability in the logfiles and the need for performance. Refer downsides. I think this is a great strategy for high performance situations.

Is it ok - yes

Are there any downsides - yes - depending on the criticality of your logging and your implementation any of the following could occur - logs written out of sequence, log thread actions not complete before event actions complete. (Imagine a scenario where you log "starting to connect to DB" and you then crash the server, log event may never get written even though the event has occurred (!))

Should it be done in a different way - you might want to look at Disruptor model as it's almost ideal for this scenario

Maybe its so fast that it deosn't even worth the effort - disagree. If yours is an "application" logic, and the only thing you do is write logs of the activity - then you will be orders of magnitude lower latency by offloading logging. If however you rely on a 5sec DB SQL call to return before logging 1-2 statements, the benefits are mixed.

ContentLicense: CC BY-SA 3.0


问:
Difference between immutable and const
I've often seen the terms immutable and const used interchangeably. However, from my (little) experience, the two differ a lot in the 'contract' they make in code:

Immutable makes the contract that this object will not change, whatsoever (e.g. Python tuples, Java strings).

Const makes the contract that in the scope of this variable it will not be modified (no promise whatsoever about what other threads might do to the object pointed to during this period, e.g. the C/C++ keyword).

Obviously, the two are not equivalent, unless the language is single-threaded (PHP), or has either linear or uniquness typing system (Clean, Mercury, ATS).

First, is my understanding of these two concepts correct?

Second, if there is a difference, why are they almost exclusively used interchangeably?

答: In C++ they are the same. Although you can change a const object if you have it's location in memory and OS permission to write to that memory.

Title: Difference between immutable and const


答:
Immutable objects are those that does not change state after creating it. For example;

```<code>string prefix = "Pre";
string postfix = "Post";
string myComplexStr = prefix + postfix;
</code>```

In this example myComplexStr object is immutable but not constant because it's value is calculated. And it is immutable because it is a string and has a static length property and cannot change.

Const objects are generally used to identify some real constants whose values are known before compilation like Pi, "USA", "StackOverflow.com", port numbers and so on.

From this perspective Const is different from Immutable objects because their values are not calculated by the program.

But if you are talking about "const" keyword in C++, you can say that "const" is used to create immutable objects.

Title: Difference between immutable and const

Body:
I've often seen the terms immutable and const used interchangeably. However, from my (little) experience, the two differ a lot in the 'contract' they make in code:

Immutable makes the contract that this object will not change, whatsoever (e.g. Python tuples, Java strings).

Const makes the contract that in the scope of this variable it will not be modified (no promise whatsoever about what other threads might do to the object pointed to during this period, e.g. the C/C++ keyword).

Obviously, the two are not equivalent, unless the language is single-threaded (PHP), or has either linear or uniquness typing system (Clean, Mercury, ATS).

First, is my understanding of these two concepts correct?

Second, if there is a difference, why are they almost exclusively used interchangeably?

Body:
Immutable objects are those that does not change state after creating it. For example;

string prefix = "Pre";
string postfix = "Post";
string myComplexStr = prefix + postfix;

In this example myComplexStr object is immutable but not constant because it's value is calculated. And it is immutable because it is a string and has a static length property and cannot change.

Const objects are generally used to identify some real constants whose values are known before compilation like Pi, "USA", "StackOverflow.com", port numbers and so on.

From this perspective Const is different from Immutable objects because their values are not calculated by the program.

But if you are talking about "const" keyword in C++, you can say that "const" is used to create immutable objects.


问:
In Search of Automatic ORM with REST interface
I have this wish that so far Google hasn't been able to fulfill. I want to find a package (ideally in PHP, because I know PHP, but I guess that's not a hard requirement) that you point at a database, it builds an ORM based on what it finds there, and exposes a REST interface over the web.

Everything I've found in my searches requires a bunch of code--like, it wants you to build the classes for it, but it'll handle the REST request routing. Or it does database and relational stuff just fine, but you have to build your own methods for all the CRUD actions.

That's dumb. REST is well defined. If I wanted to re-invent the wheel, I totally could, but I don't want to. Isn't there somebody who's built a one-shot super-simple auto-RESTing web service package?

答: I think the answer to your question may well be "no". I've been lurking around the PHP trenches for about six years and, to date, have not stumbled across the type of thing you are looking for. It does seem like a fairly straightforward thing to build though, so it is a bit of a mystery why nobody has done it yet. Zend Framework, RedBean and a whole bunch of other frameworks with database table auto-discovery should provide a good basis for such a project.</p>


答:
I think logging is generally a synchronous operation by it's nature. You want to log things if they happen or if they don't depending on your logic, so in order to log something, that thing needs to be evaluated first.

Having said that, you can improve your application's performance by caching logs and then creating a thread and saving them to files when you have a CPU bound operation.

You need to identify your checkpoints cleverly so you don't lose your important logging information during that cache period.

If you want to have a performance boost in your threads you need to balance IO operations and CPU operations.

If you create 10 threads that all do IO, then you won't get a performance boost.

Title: Logging asynchronously - how should it be done?

Body:
In many of the services I work on there are a lot of logging being done.
The services are WCF services (mostly) which use the .NET EventLogger class.

I'm in the process of improving these services' performance, and I got to think that logging asynchronously would benefit performance.

I'm unaware of what happens when multiple threads ask to log, and if it creates a bottleneck, but even if it doesn't I still think that it shouldn't interfere with the actual process being executed.

My thoughts are that I should invoke the same log method I call now but do so using a new thread, while continuing with the actual process.

Some questions about that:

Is it ok?

Are there any downsides?

Should it be done in a different way?

Maybe its so fast that it doesn't even worth the effort?


问:
Should we avoid object creation in Java?
I was told by a colleague that in Java object creation is the most expensive operation you could perform. So I can only conclude to create as few objects as possible.

This seems somewhat to defeat the purpose of object oriented programming. If we aren't creating objects then we are just writing one long class C style, for optimization?

答:
This really depends on the specific application, so it's really hard to say in general. However, I would be pretty surprised if object creation was actually a performance bottleneck in an application. Even if they are slow, the code-style benefit will probably outweigh the performance (unless it's actually noticeable to the user)

In any case, you shouldn't even start to worry about these things until you have profiled your code to determine the actual performance bottlenecks instead of guessing. Until then, you should do whatever is best for code readability, not performance.


答:
First, is my understanding of these two concepts correct?

Yes but your second question shows that you don't understand these differences.

Second, if there is a difference, why are they almost exclusively used
  interchangeably?

const in C++ is only used for access level (it means "read-only"), not for immutability. It imply that the access itself is totally separate from the data. For example you could manipulate some data then expose it through a const reference. The access is read-only, but the data itself, as all the datam is mutable.

const only garantee access limitations, while immutability (like in D for example) imply really no way to change the data at whatever stage of the life of the object.

Now, you can simulate immutability in C++ by making sure some data are not possible to be accessed in any other way than const and make sure it is initialized then not touched anymore. But that's not a strong guarantee as languages like D gives you when you mark your data as immutable. The language make sure it is not possible at all to do any operation modifying that data, while in C++ you are still potentially able to change the data through const casting and mutability if really necessary.

In the end, it is not the same at all as it don't offer at all the same guarantees.

Title: Difference between immutable and const


答:
Actually, due to the memory management strategies that the Java language (or any other managed language) makes possible, object creation is little more than incrementing a pointer in a block of memory called the young generation. It's much faster than C, where a search for free memory has to be done.

The other part of the cost is object destruction, but it's hard to compare to C. The cost of a collection is based on the amount of objects saved long-term but the frequency of collections is based on amount of objects created... in the end, it's still much faster than C-style memory management.

Title: Should we avoid object creation in Java?

Body:
I was told by a colleague that in Java object creation is the most expensive operation you could perform. So I can only conclude to create as few objects as possible.

This seems somewhat to defeat the purpose of object oriented programming. If we aren't creating objects then we are just writing one long class C style, for optimization?


答:
Speaking for Java where the keyword "final" represents "const", consider:

```<code>final Person someone = new Person();
</code>```

This means someone can NEVER refer to another Person object. But, you can still change details of the person being referred. E.g. someone.setMonthlySalary(10000);

But, if someone was an "Immutable" object, one of the following would be true:
(a) You would not have a method named setMonthlySalary
(b) Calling setMonthlySalary would always throw an exception such as UnsupportedOperationException

Title: Difference between immutable and const

Body:
Speaking for Java where the keyword "final" represents "const", consider:

final Person someone = new Person();

This means someone can NEVER refer to another Person object. But, you can still change details of the person being referred. E.g. someone.setMonthlySalary(10000);

But, if someone was an "Immutable" object, one of the following would be true:
(a) You would not have a method named setMonthlySalary
(b) Calling setMonthlySalary would always throw an exception such as UnsupportedOperationException


问:
How to implement a system to hide spammed user content?
I'm trying to work out a good way to manage user submitted content and create a method to determine when spammed/poor content should be hidden.

The aim is to create comment voting similar to youtubes like/dislike comments and if the score is good show the comments, else they're invisible.

Approach

My thought is to do this via the comments table, you could create two columns rateup, ratedown.

For each rate up the comment gets the rateup colulmn is: rateup = rateup + 1

and the same for the ratedown: ratedown = ratedown + 1

You can then put a clause into your database query to only select comments if their rateup ratio is greater than a number, say -5:

```<code>WHERE (rateup - ratedown) > -5
</code>```

but this would need a lot of voting up and down if a user posts many spam/poor content posts over the site?

To strengthen the approach I could add the same two columns to the user table and also update these columns to give an overlal view of the users combined content submission ratio and then display comments like so:

```<code>WHERE ((comment.rateup - comment.ratedown) > -5 ) && ((user.rateup - user.ratedown) > -5 )
</code>```

Issues

Would this approach lead to instances of users creating mass fake accounts to attack good users and ruin their reputation?

What other methods could I use to help hide spammed/poor content without moderators having to manually go through everything?

答: Another approach would be to use flagged posts as data points to train a neural network. Then the program could screen content as it is posted. The book Algorithms of the Intelligent Web is kind of heavy reading, but it outlines the theory behind spam filters nicely.</p>


答:
Your colleague has no idea what they are talking about.

Your most expensive operation would be listening to them. They wasted your time mis-directing you to information that is over a decade out of date (as of the original date this answer was posted) as well as you having to spend time posting here and researching the Internet for the truth.

Hopefully they are just ignorantly regurgitating something they heard or read from more than a decade ago and don't know any better. I would take anything else they say as suspect as well, this should be a well known fallacy by anyone that keeps up to date either way.

Everything is an Object ( except primitives )

Everything other than primitives ( int, long, double, etc ) are Objects in Java. There is no way to avoid Object creation in Java.

Object creation in Java due to its memory allocation strategies is faster than C++ in most cases and for all practical purposes compared to everything else in the JVM can be considered "free".

Early as in late 1990's early 2000s JVM implementations did have some performance overhead in the actual allocation of Objects. This hasn't been the case since at least 2005.

If you tune -Xms to support all the memory you need for your application to run correctly, the GC may never have to run and sweep most of the garbage in the modern GC implementations, short lived programs may never GC at all.

It doesn't try and maximize free space, which is a red herring anyway, it maximizes performance of the runtime. If that means the JVM Heap is almost 100% allocated all the time, so be it. Free JVM heap memory doesn't give you anything just sitting there anyway.

There is a misconception that the GC will free memory back to the rest of the system in a useful way, this is completely false!

The JVM heap doesn't grow and shrink so that the rest of the system is positively affected by free memory in the JVM Heap. -Xms allocates ALL of what is specified at startup and its heuristic is to never really release any of that memory back to the OS to be shared with any other OS processes until that instance of the JVM quits completely. -Xms=1GB -Xmx=1GB allocates 1GB of RAM regardless of how many objects are actually created at any given time. There are some settings that allow for percentages of the heap memory to be release, but for all practical purposes the JVM never is able to release enough of this memory for this to ever happen so no other processes can reclaim this memory, so the rest of the system doesn't benefit from the JVM Heap being free either. An RFE for this was "accepted" 29-NOV-2006, but nothing has ever been done about it. This is behavior is not considered a concern by anyone of authority.

There is a misconception that creating many small short lived objects causes the JVM to pause for long periods of time, this is now false as well

Current GC algorithms are actually optimized for creating many many small objects that are short lived, that is basically the 99% heuristic for Java objects in every program. Attempts at Object Pooling will actually make the JVM perform worse in most cases.

The only Objects that need pooling today are Objects that refer to finite resources that are external to the JVM; Sockets, Files, Database Connections, etc and can be reused. Regular objects can not be pooled in the same sense as in languages that allow you direct access to memory locations. Object caching is a different concept and may or may not be what some people naively call pooling, the two concepts are not the same thing and should not be conflated.

The modern GC algorithms don't have this problem because they don't deallocate on a schedule, they deallocate when free memory is needed in a certain generation. If the heap is big enough, then no deallocations happen long enough to cause any pauses.

Object Oriented Dynamic languages are beating C even now days on compute sensitive tests.


问:
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.

答: First try to write your own.  Then look at someone else's solution.</p>

ContentLicense: CC BY-SA 2.5


答:
Bottom line:
Don't compromise your design in order to take shortcuts creating objects. Do avoid creating objects unnecessarily. If sensible, design to avoid redundant operations (of any sort).

Contrary to most answers - yes, object allocation DOES have a cost associated. It is a low cost, but you should avoid creating unnecessary objects. Same as you should avoid unnecessary anything in your code. Large object graphs make GC slower, imply longer execution times in that you are probably going to have more method calls, trigger more CPU cache misses, and increase likelihood of your process being swapped to disk in low RAM cases.

Before anyone rants about this being an edge case - I have profiled applications that, before optimising, created 20+MB of objects in order to process ~50 rows of data. This is fine in testing, until you scale up to a hundred requests a minute and suddenly you are creating 2GB of data per minute. If you want to do 20 reqs/sec you are creating 400MB of objects and then throwing it away. 20 reqs/sec is tiny for a decent server.


答:
I’ll speak to C++, where this difference is most relevant.

As you correctly note, immutable means that an object cannot change at all after its creation. This creation can of course occur at runtime, i.e., a const object is not necessarily a compile-time constant. In C++, an object is immutable if (1) and either (2) or (3) are met:

It has no members declared mutable that are mutated by const member functions

It is declared const

const member functions do not use const_cast to remove const qualification in order to mutate any members

However, you could also consider access modifiers: if an operation internally mutates an instance, but has no effect on the state of the instance observable through its public interface, then the object is “logically immutable”.

So C++ provides the tools necessary to create immutable objects, but like most everything in C++, the tools are only minimally sufficient, and require diligence to actually use. The state of an instance is not necessarily confined to the instance member variables—because C++ does not provide a way to enforce referential transparency, it can include global or class state as well.

const also has another function in C++: to qualify references and pointers. A const reference may refer to a non-const object. It is legal (though not generally necessary or advisable) to use const_cast to mutate an object through a const reference, if and only if that object is declared non-const:

```<code>int        i = 4;         // Non-const object.
const int* p = &i;        // Pointer to a constant integer.

*const_cast<int*>(p) = 5; // Legal.
</code>```

And of course it’s undefined behaviour to mutate a const object:

```<code>const int  i = 4;         // const object.
const int* p = &i;        // Pointer to a const integer.

*const_cast<int*>(p) = 5; // Illegal.
</code>```

Title: Difference between immutable and const

Body:
I’ll speak to C++, where this difference is most relevant.

As you correctly note, immutable means that an object cannot change at all after its creation. This creation can of course occur at runtime, i.e., a const object is not necessarily a compile-time constant. In C++, an object is immutable if (1) and either (2) or (3) are met:

It has no members declared mutable that are mutated by const member functions

It is declared const

const member functions do not use const_cast to remove const qualification in order to mutate any members

However, you could also consider access modifiers: if an operation internally mutates an instance, but has no effect on the state of the instance observable through its public interface, then the object is “logically immutable”.

So C++ provides the tools necessary to create immutable objects, but like most everything in C++, the tools are only minimally sufficient, and require diligence to actually use. The state of an instance is not necessarily confined to the instance member variables—because C++ does not provide a way to enforce referential transparency, it can include global or class state as well.

const also has another function in C++: to qualify references and pointers. A const reference may refer to a non-const object. It is legal (though not generally necessary or advisable) to use const_cast to mutate an object through a const reference, if and only if that object is declared non-const:

int        i = 4;         // Non-const object.
const int* p = &i;        // Pointer to a constant integer.

*const_cast<int*>(p) = 5; // Legal.

And of course it’s undefined behaviour to mutate a const object:

const int  i = 4;         // const object.
const int* p = &i;        // Pointer to a const integer.

*const_cast<int*>(p) = 5; // Illegal.

ContentLicense: CC BY-SA 4.0


答:
There is a kernel of truth in what your colleague is saying. I respectfully suggest the issue with object creation is actually garbage collection. In C++ the programmer can control precisely how memory is deallocated. The program can accumulate crud for as long or as short as it likes. Further, the C++ program can discard the crud using a different thread than the one that created it. Thus the thread currently working never has to stop to clean up.

In contrast, the Java Virtual Machine (JVM) periodically stops your code to reclaim unused memory. Most Java developers never notice this pause, since it is usually infrequent and very short. The more crud you accumulate or the more constrained your JVM is, the more frequent these pauses are. You can use tools like VisualVM to visualize this process.

In recent versions of Java, the garbage collection (GC) algorithm can be tuned. As a general rule, the shorter you want to make the pauses, the more expensive the overhead in the virtual machine (i.e. CPU and memory spent coordinating the GC process).

When might this matter? Any time you care about consistent sub-millisecond response rates, you'll care about GC. Automated trading systems written in Java tune the JVM heavily to minimize pauses. Firms that would otherwise write Java turn to C++ in situations where systems have to be highly responsive all the time.

For the record, I do not condone object avoidance in general! Default to object-oriented programming. Adjust this approach only if the GC gets in your way, and then only after trying to tune the JVM to pause for less time. A good book on Java performance tuning is Java Performance by Charlie Hunt and Binu John.


问:
Is unit testing procedural code effective?
On a current project, the powers that be want to have unit testing incorporated into our development cycle to avoid the constant amount of bugs that seem to seep into our code. The problem is that the spaghetti code is 95% percent procedural, which I've never done unit testing with (all my experience with unit testing has been with OOP code)

So my question in a nutshell is would it be wise to proceed with unit testing with our current codebase, or suggest that it be postponed until the application has been migrated to a proper OOP framework?

PS: While I tried to style this question as language agnostic, I feel that stating the application in question uses PHP and javascript will help provide more specific answers that could answer this question since from experience this occurrence occurs most with such applications.

答:
I don't think it's possible to do true unit tests against procedural code. The main problem being that each procedure will likely have many dependencies that cannot be stubbed out.  At best the tests will be integration tests.  I've done a similar thing many moons ago with VB6 modules and VBA modules in MS Access.

That said, if you can put test scaffolding around the methods causing the most pain, that has to be of value, right?


答:
Unit testing works well with objects, especially since it provides lots of fancy features, like mock objects, which helps creating better tests faster.

This being said, nothing forbids doing unit testing on a procedural codebase. In OOP, most unit tests are testing methods by passing some parameters to them and expecting either a result, or an exception of a specific type. This can be done as far with procedural code too; just that instead of testing methods, you'll test functions.

Note that you'll have to:

Isolate the functions you have to test and the ones you don't need to. In OOP, this is easy: private methods don't have to be tested because the callers will never be able to access them directly. Chances are, in your procedural code, some functions are like this and don't need tests.

Think about global scope. The problem exists in OOP too, but if you say that you have to test spaghetti code, chances are that the people who wrote this code have bad habits, such as using global scope too much, and doing some crazy things like changing $_GET or $_POST arrays inside functions.

Deal with code outside functions. This is a more complicated case, but still possible. Either you require_once a page to see what happens and catch the output through ob_start/ob_get_clean, or you do an HTTP request from the test suite and analyze the response by parsing the HTML. This is not really an UI testing: here, you don't care if a button on a page appears at the left or at the right or if a link is in big red capital letters or in small blue ones. What you care about is to find some HTML elements through DOM and compare their content to the expected one.

Test the response codes. require_once with output buffering is good, but you also have to test how the web application deal with errors. For example if the expected result of a test is 404 Not Found, you must do an HTTP request in order to know what the response is.

Title: Is unit testing procedural code effective?

Body:
On a current project, the powers that be want to have unit testing incorporated into our development cycle to avoid the constant amount of bugs that seem to seep into our code. The problem is that the spaghetti code is 95% percent procedural, which I've never done unit testing with (all my experience with unit testing has been with OOP code)

So my question in a nutshell is would it be wise to proceed with unit testing with our current codebase, or suggest that it be postponed until the application has been migrated to a proper OOP framework?

PS: While I tried to style this question as language agnostic, I feel that stating the application in question uses PHP and javascript will help provide more specific answers that could answer this question since from experience this occurrence occurs most with such applications.


问:
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

答:
The Pragmatic Programmer calls these 'Broken Windows'.

If you don't fix broken windows then there is a tendency for them to create a downward spiral of code quality. And the more of them there are the bigger job of fixing them, and therefore it is less likely that they will be fixed.

Whether to fix them now or later is up to a matter of judgment. Is it a simple fix? Are you sure the code is doing what you think it is? Is it likely to distract from your current task? Are you under time constraints? Is it likely to introduce more bugs?

At the very least, mark the item in your tracking system and make sure it gets fixed later. It is a important to mark it in the tracking system even if you decide to fix it now, to make sure that it is tested as well, and to document changes.


问:
How were Fortran's original control structures insufficient?
In my Programming Language Concepts class it was mentioned in passing that Fortran's original control structures were insufficient. It was alluded that they were too similar to machine instructions for the IBM 704. Was this the case? What exactly made them insufficient?</p>

答:
Well let's see early versions of Fortran had IF GOTO and DO.

There were several variations on IF and GOTO including ASSIGNED GOTOs and computed GOTO which was sort of like a CASE statement.

So apart from the DO loops all the control statements were variations on IF and GOTO involving hard coded statement numbers. The result was more vermicelli than spaghetti.

The DO loop itself was problematic in that it was strictly "do until" with the test at the bottom of the loop, so there was no way to skip the first iteration other than preceding it with yet another "IF (cond) GOTO 9999".

So as most control structures were "GOTO linenumber" any substantial change to the code would involve lots error prone changes to the target line numbers.

The DO loop needed to be supplemented with a GOTO to turn it into a DO WHILE.

The earliest Fotrans had a "GOTO" of the form.

```<code>IF (VAR) 100,200,300
</code>```

Which meant if VAR is <0 then go to statement 100. If = 0 then statement 200, if > 0 then statement 300.

On the whole it was not too bad an attempt. The fact that you could write formulas that looked similar to what you professor wrote on the blackboard was the killer feature of FORTRAN, the program flow had to wait a few years to catch up.

Body:
Well let's see early versions of Fortran had IF GOTO and DO.

There were several variations on IF and GOTO including ASSIGNED GOTOs and computed GOTO which was sort of like a CASE statement.

So apart from the DO loops all the control statements were variations on IF and GOTO involving hard coded statement numbers. The result was more vermicelli than spaghetti.

The DO loop itself was problematic in that it was strictly "do until" with the test at the bottom of the loop, so there was no way to skip the first iteration other than preceding it with yet another "IF (cond) GOTO 9999".

So as most control structures were "GOTO linenumber" any substantial change to the code would involve lots error prone changes to the target line numbers.

The DO loop needed to be supplemented with a GOTO to turn it into a DO WHILE.

The earliest Fotrans had a "GOTO" of the form.

IF (VAR) 100,200,300

Which meant if VAR is <0 then go to statement 100. If = 0 then statement 200, if > 0 then statement 300.

On the whole it was not too bad an attempt. The fact that you could write formulas that looked similar to what you professor wrote on the blackboard was the killer feature of FORTRAN, the program flow had to wait a few years to catch up.


答:
suggest that it be postponed until the application has been migrated to a proper OOP framework

Get some automatic tests in place before migrating to another platform, not afterwards.  Add further tests while doing the migration, not afterwards. If those tests are "integration tests" or unit tests you have to decide yourself, but typically you can use your favorite xUnit test framework for both kinds.


答:
The most effective way to start unit testing is to identify the class of errors that occur most often, or are the highest cost.  Then create tests that target those errors.

How those test get implemented will differ between paradigms and languages.  The biggest things that will impact your ability to do unit testing is the quality of the code; less so the paradigm used.  Remember unit testing is about testing a "unit" of code in isolation.  Anything that impacts your ability to isolate "units" of code will make testing harder.

use of globals

side effects

tightly coupled code

badly coupled code

a large number of conditionals

badly designed "units"

All these will have a higher impact on difficulty of testing than language paradigm.


问:
How do asserts and other error avoidance checks fit into TDD?
http://butunclebob.com/ArticleS.UncleBob.TheThreeRulesOfTdd

You are not allowed to write any production code unless it is to make a failing unit test pass.

So where do asserts fit into this?  If you followed this rule you'd never write an assert without a unit test.  But how would you test for the existence of an assert?  The very nature of assert seems to make this idea impossible as the test would explode.

And what about code meant to handle absurd conditions that are difficult or impossible to replicate?  Some sort of FUBAR from a system call for example...  You need to handle the error but the condition that causes the error is pretty rare and comes from the OS.  How do you write a unit test to make that fail?

Or say you're writing a template library and want to do some concept checks before going too deep into template vomit land?  I don't know of any framework that supports compile time failure as a test PASS.

I've tried to live by some of these TDD edicts, but at some point I've always run into walls I can't get around.  These are some.

I guess I should say that I'm talking about assert in the C/C++ sense in which a program, built without NDEBUG, will fault out if the assertion fails.  Not some exception throwing mechanism that's called assert.  Didn't even realize someone would use that name for throwing exceptions.

答:
I use tests and asserts for two different purposes.

I use tests primarily to communicate the desired behavior of my program, and secondarily to validate said behavior.  I use asserts primarily to communicate assumptions with potential pitfalls, and secondarily to validate said assumptions.

Neither are silver bullets, and in my experience both function better when viewed as a tool for communicating intent to other programmers, as I feel this is what they're good at.  As others have said, don't get caught up in the dogma.  Figure out what value the tools offer you and your team, and add them to your process as necessary.


问:
Can I legally use the icon of a different software?
Suppose I am including a feature in my image-viewing software, which opens an image in Photoshop ('Send to Photoshop'), using Photoshop's OLE automation framework.

Am I allowed to use the icon of Photoshop.exe as the image of this 'Send to' button?

答:
No. The photoshop icon is artwork that is protected and you must get a written permission from adobe.

That said, I saw lot of applications using protected artworks, especially Excel & Word icons, without problems, but you really don't want to be exposed like this.


答:
No, as per Use of Adobe icons and web logos:

You may not use Adobe product icons except under a written license from Adobe.You may qualify for use of an Adobe product icon(s) under a program offered through an Adobe Partner program. If you are not eligible for any of these programs, you may be eligible to use one of Adobe's web logos or a box shot of an Adobe product instead.

You should however contact Adobe directly and ask permission to use Photoshop's icon. It's a long shot, but it's not unthinkable that they'd want their icon to be in an image viewing software since it's one of their core areas of expertise and you'd be advertising them for free. Long shot, but worth a try, all you need to do is send them an email.

Title: Can I legally use the icon of a different software?

Body:
Suppose I am including a feature in my image-viewing software, which opens an image in Photoshop ('Send to Photoshop'), using Photoshop's OLE automation framework.

Am I allowed to use the icon of Photoshop.exe as the image of this 'Send to' button?


答:
Icons are protected works under international copyright law.  As with all protected works, you need permission in writing before using them.  Typically larger companies like Adobe have blanket licenses for this sort of thing.

From their website:

You may not use Adobe product icons except under a written license
  from Adobe.You may qualify for use of an Adobe product icon(s) under a
  program offered through an Adobe Partner program. If you are not
  eligible for any of these programs, you may be eligible to use one of
  Adobe's web logos or a box shot of an Adobe product instead.

Emphasis mine.

I'd take a look at the site and see where you fit in.  If it's really worth it to you, I'd pursue participation in the Adobe Partner program.

Note that some uses of copyright works in some countries may be covered by exclusions allowed under Article 10 of WIPOCT, but what exclusions are available, and whether they apply in your jurisdiction is way beyond the scope of a programmers stack exchange question, you would have to consult a copyright lawyer.


问:
What's the difference between Entry Level/Jr/Sr developers?
Other than title and pay, what is the difference?

What different responsibilities do they have.

How knowledgeable/experienced are they?

What is the basic measure to determine where a developer fits into this basic structure?

答:
I think the old school craftsman slots of apprentice, journeyman and master fit into these slots well for entry level, junior (or just no prefix) and senior.

Someone entry level is given relatively simple tasks that do not have profound consequences and their work is checked by a junior or senior. Over time they get more responsibility and are given more complex tasks, learning the ropes along the way.

At a junior (or just the removal of "entry level" / "junior" from the title / description) you have completed your apprenticeship and have covered the major areas of development for your company, having dipped into each major area so that you are familiar with each of them. You now help provide guidance and input for the apprentice equivalent, but your own work is still reviewed by the master / senior, though perhaps not as much as when you were a junior.

Over time and the delivery of successful projects you eventually become senior. At a senior level you have mastered everything that is covered in your area, covering the entire development process and all the tools and technologies that are involved. You are empowered to make significant technical decisions and are expected to provide insight to management into the software development process.

So, given those guidelines you should be able to look at a person or a position and determine which of the three bins they land in.


问:
Testing thread safety
Say you have a function f that is or contains a critical section.  How would you unit test that only one thread can run it at once, that it doesn't have race conditions, and that it doesn't cause a deadlock, etc...?

答:
You cannot do a "strong" test, but you can mitigate some risk by doing a "weak" test.

Parameterize f to take some additional code if passed in.  Then in the test, pass code for a thread counter, a sleep and an assertion that the thread counter never got above 1.  When running the test I would use 5-10 threads.  I would also restructure a function without a critical section and make sure the thread counter got above 1.  The idea would be to make sure the serialization was a result of the critical section only.

Title: Testing thread safety


答: If you use the photoshop icon from the photoshop exe (if installed on the clients computer), wouldn't the client already have a license to view that icon? Explorer shows the icon, as do a lot of other filetools.</p>


答: The bad thing about FORTRAN IV was that all control "structures" (including loops) depended on labels.  So they provided unstructured control. They were too powerful. How about, for example branching into a label inside a loop and then, later, branching out again ... </p>

Title: How were Fortran's original control structures insufficient?

Body: In my Programming Language Concepts class it was mentioned in passing that Fortran's original control structures were insufficient. It was alluded that they were too similar to machine instructions for the IBM 704. Was this the case? What exactly made them insufficient?</p>


问:
Should devs, testers and business users have one unified test script?
In development, I would normally have my own test scripts that would document the data, scenarios and execution steps that I plan to test; this is my dev test plan. When the functionality has been deployed to Test, testers test it using their own test script that they wrote. In UAT, the business user then tests using their own test plan.

In retrospect, it looks like this provides a better coverage, with dev tests having a mix of black and white box testing, while testers and business users focus on black box testing. But on the other hand, this brings up distinct test cases that only are executed per stage (ie. some cases which testers thought of are only executed on Test stage) and it would like the dev missed it, which makes it a finding/bug.

Is it worth consolidating the test scripts from the start? Thus using one unified test script, or is it abit difficult to do this upfront?

答: In perfect world devs must have unit tests(xUnit), testers - automated integration tests(Selenium) and business users - acceptance tests(FIT). They can have access to each other tests.


答:
You can't. Testing can only prove that you didn't find any bugs, not that none exist, and in the presence of multi-threaded code, I would say that it's almost pointless. You cannot test for how your function behaves when the OS changes it out or pauses execution or any of a thousand external events which can affect when the thread is scheduled and it's behaviour.

You need to, at least informally, prove the function correct.

Title: Testing thread safety

Body: Say you have a function f that is or contains a critical section.  How would you unit test that only one thread can run it at once, that it doesn't have race conditions, and that it doesn't cause a deadlock, etc...?


答:
There is one case where you may be discouraged from creating too many objects in Java because of the overhead -
designing for performance on the Android platform

Other than that, the above answers hold true.


问:
What's the most effective way to perform code reviews?
I've never found the ideal way to perform code reviews and yet often my customers require them. Each customer seems to do them in a different way and I've never felt satisfied in any of them.

What has been the most effective way for you to perform code reviews?

For example:

Is one person regarded as the gatekeeper for quality and reviews the code, or do the team own the standard?

Do you do review code as a team exercise using a projector?

Is it done in person, via email or using a tool?

Do you eschew reviews and use things like pair programming and collective code ownership to ensure code quality?

答:
I recommend using code reviews if you are not doing pair programming.

Not to argue the pros and cons with pairing, but it is hard to dispute the positive effects of having your code constantly reviewed by (at least) another person. The code is even written and designed by (at least) two programmers -- it can hardly get any better than that. I'm saying "at least" because imo, you should try to switch pairs a lot so everyone gets a shot at working with the code.


答:
Anytime you have a situation where you can test parts of your code automatically, unit testing can be effective.   So, the question isn't can procedural code be effectively unit tested, the question is can THIS code be unit tested.  That will depend upon how much state it reads and much state it sets.  Ideally the answer to both is zero, but if it's not, you can still test it.

As always you need to weigh the confidence that the code is correct against the cost of gaining that confidence.  Keep in mind that part of the gain for unit testing is explicitly identifying the dependencies, and in that sense it is even more effective to unit test procedural code as compared to OOP code.


答:
the GC is tuned for many short lived object

that said if you can trivially reduce object allocation you should

one example would be building a string in a loop, the naive way would be

```<code>String str = "";
while(someCondition){
    //...
    str+= appendingString;
}
</code>```

which creates a new String object on each += operation (plus a StringBuilder and the new underlying char array)

you can easily rewrite this into:

```<code>StringBuilder strB = new StringBuilder();
while(someCondition){
    //...
    strB.append(appendingString);
}
String str = strB.toString();
</code>```

this pattern (immutable result and a local mutable intermediate value) can be applied to other things as well

but other than that you should pull up a profiler to find the real bottleneck instead of chasing ghosts

Body:
the GC is tuned for many short lived object

that said if you can trivially reduce object allocation you should

one example would be building a string in a loop, the naive way would be

String str = "";
while(someCondition){
    //...
    str+= appendingString;
}

which creates a new String object on each += operation (plus a StringBuilder and the new underlying char array)

you can easily rewrite this into:

StringBuilder strB = new StringBuilder();
while(someCondition){
    //...
    strB.append(appendingString);
}
String str = strB.toString();

this pattern (immutable result and a local mutable intermediate value) can be applied to other things as well

but other than that you should pull up a profiler to find the real bottleneck instead of chasing ghosts


问:
Do DVCSes discourage continuous integration?
Say there is a team of ten agile developers. Every day they each pick a task from the board, commits several changes against it, until (by the end of the day) they have completed the task. All developers check in directly against trunk (Google-style, every commit is a release candidate, using feature toggles etc).

If they were using a centralized CVS like SVN, every time one of them commits, the build server will integrate and test their changes against the other nine developers' work. The build server will be pretty much running continuously all day.

But if they were using a DCVS like git, the developer may wait until they complete the task before pushing all their local commits together up to the central repository. Their changes will not be integrated until the end of the day.

In this scenario, the SVN team is continuously-integrating more frequently, and discovering integration problems much faster than the git team.

Does this mean DVCSs are less suitable for continuous teams than older centralized tools? How do you guys get around this deferred-push issue?

答:
There are awesome technical solutions like @jdunay mentioned, but for us it's a people issue - in the same way that fostering an environment where people commit to svn often is a people issue.

What's worked for us is: (replace 'master' with the currently active dev branch)

Frequent merges/rebases from master

Frequent-enough pushes to master

Awareness of things that cause merge hell, such as certain refactorings, and mitigating this by communicating. For example:

Make sure everyone pushes before lunch

Perform and push the refactoring during lunch

Make sure everyone pulls after lunch


问:
Scheduling Thousands of *Recurring* Jobs
I'm looking for general approaches and ideally libraries/tools for scheduling many thousands of recurring jobs.

A simple example is a feed aggregator, where I'd want to repeatedly poll thousands of feeds. I would never want to poll a website more than once an hour (overuses everyone's resources), but I could deal with polling websites less than once an hour if there isn't time to finish everything in an hour (and worry later about sharding the process or whatever to make it faster, if this keeps happening). So I'd basically want a framework where I can say "run this task as often as possible, but no more than once an hour".

An additionally nice feature would be for such a framework to exponentially decay unsuccessful tasks, i.e. if a feed URL was broken, it would be scheduled for 2 hours, then 4 hours, etc.

I've heard of an approach involving a binary tree which acts as a kind of giant cronjob-like data structure. The system would constantly trawl through this tree to see if any tasks are overdue. I don't have much more information than this. I've looked at tools like Resque, but they don't really seem to cover this use case.

答:
You can use a list of triggerables, sorted ascending by the time of the next trigger. When you need to trigger something, you can always pick off the front of the list, O(1). When you need to (re)schedule something, you can fit it in the list in O(log N) time.

It would be fairly simple & straightforward, and you can leverage any form of timer API (your scheduler needs to wake up only when the front of the list needs to be triggered).


答:
Depends on the size of the required solution and the community feedback to any existing solution.

Useing web dev as an example, I can write a forum but wouldn't bother, just use a respected well known solution, almost anything smaller write myself.

Title: Which is best for learning how to do a certain thing: writing your own or looking at someone else's?

Body:
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.


问:
How to gain experience?
This is a problem that I think many people will find very common and some guidance from the expert users around here will be appreciated.

Background

Basically I'm a junior web developer in a team of 6 (all juniors too). 6 months ago our team leader and project manager left the company. Currently we are being managed by a non technical person.

The new manager chose me to act as a technical leader for the rest of the team till the company hires a someone more experienced.

Problem

Although I'm a good developer my experience in providing solution to the company's needs is somewhat lacking. I mean I have no problem implementing solutions or adding new modules to the system as I have been working for 2 years already in PHP and MySql.

The problem is when we are designing a new heavy feature or building a critical module that can't tolerate trial and error.

Check this link for a design issue that I recently had to implement:
https://stackoverflow.com/questions/10529459/building-a-cron-job-scheduler

I can easily build all solutions that were mentioned in the post. The only problem is that I don't have enough experience to choose one of them. My ex-Team leader used to make the hard decisions and I really used to learn a lot from him. However, now he's gone and I'm left out all alone.

Solution

Now There is 2 solutions that I figured would be best for me:

Leave the company ASAP :D and find a better company that can provide me with good experience and increase my knowledge (Although I can't leave the company any time soon due to various reasons).

Find books, references or any available materials for large scale projects or pro web developers techniques. Basically anything beyond simple applications. This is the only option I have right now.

Notes:

I am not looking for resources to learn PHP, MySql, frameworks, ORMs or design patterns. I want knowledge transfer from experienced programmers.

答:
If you are looking for experience it won't come unless you start working on something new.

Have you considered doing some freelance work?

Doing some new projects outside the scope of your work can greatly affect your work experience. It helps to see other people requirements in a field that is much dynamic as freelancing.

For example, I never thought about integrating PayPal APIs in my work. However, I was forced to in one of my jobs recently.

Title: How to gain experience?


问:
TDD: Am I doing it right?
I'm a new programmer (only been learning for about a year) and in my goal to become better at it I have just recently learned about TDD. I wanted to get into the habit of using it since it seems very helpful. I wanted to check and make sure I'm using it correctly.

What I'm doing:

Think of a new method I need.

Create a test for that method.

Fail test.

Write method.

Pass test.

Refactor method.

Repeat.

I'm doing this for EVERY method I write, are there some I shouldn't bother with? Later on I usually think of a way to test my already existing methods in a different way or situation. Should I make these new tests I think of, or since each method already has a test of their own should I not bother? Can I be OVER testing my code I guess is my main concern in asking this.

EDIT

Also, this was something I was just wondering. When doing something like making a GUI, would TDD be necessary in that situation? Personally, I can't think of how I would write tests for that.

答:
When you start learning TDD, yes, you should blindly follow the dogmatic approach of not writing a single line of code except to make a failing test pass, and writing only enough of a test to fail (and fail for the right/expected reason).

Once you have learned what TDD is about, THEN you can decide that certain kinds of things aren't worth testing. This is the same approach you should follow for everything, and the Japanese martial arts call this "shuhari". (The link also explains how one can progress through the stages of learning without a teacher which is, I suspect, how most people have to learn.)

Title: TDD: Am I doing it right?


问:
How many developers before continuous integration becomes effective for us?
There is an overhead associated with continuous integration, e.g., set up, re-training, awareness activities, stoppage to fix "bugs" that turn out to be data issues, enforced separation of concerns programming styles, etc.

At what point does continuous integration pay for itself?

EDIT: These were my findings

The set-up was CruiseControl.Net with Nant, reading from VSS or TFS.

Here are a few reasons for failure, which have nothing to do with the setup:

Cost of investigation: The time spent investigating whether a red light is due a genuine logical inconsistency in the code, data quality, or another source such as an infrastructure problem (e.g., a network issue, a timeout reading from source control, third party server is down, etc., etc.)

Political costs over infrastructure: I considered performing an "infrastructure" check for each method in the test run. I had no solution to the timeout except to replace the build server. Red tape got in the way and there was no server replacement.

Cost of fixing unit tests: A red light due to a data quality issue could be an indicator of a badly written unit test. So, data dependent unit tests were re-written to reduce the likelihood of a red light due to bad data. In many cases, necessary data was inserted into the test environment to be able to accurately run its unit tests. It makes sense to say that by making the data more robust then the test becomes more robust if it is dependent on this data. Of course, this worked well!

Cost of coverage, i.e., writing unit tests for already existing code: There was the problem of unit test coverage. There were thousands of methods that had no unit tests. So, a sizeable amount of man days would be needed to create those. As this would be too difficult to provide a business case, it was decided that unit tests would be used for any new public method going forward. Those that did not have a unit test were termed 'potentially infra red'. An intestesting point here is that static methods were a moot point in how it would be possible to uniquely determine how a specific static method had failed.

Cost of bespoke releases: Nant scripts only go so far. They are not that useful for, say, CMS dependent builds for EPiServer, CMS, or any UI oriented database deployment.

These are the types of issues that occured on the build server for hourly test runs and overnight QA builds. I entertain that these to be unnecessary as a build master can perform these tasks manually at the time of release, esp., with a one man band and a small build. So, single step builds have not justified use of CI in my experience. What about the more complex, multistep builds? These can be a pain to build, especially without a Nant script. So, even having created one, these were no more successful. The costs of fixing the red light issues outweighed the benefits. Eventually, developers lost interest and questioned the validity of the red light.

Having given it a fair try, I believe that CI is expensive and there is a lot of working around the edges instead of just getting the job done. It's more cost effective to employ experienced developers who do not make a mess of large projects than introduce and maintain an alarm system.

This is the case even if those developers leave. It doesn't matter if a good developer leaves because processes that he follows would ensure that he writes requirement specs, design specs, sticks to the coding guidelines, and comments his code so that it is readable. All this is reviewed. If this is not happening then his team leader is not doing his job, which should be picked up by his manager and so on.

For CI to work, it is not enough to just write unit tests, attempt to maintain full coverage, and ensure a working infrastructure for sizable systems.

The bottom line: One might question whether fixing as many bugs before release is even desirable from a business prespective. CI involves a lot of work to capture a handful of bugs that the customer could identify in UAT or the company could get paid for fixing as part of a client service agreement when the warranty period expires anyway.

答:
It is not a matter of how many developers, but of

a. How much time you save using automation and how often.

Time saved on building after integrations, running automated tests and creating setups * frequency of check-in = percent of time saved.

b. How many versions/branches/products you have.

If you have one developer working on two different branches then the time saved is doubled, since each branch would require building, testing and packaging.


问:
JSF for an internet facing, high traffic web application
I, perhaps, made a wrong choice of going with a Component-based Framework like JSF for an internet facing, high traffic web application.
Development with JSF has although been easier but what I fear now is whether JSF would allow me that scalability & performance with all it fundamental problems & issues. State saving in a high traffic web app, does that make sense at all!?

How do I tune up my JSF app now to make it perform better under heavy load? I am already trying to reduce the state / component tree by reducing the no of components on page. What are other things I can tune up to make JSF app perform better ?

答:
There is one (possibly) significant performance problem with JSF: The creation of the "View" (the server-side representation of the page structure) is quite expensive.

At least the reference implementation (Mojarra) does this for every request. This means that there is a high (as in several 100 ms) overhead if you have a large page, even if you only update a part via AJAX.

One possible solution is "stateless JSF": http://industrieit.com/blog/2011/11/stateless-jsf-high-performance-zero-per-request-memory-overhead/

It's non-standard, but seems to work well.


答:
As always, it depends.

If it's trivial and you are sure you can fix it, fix it.

If there are plenty of unit tests, so you can be fairly sure you haven't broken anything, fix it.

Otherwise, add a //TODO, add it to your bug tracking, whatever

Basically you're doing a risk assessment: what's the risk of changing vs not changing. If you don't feel like you've got enough experience (with programming in general, or the system in particular) ask someone else in the team.

Title: Should you fix preexisting defects while working on something else?

Body:
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


答:
Not really a solution for your problem, but you are gaining experience right now and in one of the more effective ways.

Experience isn't knowledge acquirable in books. Experience is time spent outside your depth. Years spent inside your comfort zone isn't experience even if HR people thinks otherwise.

You probably would fell better with someone available as life guard (as some says, experience is a bad teacher, it gives the test before the lesson so a life guard is good) and the company would for sure be better with a less risky way for you to acquire the experience it needs, but you are acquiring it.

Title: How to gain experience?

Body:
This is a problem that I think many people will find very common and some guidance from the expert users around here will be appreciated.

Background

Basically I'm a junior web developer in a team of 6 (all juniors too). 6 months ago our team leader and project manager left the company. Currently we are being managed by a non technical person.

The new manager chose me to act as a technical leader for the rest of the team till the company hires a someone more experienced.

Problem

Although I'm a good developer my experience in providing solution to the company's needs is somewhat lacking. I mean I have no problem implementing solutions or adding new modules to the system as I have been working for 2 years already in PHP and MySql.

The problem is when we are designing a new heavy feature or building a critical module that can't tolerate trial and error.

Check this link for a design issue that I recently had to implement:
https://stackoverflow.com/questions/10529459/building-a-cron-job-scheduler

I can easily build all solutions that were mentioned in the post. The only problem is that I don't have enough experience to choose one of them. My ex-Team leader used to make the hard decisions and I really used to learn a lot from him. However, now he's gone and I'm left out all alone.

Solution

Now There is 2 solutions that I figured would be best for me:

Leave the company ASAP :D and find a better company that can provide me with good experience and increase my knowledge (Although I can't leave the company any time soon due to various reasons).

Find books, references or any available materials for large scale projects or pro web developers techniques. Basically anything beyond simple applications. This is the only option I have right now.

Notes:

I am not looking for resources to learn PHP, MySql, frameworks, ORMs or design patterns. I want knowledge transfer from experienced programmers.


问:
replacement for fanfold paper printouts
Back in university, we were able to print "unlimited" printouts on wide fanfold paper, (perhaps 128 characters wide or maybe more).  I could then unfurl the printed code out across the desks or the room and get a great overview of my code, draw circles and arrows and a paragraph on each one in the wide margin, see if this code matched that code, tweak variable names by seeing their brethren, etc, and I loved it.

Right now I'm using xcode for iOS programming, but the question comes up no matter what editor I've used: how can I get a good code overview that's bigger than my screen?

答:
Two simple things:

only write functions that fit on one screen

use a dual screen display (which is quite affordable nowadays)

The last time I needed a "fanfold paper printout" of some code was for a legacy function with several hundreds LOC. After refactoring this monster into small functions I never missed fanfold printouts again.

Title: replacement for fanfold paper printouts


问:
Should we avoid object creation in Java?
I was told by a colleague that in Java object creation is the most expensive operation you could perform. So I can only conclude to create as few objects as possible.

This seems somewhat to defeat the purpose of object oriented programming. If we aren't creating objects then we are just writing one long class C style, for optimization?

答:
Other posters have rightly pointed out that object creation is extremely fast in Java, and that you should not usually worry about it in any normal Java application.

There are a couple of very special situations where is is a good idea to avoid object creation.

When you are writing a latency-sensitive application and wish to avoid GC pauses. The more objects you produce, the more GC happens and the greater the chance of pauses. This might be a valid consideration for relevant for games, some media applications, robotic control, high-frequency trading etc. The solution is to pre-allocate all the objects / arrays you need up front and re-use them. There are libraries that specialise in providing this kind of capability, e.g Javolution. But arguably, if you really care about low latency you should be using C/C++/assembler rather than Java or C# :-)

Avoiding boxed primitives (Double, Integer etc.) can be a very beneficial micro-optimisation in certain circumstances. Since unboxed primitives (double, int etc.) avoid the per-object overhead, they are much faster CPU intensive work like numerical processing etc. Typically, primitive arrays perform very well in Java so you want to use these for your number crunching rather than any other kinds of objects.

In constrained memory situations you want to minimise the number of (active) objects created since each objects carries a small overhead (typically 8-16 bytes depending on JVM implementation). In such circumstances you should prefer a small number of large objects or arrays to store your data rather than a large number of small objects.


问:
Properties under ARC: Always or public-only?
After reading an article humbly named "The Code Commandments: Best Practices for Objective-C Coding" by Robert McNally a little less than two years ago, I adopted the practice of using properties for pretty much every data member of my Objective-C classes (the 3rd commandment as of may 2012). McNally lists these reasons for doing so (my emphasis):

Properties enforce access restrictions (such as readonly)

Properties enforce memory management policy (strong, weak)

Properties provide the opportunity to transparently implement custom setters and getters.

Properties with custom setters or getters can be used to enforce a thread-safety strategy.

Having a single way to access instance variables increases code readability.

I put most of my properties in private categories, so number 1 and 4 are usually not issues I run in to. Arguments 3 and 5 are more 'soft', and with the right tools and other consistencies they could become non-issues. So finally, to me the most influential of these arguments was number 2, memory management. I've been doing this ever since.

```<code>@property (nonatomic, strong) id object; // Properties became my friends.
</code>```

For my last few projects I've switched to using ARC, which made me doubt whether creating properties for pretty much anything is still a good idea or maybe a little superfluous. ARC takes care of memory managing Objective-C objects for me, which for most strong members works fine if you just declare the ivars. The C-types you had to manually manage anyway, before and after ARC, and the weak properties are mostly public ones.

Of course I still use properties for anything that needs access from outside of the class, but those are mostly only a handful of properties, while most data members are listed as ivars under the implementation header

```<code>@implementation GTWeekViewController
{
    UILongPressGestureRecognizer *_pressRecognizer;
    GTPagingGestureRecognizer *_pagingRecognizer;
    UITapGestureRecognizer *_tapRecognizer;
}
</code>```

As an experiment I've been doing this a bit more rigorously, and the move away from properties for everything has some nice positive side effects.

Data member code requirements (@property/@synthesize) shrunk down to just the ivar declaration.

Most of my self.something references cleaned up to just _something.

It's easily distinguishable which data members are private (ivars) and which are public (properties).

Lastly, it 'feels' more like this was the purpose Apple intended properties for, but that's subjective speculation.

On to the question: I'm slowly sliding towards the dark side, using less and less properties in favor of implementation-ivars. Can you provide me with a bit of reasoning for why I should stick to using properties for everything, or confirm my current train of thoughts as to why I should use more ivars and less properties only where needed? The most persuasive answer for either side will receive my mark.

EDIT: McNally weighs in on Twitter, saying: "I think my main reason for sticking with properties is: one way to do everything, that does everything (including KVC/KVO.)"

答:
Can you provide me with a bit of reasoning for why I should stick to
  using properties for everything, or confirm my current train of
  thoughts as to why I should use more ivars and less properties only
  where needed?

Right now, I think it's fair to say that it's mostly a matter of style. As you say, the memory management benefit of properties is less important with ARC. On the other hand, the "benefits" of going back to direct ivar access aren't very compelling either:

A @property declaration is quite similar to an ivar declaration. Avoiding the @synthesize directive doesn't seem like a big win -- we're not talking about a lot of code.

The foo.something syntax is arguably a lot better than _something. Property access syntax is obviously designed to look like and work like C's dot syntax for accessing members of a structure. Being explicit about which object you're accessing (whether that's self or something else) is helpful. (Some people -- not me! -- advocate self->something for ivar access for this reason.) The leading underscore convention for ivars is fine, but it's not used consistently by all Objective-C code.

Properties seem a better choice for accessing data stored in other objects of the same class (which is allowed under "private" access) and for access by subclasses (like C++'s "protected"). So the 'properties == public' idea is somewhat blurry.

My sense is that properties were intended to simplify memory management and provide some other benefits. As you say, with the memory management benefit decreased, properties seem less compelling.

The path you've chosen -- going back to direct ivar access for internal data -- seems like a very reasonable choice and there's no obvious reason to change your course. But sticking to properties is also quite reasonable -- the drawbacks aren't significant, and there are some nice benefits like KVO compliance and a more consistent member access style.

Properties weren't the last step in the evolution of Objective-C, and I don't expect that ARC will be either. I don't have any specific information, but it seems like a good guess that additional features might be added at some point that make properties either more compelling or less so. We'll have to wait and see what happens.


问:
What do I need for Java Socket programming?
I am trying to learn Socket programming in Java to make a game I created playable via network. I have never done much network programming so the subject is a bit confusing. In php I use apache to test my aplications on a local server. What do I need to install to be able to run network applications with Java?</p>

答:
You don't need to install anything special. Socket has been in the standard JDK since version 1.0.

See socket tutorial to get started.

If you want to test how the communication works between processes, then simply start >1 processes in the same machine. In principle it works similarly over any network.


问:
Design: Calling back to the parent class
When modelling an object with children it's common to include the children via composition, as a member of the parent class. Sometimes however the children need to tell the parent something, they need to call a function of the parent. How can this be accomplished using C++? Some options are:

Make the parent class global therefore the child objects will be able to call member functions of the parent object.

Inject the parent object as a, pointer or reference, into every child object. Then when the child needs to tell the parent object something, it can always do so because it has a member variable that it can use.

What are other methods of doing this? Is there a general design pattern or name for this sort of thing?

Note that I'm interested in ideas and solutions in C++ because the details are going to be different in other object-oriented languages. For example point 2 above mentions 'pointers or references' and both are only possible in C++. C++ has language features that are not present in other languages therefore implementations of a solution to the problem will potentially incorporate these language features making the solution different from what someone might come up with in another language.

答: Pass them a reference or a pointer to the parent. You can make them friends of the parent, or make the called method public. If you don't want to do any of the above, you can pass them a "bridge" object which exposes one of the parent's methods as public and is itself a prive nested class of the parent (therefore it has access to every parent method). This can be a bit too complex in many situations, however.</p>


答:
What you can do is keep a reference to the parent in the child class, by composition. That way, the child knows his parent and can invoke public methods on it.

So I would go with option 2. You have to be careful though, when a child is removed from the parent, you need to remove the reference to the parent in the child and point it to null (or a new parent, if he has one). Or you could simply delete the child object, depending on the context.

Title: Design: Calling back to the parent class

Body:
When modelling an object with children it's common to include the children via composition, as a member of the parent class. Sometimes however the children need to tell the parent something, they need to call a function of the parent. How can this be accomplished using C++? Some options are:

Make the parent class global therefore the child objects will be able to call member functions of the parent object.

Inject the parent object as a, pointer or reference, into every child object. Then when the child needs to tell the parent object something, it can always do so because it has a member variable that it can use.

What are other methods of doing this? Is there a general design pattern or name for this sort of thing?

Note that I'm interested in ideas and solutions in C++ because the details are going to be different in other object-oriented languages. For example point 2 above mentions 'pointers or references' and both are only possible in C++. C++ has language features that are not present in other languages therefore implementations of a solution to the problem will potentially incorporate these language features making the solution different from what someone might come up with in another language.


问:
Do Python programmers find the whitespace issue inconvenient?
Many programmers, upon first encountering Python, are immediately put off by the significance of whitespace. I've heard a variety of reasons that this is inconvenient, but I've never heard a complaint from a Python programmer.

Of course, I haven't met a lot of Python programmers, as I have spent my career in the Java world.

So my question is for those of you that have participated in a large Python project (more than 3 months, with Python being the primary language used): Did you find the whitespace issue to be inconvenient and continually annoying? Or was it a non-issue once you got in the flow?

I'm not asking the question because I'm for or against Python, or for or against its use of whitespace. I happen to like Python, but I've never used it for anything big.

Please don't provide speculations if you are not experienced in Python.

答: I come from a C# / Javascript / XBase background in no particular order, and in my dabblings with Python it is not a consideration at all for me. It's like braces in other languages - that's how it works, put the things in like the rules say, and dry your eyes is my attitude.</p>


问:
How do you keep track of complex business rules outside of code?
I'm interested in seeing how other people do this. Especially in situations where multiple different clients are using the same software base with slightly different business rules. What kind of practices do you use to document how everything is supposed to work or business rules.

Basically so when a new developer comes on the team is easy access to see how things are supposed to work because there's obviously a difference between making something bug free and making something work properly.

It would be really nice to have a go to resource rather than having to bring an architect or BSA into the conversation every time a question comes up on how something should be processed.

答:
We have used BPMN to document and model our business workflows if that's what you mean.

We've also tried to use a workflow engine in a project to let the users participate in modelling, but that hit quite some resistance because they were too afraid to break things, even if it the modeling was done together with a workflow specialist from our IT department.


答:
Note this is c# specific. I donot know if c++ has something similar.

If you have a gui-form with pushbuttons you usually have an a different approach using Event-Subscribtion also known as Observer_pattern or Publish–subscribe pattern.

The pushbutton usally does not know the specific form where it lives. Instead the button triggers or publishes an event  and the form receives a subscribed notification and can react accordingly.

Beside gui-s this mechanism can be used in every paren-child-relation


答:
First things first, this can be a code smell. The point of using composition for the parent/children is that the parent knows about the children but not vice versa. Especially if the relation is more of a 'contains' than 'is composed of'.

A reference to the parent is possible and fairly common in C++. In other languages, a function object or event is more often used to allow the child to communicate things that outsiders might want to know. This is a common publish-subscriber sort of pattern. I suspect that which is more idiomatic depends on which version of C++ you're using and the standards of your codebase.


答: This is one of the use cases for BDD frameworks, like Cucumber, that allow you to capture the business requirements in code and test against those requirements frequently. Other approaches I've seen used include long and complicated specification documents, large sheets of paper tacked to the wall, slide decks, and Joe, the guy at the end of the table who knows everything.</p>

Title: How do you keep track of complex business rules outside of code?

Body:
I'm interested in seeing how other people do this. Especially in situations where multiple different clients are using the same software base with slightly different business rules. What kind of practices do you use to document how everything is supposed to work or business rules.

Basically so when a new developer comes on the team is easy access to see how things are supposed to work because there's obviously a difference between making something bug free and making something work properly.

It would be really nice to have a go to resource rather than having to bring an architect or BSA into the conversation every time a question comes up on how something should be processed.


答:
2) Inject the parent object as a, pointer or reference, into every
  child object. Then when the child needs to tell the parent object
  something, it can always do so because it has a member variable that
  it can use.

Is a perfectly viable option. All modern languages have a feature which can be used to refer to another language.


问:
Which data structure to represent a triangular undirected graph
I was wanting to create a graph similar to this in C++:

The one I will implement will have more edges and vertices, but will use this triangle style. I was wanting to create something that I could perform various search algorithms on in order to find shortest paths to selected vertices (or longest without loops etc.). It is an unweighted graph to begin with; however, I was planning to give the edges weights in the future.

I was having some trouble with how I would represent this graph for a couple of reasons: since I want to have more vertices (maybe 105 vertices), any kind of list would be tedious to write out which vertices are connected to which in every object (or is there a way to automate the assignment of members of a vertex object signifying the connectedness?). Also, I was finding it strange trying to implement it in a 2d array because the array is square in nature, and I am dealing with triangles; thinking about the weighting of edges and assigning a value in between two vertices made it even less intuitive with an array.

答:
You may not necessarily need to solve your problem through a specialized data structure; you can, for instance, find an addressing scheme for each node, which allows you to locate neighbouring nodes in O(1) time, and use a generic data structure to navigate.

A simple scheme here would be assigning to each node a tuple (n, m), where n is the tier and m is the index of the node (assuming 0-indexed, for a node to be valid 0 <= m <= n). For any node, deriving all possible neighbour nodes (ni, mi) is straightforward (smth like (n-1, m-1), (n-1,m), (n, m-1), (n, m+1) etc) - of these you keep those who are valid (0 <= mi <= ni < your triangle size here).

The values can be stored in a vector, the index of node (n, m) is, uniquely, n(n+1)/2 + m.


问:
How much time do you spend actually developing vs. infrastructure activites?
When I'm working I feel like most of the time I'm not doing actual work. For example after making a change to the code in order to test it, I have to first build the project, and start the server(say JBoss). Upon testing, I find that there is another small issue. So I bring down the server, make the changes, build again and start up the server again.The building and bringing the server up/down is not very useful work.

Also, the IDE (let's say Eclipse) does things such as updating Maven indexes and building the workspace which take some more time to get things done.

Have you come across this kind of situation? Do you have tips on how to overcome/bypass this? Any features on the IDE/build tools that can be helpful? Any architecture/application design/technology that attempts to overcome this?

答:
It may look capricious, but having powerful hardware can easily improve your productivity. A lot of the tasks you mention (building, starting the server, updating Eclipse indexes…) are highly hardware-intensive (CPU, HDD, RAM…). Improving hardware performance has a very quick ROI.

A few month ago we switched our environment to 8Gb RAM in x64 (previously 4Gb RAM in x86, which thus meant ~3.2Gb usable) and I can say this has been a huge productivity improvement. Now I don't have to worry any more about memory usage or closing some software because it is too heavy. I can even start Eclipse on 2 or 3 different workspaces, start 2 different servers and run a database server simultaneously!

We are also using JRebel as proposed by Jarle Hansen.


问:
Was classical BASIC ever used for commercial software development, and if so, how were limitations overcome?
Many of us, including me, started their programming life with programs written on home computers, something like

```<code>10 PRINT "ENTER RADIUS"
20 INPUT R
30 PRINT "CIRCUMFERENCE="; 2 * R * PI
40 PRINT "AGAIN?"
50 INPUT A$
60 IF A$="Y" THEN GOTO 10
70 END
</code>```

Of course, the line-number based BASIC was prone for creating spagetti code, also because most BASIC dialects missed structural statements like WHILE, doing everything but the FOR-loop with IF, GOTO and GOSUB. I'm talking about BASIC dialects before 1991, when QBASIC and Visual Basic appeared.

While BASIC dialects may have promoted bad style amongst aspiring programmers, were there larger commercial projects created in such a BASIC dialect? If so, how did they manage to live with and workaround the obvious shortcomings?

By "serious", I mean:

Not a game (I know some commercial games were written in BASIC, for example, Pimania)

Not freeware

Not trivial, that is, reasonably large (say: at least 1500 LOC)

Sold to several customers (not an in-house development)

"Mission critical" is a plus

答: Back in the days of the Commmodore 64 part of the game Gunship was written in BASIC. You could even edit the code, so your helicoper could be equipped each time you landed.</p>


答:
You should begin by keeping track of how much time is spent by each of your developers are doing their different tasks.

Take note of the tasks that are repetitive and easily scriptable (ie- run build on code & reboot server with updated code)

Prioritize impact of each class of task (ie- launch new build, startup/shutdown, source control)

Investigate the most time/cost effective solution to each individual task, whether the solution should be a script, more hardware or a new software package.

Work each solution into your processes individually.

Evaluate at preset time periods to ensure you are seeing the productivity gains expected and tweak as needed.

Bill out all possible parts of this list to clients. :-)

Profit!

At my company when a new build is created, we update a dropdown box on an internal server and whenever any of our dev servers restarts apache it automatically pulls and deploys the new build.

While free/open-source solutions can seem to be great to start with, sometimes you'll see greater productivity savings by paying for a service to manage your processes.

For instance, my company uses JIRA for our issue tracking which integrates with source control and allows anyone to view the specific source changes that apply to a particular ticket.

Title: How much time do you spend actually developing vs. infrastructure activites?

Body:
When I'm working I feel like most of the time I'm not doing actual work. For example after making a change to the code in order to test it, I have to first build the project, and start the server(say JBoss). Upon testing, I find that there is another small issue. So I bring down the server, make the changes, build again and start up the server again.The building and bringing the server up/down is not very useful work.

Also, the IDE (let's say Eclipse) does things such as updating Maven indexes and building the workspace which take some more time to get things done.

Have you come across this kind of situation? Do you have tips on how to overcome/bypass this? Any features on the IDE/build tools that can be helpful? Any architecture/application design/technology that attempts to overcome this?


问:
Choosing names for integration tests
With unit tests the domain is quite small, so it's easy. I used Osherove's methodName_conditions_result() scheme and found it very clear.

But with integration tests I feel like it would make a very long name, and what do I put in place of methodName? How do I name integration test classes?

Real world examples of integration test names are very welcome. I hope the answers will also help me to better understand these tests.

答: So the problem is that a proper name of functionality is too long for a method name? I know it's awkward to start writing test methods with names like registerAndValidateUnderageUniversityDriverWithCoverageSetA_test() and might ever break compiler rules for long method names (PL/SQL only allows up to 30 characters - I don't know if Java and C# impose such short name limits, but even if they don't it gets pretty unwieldly past a certain point and really really long method names might only be useful for generated code that is read/managed by other generated code). You can try to shorten it to regValUnderageUnivDrvrWCovrgA_test() but that's also really horrible to read. One option I've used that I didn't like but was the best choice at the time was underageUnivDrvr_test_01() and then there was a spreadsheet mapping the method names to a much longer description of the functionality being tested. Ugly, but it worked. You could also document the description of the test in the documentation of the function in the source file, which could be useful because you can generate documentation of the tests directly from the code, instead of mapping back and forth between spreadsheet and code.

Title: Choosing names for integration tests


答:
I agree with @saba7saba7 that experience won't come unless you start working on something new.

I have found that reading helps me learn about new ways of doing things.  Sometimes, doing something in a new way can be a new experience even if I'm doing something similar to what I've done before, but in a new way.

I had seen a few sparks catch fire by following along with the ideas described in the book "The Pragmatic Programmer", although many of the ideas in the book are already familiar to me.  I think that reading this particular text would be a great way to get exposure to some new ways of thinking that could send you in new directions.

Title: How to gain experience?


问:
Creating a websocket server on Linux
I want to create a websocket server and I've found a great article here. However C# will output an exe file.

I'd like to have it run on a linux box. What I want to do is to connect to the server, and when something happens on the filesystem to retrieve a message from the server (using the FileSystemWatcher on Windows or the iNotify daemon on linux) and the program will run the corresponding code.

So, how can such daemon for linux (in C#) or any other way to achieve this?

答:
I'm not sure if you're really requiring C# on linux (which isn't really wise and forces you to use mono).

There are other great ways to manage websockets on a linux server. For example node.js, java(not personally tested)  or my favorite : go.

Title: Creating a websocket server on Linux


答:
I would think, at the very least, these would be documented and maintained in the requirements document.

I realize that most places either don't have written requirements, or they're not maintained, but that's a different problem. :-)


问:
What alogrithm is used on the smart cards for the DNSSEC Trusted Community Representatives?
I've been doing some reading about DNSSec and am interested in the algorithm that they chose to use when splitting the trusted key up between the 7 Trusted Community Representatives (TCR).

I unfortunately can't find any information about the algorithm itself anywhere.

Is it just an implementation of the Shamir Secret Sharing Algorithm, or is it using a different approach?

A little bit of information can be found here.

答: The DNSSEC Practice Statement says in section 5.2.2 that they use secret sharing but does not specify an algorithm. However if you do some Google searches, people seem to assume it is indeed Shamir's Secret Sharing algorithm, including Bruce Schneier.</p>


问:
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?

答:
You may want to draw a wider system for the diagram.  I would consider adding the following elements:

Show your inputs to the system, which are fed to the developers.  Call them requirements, bug fixes, stories, or whatever.  But currently your workflow assumes the viewer knows how those inputs are inserted.

Show the control points along the workflow.  Who / what decides when a change is allowed into trunk / main / release-branch / etc...?  What codetrees / projects are build on the CIS?  Is there a checkpoint to see if the build was broken?  Who releases from CIS to staging / production?

Related to the control points is identifying what your branching methodology is and how it fits into this workflow.

Is there a Test team?  When are they involved or notified?  Is there automated testing being performed on the CIS?  How are breakages fed back into the system?

Consider how you would map this workflow to a traditional flowchart with decision points and inputs.  Have you captured all of the high-level touch points that are needed to adequately describe your workflow?

Your original question is attempting to make a comparison, I think, but I'm not certain on which aspect(s) you're trying to compare.  Continuous Integration has decision points just like other SDLC models, but they may be at different points in the process.


问:
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>

答: It's not merely adage; it's verifiable.  Check out Brooks' The Mythical Man-Month.