问:
Generalise variable usage inside code
I would like to know if it is a good practice to generalize variables (use single variable to store all the values).

Consider simple example

```<code> Strings querycre,queryins,queryup,querydel;
    querycre = 'Create table XYZ ...';
    execute querycre ;
    queryins = 'Insert into XYZ ...';
    execute queryins ;
    queryup  = 'Update  XYZ set ...';
    execute queryup;
    querydel = 'Delete from XYZ ...';
    execute querydel ;
</code>```

and

```<code> Strings query;
    query= 'Create table XYZ ... ';
    execute query ;
    query= 'Insert into XYZ ...';
    execute query ;
    query= 'Update  XYZ set ...';
    execute query ;
    query= 'Delete from XYZ ...';
    execute query ;
</code>```

In first case I use 4 strings each storing data to perform the actions mentioned in their suffixes.

In second case just 1 variable to store all kinds the data.

Having different variables makes it easier for someone else to read and understand it better. But having  too many of them makes it difficult to manage.

Also does having too many variables hamper my performance?

P.S: please don't answer w.r.t the code in example it was just to convey what I really mean.

答:
Normally, this is a bad practice.

Reusing a variable is this way can make code that is confusing to read an understand.

Those reading the code will not expect a variable to be reused in such a way and will not know why a value set at the start has a different value at the end of the function.

The examples you posted are very simple and don't really suffer from this issue, but they are not representative of some code that does reuse variables (where it is set at the start, gets reused somewhere in the middle - out of sight).

The examples you have given lend themselves to encapsulation into functions, where you would pass in the query and execute it.

Title: Generalise variable usage inside code


答: It can increase stack usage if your compiler is particularly dumb. Personally I don't think having a separate variable for each query adds to any readability whatsoever, you still need to actually look at the query string to see what it does.</p>

ContentLicense: CC BY-SA 3.0

Title: Generalise variable usage inside code

Body:
I would like to know if it is a good practice to generalize variables (use single variable to store all the values).

Consider simple example

```<code> Strings querycre,queryins,queryup,querydel;
    querycre = 'Create table XYZ ...';
    execute querycre ;
    queryins = 'Insert into XYZ ...';
    execute queryins ;
    queryup  = 'Update  XYZ set ...';
    execute queryup;
    querydel = 'Delete from XYZ ...';
    execute querydel ;
</code>```

and

```<code> Strings query;
    query= 'Create table XYZ ... ';
    execute query ;
    query= 'Insert into XYZ ...';
    execute query ;
    query= 'Update  XYZ set ...';
    execute query ;
    query= 'Delete from XYZ ...';
    execute query ;
</code>```

In first case I use 4 strings each storing data to perform the actions mentioned in their suffixes.

In second case just 1 variable to store all kinds the data.

Having different variables makes it easier for someone else to read and understand it better. But having  too many of them makes it difficult to manage.

Also does having too many variables hamper my performance?

P.S: please don't answer w.r.t the code in example it was just to convey what I really mean.


问:
Is it common to declare class properties at the bottom of the class declaration?
I work in a PHP development shop and several new developers have joined the team.  One of the new members insists on declaring class properties at the bottom of the class declaration rather than the at the top, as one would normally expect.

In all my 5 years of working in web development, I have never seen this done. Is it a common coding style?

答: I think that the simplest way is to follow a coding standard like PEAR or Zend Framework and many others. so if the company have its own standards then the user must apply them.</p>


答:
Having to ask yourself this question is a pretty strong smell that you are not following DRY (Don't Repeat Yourself). Suppose you have this, in a hypothetical curly-brace language:

```<code>function doFoo() {
    query = "SELECT a, b, c FROM foobar WHERE baz = 23";
    result = runQuery(query);
    print(result);

    query = "SELECT foo, bar FROM quux WHERE x IS NULL";
    result = runQuery(query);
    print(result);

    query = "SELECT a.foo, b.bar FROM quux a INNER JOIN quuux b ON b.quux_id = a.id ORDER BY date_added LIMIT 10";
    result = runQuery(query);
    print(result);
}
</code>```

Refactor that into:

```<code>function runAndPrint(query) {
    result = runQuery(query);
    print(result);
}

function doFoo() {
    runAndPrint("SELECT a, b, c FROM foobar WHERE baz = 23");
    runAndPrint("SELECT foo, bar FROM quux WHERE x IS NULL");
    runAndPrint("SELECT a.foo, b.bar FROM quux a INNER JOIN quuux b ON b.quux_id = a.id ORDER BY date_added LIMIT 10");
}
</code>```

Notice how the need for deciding whether or not to use different variables goes away, and how you can now change the logic for running a query and printing the result in one place, rather than having to apply the same modification three times. (For example, you might decide you want to pump the query result through a template system instead of printing it right away).

Title: Generalise variable usage inside code

Body:
Having to ask yourself this question is a pretty strong smell that you are not following DRY (Don't Repeat Yourself). Suppose you have this, in a hypothetical curly-brace language:

function doFoo() {
    query = "SELECT a, b, c FROM foobar WHERE baz = 23";
    result = runQuery(query);
    print(result);

    query = "SELECT foo, bar FROM quux WHERE x IS NULL";
    result = runQuery(query);
    print(result);

    query = "SELECT a.foo, b.bar FROM quux a INNER JOIN quuux b ON b.quux_id = a.id ORDER BY date_added LIMIT 10";
    result = runQuery(query);
    print(result);
}

Refactor that into:

function runAndPrint(query) {
    result = runQuery(query);
    print(result);
}

function doFoo() {
    runAndPrint("SELECT a, b, c FROM foobar WHERE baz = 23");
    runAndPrint("SELECT foo, bar FROM quux WHERE x IS NULL");
    runAndPrint("SELECT a.foo, b.bar FROM quux a INNER JOIN quuux b ON b.quux_id = a.id ORDER BY date_added LIMIT 10");
}

Notice how the need for deciding whether or not to use different variables goes away, and how you can now change the logic for running a query and printing the result in one place, rather than having to apply the same modification three times. (For example, you might decide you want to pump the query result through a template system instead of printing it right away).


答:
I think reusing the variable is fine most of the time.

For me, I simply reuse the query variable most of the time. I almost always execute the query right after. When I don't execute the query right away, I usually use a different variable name.

Title: Generalise variable usage inside code


问:
How does one unit test an algorithm
I was recently working on a JS slideshow which rotates images using a weighted average algorithm. Thankfully, timgilbert has written a weighted list script which implements the exact algorithm I needed. However in his documentation he's noted under todos: "unit tests!".

I'd like to know is how one goes about unit testing an algorithm. In the case of a weighted average how would you create a proof that the averages are accurate when there is the element of randomness?

Code samples of similar would be very helpful to my understanding.

答: It's all about expected results. If you know the numbers should return within a certain range, test for that.</p>

OwnerDisplayName: Asa Baylus

Title: How does one unit test an algorithm

OwnerDisplayName: vidalsasoon


答:
I would just take the example and make what assertions I could. Of course, I would make this more than one test, not just a giant one. I'm going to write this mostly in pseudocode assuming that the utility methods have obvious implementations.

```<code>var data = [['a', 10],
            ['b',  1],
            ['c',  1],
            ['d',  5],
            ['e',  3]];

var wl = new WeightedList(data);

// wl.peek() returns items at random from the list, and does not modify the list.
var result = wl.peek();   // Ex: ['a']
assertContains(keySet(wl), result);
assertLength(1, result);
var result = wl.peek(3);  // Ex: ['a', 'c', 'd']
assertContainsAll(keySet(wl), result);
assertLength(3, result);

// wl.pop() returns random items from the list and removes the items it found
var result = wl.pop(2);  // Ex: ['a', 'd'], after which wl consists of [ ['b',  1], ['c',  1], ['e',  3] ]
assertIntersectionIsEmpty(result, keySet(wl));
assertLength(2, result);

// wl.push() adds new data into the set
// note that despite the terms push and pop, the weighted list has no natural order
wl.push('f', 6);     // wl is now [ ['b',  1], ['c',  1], ['e',  3], ['f',  6] ]
assertLength(4, wl);

// wl.addWeight() will increase the weight of a list item (or decrease it if the user passes a negative number)
wl.addWeight('b', 4);   // wl is now [ ['b',  5], ['c',  1], ['e',  3], ['f',  6] ]
// I doubt you can assert much here but no exception

// wl.shuffle() will return the entire list in random order.
result = wl.shuffle();           // Ex: ['b', 'f', 'c', 'e']
assertLength(4, result);
assertContainsAll(keySet(wl), result);
</code>```

Also, if the weights are not drastically different, you can repeat some of the operations many times and assert that you got all the values inside the WeightedList at some point. You just have to make sure that you repeat it enough that there is a very high probability they will appear. I would suggest a quick very high estimate of how many times you expect to run the test (say 100 times a day for a decade). Make the probability of failure one in that many runs. All you need to make sure is that the probability of this code failing due to bad luck with the random values is on the same order as the probability of failure due to a bug. Then you will not greatly increase your failure rate.

Title: How does one unit test an algorithm

Body:
I was recently working on a JS slideshow which rotates images using a weighted average algorithm. Thankfully, timgilbert has written a weighted list script which implements the exact algorithm I needed. However in his documentation he's noted under todos: "unit tests!".

I'd like to know is how one goes about unit testing an algorithm. In the case of a weighted average how would you create a proof that the averages are accurate when there is the element of randomness?

Code samples of similar would be very helpful to my understanding.

Body:
I would just take the example and make what assertions I could. Of course, I would make this more than one test, not just a giant one. I'm going to write this mostly in pseudocode assuming that the utility methods have obvious implementations.

var data = [['a', 10],
            ['b',  1],
            ['c',  1],
            ['d',  5],
            ['e',  3]];

var wl = new WeightedList(data);

// wl.peek() returns items at random from the list, and does not modify the list.
var result = wl.peek();   // Ex: ['a']
assertContains(keySet(wl), result);
assertLength(1, result);
var result = wl.peek(3);  // Ex: ['a', 'c', 'd']
assertContainsAll(keySet(wl), result);
assertLength(3, result);

// wl.pop() returns random items from the list and removes the items it found
var result = wl.pop(2);  // Ex: ['a', 'd'], after which wl consists of [ ['b',  1], ['c',  1], ['e',  3] ]
assertIntersectionIsEmpty(result, keySet(wl));
assertLength(2, result);

// wl.push() adds new data into the set
// note that despite the terms push and pop, the weighted list has no natural order
wl.push('f', 6);     // wl is now [ ['b',  1], ['c',  1], ['e',  3], ['f',  6] ]
assertLength(4, wl);

// wl.addWeight() will increase the weight of a list item (or decrease it if the user passes a negative number)
wl.addWeight('b', 4);   // wl is now [ ['b',  5], ['c',  1], ['e',  3], ['f',  6] ]
// I doubt you can assert much here but no exception

// wl.shuffle() will return the entire list in random order.
result = wl.shuffle();           // Ex: ['b', 'f', 'c', 'e']
assertLength(4, result);
assertContainsAll(keySet(wl), result);

Also, if the weights are not drastically different, you can repeat some of the operations many times and assert that you got all the values inside the WeightedList at some point. You just have to make sure that you repeat it enough that there is a very high probability they will appear. I would suggest a quick very high estimate of how many times you expect to run the test (say 100 times a day for a decade). Make the probability of failure one in that many runs. All you need to make sure is that the probability of this code failing due to bad luck with the random values is on the same order as the probability of failure due to a bug. Then you will not greatly increase your failure rate.

OwnerDisplayName: John Watts


问:
rails fake data, considering switch from faker to forgery, any advantages or pitfalls?
With Ruby on Rails I've usually used Forgery for generating dummy data for testing.

I've noticed recently that several clients and tutorials are using Faker

They both seem fairly similar in use and popularity:

Faker 128 forks, 418 watchers.

Forgery 59 forks, 399 watchers.

They both seem similar in how current they are:

Faker Most updates are from 6 and 9 months ago.

Forgery Most updates are from 4 and 9 months ago.

The one distinguishing factor I've found so far is that Forgery seems like it has better instructions.

Are there any particular benefits or disadvantages to using one over the other?

Have you ever needed to switch from one to another for a particular reason?

答: I use Ffaker so I guess that's one for the Faker camp - I found the API docs to be plenty sufficient, it's not like it's a hugely technical process, generating fake data.</p>


问:
Develop for Desktop and mobile use?
I am in the very beginning of developing an app / desktop program. I want it to be cross-platform and possibly also as a tablet version (preferably Android Icecream sandwich).
Note that I need to run it offline.

I thought about the following approaches:

ADOBE Air, since I do not need much performance. Plus I did some web programming in the past which might be of some use. Afaik it would run on OS X and Windows and should run on mobile OSes, too.

Qt. Found some nice Qt based desktop recently and read it also works on android. Plus I like the SDK.

HTML5 / JS. Again my web background should help me here. I wont need no sever side scripts, thus it should work without installing anything but a browser. How easy could this be converted into an Android app?

There might be a plethora of other (better) ways to do it, but I haven't thought of them yet. Can you help out? How would you create such an application. Would it be better to do some pure desktop client and then create tablet versions?

Would you rather start to create a website and worry later on how to turn into an app?

答:
```<code>  > HTML5 / JS ... How easy could this be converted into an Android app?
</code>```

You can develp with html5/js and wrap this app into a native mobile app using phonegap

Title: Develop for Desktop and mobile use?

Body:
  > HTML5 / JS ... How easy could this be converted into an Android app?

You can develp with html5/js and wrap this app into a native mobile app using phonegap


答:
In my experience, even frameworks that are "compatible" with both the desktop and mobiles typically suffer from the click/touch impedance mismatch. Briefly described, this means that your UI will either be easier to use with a mouse or with a touch screen, but not both. I have never seen a generally-useful framework that can automatically make a UI that is great on both click and touch interfaces.

My recommendation would be to use a programming language that works on all desired platforms; code any business logic (the "model" and "controller" parts of the MVC pattern) so that it will work identically on all the platforms; and then create two separate "Views" (GUIs) that are optimized for the experience of the targeted device.

You can do this with Qt; you can also do this with desktop Java or with HTML5/JS.

Taking the Qt route, I'd say write a normal QtGui interface for the desktop, but for Android you'll probably want to look into Qt Quick for a more touch-enabled experience. Not sure how stable / production-ready this is though.

Taking the Java route, you can use large swaths of the J2SE API for your business logic, but not all. I'd say develop your business logic targeting the more-limited Dalvik VM so any issues immediately obviate themselves (use Eclipse ADT and make it target the Android API). Write the UI using Android's native GUI library. Then lift out the business logic classes, drop them in a new desktop J2SE project, and write a SWT or Swing GUI for the desktop.

Taking the HTML5 route, you MIGHT be able to write one app that works well for desktop browsers and mobile browsers alike, but it largely depends on how dynamic you want your app to be, and what resolution you target. If you want to forget about phones (which have a much lower resolution than tablets or desktops), this may be your best bet. My experience using an Android phone on most HTML5 websites is that it requires tons of zooming and scrolling because they're desired for a larger screen. I really dislike that, so I end up looking for the "m." subdomain, which is pretty much the standard way that companies present their mobile site for small screen users. It's not a bad idea to go that route if you care at all about smartphone users.

Here is a Youtube video of someone with a Mac using Eclipse to create a HTML5/CSS app for Android. http://www.youtube.com/watch?v=uVqp1zcMfbE

Title: Develop for Desktop and mobile use?

Body:
I am in the very beginning of developing an app / desktop program. I want it to be cross-platform and possibly also as a tablet version (preferably Android Icecream sandwich).
Note that I need to run it offline.

I thought about the following approaches:

ADOBE Air, since I do not need much performance. Plus I did some web programming in the past which might be of some use. Afaik it would run on OS X and Windows and should run on mobile OSes, too.

Qt. Found some nice Qt based desktop recently and read it also works on android. Plus I like the SDK.

HTML5 / JS. Again my web background should help me here. I wont need no sever side scripts, thus it should work without installing anything but a browser. How easy could this be converted into an Android app?

There might be a plethora of other (better) ways to do it, but I haven't thought of them yet. Can you help out? How would you create such an application. Would it be better to do some pure desktop client and then create tablet versions?

Would you rather start to create a website and worry later on how to turn into an app?


问:
What is the definition of "Big Data"?
Is there one?

All the definitions I can find describe the size, complexity / variety or velocity of the data.

Wikipedia's definition is the only one I've found with an actual number

Big data sizes are a constantly moving target, as of 2012 ranging from a few dozen terabytes to many petabytes of data in a single data set.

However, this seemingly contradicts the MIKE2.0 definition, referenced in the next paragraph, which indicates that "big" data can be small and that 100,000 sensors on an aircraft creating only 3GB of data could be considered big.

IBM despite saying that:

Big data is more simply than a matter of size.

have emphasised size in their definition.

O'Reilly has stressed "volume, velocity and variety" as well. Though explained well, and in more depth, the definition seems to be a re-hash of the others - or vice-versa of course.

I think that a Computer Weekly article title sums up a number of articles fairly well "What is big data and how can it be used to gain competitive advantage".

But ZDNet wins with the following from 2012:

“Big Data” is a catch phrase that has been bubbling up from the high
  performance computing niche of the IT market... If one sits through
  the presentations from ten suppliers of technology, fifteen or so
  different definitions are likely to come forward. Each definition, of
  course, tends to support the need for that supplier’s products and
  services. Imagine that.

Basically "big data" is "big" in some way shape or form.

What is "big"? Is it quantifiable at the current time?

If "big" is unquantifiable is there a definition that does not rely solely on generalities?

答:
As it is pointed in Oracle link (comment by Immad Careem) oracle.com/us/technologies/big-data/index.html. The Big Data is everything which is not a relational data stored in a RDBMS. Few years before the hype it was just "a lot of data". Now it did grow and was promoted by marketers to be some kind of special data.

There are several secondary reasons (other than marketing) to consider Big Data a real thing.

Invention of Map-Reduce

NOSQL technologies like Hadoop

Some evolution in traditional RDBMS influenced by demand of unstructured data types

Possibly some hardware technologies offered by EMC2 corporation

Title: What is the definition of "Big Data"?


问:
What is the point of dynamic allocation in C++?
I really have never understood it at all. I can do it, but I just don't get why I would want to.

For instance, I was programming a game yesterday, and I set up an array of pointers for dynamically allocated enemies in the game, then passed it to a function which updates their positions.

When I ran the game, I got one of those nondescript assertion errors, something about a memory block not existing, I don't know. It was a run-time error, so it didn't say where the problem was. So I just said screw it and rewrote it with static instantiation, i.e.:

```<code>while(n<4)
{
Enemy tempEnemy = Enemy(3, 4);
enemyVector.push_back(tempEnemy);
n++;
}
updatePositions(&enemyVector);
</code>```

And it immediately worked perfectly.

Now sure, some of you may be thinking something to the effect of "Maybe if you knew what you were doing," or perhaps "n00b can't use pointers L0L," but frankly, you really can't deny that they make things way overcomplicated, hence most modern languages have done away with them entirely.

But please-- someone -- What IS the point of dynamic allocation? What advantage does it afford? Why would I ever not do what I just did in the above example?

答:
First off, you are using dynamic allocation. You just don't handle raw pointers yourself. But std::vector, as nearly all other useful data structures, internally allocates memory dynamically. This is because your only alternatives are: Static allocation (far too limited, you have to know the size at compile time) and stack allocation (far too limited, a few megabytes at most and it's deallocated as soon as the allocating function returns). Dynamic gives you the largest amount of memory and the most freedom in how you use it. A pointer or reference also abstracts over the size of what's allocated - on the stack, you have to know at compile time (or use alloca to allocate manually, but then you need even more care and still get a pointer).

Second, many C++ programmers will agree that raw pointers are not very useful most of the time, precisely due to the complexity and error-proneness you cite. You need them under the hood, and you should absolutely be able to use them, but you shouldn't do it in 99% of all code in the interest of sanity, correctness, programmer performance, exception safety, memory leak avoidance, etc. Your alternatives are some combination of containers (std::vector is just the tip of the iceberg), smart pointers, other forms of RAII, plain old stack allocation whenever you can get away with it, and references.

Also note that there is a difference between pointers (and other kinds of indirection) and dynamic allocation. Pointers (raw and smart, as well as references) afford you (as a commenter pointed out) polymorphism, regardless of how the pointed-to object is allocated. You will have to wrap your head around them, around references, around smart pointers, and about issues like ownership that follow suit, regardless of what/where/how you allocate.


答:
The main difference between C++ and a language like Java, is that in Java, you make a statement like

```<code>MyObject b = new MyObject(...);
myArrayOfObjects.add(b);
</code>```

Objects ARE references. This abstraction has proven to be very powerful in higher level languages. Objects are allocated on the heap and reference counted, taking away our responsibility to de-allocate that memory. The garbage collector simply can tell when an object has no references left to it, and sweeps it clean.

The fact of the matter is, C++ is not AS higher level. An advantage of C++ is that you CAN drop down to very manual memory management to get better performance or tweak certain performance intensive areas of your code.

In C++, if your object is going to be a member of a class, or otherwise passed around, stored, and needed by other classes, etc., you should use a pointer.

```<code>MyObject *myClassMemberVariable
</code>```

Now, there are propenents in C++ that advocate never using raw pointers like this. Libraries like boost and even the standard library make classes like smart pointers and other things that attempt to implement somewhat automatic memory management of resources, by "wrapping" raw pointers, providing different schemes for them to manage the memory.

It all comes down to you having to make your own decision about when to use pointers and how to manage memory. This is mainly what makes C++ harder than other languages (that among... other things). However, it does have its use and its advantages to the projects that use it.

Title: What is the point of dynamic allocation in C++?

Body:
I really have never understood it at all. I can do it, but I just don't get why I would want to.

For instance, I was programming a game yesterday, and I set up an array of pointers for dynamically allocated enemies in the game, then passed it to a function which updates their positions.

When I ran the game, I got one of those nondescript assertion errors, something about a memory block not existing, I don't know. It was a run-time error, so it didn't say where the problem was. So I just said screw it and rewrote it with static instantiation, i.e.:

```<code>while(n<4)
{
Enemy tempEnemy = Enemy(3, 4);
enemyVector.push_back(tempEnemy);
n++;
}
updatePositions(&enemyVector);
</code>```

And it immediately worked perfectly.

Now sure, some of you may be thinking something to the effect of "Maybe if you knew what you were doing," or perhaps "n00b can't use pointers L0L," but frankly, you really can't deny that they make things way overcomplicated, hence most modern languages have done away with them entirely.

But please-- someone -- What IS the point of dynamic allocation? What advantage does it afford? Why would I ever not do what I just did in the above example?

Body:
The main difference between C++ and a language like Java, is that in Java, you make a statement like

MyObject b = new MyObject(...);
myArrayOfObjects.add(b);

Objects ARE references. This abstraction has proven to be very powerful in higher level languages. Objects are allocated on the heap and reference counted, taking away our responsibility to de-allocate that memory. The garbage collector simply can tell when an object has no references left to it, and sweeps it clean.

The fact of the matter is, C++ is not AS higher level. An advantage of C++ is that you CAN drop down to very manual memory management to get better performance or tweak certain performance intensive areas of your code.

In C++, if your object is going to be a member of a class, or otherwise passed around, stored, and needed by other classes, etc., you should use a pointer.

MyObject *myClassMemberVariable

Now, there are propenents in C++ that advocate never using raw pointers like this. Libraries like boost and even the standard library make classes like smart pointers and other things that attempt to implement somewhat automatic memory management of resources, by "wrapping" raw pointers, providing different schemes for them to manage the memory.

It all comes down to you having to make your own decision about when to use pointers and how to manage memory. This is mainly what makes C++ harder than other languages (that among... other things). However, it does have its use and its advantages to the projects that use it.


答:
delnan provided a good explanation of what dynamic allocation is. +1 to that.

The only thing I want to add is that you use dynamic allocation when you need to. If you have small fixed size of objects, sure allocating them statically is good enough for now. If you have a need for short lived objects within a single function, sure local objects on the stack are great.

Only allocate objects dynamically when the other methods are not good enough. Don't use it just because the language allows it. Sooner or later, you will have a need.

Same goes with C++ templates. I have seen way too many people start plopping templates all over the place just because. Then same people complain how C++ is too convoluted and complicated. C++ has many advanced features, but it is up to the developer to determine when and where to use those features. But when there's no other alternatives, dynamic allocation (and templates) will allow you to do things which otherwise would've been impossible.


问:
What are the advantages of GLSL's compilation model?
GLSL is fundamentally different from other shader solutions because the server (GPU driver) is responsible for shader compilation. Cg and HLSL are (afaik) generally compiled a priori and sent to the GPU in that way.

This causes some real-world practical issues:

many drivers provide buggy compilers

compilers differ in terms of strictness (one GPU can accept a program while another won't)

also we can't know how the assembler code will be optimised

What are the upsides of GLSL's current approach? Is it worth it?

答:
The advantage is that it's easy to write programs that dynamically generate GLSL code, for example you can dynamically generate new shaders when the lights affecting an object changes.

The disadvantage is that the compile time can become significant and that the compilers generally do less optimization (in order to keep compile times down).


问:
Is constantly looking for code examples a sign of a bad developer?
I am a CS student with several years of experience in C and C++, and for the last few years I've been constantly working with Java/Objective C doing app development and now I have switched to web development and am mainly focused on ruby on rails and I came to the realization that (as with app development , really) I reference other code way too much. I constantly Google functionality for lots of things I imagine I should be able to do from scratch and it's really cracked my confidence a bit.

Basic fundamentals are not an issue, I hate to use this as an example but I can run through javabat in both java/python at a sprint - obviously not an accomplishment and but what I mean to say is I have a strong base for the fundamentals I think?

I know what I need to use typically but reference syntax constantly. Would love some advice and input on this, as it has been holding me back pretty solidly in terms of looking for work in this field even though I'm finishing my degree. My main reason for asking is not really about employment, but more that I don't want to be the only guy at a hackathon not hammering out nonstop code and sitting there with 20 Google/github tabs open, and I have refrained from attending any due to a slight lack of confidence...

Is a person a bad developer by constantly looking to code examples for moderate to complex tasks?

答:
So reading books with examples and referring to them is bad programming is the context of your question. Well seeing as few people document their API a book is all we have left.

I don't know what your reasons are for asking this question perhaps you can answer this yourself after reading my situation as I refer to a lot of code examples.

I never had a chance to go to university as I was on the street at age 16. Somehow at 24 I was in the position to study through a correspondence college and do vendor certifications as SCJP, SCJD, SCBCD and SCWCD. I must admit that at times I struggled and had to turn online for examples. Unknowingly though at this time I had a brain tumor growing in my head (by 2010 it was the size of an orange). After my 5 brain surgeries, 6 weeks combine chemo/radiotherapy and 10 months of chemo, I still am programming with hand written coded sites up that are viewable from my profile.

Yes I need a lot of code examples now with brain damage, so does that make me a bad programmer?


问:
Should I strictly follow every single HTML and CSS Standard?
A few years ago I considered myself somewhat of a web developer, knowing the basic 3 languages (HTML, CSS, JS) and lots of PHP. Moving on from simple text to actual websites was a pain because of the so called "standards" out there, which at the time were ridiculously complicated for me. It pretty much boiled down to this (minus the IE related stuff):

Standards are there to replace old ways of doing things in a simpler way. However when trying to actually implement some of the stuff (Entirely CSS based layout for example), it took me 10x longer to actually do it then if I did the simpler and still working solution. If it rendered the same, then why should I use the more complicated example that takes 10x longer and breaks once you change browsers? This sparked many long religious debates in ##php, ##css, and ##js in Freenode IRC and actually got me banned from ##css because I messed with their little world over there.

My question: Should I follow every single standard and coding conventions even if they take me 10x longer but get me the same result as the simple one?

For the poll tag, those of you who have websites of any size (huge or small), do you follow all the standards?

答:
Product first, then polish.

Get your site/application/game doing what it's supposed to do. Get it up and running, and get people interested.

Then, when you have the time, go back and polish it up. But only because you care, not because anybody else does.

Of course, if the non-compliance issues mean people can't view it, or it's unreadably ugly, or it takes a month to load, or it's hard to maintain, or it crashes the browser, this is a major problem. But it would still be a major problem even if you were standards-compliant.

Ordinary users do not look at the source for a website that isn't loading and go, "Well, it's not displaying the pictures, but it's completely W3C-compliant". They simply browse to another website and never return.

Bottom line, standards are there to make writing browsers easier, and to close up potential security holes. Amazon, Penny-Arcade and Stack Overflow do not make their money from running a standard-compliant website. And unless you're in a website-writing competition, neither will you.

ContentLicense: CC BY-SA 2.5


问:
Does a team of developers need a manager?
Background:

I'm currently part of a team of four: 1 manager, 1 senior developer and 2 developers. We do a range of bespoke in-house systems / projects (e.g. 6-8 weeks) for an organisation of around 3500 staff, as well as all the maintenance and support required from the systems that have been created before. There is not enough of us to do all the work that is potentially coming our way - we're understaffed. Management acknowledge this, but budget restraints limit our ability to recruit additional members to the team (even if we make the salary back in savings).

The Change

This leaves us where we are now. Our manager is due to leave his role for pastures new, leaving a vacancy in the team. Management are using this opportunity to restructure our team which would see the team manager role replaced by another developer and another senior developer. Their logic being that we need more developers, so here's a way of funding it (one of the roles is partially funded from another vacant post).

The team would have no direct line manager and the roles and responsibilities would be divided up between the seniors and the (relatively new to post) service manager (a non-technical role with little-to-no development knowledge/experience whose focus is shared amongst a number of other teams and individuals) - who would be our next actual manager up the food chain.

I guess the final question is:

Is it possible to run a development team without an manager? Have you had experience of this? And what things could go wrong / could be of benefit to us?

I'd ideally like to "see the light" and the benefits of doing things this way, or come up with some points for argument against it.

答:
A team of developers does not need a manager if each person is mature enough to work as a team and meet stakeholder expectations.

There are certain roles (say developers) which required to be focused on a problem that needs to be resolved and not worry about other environmental factors. That is where having a manager helps.

Having said that someone senior who can add value always helps. Even a CEO reports to a team of managers (board of directors).

My 2 cents...


问:
Sharing object between 2 classes
edit: I am thinking that dependency injection is the best approach.

I am struggling to wrap my head around being able to share an object between two classes. I want to be able to create only one instance of the object, commonlib  in my main class and then have the classes, foo1 and foo2, to be able to mutually share the properties of the commonlib. commonlib is a 3rd party class which has a property Queries that will be added to in each child class of bar. This is why it is vital that only one instance is created. I create two separate queries in foo1 and foo2.

This is my setup:

```<code>abstract class bar{
//common methods
}

class foo1 extends bar{
//add query to commonlib
}

class foo2 extends bar{
//add query to commonlib
}

class main {

    public $commonlib = new commonlib();

    public function start(){
    //goal is to share one instance of $this->commonlib between foo1 and foo2
    //so that they can both add to the properites of $this->commonlib (global
    //between the two)

    //now execute all of the queries after foo1 and foo2 add their query
    $this->commonlib->RunQueries();

}

}
</code>```

答:
Approach 1: Use a property in bar

Make commonlib a property in bar and declare getters and setters. Share that one instance of commonlib that you declared in main between foo1 and foo2.

abstract class bar {
    protected $commonlib;

    public function __get($property) {
        if (property_exists($this, $property)) {
            return $this->$property;
        }
    }

    public function __set($property, $value) {
        if (property_exists($this, $property)) {
            $this->$property = $value;
        }
        return $this;
    }
}

class foo1 extends bar{
    public function someMethod() {
        $this->commonlib->addQueries($fromSomeWhere);
    }
}

class foo2 extends bar{
    public function someMethod() {
        $this->commonlib->addQueries($fromSomeWhereElseAndInADifferentWay);
    }
}

class main {

    public $commonlib = new commonlib();

    public function start(){
        //goal is to share one instance of $this->commonlib between foo1 and foo2
        //so that they can both add to the properites of $this->commonlib (global
        //between the two)
        $foo1 = new foo1();
        $foo1->commonlib = $commonlib;

        $foo2 = new foo2();
        $foo2->commonlib = $commonlib;

        $foo1->someMethod();
        $foo2->someMethod();

        //now execute all of the queries after foo1 and foo2 add their query
        $this->commonlib->RunQueries();

}
```
<p>Edit:</p>
<h3>Approach 2: Pass common lib as an argument and only put algos in foo1 and foo2</h3>
<p>Thus,</p>
```class foo1 {
    public function addQueries($commonlib) {
        $commonlib->addQueries($fromSomeWhere);
    }
}

class foo2 {
    public function addQueries($commonlib) {
        $commonlib->addQueries($fromSomeWhereElseAndInADifferentWay);
    }
}

class main {

    public $commonlib = new commonlib();

    public function start(){
        //goal is to share one instance of $this->commonlib between foo1 and foo2
        //so that they can both add to the properites of $this->commonlib (global
        //between the two)
        $foo1 = new foo1();
        $foo2 = new foo2();

        $foo1->someMethod($commonlib);
        $foo2->someMethod($commonlib);

        //now execute all of the queries after foo1 and foo2 add their query
        $this->commonlib->RunQueries();

}
```

Title: Sharing object between 2 classes

Body:
Approach 1: Use a property in bar

Make commonlib a property in bar and declare getters and setters. Share that one instance of commonlib that you declared in main between foo1 and foo2.

abstract class bar {
    protected $commonlib;

    public function __get($property) {
        if (property_exists($this, $property)) {
            return $this->$property;
        }
    }

    public function __set($property, $value) {
        if (property_exists($this, $property)) {
            $this->$property = $value;
        }
        return $this;
    }
}

class foo1 extends bar{
    public function someMethod() {
        $this->commonlib->addQueries($fromSomeWhere);
    }
}

class foo2 extends bar{
    public function someMethod() {
        $this->commonlib->addQueries($fromSomeWhereElseAndInADifferentWay);
    }
}

class main {

    public $commonlib = new commonlib();

    public function start(){
        //goal is to share one instance of $this->commonlib between foo1 and foo2
        //so that they can both add to the properites of $this->commonlib (global
        //between the two)
        $foo1 = new foo1();
        $foo1->commonlib = $commonlib;

        $foo2 = new foo2();
        $foo2->commonlib = $commonlib;

        $foo1->someMethod();
        $foo2->someMethod();

        //now execute all of the queries after foo1 and foo2 add their query
        $this->commonlib->RunQueries();

}

Edit:

Approach 2: Pass common lib as an argument and only put algos in foo1 and foo2

Thus,

class foo1 {
    public function addQueries($commonlib) {
        $commonlib->addQueries($fromSomeWhere);
    }
}

class foo2 {
    public function addQueries($commonlib) {
        $commonlib->addQueries($fromSomeWhereElseAndInADifferentWay);
    }
}

class main {

    public $commonlib = new commonlib();

    public function start(){
        //goal is to share one instance of $this->commonlib between foo1 and foo2
        //so that they can both add to the properites of $this->commonlib (global
        //between the two)
        $foo1 = new foo1();
        $foo2 = new foo2();

        $foo1->someMethod($commonlib);
        $foo2->someMethod($commonlib);

        //now execute all of the queries after foo1 and foo2 add their query
        $this->commonlib->RunQueries();

}


答:
Isn't Singleton the pattern you are looking for?

The singleton pattern allows you to have only one instance of an object. This instance can generally be called by every object or functions who need it and as it is a single instance every changes will be accessible everywhere.

Title: Sharing object between 2 classes

Body:
edit: I am thinking that dependency injection is the best approach.

I am struggling to wrap my head around being able to share an object between two classes. I want to be able to create only one instance of the object, commonlib  in my main class and then have the classes, foo1 and foo2, to be able to mutually share the properties of the commonlib. commonlib is a 3rd party class which has a property Queries that will be added to in each child class of bar. This is why it is vital that only one instance is created. I create two separate queries in foo1 and foo2.

This is my setup:

```<code>abstract class bar{
//common methods
}

class foo1 extends bar{
//add query to commonlib
}

class foo2 extends bar{
//add query to commonlib
}

class main {

    public $commonlib = new commonlib();

    public function start(){
    //goal is to share one instance of $this->commonlib between foo1 and foo2
    //so that they can both add to the properites of $this->commonlib (global
    //between the two)

    //now execute all of the queries after foo1 and foo2 add their query
    $this->commonlib->RunQueries();

}

}
</code>```


答:
It sounds to me like the problem for you is less in understanding what you're referencing, and more with issues of facility and memory. If it's sapping your confidence, then yes it's a problem – but it can certainly be addressed!

For me, these kinds of challenges come up in many different aspects of my life. For example, to get good at performing a piece of music, I need to develop my independence from the sheet music I'm given – how can you really feel the music if your nose is still buried in your booklet? Sometimes, if I have the time, I'll memorize the whole piece of music – even if it's not required for my gig. Why? With the sheet music gone, it's much easier for me to focus on the more challenging and overarching aspects of the music I need to get right, and it's much easier for me to get into that incredible zone of pure music-making. So I find it's often well worth the extra trouble.

My experience with programming has been similar. I think the keys are:

practice the language – type it, run it, speak it if it helps; do so repeatedly.

build your facility – use the same feature or pattern in different situations; put features together; make programs.

give enough time between repetitions to make sure that things are really making their way into your long-term memory.

These principles seem to apply when learning any language, actually! See How to Remember New Words for example. The Pimsleur method also works like this.

I've found that almost all of the principles, syntax, and common libraries of the language and technologies I use regularly can be completely memorized, by using these keys. Even so, I still constantly scour the Internet for examples and wisdom! But that point, I'm looking for validation on the problem I'm trying to solve, various approaches that have been taken, tools that can help, and consultation for less frequently used libraries. It's a very different kind of search than I use when I'm first learning a language and neck-deep in tutorials and manuals.

From your story, here are some specific stumbling blocks I think you might be running into.

If you're struggling with syntax, you might not be getting enough practice. This is especially true if you're copying and pasting straight into your code, instead of developing the repetition and – may I say? – muscle memory that will help you get really good. To counter this, simply develop exercises and discipline, focusing on repetition and time, that will improve your facility in the areas you want. Suggestions:

Write a simple program in the same language once a day, every day.

Type examples instead of copying and pasting them.

If you're struggling with constructing solutions to moderate-sized problems, you might not be getting enough experience with building. Try these:

Start a medium-sized project in some technology or language you want to get good at. Or try your hand at a chunkier feature on an open-source project you're interested in. Hack away at it a bit every day. (Remember, when you're going after these larger projects: go at them brick by brick. Don't try and build the whole thing at once!)

Use the same new feature on four consecutive days, in four different contexts.

Challenge yourself to code something with the web browser turned off!

Actually take notes on stuff you're learning. Synthesize what you're learning, and write down your observations. (Actually writing things down, and forcing myself to express something in my own words, helps me a lot.)

Write answers, and verify them, for StackOverflow questions on the technology you're absorbing. (This often has the added benefit of earning you a little reputation while you're learning. :-) )

You might be spreading your practice too thinly. You seem to be working in many different languages. This has a lot of advantages, but it does have the disadvantage of diluting your experience. If you're spending time working in five different languages, you'll memorize less than if you're spending the same time in one language. Worse, there are lots of not-quite-similar cognates between different languages (was that else if, elsif, or elif??) to trip you up. To counter this, sharpen your focus. Pick one thing to learn and learn it cold. Then move on to the next thing.

Title: Is constantly looking for code examples a sign of a bad developer?

Body:
I am a CS student with several years of experience in C and C++, and for the last few years I've been constantly working with Java/Objective C doing app development and now I have switched to web development and am mainly focused on ruby on rails and I came to the realization that (as with app development , really) I reference other code way too much. I constantly Google functionality for lots of things I imagine I should be able to do from scratch and it's really cracked my confidence a bit.

Basic fundamentals are not an issue, I hate to use this as an example but I can run through javabat in both java/python at a sprint - obviously not an accomplishment and but what I mean to say is I have a strong base for the fundamentals I think?

I know what I need to use typically but reference syntax constantly. Would love some advice and input on this, as it has been holding me back pretty solidly in terms of looking for work in this field even though I'm finishing my degree. My main reason for asking is not really about employment, but more that I don't want to be the only guy at a hackathon not hammering out nonstop code and sitting there with 20 Google/github tabs open, and I have refrained from attending any due to a slight lack of confidence...

Is a person a bad developer by constantly looking to code examples for moderate to complex tasks?


答:
Well, you're way wrong about modern languages not using pointers. They call them different things, but they're still pointers under the hood. And they do not even get rid of stack-allocations either, look at .NET for example and see the difference between reference types and value types.

However that's as makes no difference to you. Your problem is that you don;t quite understand
what happens with your allocations.

Computers work with a huge lump of memory that they split into 2 groups, the heap and the stack. The stack is used for temporarily passing data between function calls, the heap is a more 'global' storage space for objects. In C++ you get the stack for free by allocating as you've done - Enemy e; is a stack allocation. To use the heap you must create the object and then keep track of where it was allocated yourself, usually by using a pointer. So Enemy* e = new Enemy(); will allocate an Enemy-sized object on the heap, but will be a pointer to that object, no that object itself. Note that e itself is allocated on the stack (every variable has to be stored somewhere after all).

Now thing what happens when you call a function - you know about copy by value and copy by reference? If you've allocated your object on the stack you will get a copy of the object when you call a function, but if you've allocated it on the heap, when you pass the pointer, you will get a copy of the pointer (which, of course, still points to the same object on the heap).

I guess if you're used to Java or .NET's way of handling heap-based objects for you, then the closest you'll get with C++ is to use the smart pointers, shared_ptr<> is probably what you want. Use these instead of raw pointers, or stack objects and you'll be a lot happier. The bonus over  GC languages is that you'll also get instant deallocation of them once no-one is using the object anymore (so you can put your enemy death throes routines in the destructor and let the system automatically call it when the enemy is deleted)


答:
Unit tests don't prove general cases. They merely assert that certain (hopefully well chosen) cases meet a few expectations. And that's good enough for most things.

Find some examples, manually calculate and verify the results, and when deemed correct, put them under assertion.

Make sure to choose your examples well. In case of "testing division" it doesn't make much sense to test 8/4, 4/2 and 6/3. It'd be much better to only test 8/4, but to also include 8/3 (= 2, or 2.66?), 8/(-2), 8/0, 0/8, 0/0, 2/8,... include corner cases.

Title: How does one unit test an algorithm


答:
First look at a set of inputs that the algorithm would deal with. Try to find different classifications for the input. For example, if the algorithm was something that computers the sqrt of a number (as an example), think of the kinds of inputs that the algorithm will deal with. One such input classification might be positive numbers, 0, and negative numbers. Then take any input from each of these classes and write a test that uses it.

This is an example of input space partitioning, and can help cover all the logical cases your program may have to deal with.

After this, use a code-coverage analysis tool to find any code (or cases) that aren't tested yet. Then try to formulate inputs that test that particular path in the code. This is an example of black-box testing.

Title: How does one unit test an algorithm


问:
Zooming options terminology
I've come up with 4 different ways to fit an image inside a viewing region, but I'm trouble coming up with names for them. Perhaps someone can suggest some?

Fit image in viewing region, do not enlarge if image is smaller

Size image so it fits snuggly inside the viewing region (enlarge if necessary) -- the image is as large as possible while still fitting within the viewing region

Size image so that it fills the entire viewing region -- the image will be the same size or bigger than the viewing region

1:1 ratio; 1 pixel in the image corresponds to 1 pixel on screen

All zooming options maintain aspect ratio. Stretching is just ugly, so it's not an option :)

答:
Edited to match your clarification

Shrink to fit

Enlarge to fit

Fill

Center

Or just wrap 1. and 2. in a single "Fit" option, given that you'll never be able to do both to the same image.

Title: Zooming options terminology


答:
You are talking about two different concepts in your list: Zooming and Resizing. One just enlarges the view while the other alters the actual image.

Image editing software such as Photoshop and Paint use similar terminology as the following:

Zoom to Fit Screen

Resize to Fit Screen (enlarges image's width and height independently until they match the screen).

Resize to Fit Screen with Constrain Proportions option/flag (resizes width and height in equal amounts until largest side fits viewing region)

Actual Pixels ("Actual Size" is also an option).

I assume #4 in the question is a zoom option instead of a resize option.

Title: Zooming options terminology

Body:
I've come up with 4 different ways to fit an image inside a viewing region, but I'm trouble coming up with names for them. Perhaps someone can suggest some?

Fit image in viewing region, do not enlarge if image is smaller

Size image so it fits snuggly inside the viewing region (enlarge if necessary) -- the image is as large as possible while still fitting within the viewing region

Size image so that it fills the entire viewing region -- the image will be the same size or bigger than the viewing region

1:1 ratio; 1 pixel in the image corresponds to 1 pixel on screen

All zooming options maintain aspect ratio. Stretching is just ugly, so it's not an option :)


问:
Is it possible to know what programming language a web-site uses?
For example, stackexchange.com, without asking the site owner or Google their information about developing the website, is this possible to know what language is used in the back end?

Seems, the website don't have .extension bar, for example .php that can indicated which is developed in PHP, but without the extension, how can I know that?

答: I don't know if this specifically answer your question but there is a tool that was really helpful to me: Wappalyzer. It is a Firefox/Chrome extension that uncovers the technologies used on websites. It detects content management systems, web servers, JavaScript frameworks, analytics tools and many others. I know is not precisely what you are looking for but it give you a very close idea of what a site use. This is what it shows for programmers.stackexchange.com


问:
Bad idea to display mail server info in public github project?
I have the project for work that requires me to send e-mails to people using our work mail server. The server doesn't require authentication. Part of my project is using a Java-Helper I'm developing on GitHub. I don't know if I completely understand how it all works, but I'm guessing it would be a bad idea to have the server information available on GitHub for the world to see. Is this correct?

After thought: I'm not going to put it in the Java-Helper because that wouldn't be helpful for anyone but me. but I'm still curious to know the answer to this question :) Thanks!

答:
Of course, that's a bad idea. This is not just good security, but this will also make your project potentially more useful to others.

Ideally, you should be externalizing all of that information into a configuration file that you tell git to ignore and then you should add a well commented blank configuration file that others downloading your project can tailor to their needs.

Bonus points if you mention the need to modify that file in your README file and if you centralize all of those environment-specific constants into just one file. Others are less likely to make a mistake if they just have to modify a single file.

Then, don't forget to double-check your work. From a different computer, from home or elsewhere, try to see how easy it is to download and rebuild your project from scratch as if it were the first time you ran across it on GitHub.


答:
There a couple of technique you can use here:

1) Replace the random number generator with one that produces canned values, and check that the expected values are gotten

```<code>   old_random = Math.random;
   Math.random = function() { return 0.5; };
   assert_equals(random_pick(), expected_random_pick);
</code>```

2) Run the algorithm a whole lots of times, and sum up the results

```<code>weights = {0:.1, 2:.5, 6:0.4}
totals = {}
count = 10000;
for(x = 0; x < count; x++)
{
    totals[random_pick(weights)] += 1 / count;
}
assert(totals[0] - weights[0] < 0.1)
assert(totals[2] - weights[2] < 0.1)
assert(totals[6] - weights[6] < 0.1)
</code>```

The idea here is that if you run the algorithm enough times the law of large numbers will make the totals similar the theoretically expected ones. Then you check that.

Title: How does one unit test an algorithm

Body:
There a couple of technique you can use here:

1) Replace the random number generator with one that produces canned values, and check that the expected values are gotten

   old_random = Math.random;
   Math.random = function() { return 0.5; };
   assert_equals(random_pick(), expected_random_pick);

2) Run the algorithm a whole lots of times, and sum up the results

weights = {0:.1, 2:.5, 6:0.4}
totals = {}
count = 10000;
for(x = 0; x < count; x++)
{
    totals[random_pick(weights)] += 1 / count;
}
assert(totals[0] - weights[0] < 0.1)
assert(totals[2] - weights[2] < 0.1)
assert(totals[6] - weights[6] < 0.1)

The idea here is that if you run the algorithm enough times the law of large numbers will make the totals similar the theoretically expected ones. Then you check that.


问:
Is an 'if password == XXXXXXX' enough for minimum security?
If I create a login for an app that has middle to low security risk (in other words, its not a banking app or anything), is it acceptable for me to verify a password entered by the user by just saying something like:

```<code>if(enteredPassword == verifiedPassword)
     SendToRestrictedArea();
else
     DisplayPasswordUnknownMessage();
</code>```

It seems to easy to be effective, but I certainly would not mind if that was all that was required. Is a simple check on username/password combo enough?

Update: The particular project happens to be a web service, the verification is entirely server side, and it is not open-source. Does the domain change how you would deal with this?

答:
It has been noted in a couple of answers that you should not store the password itself, but a hash - and you should use SSL.

You may say, what is the big deal? If my application gets hacked, that is of little concern. Well it is a quite common pattern for users to reuse the same password on all sites. Was a hacker to hack your site and gain access to user's passwords, the hacker would be able to impersonate a lot of those users on other sites of greater importance to those users. So hacking your site could be the first step for a hacker to gain access to banking information for the users.

And just hashing the password is not enough. You need to hash it with a salt. Hackers have reverse hash lookup tables, so for a given hash, they can find a matching password.

If you choose not to implement these feature, you should inform the users of of this lack of security, encouraging them not to use the same password that they use elsewhere.


问:
Why isn't Java used for modern web application development?
As a professional Java programmer, I've been trying to understand - why the hate toward Java for modern web applications?

I've noticed a trend that out of modern day web startups, a relatively small percentage of them appears to be using Java (compared to Java's overall popularity).  When I've asked a few about this, I've typically received a response like, "I hate Java with a passion."  But no one really seems to be able to give a definitive answer.

I've also heard this same web startup community refer negatively to Java developers - more or less implying that they are slow, not creative, old.

As a result, I've spent time working to pick up Ruby/Rails, basically to find out what I'm missing.  But I can't help thinking to myself, "I could do this much faster if I were using Java," primarily due to my relative experience levels.

But also because I haven't seen anything critical "missing" from Java, preventing me from building the same application.

Which brings me to my question(s):

Why is Java not being used in modern web applications?

Is it a weakness of the language?

Is it an unfair stereotype of Java because it's been around so long (it's been unfairly associated with its older technologies, and doesn't receive recognition for its "modern" capabilities)?

Is the negative stereotype of Java developers too strong? (Java is just no longer "cool")

Are applications written in other languages really faster to build, easier to maintain, and do they perform better?

Is Java only used by big companies who are too slow to adapt to a new language?

答:
In the startup I work for we chose to use both Java and JRuby to implement our API because they complement each other.

For infrastructure, process distribution and communications we leverage Java's robustness, whereas for the actual implementation of the API endpoints we chose JRuby since all the calls involve JSON and it makes a lot more sense to manipulate a loosely-typed representation (JSON) using a loosely-typed language (Ruby).

If we see one of our JRuby classes is becoming a bottleneck, we just re-implement it directly in Java (basically a line-by-line translation). This can happen quite often with classes which must do a lot of computation, and in this context JRuby behaves much like a prototyping language.

We implemented our own dynamic class loader which means we can change Java classes on the fly without restarting the server, and we've been very happy with the choice. So the "you need to compile and restart each time" argument does not hold much weight.

The key is to avoid all the Java EE stuff - it's huge and cumbersome and anti-agile.


答:
The question should be "Why isn't Java used by startups or for small projects?". Java certainly used for "modern Web apps". At Google, Java is used on the backend for many services, and closure compiled JS or GWT is used for the frontend. The issue is one of speed vs scale. Startups need to get to minimum viable product. They are usually small teams of 1-3 engineers, and value iteration speed over performance or maintainability. Running up against scalability issues or team code code maintenance issues is a problem "you'd like to have", that is, by the time you reach that stage, it's a sign your initial implementation helped you over the initial hump of getting customers or investment. You can afford to rewrite the app at that point.

A company like Google can afford the luxury of building things for scale up front, even though they may be wasting their time implementing scaling for something that might get no users, because they can absorb the loss.

At least, that's my opinion, that many many "cool", "hip", "modern" companies build small apps with small teams where iteration speed and simplicity are the greatest requirements.

Title: Why isn't Java used for modern web application development?

Body:
As a professional Java programmer, I've been trying to understand - why the hate toward Java for modern web applications?

I've noticed a trend that out of modern day web startups, a relatively small percentage of them appears to be using Java (compared to Java's overall popularity).  When I've asked a few about this, I've typically received a response like, "I hate Java with a passion."  But no one really seems to be able to give a definitive answer.

I've also heard this same web startup community refer negatively to Java developers - more or less implying that they are slow, not creative, old.

As a result, I've spent time working to pick up Ruby/Rails, basically to find out what I'm missing.  But I can't help thinking to myself, "I could do this much faster if I were using Java," primarily due to my relative experience levels.

But also because I haven't seen anything critical "missing" from Java, preventing me from building the same application.

Which brings me to my question(s):

Why is Java not being used in modern web applications?

Is it a weakness of the language?

Is it an unfair stereotype of Java because it's been around so long (it's been unfairly associated with its older technologies, and doesn't receive recognition for its "modern" capabilities)?

Is the negative stereotype of Java developers too strong? (Java is just no longer "cool")

Are applications written in other languages really faster to build, easier to maintain, and do they perform better?

Is Java only used by big companies who are too slow to adapt to a new language?


答:
Java was cool, Java is cool and Java will be cool in future. I'm developing a web App. Using Java.

The main problem with Java is it needs a medium size team 7-10 people to see the results of implementation. Developers of the back end must have the knowledge of application architecture from ORM to Application framework to presentation layer. Too many options for developers on the table, and this raises the questions, is it a good idea to use a ORM or not? Which ORM framework to use? Which application framework to use? How to implement the front end? All this makes the developers struggle and makes the combinations endless from the end user to pick this technology with that framework that developers are not familiar with. The same is with IDE plugins; too many options, a lot of time is spent on installing, configurating, and testing if this version of a plugin works with this version of the IDE and so on. The last thing is hosting; many developed Java Apps don't go out to public because there is no proper web hosting for Java web apps, getting one VPS for $80/month is not an option for too many developers, and most applications needs more than one VPS.


问:
Test a simple multi-player (upto four players) Android game in single developer machine
I'm working on a multi-player Android game (very simple it is that it doesn't have any game-engine used). The game is based on Java Socket. Four devices will connect the game server and a new thread will manage their session. The game server will server many such sessions (having 4 players each).

What I'm worried about is the testing of this game. I know it is possible to run multiple android emulators, but my development laptop is very limited in capabilities (3 GB RAM, 2 Ghz Intel Core2Duo and on-board Graphics). And I'm already using Ubuntu to develop the game so that I have more user memory available than I'd have with Windows.

Hence, the laptop will burn-to-death on running 4 emulator instances. I don't have access to any android device, neither I have another machine with higher configuration. And I still have to develop and test this game.

P.S. : I'm a CS student, and currently don't work anywhere, and this game is college project, so if there are any paid solutions, I cannot afford it.

What can I do to test the app seamlessly? ability to test even only 4 clients (i.e. only 1 session) would suffice, its alright if I can't simulate real environment with some 10-20 active game sessions (having 4 players each).

答: You should ideally write your classes in such a way you can instantiate multiple clients in the same program instance, and mux the input/outputs accordingly... That's the best way to do this IMHO.</p>


问:
0.00006103515625 GB of RAM. Is .NET MicroFramework part of Windows CE?
The .NET MicroFramework claims to work on 64K RAM and has list of compatible targets vendors. At the same time, same vendors who ship hardware and create Board Support Packages (vendors like Adeneo) keep releasing something named Windows 7 CE BSP for the same hardware targets. Obviously the OS as heavy as WinCE needs more than 64K RAM. So, somehow .NET MicroFramework is relevant to WinCE, but how ?

Is it part of bigger OS or is it base of it, or are both mutually exclusive ?

Background:

0.00006103515625 GByte of RAM is same as 64Kbyte of RAM.
I am looking for possiblity to use Microsoft development tools for small target like BeagleBone.

http://www.adeneo-embedded.com/About-Us/News/Release-of-TI-BeagleBone

Nice. Now .. where is a MicroFramework for the same beaglebone ? Is it inside the released pile ?

答:
No, Windows CE should use CompactFramework.

MicroFramework is for low level electronic devices and it is now open source (v4.x).
It interprets MSIL rather than performs JIT compilation.
MicroFramework contains classes for controlling electronic signals, digital in/out, analog in/out, Serial, SPI, I2C, ...


问:
When writing specs BDD-style, should you use "should", or should you not?
I realize this is somewhat subjective, but I can't find a good case for one or the other :

it "should do something"

    it "does something"

Proponents of the should style mention that it forces you to actually question what it is you are trying to achieve, while detractors find it just redundant.

Is there a consensus on this, or is it purely a matter of style ?

答:
From behaviour-driven.org titled "GettingTheWordsRight":

In short, the words that we use to describe things influences the way in which we (and others) think about those things. This isn't just a simple question of being petty about semantics either, as certain words carry with them nuances that affect how we interpret the meaning of a phrase at both an intellectual and an emotional level. Our language is rich with descriptive words and phrases so it seems reasonable to use words that will clearly convey the intention of the elements that we wish to describe in code.

In the case of BDD, I'm personally who almost always uses the word should when naming tests, because its usage implies that while the intention is for a test to provide a certain result, other unexpected consequences may arise which will need to be dealt with if a test result is to be considered valid. You could perhaps use the words expect or must similarly, however these words imply a more imperative viewpoint such that the name of the test could be mistaken to mean "there is nothing wrong with the test, assume the implementation is messed up", whereas *should" implies that the test is likely to be correct, yet may need to be checked again for error if the test results don't seem to add up.  I like this, because it influences your thinking such that you are encouraged to keep an open mind as you code, which is very important when you wish to avoid getting stuck as you attempt to debug your code and find yourself looking in the wrong place for errors because of an assumption.

I have however seen the near 'religious' application of the word should fail when it has been enforced as a prefix for test names, as it has forced the programmers involved to go through certain mental and linguistical gymnastics in order to provide a test name that was meaningful, and in such cases it has meant that the intention to get the words right does not meet its expectations, and the tests themselves become difficult to decipher as a result. When this sort of situation crops up, I would usually use the word should at any place within the test method name, to ensure the name conveys its method simply and clearly. I would certainly not however enforce a particular word usage if other words were equally appropriate within a given context. The trick however is to choose words that leave no room for argument about what something represents in code, and that provoke you into thinking about the things that your code is supposed to do without relying on mere implication.


问:
Why don't browsers support haml and sass?
The time needed to download a website would be significantly reduced, and parsing would be also easier I think.

Why are not these languages imposed as a standard? Obviously they are better than raw html and CSS...

Browsers are the only thing that keeps us away from eliminating the intermediate HTML/CSS code.

答:
Yes, they do look cooler and easier to use than html and CSS. But html and CSS are existed and built for a long time, many many applications both on web or desktop use them.

Therefore, it's not easy to make something standard. HAML and SASS are really fun and cleaner to use but being standard, it will take a long time or never. Since, w3c does care about developers, so they indeed make html and css better in html5 and css3.


答:
I still have the feeling that Java is being used in a lot of web development. But it's usually on the more business-oriented-no-mainly-tech-big-company kind of developments, which typically are less open then new startups that have to get some traction and promote their own work, as well as more interested in technology. So, even if it is used in a lot corporate web sites, you'll probably never know, as they won't really care to tell publicly about their technology stack.

That said, commenting all the original questions...

Is it a weakness of the language?
Compared with other languages like Python or Ruby, Java is verbose and tends to need more code to do similar stuff. But it's not just the capabilities of the language, also the community surrounding it and the kind of developers that uses those tools.
So, most of the modules and tools on Python, Ruby, PHP, etc are open source and are easier to find than in Java world, just because this one is more focused on giving (and charging) services.
For example, the Ruby community is really really oriented to web development, so every developer that is able to use Ruby will know about the problems and available tools for a web project. That is not necessarily true for Java developers, that could have been working on other kind of systems, like reporting systems. Of course, any good developer will catch up, but the perception is that the average Java developer is less worried about learning new technologies and new languages.

Is it an unfair stereotype of Java because it's been around so long (it's been unfairly associated with its older technologies, and doesn't receive recognition for its "modern" capabilities)?
Java is not really that old, and, being fair, it has greatly improved. It was the cool, relevant platform about 10 years ago. But since then, there have been new platforms with newer problems in mind, like Ruby on Rails. The core sector of Java has been mainly the corporate world, with different problems, so the people searching for new projects outside that has been looking for different tools.
Also, the main advantage of Java design, being multiplatform, is not as relevant today as it was before.

Is the negative stereotype of Java developers too strong? (Java is just no longer "cool")
That has also some truth in it. Java still is the language to learn "to get a job". So, if you don't care, but just want to learn something to earn money, you'll end learning a little Java and not caring ever again to improve.
Again, is a lot about perception and visibility. There are tons of great Java developers that are coding without sharing their knowledge, while there are lots of PHP developers, maybe not as good, that are writing blogs and collaborating into open source. That leads to think that the PHP developers are better than Java ones, as you have certain feedback about them.

Are applications written in other languages really faster to build, easier to maintain, and do they perform better?
I'd say that they are faster to build. The principles of languages like PHP, Python or Ruby makes them quite good for generate software that can change constantly. E.g. Dynamic typing makes easier to change an interface. In Java having a well defined interface is important, which leads to more stable (and difficult to change) interfaces.
This is very important in a new startup, which main problem is to get a product before you run out of money.
About performance, it is very very easy to misunderstood the needs and try to use magic tricks to achieve the required performance, like "Java is faster than Ruby. Period" or "MongoDB is web scale". Reality is more difficult than than.

Is Java only used by big companies who are too slow to adapt to a new language?
Definitively, having already an existing team of Java developers in the company, makes easier to keep using the same language for new projects. This is perceived as "the safe bet", specially if the core of the company is not technology.
But, anyway, Java is not ONLY used on big companies, there are still a lot of startups that uses Java for cool stuff (For example, FightMyMonster or Swrve uses Java extensively), but I'd say that the general tendency in the startup scene is to use other languages.
That is also a way of getting people, as most people will be more exciting to work with Ruby, Python or PHP, perceived as more "friendly" and "fun" languages than to work with Java.


答:
Another thing to consider is that standards organizations have limited bandwith--they can only work on so much at a time.

Given these constraints, I would rather they work on solving problems the web developers cannot solve themselves (like adding new tags or CSS animations). SASS and haml are trivial to compile down to CSS/HTML, so the advantage of native browser support would be limited, since it's so easy to do yourself.

Title: Why don't browsers support haml and sass?

Body:
The time needed to download a website would be significantly reduced, and parsing would be also easier I think.

Why are not these languages imposed as a standard? Obviously they are better than raw html and CSS...

Browsers are the only thing that keeps us away from eliminating the intermediate HTML/CSS code.


答:
sass and haml are not standards. HTML and CSS are.

If and once both become standards (and are widely accepted and used), then there will be a compelling reason for browser makers to add support for them.


答:
Who says it isn't?

Spring MVC + Spring Data JPA or Mongo + Thymeleaf for templating + coffee-maven-plugin for Coffee to JS transpiling and you're good to go.


答:
The problem with Java is that this language is learnt in school, so it's the language the most known by new programmers.
So if you want to differentiate yourself from the mass, you have to learn a new language, Java is the language of the everybody.

The second reason is that at school or in big companies when you want to build a web application, teachers or people already in place give you tons of java frameworks to help you to build this application faster. But in fact, in this way you build your web application without really understand web (HTTP, HTML, CSS, Javascript, etc...).
This trend is less visible with other languages like RoR or Python, developpers using these languages have a better understanding of the web.

So the statups who want to build modern web applications prefer to use RoR, PHP or Python to attract good web developpers, those who understand the web and not only a programming language.


问:
How do I completely-self-study Computer Science?
Being a completely self taught programmer, I would like it if I could better myself by self-learning the computer science course taught to a typical CS grad.

Finding different resources on internet has been easy, there is of course MIT open course ware, and there are Coursera courses from Stanford and other universities. There are numerous other open resources scattered around the Internet and some good books that are repeatedly recommended.

I have been learning a lot, but my study is heavily fragmented, which really bugs me. I would love If somewhere, I could find a path I should follow and a stack I should limit myself to, so that I can be sure about what essential parts of computer science I have studied, and then systematically approach those I haven't.

The problem with Wikipedia is it doesn't tell you what's essential but insists on being a complete reference.

MIT open course ware for Computer science and Electrical Engg. has a huge list of courses also not telling you what courses are essential and what optional as per person's interest/requirement. I found no mention of an order in which one should study different subjects.

What I would love is to create a list that I can follow, like this dummy one

```<code>SUBJECTS                                                        DONE

Introduction to Computer Science                                  *
Introduction to Algorithms                                        *
Discrete Mathematics
Adv. Discrete Mathematics
Data structures                                                   *
Adv. Algorithms
...
</code>```

As you can clearly see, I have little idea of what specific subjects computer science consists of.

It would be hugely helpful, even if someone pointed out essential courses from MIT Course ware ( + essential subjects not present at MIT OCW) in a recommended order of study.

I'll list the Posts I already went through (and I didn't get what I was looking for there)

https://softwareengineering.stackexchange.com/questions/49557/computer-science-curriculum-for-non-cs-major - top answer says it isn't worth studying cse

https://softwareengineering.stackexchange.com/questions/110345/how-can-a-self-taught-programmer-learn-more-about-computer-science - points to MIT OCW

https://softwareengineering.stackexchange.com/questions/49167/studying-computer-science-what-am-i-getting-myself-into

https://softwareengineering.stackexchange.com/questions/19912/overview-of-computer-science-programming

答:
Open Course ware is just a list of courses that they have made available.  If you want to know what a student would have taken, swing by MIT's(non OCW) website and look at the actual program.  They have a list of what is required and what is considered a prereq for what.
Here is their page.</p>


答:
I've seen some course material from MIT, and it was shockingly bad. They had teaching materials which required VC5, bunches of implicit global variables, passing colours as "Blue" instead of 32bit ARGB, let alone 4x [0,1] floats, that sort of thing. I wouldn't trust a curriculum or code just because it comes from a big-name university.

My CS degree (from a university which is top 10 in the UK for CS) consisted of:

First year:

OOP- the super basics

Computer Systems- stuff like, binary integer representations.

Basic relational database theory

Mathematics for CS- simple 2D and 3D geometry.

A little bit of HTML/JS- complete beginner's stuff

An equally tiny bit of PHP.

A tad of functional programming

Second year:

Legal issues in computing- stuff like, laws revolving around
protection of user data

Programming languages- Chomsky hierarchy and lexing was covered

Operating Systems, Networks, and the Internet- mostly stuff like
virtual memory and paging, IP stack

2D computer graphics- mostly just proving theorems of the underlying
mathematics

AI- basic descriptions of neural networks, Bayesian belief systems,
etc.

Requirements analysis- brief overview of UML,
functional/nonfunctional requirements.

Team project

Third year:

Algorithm analysis- complexity theory, mostly

Implementation of programming languages- LL/LR parsing techniques,
CFGs, and such things.

Software Project Management- a look at Waterfall/Agile models

International Computing- Unicode and other localization fun

Advanced AI- don't know, honestly, and I've got an exam on it soon

3D computer graphics- mostly, again, just proving theorems for
rotation matrices and such

Agent-based Systems- mostly about asynchronous agents communicating,
reaching group decisions, etc.

Microprocessor Applications- digital signal processing

Robotics- covers stuff like computer vision and robot decision
making at a high level

As you'll notice, pretty much everything is "the basics" of something and almost nothing is covered to a useful depth.

The stuff that was actually worth doing, essential:

OOP- and then some more, and then some more

Functional programming- also some more. Try to pick a language like C++ or C# where you don't have to re-learn the syntax and tools, etc, to cover both styles.

The OS part- virtual memory is good to know about, as is kernel mode vs user mode. Skip segmentation and the IP stack.

Requirements analysis- Gotta be useful for any project

Algorithm analysis- knowing what algorithmic complexity is, how to reduce it, and what the complexity is of common operations is important.

Software project management models- many shops do Agile and many older ones still do Waterfall-style models.

International computing- Unicode is essential

The stuff that was worth doing, optionally:

Programming languages- Chomsky hierarchy, the tools of lexing and parsing. Skip the theory behind LL or LR parsers- an LR parser can accept virtually any realistic unambiguous CFG, and when it can't, your parser generator's documentation will tell you about it.

3D Graphics. I don't mean "Prove this is a rotation matrix formula" wastes of time, I mean actual "This is a vertex shader" stuff, or GPGPU. That's fun, interesting, and different.

Some of the AI stuff is fun- like potential fields and pathfinding.

Stuff that's essential but I didn't cover it anyway:

Concurrency- a must-know, at least the basics, for anyone in 2012.

The rest were a complete waste of time. Unfortunately, most of these nine points I either already knew, or picked up the useful parts elsewhere. If you read about things like the FizzBuzz problem it rapidly becomes apparent that you don't actually need to know all that much to be on top of the pack- which is fortunate, since my degree and many of the materials I've seen online for other degrees really do not teach much at all.

Title: How do I completely-self-study Computer Science?

Body:
Being a completely self taught programmer, I would like it if I could better myself by self-learning the computer science course taught to a typical CS grad.

Finding different resources on internet has been easy, there is of course MIT open course ware, and there are Coursera courses from Stanford and other universities. There are numerous other open resources scattered around the Internet and some good books that are repeatedly recommended.

I have been learning a lot, but my study is heavily fragmented, which really bugs me. I would love If somewhere, I could find a path I should follow and a stack I should limit myself to, so that I can be sure about what essential parts of computer science I have studied, and then systematically approach those I haven't.

The problem with Wikipedia is it doesn't tell you what's essential but insists on being a complete reference.

MIT open course ware for Computer science and Electrical Engg. has a huge list of courses also not telling you what courses are essential and what optional as per person's interest/requirement. I found no mention of an order in which one should study different subjects.

What I would love is to create a list that I can follow, like this dummy one

```<code>SUBJECTS                                                        DONE

Introduction to Computer Science                                  *
Introduction to Algorithms                                        *
Discrete Mathematics
Adv. Discrete Mathematics
Data structures                                                   *
Adv. Algorithms
...
</code>```

As you can clearly see, I have little idea of what specific subjects computer science consists of.

It would be hugely helpful, even if someone pointed out essential courses from MIT Course ware ( + essential subjects not present at MIT OCW) in a recommended order of study.

I'll list the Posts I already went through (and I didn't get what I was looking for there)

https://softwareengineering.stackexchange.com/questions/49557/computer-science-curriculum-for-non-cs-major - top answer says it isn't worth studying cse

https://softwareengineering.stackexchange.com/questions/110345/how-can-a-self-taught-programmer-learn-more-about-computer-science - points to MIT OCW

https://softwareengineering.stackexchange.com/questions/49167/studying-computer-science-what-am-i-getting-myself-into

https://softwareengineering.stackexchange.com/questions/19912/overview-of-computer-science-programming


答:
Java is more complex to learn than PHP/Python/Ruby

Java ecosystem is very complex, very large and quite confusing to beginners

There are many historically bad frameworks with negative reputations associated with java, you have to know which frameworks to avoid wasting time on

Java build tools are way to complex (maven & ant)

Java does not have a module systems that is easy to use (OSGI is way too complex)

Java IDE such as Eclipse while very powerful with amazing features are difficult to configure for effective web development without lots of experience.

If you are using anything other than Tomcat or Jetty as a server then you will be frustrated by long startup times of WebSphere/WebLogic/JBOSS

Java EE solves problems that many people don't have such as distributed transactions

A new developer getting into professional development will find Java an Order of Magnitude harder than rails, python, or php to get going with so they go with what is easy to learn.

Having said all the above, I made the decision to use Java for my Startup because a properly configured Java Development environment is very productive to work in. By properly configured I mean.

Less than 10 seconds start-up time

Properly configured eclipse workspace, with a all frameworks wrangled up and configured

Good selection of libraries (Spring, Spring MVC, Spring Social, Spring Security, JPA, Hibernate, Velocity, .... etc)

Fast developer machines with SSDs

Orielly Safari subscription


答:
for testing the server you'll need to mock the clients (mock the input and output stream of the socket or the object that parses the input depending on what it easier)

the mocked clients are bots really that do some prearranged moves as they receive the moves of the other players (and send an error when they see something they don't expect)

for testing the client you can mock the server

Title: Test a simple multi-player (upto four players) Android game in single developer machine

Body:
I'm working on a multi-player Android game (very simple it is that it doesn't have any game-engine used). The game is based on Java Socket. Four devices will connect the game server and a new thread will manage their session. The game server will server many such sessions (having 4 players each).

What I'm worried about is the testing of this game. I know it is possible to run multiple android emulators, but my development laptop is very limited in capabilities (3 GB RAM, 2 Ghz Intel Core2Duo and on-board Graphics). And I'm already using Ubuntu to develop the game so that I have more user memory available than I'd have with Windows.

Hence, the laptop will burn-to-death on running 4 emulator instances. I don't have access to any android device, neither I have another machine with higher configuration. And I still have to develop and test this game.

P.S. : I'm a CS student, and currently don't work anywhere, and this game is college project, so if there are any paid solutions, I cannot afford it.

What can I do to test the app seamlessly? ability to test even only 4 clients (i.e. only 1 session) would suffice, its alright if I can't simulate real environment with some 10-20 active game sessions (having 4 players each).


答:
Many might associate Java and web application development with the horrors of J2EE which, bundled with monstrous J2EE application servers from big blue and red corporations, equaled weeks of work before the basic "Hello World" was online.

True, recent JEE specifications and implementations are lighter weight, but I'd still think thrice before suggesting anything like this for a short cycle rapid development project.

This is still the standards-based way of doing web application development in Java.  The alternatives, many of which are mentioned in other answers, convey a more mixed and confusing picture with too many choices to make.

Other languages portray a single turnkey solution instead of this multitude.  This makes this choice seem more fit-for-purpose when you have more important fish to fry.