问:
Recommendations for teaching junior programmers good coding style
I am a big fan of good coding style, producing clean, clear code that runs well and is easy to use and integrate into larger systems. I believe that we programmers are essentially craftspeople who should take pride in our work, every line. I am not fond of code that is inconsistently formatted, cluttered with commented out experimental code, and rife with unhelpful or misleading function and variable names. But I sometimes find it hard to argue with code like this that basically works.

If you think that coding style matters, I am looking for recommendations for ways of teaching good, professional coding style to the junior programmers under me. I want them to take pride in their work, but my concern is that they appear to become satisfied when their code just barely works, and seem to have no interest in producing what professionals like me would consider professional code. On the other hand, if you think coding style is not particularly valuable, I welcome your comments and am open to reconsidering my standards and tolerances.

I know the usual arguments in favor of good code: comprehensibility, ease of maintenance, etc., but I would also like to hear some rebuttals to arguments like "it works, what more do you want?"

In our industry we can use the compiler to hide a multitude of sins. Clean code and messy code can both lead to identically functioning programs, so does cleanliness matter, and if so, why?

[While there are several existing questions on coding style, I didn't find any that related to teaching methods and ways to instill good coding style in junior programmers.]

答:
Talk them about D. Knuth's literate programming.

I believe that the time is ripe for significantly better documentation of programs, and that we can best achieve this by considering programs to be works of literature. Hence, my title: "Literate Programming."

Let us change our traditional attitude to the construction of programs: Instead of imagining that our main task is to instruct a computer what to do, let us concentrate rather on explaining to human beings what we want a computer to do

Donald Knuth, about literate programming.

In my humble opinion, the fact that a computer program's primary goal is to communicate intellectual entities to other programmers, is a decisive argument for the importance of coding style.


问:
Thoughts on web development architecture through integrating C++ in the future to a web application
I'm looking to build a website (it's actually going to be a commercial startup) I saw this question and it really shed some light on a few things that I was hoping to understand (kudos to the op). After seeing that, it would make sense that, unless the website were required to actually have millions of hits per day, it wouldn't be a viable solution to write a C++ backend on the server side.

But this got me thinking.

what if it in the (unlikely) events of the future, it does go that route? The problem is that, while I'm thinking of starting this all using .Net (in the beginning) just to get something quick and easy up without a lot of hassle (in terms of learning), and then moving towards something more Open Source (such as Python/Django or RoR) later to save money and to support OSS, I'm wondering IFF the website actually becomes big, will it be a good idea to integrate a C++ backend, and use Python ontop of C++ for a strong foundation, and then mitigate HTML/CSS/AJAX/etc ontop of the backend's foundation? I guess, what I'd like to know is that, given the circumstance, if this were to happen, would it be a proper approach in terms of architecture? I'd definitely be supporting MVC as that seems to be a great way to implement a website.

All in all, would one consider this rational, or are there other alternatives? I like .Net, and I'd like to use it in the beginning, because I have much more experience with that than, say, Python or PHP, and I prefer it in general, but I really do want to support OSS in the future. I suppose the sentence I'm looking for is, "is this pragmatic?"

答:
You might as well ask Facebook, they had the same issue you do - they started with PHP thinking they could do a site quickly and easily, but when it got big they had to do something to manage the scalability problems.

If you learn from their example, you should go straight to the C++ version from day 1 and save yourself the hassle of rewriting it all. However, that assumes you will need to, many sites work acceptably with perl or PHP code.

Writing web code is quite straightforward, you only need to grab the request, process it and generate some HTML code to return. The frameworks that other languages provide just make manipulating the standard XML (but don't forget JSON) and HTTP protocol bits easier - and there are several C++ frameworks or libraries that give you these features, so the problem just becomes one of integrating them into your code.

The best thing you can do is to split your code away from the webserver, when I worked for a company that had a very large website-based system, we wrote all our business logic code in services that ran on application servers, the web server and associated code was pretty much there to server static data (images and css) and to pass the requests to the services. This let us scale tremendously. IMHO webservers should be considered part of the presentation layer, not somewhere to stick your business logic. This especially applies if you need stronger security as webservers are notoriously bad at being un-hackable.

ContentLicense: CC BY-SA 3.0


问:
Web application - database design/infrastructure
I have just begun development of a web application (that will be deployed using Google app engine), without going into the specifics, the web app will allow users to deploy a small website of their own, part of app allows the users to create a form to allow customers to sign up to the users website, however each user may require to collect different data on its customers, for example one user may require a customer’s first name and email address only where as another may also require the customers age.

My question is what would be the best way to structure the database(s)?

By structure the database(s) I mean how can I implement them so that I can store the different data collection sets for each user and then store the information that is retrieved by each of these users from their customers? For example I don’t think this is right but my initial though was that I would have to deploy a database for each of the users but this seems like overkill, or add a new table for each of the users (I don’t even know if these two are options). I have only had experience with trivial databases and this problem has me confused.

答:
That part of your application is not very "relational". You would need to implement a key-value schema such as:

```<code>users
  user_id         pk

attributes
  attribute_id    pk

user_attributes
  user_id         references users(user_id)
  attribute_id    references attributes(attribute_id)
</code>```

or something like PostgresSQL's hstore. This would let keep you all of your data within a relational database if it suits the rest of your application; you will have to judge how "relationalish" is your entire application.

Body:
That part of your application is not very "relational". You would need to implement a key-value schema such as:

users
  user_id         pk

attributes
  attribute_id    pk

user_attributes
  user_id         references users(user_id)
  attribute_id    references attributes(attribute_id)

or something like PostgresSQL's hstore. This would let keep you all of your data within a relational database if it suits the rest of your application; you will have to judge how "relationalish" is your entire application.


问:
What makes a hashing algorithm "secure"?
After reading this interesting question, I felt like I had a good idea of which insecure hashing algorithm I'd use if I needed one, but no idea why I might use a secure algorithm instead.

So what is the distinction?  Isn't the output just a random number representing the hashed thing?  What makes some hashing algorithms secure?

答:
A "secure" hash is a hash that is believed to be difficult to "spoof" in a formulaic, reproducible way without prior knowledge of the message used to create the hash. As that information is generally secret, hence the need for a hash, this is a good property of a hashing function intended for use in authentication.

A hash is generally considered "secure" if, given a message M, a hash function hash(), and a hash value H produced by hash(M) with a length in bits L, none of the following can be performed in less than O(2L) time:

Given hash() and H, produce M. (preimage resistance)

Given hash() and M, produce a different M2 such that hash(M2) == H. (weak collision resistance)

Given hash(), produce any M1 and M2 such that hash(M1) == hash(M2). (strong collision resistance)

Additionally, a "secure" hash must have a hash length L such that 2L is not a feasible number of steps for a computer to perform given current hardware. A 32-bit integer hash can only have 2.1 billion values; while a preimage attack (finding a message that produces a specific hash H) would take a while, it's not infeasible for many computers, especially those in the hands of government agencies chartered with code-breaking. In addition, an algorithm that creates and stores random messages and their hashes would, according to probability, have a 50% shot at finding a duplicate hash with each new message after trying only 77,000 messages, and would have a 75% chance to hit a duplicate after only 110,000. Even 64-bit hashes still have a 50% chance to collide after trying only about 5 billion values. Such is the power of the birthday attack on small hashes. By contrast, a computer looking for collisions in a 256-bit hash (SHA-256) wouldn't even have a one-in-a-billion chance for the next message it tried to collide until it had tried 15 decillion numbers (1.5*1034).

Most demonstrated attacks on cryptographic hashes have been collision attacks, and have demonstrated the ability to generate colliding messages in less than 2L time (most have still been exponential-time, but reducing the exponent by half is a significant reduction in complexity as it makes a 256-bit hash as easy to solve as a 128-bit, a 128-bit as easy to solve as a 64-bit, etc).

In addition to small hash size, other factors that can make a hash demonstrably insecure are:

Low work - a hash designed for use by a hashtable or for other "checksum"-type purposes are usually designed to be computationally inexpensive. That makes a brute-force attack that much easier.

"Sticky State" - The hashing function is prone to patterns of input where the current hashed value of all inputs so far does not change when given a particular additional byte of input. Having "sticky state" makes collisions easy to find, because once you identify a message that produces a "sticky state" hash it is trivial to generate other messages that have the same hash by appending input bytes that keep the hash in its "sticky state".

Diffusion - Each input byte of the message should be distributed among the bytes of the hash value in an equally-complex way. Certain hash functions create predictable changes to certain bits in the hash. This again makes collision creation trivial; given a message that produces a hash, collisions can be easily created by introducing new values to the message that only affect the bits that change predictably.


问:
Merge sort versus quick sort performance
I have implemented merge sort and quick sort using C (GCC 4.4.3 on Ubuntu 10.04 running on a 4 GB RAM laptop with an Intel DUO CPU at 2GHz) and I wanted to compare the performance of the two algorithms.

The prototypes of the sorting functions are:

```<code>void merge_sort(const char **lines, int start, int end);

void quick_sort(const char **lines, int start, int end);
</code>```

i.e. both take an array of pointers to strings and sort the elements with index i : start <= i <= end.

I have produced some files containing random strings with length on average 4.5 characters. The test files range from 100 lines to 10000000 lines.

I was a bit surprised by the results because, even though I know that merge sort has complexity O(n log(n)) while quick sort is O(n^2), I have often read that on average quick sort should be as fast as merge sort. However, my results are the following.

Up to 10000 strings, both algorithms perform equally well. For 10000 strings, both require about 0.007 seconds.

For 100000 strings, merge sort is slightly faster with 0.095 s against 0.121 s.

For 1000000 strings merge sort takes 1.287 s against 5.233 s of quick sort.

For 5000000 strings merge sort takes 7.582 s against 118.240 s of quick sort.

For 10000000 strings merge sort takes 16.305 s against 1202.918 s of quick sort.

So my question is: are my results as expected, meaning that quick sort is comparable in speed to merge sort for small inputs but, as the size of the input data grows, the fact that its complexity is quadratic will become evident?

Here is a sketch of what I did.
In the merge sort implementation, the partitioning consists in calling merge sort recursively, i.e.

```<code>merge_sort(lines, start, (start + end) / 2);
merge_sort(lines, 1 + (start + end) / 2, end);
</code>```

Merging of the two sorted sub-array is performed by reading the data from the array lines and writing it to a global temporary array of pointers (this global array is allocate only once). After each merge the pointers are copied back to the original array. So the strings are stored once but I need twice as much memory for the pointers.

For quick sort, the partition function chooses the last element of the array to sort as the pivot and scans the previous elements in one loop. After it has produced a partition of the type

```<code>start ... {elements <= pivot} ... pivotIndex ... {elements > pivot} ... end
</code>```

it calls itself recursively:

```<code>quick_sort(lines, start,          pivotIndex - 1);
quick_sort(lines, pivotIndex + 1, end);
</code>```

Note that this quick sort implementation sorts the array in-place and does not require additional memory, therefore it is more memory efficient than the merge sort implementation.

So my question is: is there a better way to implement quick sort that is worthwhile trying out? If I improve the quick sort implementation and
perform more tests on different data sets (computing the average of the running times on different data sets) can I expect a better performance
of quick sort wrt merge sort?

EDIT

Thank you for your answers.

My implementation is in-place and is based on the pseudo-code I have found
on wikipedia in Section In-place version:

```<code>function partition(array, 'left', 'right', 'pivotIndex')
</code>```

where I choose the last element in the range to be sorted as a pivot, i.e. pivotIndex := right.
I have checked the code over and over again and it seems correct to me.
In order to rule out the case that I am using the wrong implementation
I have uploaded the source code on github (in case you would like
to take a look at it).

Your answers seem to suggest that I am using the wrong test data. I will look into it and try out different test data sets. I will report as soon as I have some results.

答:
I will agree with Michael; Quicksort is difficult to implement correctly. Back when I was in college writing my final exam (a comparison of sorting algorithms) my QuickSort implementation managed to blue-screen a Windows NT computer (it didn't cause a GPF; it BSODed).

The biggest problem I generally encounter when quicksorting is pivot selection. Remember that QuickSort's Achilles' heel is pretty common; a near-sorted list. For that reason, proper pivot selection is crucial despite the extra complexity. Even something so simple as picking the middle element of the subarray is generally better than picking at either end; for the two most common cases of a near-sorted list and a truly random list, this will generally produce a good result. Median-of-3 is even better.

Another thing to check is that you have an intelligent "base case". A partition of 2 elements can be sorted trivially (are they in order? if not, swap em), so pivoting a 2-element array in order to reach the base case of zero or one elements is wasteful.

One more thing is to ensure your algorithm is "in-place" (a major advantage of the "intuitive" QuickSort over the "intuitive" MergeSort; allocating memory is expensive), and that you aren't trying to keep the pivot in between the two halves while you're pivoting. Choose your pivot, swap it with the last element, then work in from the left looking for a "big" element, and then from the right looking for a "small" element; swap and continue until a "big" value is found without a "small" value on its right to swap it with (swap it with the pivot at the last element and recurse). This prevents unneeded swapping to keep the pivot in the "middle" of the two halves.


答:
Update: also check this question: Are C and/or C++ viable/practical options for web development?

I think it is pragmatic to use C++ for projects that will have an impact on both energy and necessary infrastructure necessary, as it might reduce both a lot (check for Hip Hop from Faccebook:http://developers.facebook.com/blog/post/2010/02/02/hiphop-for-php--move-fast/ they reduced their server use by half just by converting PHP to C++).

I think it depends on your main bottleneck for the project: is it developer productivity OR application efficiency? If it's the second then you can use C++, as suggested by CPPCMS:

When CppCMS Should Be Used.

C++ language is far from being popular for Web development for many
  reasons: lack of appropriate tools, skills of developers and many
  more.

However, there are areas where C++ web programming with CppCMS becomes
  very useful and efficient, and some where it is just a waste of time.

When CppCMS should or can be used?

High load web sites and application with hundreds and thousands hits
  per second, where high performance, efficiency and scalability is
  required. Application that require scalable Comet/Server Push(1)
  technologies --- CppCMS can efficiently handle hundreds and thousands
  simultaneous HTTP connection with minimal resources usage. Embedding
  web interface(2) into existing C++ applications/services with a small
  cost of additional library. Embedded underpowered devices -- CppCMS
  allows creation of rich applications with relatively low cost of
  hardware that would perform reasonably fast. When Not To Use?

If you create small web applications that do not require high loads
  and require very short time-to-market period -- probably tools like
  Django or RoR would be more appropriate for such tasks.

(1) Available in upcoming CppCMS 1.x.
  (2) Current version of CppCMS (0.0.x)
  can be used for embedding web interface to existing applications, but
  the next version 1.x would support it much better.

If C++ (or like) language were used for all websites, internet would be faster, more responsive, lower cost on energy and memory. But realistically, not all web project have efficiency as the main bottleneck to prioritize the work on. That said, it might help our planet to heat less if we tried to go this way...

Title: Thoughts on web development architecture through integrating C++ in the future to a web application

Body:
I'm looking to build a website (it's actually going to be a commercial startup) I saw this question and it really shed some light on a few things that I was hoping to understand (kudos to the op). After seeing that, it would make sense that, unless the website were required to actually have millions of hits per day, it wouldn't be a viable solution to write a C++ backend on the server side.

But this got me thinking.

what if it in the (unlikely) events of the future, it does go that route? The problem is that, while I'm thinking of starting this all using .Net (in the beginning) just to get something quick and easy up without a lot of hassle (in terms of learning), and then moving towards something more Open Source (such as Python/Django or RoR) later to save money and to support OSS, I'm wondering IFF the website actually becomes big, will it be a good idea to integrate a C++ backend, and use Python ontop of C++ for a strong foundation, and then mitigate HTML/CSS/AJAX/etc ontop of the backend's foundation? I guess, what I'd like to know is that, given the circumstance, if this were to happen, would it be a proper approach in terms of architecture? I'd definitely be supporting MVC as that seems to be a great way to implement a website.

All in all, would one consider this rational, or are there other alternatives? I like .Net, and I'd like to use it in the beginning, because I have much more experience with that than, say, Python or PHP, and I prefer it in general, but I really do want to support OSS in the future. I suppose the sentence I'm looking for is, "is this pragmatic?"


问:
Designing complex query builders in java/jpa/hibernate
I need to build complex sql queries programatically, based on large filter conditions.

For example, below are few sample/hypothitical filter conditions, based on which i need to fetch users

Country: india

States: Andhra Pradesh(AP), Gujarat(GUJ), karnataka(KTK)

Districts: All districts in AP except 3 district, 5 any districts from GUJ, all district from KTK except 1 district

Cities: All cities in AP, all cities except few, include only 50 specific cities from KTK

Villages: similar conditions like above with varies combinations...

Currently, we have a query builder, which is very complex in nature, and not easy to modify/re-factory for improvements. So, thinking of complete re-design of it.

Any suggesations on how to build this kind of complex query builders programmatically using some best practices/deisgn patterns?

答:
With torpedoquery your query could look like this

```<code> public List<User> findUsers() {
    User from = from(User.class);
    City city = innerJoin(from.getCity());
    with(city.getCode()).in("one", "two").or(city.getCode()).notIn("three", "four");
    District district = innerJoin(city.getDistrict());
    with(district.getCode()).notIn("exclude1", "exclude2");
    State state = innerJoin(district.getState());
    with(state.getCode()).eq("AP").or(state.getCode()).eq("GUJ").or(state.getCode()).eq("KTK");
    with(state.getCountry().getCode()).eq("india");

    return select(from).list(manager);
}
</code>```

I push on github the example if you want to take a look https://github.com/xjodoin/torpedoquery/tree/master/src/test/java/org/torpedoquery/jpa/examples

Body:
With torpedoquery your query could look like this

 public List<User> findUsers() {
    User from = from(User.class);
    City city = innerJoin(from.getCity());
    with(city.getCode()).in("one", "two").or(city.getCode()).notIn("three", "four");
    District district = innerJoin(city.getDistrict());
    with(district.getCode()).notIn("exclude1", "exclude2");
    State state = innerJoin(district.getState());
    with(state.getCode()).eq("AP").or(state.getCode()).eq("GUJ").or(state.getCode()).eq("KTK");
    with(state.getCountry().getCode()).eq("india");

    return select(from).list(manager);
}

I push on github the example if you want to take a look https://github.com/xjodoin/torpedoquery/tree/master/src/test/java/org/torpedoquery/jpa/examples


答:
Stackoverflow itself is a pure C#/.net site and it doesn't seem to do too badly.

While facebook may have decided to re-write some critical parts in C++ after it made its first billion. Had they started out writing in C++ I think don't think they would have got that first billion.

The LAMP stack (and .NET) allows you to develop stuff quickly, which gives you the freedom to try out new ideas, and, to quikly discard old ideas that didnt quite work out.

The whole point of facebook was the user experience. While you are messing about with memory allocations for string classes you will not be thinking about appearence and usability.


问:
Any recognized convention for repository changelogs?
We use TortoiseSVN, but we have no bug tracking system. I know, lame, but beyond my control.

There were times when svn wasn't in daily use.
Now I've had succeeded in pressing for using it regularly, with proper merging, branching, tagging etc.

As you could expect,  the number of revisions increased in result, which makes browsing repository log a bit troublesome now.

I thought about utilizing some convention based on keywords ("[bugfix]", "[feature]", "[refactored]", "[minor]", "[merged-from-trunk]"... :) so as to make it more searchable.

It feels like reinventing the wheel, though. Is there any established convention for that?
Or is my approach wrong from the beginning? Any better, alternative solution?

答:
When we're doing stuff that refers to external problem reports (eg, via RT or whatever) we often end up with the string "fixes RT#12345" or similar if it's a bugfix.

For everything else, we often end up using Trac (which integrates nicely with an SVN repository) and provides roadmaps, wikis (for documentation etc), a bug tracking system, and a syntax/diff highlighted revision browser/search facility.

One thing this does is integrate a type of Wiki formatting with changeset revisions, including (most importantly and relevantly here) applying wiki formatting to the bare text of the changeset log. As a result, you can put wiki formatting in the commit message and have it do things like link to the correct branch revisions you're merging, or linking to the bug tracking systems actual bug report.

Eg, if there's a bug in the trac system that a revision changes we say "fixes #124" and when you browse that changeset via trac it will actually turn "#124" into a link to bug #124. Similarly if we say "merges [37:54/branches/featurex]" it turns it into a link to the source browser for /branches/featurex showing changesets between revision 37 and revision 54, with the option to select first and last and just show all changes between start and end revisions.

There's more info on the kind of internal links you can make in checkins here:

http://trac.edgewall.org/wiki/TracLinks

Hope that helps!


问:
How can I do test automation using a python script to test a c program?
I was wondering if I can use a Python script to test a C program automatically.

Suppose I have a very simple C program which reads data (numbers as test cases) from the console, calculates them, then outputs it to the console. Now I want to read data from a file then output whatever the program outputs into a file.

Suppose in the original C program I use while loop andscanf to read two numbers into two variables a and b for several times and do different calculations according to the values of a and b, like this:

```<code>if(a>4 && a<10){...}
else if(a>=10){...}
</code>```

Now can I use a Python script to test the program automatically? And do I need to modify my C program? How?

EDIT: If any method is permitted, then what is the best way to test the C program automatically without using frameworks?

答:
might be a bit off topic but you could try looking up the ctypes library in python, it's a means of python interacting with c/c++ programs to call routines in headers, dlls etc..

I use it mainly for programming windows applications in python using the windows api, hope it helps !!

Here's the link:

Python documentation


问:
Diving into microcontroller programming
I just got a batch of LED matrix modules from Sure Electronics (http://www.sureelectronics.net/goods.php?id=1120) and a driver board (http://www.sureelectronics.net/goods.php?id=972).

I've got it wired up, and connected to my Mac. I found the right drivers, and I'm now able to send text to the displays using the virtual COM port, as per the documentation from Sure Electronic's website:

```<code>start with "0xFE,0x47 (G) 0x01,0x01" followed by 16 characters - display the 16 characters in the first row
start with "0xFE,0x47 (G) 0x01,0x02" followed by 16 characters - display the 16 characters in the second row
</code>```

The plan is to hook it all up to a Raspberry Pi (when I eventually get one) and use it all to display information from a web service.

However, this setup is not optimal. The driver board requires some initialization each time it is powered up, in order to be available via USB. Also, I'd like more control over the display of characters (this setup, for instance, does not support non-ASCII characters, or text scrolling).

Heavy googling has led me to believe that I need to go deeper into the HT1632 chip on the driver board. The documentation from Sure Electronics is sparse.

The goal would be to be able to address each LED pixel individually from my code running on my computer (as in a 2D array of booleans, for example).

I'm totally new to micro programming, so I have no idea where to start.
What do I need to do in order to program it? Can I even modify the code of the driver board, or do I need another kind of driver board? And how do I automate the boot up sequence, so that the board is automatically USB enabled?

Also, I'm mostly a Java/Web developer guy, so I would like to avoid as much C programming as possible.

If anyone with experience with this kind of programming could point me in the right direction to start, I would be grateful.

答:
Most microcontrollers can be programmed but you'll need to do things like set their reset pins to a higher voltage to put them into "programming mode", or in some other way signal them to do that. A brief look at the hardware you purchased indicates the micro is integrated into the board, so unless they support reprogramming of the controller they're using, you'd have to remove it from the board, hook it up to a programmer board, and then use whatever software comes with the programmer board to backup, modify, whatever the code on the controller.

I can't tell based on the small look I had at it which options are going to be available in this case, but that at least lets you know how it all hooks in in general.

Ultimately though, if you're a Java guy you're probably not going to enjoy micro programming - it's a totally different ballgame. You're also going to have to spend significant time in at least variants of C (and possibly occasional jumps to Assembly for things like control registers etc), because most hobby micros do not have nearly enough memory in general or powerful enough processors to run anything approaching the complexity of Java.

Title: Diving into microcontroller programming


问:
Combining source files, like header files
I have a project where my files have gotten out of hand because of the volume of them. I have started to combine classes of similar types in single header files because you can, and it still is good practice, now can i do the them same for those classes functions, that are declared in the source files.

Is it a good idea to combine several classes functions in a single source file, if the classes are say all sub classes of the same super class?

答:
It is not bad practice to do so, just make sure that if the user only want a part of the system, he can include only one header and get the necessary bits. Having several definitions of class and other things in one header is fine and can even help compilation time if well done. If not well done, it can kill the build time in a bad way. So, just make sure each header gather elements that cannot be separated and that represent one (sub)module.

Look at readable C++ standard library implementation (most are not, depends on the provider) and/or better, look at boost code as good examples of this practice.


答:
Also, I'm mostly a Java/Web developer guy, so I would like to avoid as
  much C programming as possible.

You're going to have to learn to live with C if you wish to do much of anything with microcontrollers, at least have a passing knowledge anyway. Most code you'll see for microcontrollers is written in C. Even if you don't want to write it, you'll at least need to be able to read it.

Also, http://arduino.cc/playground/Main/HT1632C indicates how to set a font for that board and such. I'm sure it's possible to control individual pixels, but if you're planning on circumventing using their font support on their board and instead draw each letter by toggling pixels, your display is going to update very slowly...

Title: Diving into microcontroller programming

Body:
I just got a batch of LED matrix modules from Sure Electronics (http://www.sureelectronics.net/goods.php?id=1120) and a driver board (http://www.sureelectronics.net/goods.php?id=972).

I've got it wired up, and connected to my Mac. I found the right drivers, and I'm now able to send text to the displays using the virtual COM port, as per the documentation from Sure Electronic's website:

```<code>start with "0xFE,0x47 (G) 0x01,0x01" followed by 16 characters - display the 16 characters in the first row
start with "0xFE,0x47 (G) 0x01,0x02" followed by 16 characters - display the 16 characters in the second row
</code>```

The plan is to hook it all up to a Raspberry Pi (when I eventually get one) and use it all to display information from a web service.

However, this setup is not optimal. The driver board requires some initialization each time it is powered up, in order to be available via USB. Also, I'd like more control over the display of characters (this setup, for instance, does not support non-ASCII characters, or text scrolling).

Heavy googling has led me to believe that I need to go deeper into the HT1632 chip on the driver board. The documentation from Sure Electronics is sparse.

The goal would be to be able to address each LED pixel individually from my code running on my computer (as in a 2D array of booleans, for example).

I'm totally new to micro programming, so I have no idea where to start.
What do I need to do in order to program it? Can I even modify the code of the driver board, or do I need another kind of driver board? And how do I automate the boot up sequence, so that the board is automatically USB enabled?

Also, I'm mostly a Java/Web developer guy, so I would like to avoid as much C programming as possible.

If anyone with experience with this kind of programming could point me in the right direction to start, I would be grateful.


答:
I think it would be great way to train the new programmers with the techique of Naming Conventions [ it is the standard for naming a variable, method or class]. For better following flow of programmers who touch the code will be easily handle such with knowing the relevant names used.

For eg: static Variables starts with s,
        argument Variables starts with a, etc.,

Title: Recommendations for teaching junior programmers good coding style

Body:
I am a big fan of good coding style, producing clean, clear code that runs well and is easy to use and integrate into larger systems. I believe that we programmers are essentially craftspeople who should take pride in our work, every line. I am not fond of code that is inconsistently formatted, cluttered with commented out experimental code, and rife with unhelpful or misleading function and variable names. But I sometimes find it hard to argue with code like this that basically works.

If you think that coding style matters, I am looking for recommendations for ways of teaching good, professional coding style to the junior programmers under me. I want them to take pride in their work, but my concern is that they appear to become satisfied when their code just barely works, and seem to have no interest in producing what professionals like me would consider professional code. On the other hand, if you think coding style is not particularly valuable, I welcome your comments and am open to reconsidering my standards and tolerances.

I know the usual arguments in favor of good code: comprehensibility, ease of maintenance, etc., but I would also like to hear some rebuttals to arguments like "it works, what more do you want?"

In our industry we can use the compiler to hide a multitude of sins. Clean code and messy code can both lead to identically functioning programs, so does cleanliness matter, and if so, why?

[While there are several existing questions on coding style, I didn't find any that related to teaching methods and ways to instill good coding style in junior programmers.]


问:
Approach to module development and testing
I have read somewhere that the cost of resolving bugs increases if it is not resolved at the initial stage. Which approach should I take while creating programs?

Divide program development in modules. Complete coding one module. Fix ALL bugs of that module before starting coding other modules.

Divide program development in modules. Complete coding all modules. Then start fixing bugs in the whole program.

Which of these approaches is better, and why?

答:
Managing bug resolution really needs to be handled on a case by case basis, and scheduled according to both business needs and the nature of the bug itself.

With that said, if you identify a bug while you are working on some code, and if the bug will affect your ability to continue implementing a feature, then it is probably better handled relatively quickly, and therefore scheduled as a priority.  If however the bug is found but not directly affecting the feature you are implementing, then you need to log it, and at a minimum do a little debugging to determine the extent and severity of the bug found, then schedule accordingly, either at the end of an iteration, or at the tail end of a project, or even as a part of post-release maintenance if the bug isn't very likely to appear, or is not very severe in nature.

Ideally, we would all be writing software without bugs.  The nearest we can get to this ideal however, is to write software in a way that ensures we minimise the opportunities for bugs to appear.  This is where following ideals, such as SOLID, Clean Code, Behavior/Test driven development, YAGNI, Refactoring, and all of those other lovely little buzz-words we're so addicted to can be of great benefit.  In particular, the key is to keep our designs and code things simple, lean, and a clean as possible, and with a high degree of test coverage. Essentially heading the problem off early in order to avoid the bugs getting out of control early.

Of course, you'll never really overcome those bugs that come about as a result of poorly understood requirements, and imperfect logic, but with a good methodical approach to developing robust software from the outset, you'll effectively reduce the amount of bug hunting you'll likely need to do later.


答:
Its depends on your requirement of project.If your project contain module those are pretty much independent then you can divide your project in module and then test by them as unit, fix bug.Finally integrate all module

But second case, If module are highly related and they have strong communication among them.Then we can not test a module independently .So you should code first and test as much as possible functionality you can test.Then go for complete testing after integration and fix bug.

In second case it increase overhead on a developer.

Title: Approach to module development and testing

Body:
I have read somewhere that the cost of resolving bugs increases if it is not resolved at the initial stage. Which approach should I take while creating programs?

Divide program development in modules. Complete coding one module. Fix ALL bugs of that module before starting coding other modules.

Divide program development in modules. Complete coding all modules. Then start fixing bugs in the whole program.

Which of these approaches is better, and why?


答:
There are generally two problems in delaying bug fixing: 1) You don't know how long it will take to fix them; 2) Other parts of the code that depends on the buggy part will either be buggy as well or work fine until the bug is fixed (and later become buggy).

For the first problem, it's important that you keep track and prioritize bugs, since in practice is hard to fix every single small thing you come across right on the spot (especially if you're in a deadline). If a bug must be fixed before a particular release, then fix it as early as possible, so you can better manage your schedule (eliminating the imprecise task, the more precise ones will get easier to manage).

The second problem, however, is very significant: unless your design is particularly clear (so you can keep track on which parts of your program depends on which other parts) delaying bug fixes will likely introduce many more problems, and it gets worse the more time it passes. For this reason, developing modules that depend on it before fixing its bugs is more often than not a recipe for trouble.

So, my answer to your question is: you don't necessarily need to fix all bugs in a module before proceeding to the next, but if module B depends on buggy module A, fix all known bugs in A before starting coding module B.


答:
What you've read somewhere is very true. When working on software you want to minimize all your feedback loops (this is the main principle behind agile/lean development). The sooner you find out that a correction is needed, the easier (effort, risk...) it will be to make that correction.

So if I had to choose between the two approaches you listed, I would go with (1), develop/test module at a time because the other approach has the largest feedback loop that you could possibly have. Writing entire program and only then testing it is asking for disaster.

However, I want to point out few more things to you:

It seems you are assuming that "a bug" is a coding error. And yes, coding errors are bugs, but when building software you also need to be aware of other bug types:

design bugs - your code works as intended but your design doesn't work. Maybe it's too complex, maybe it fails to properly address the requirements.

requirements bugs - your code works as intended and as designed but your understanding of what the user needs isn't correct. Sometimes that user is you.  It can happen that you'll picture how you want your app to look and behave. Then you create a UI for it and discover that your original plan was completely inadequate because it fails to solve (or solve elegantly) whatever problem your program is meant to do.

Neither one of your approaches is good for finding these other types of bugs. And just like coding bugs are cheapest to fix as soon as you write them, requirements and design bugs are also cheapest to fix as soon as you decide on strategy and before you write too much code. After your program is mostly done, design bugs become way more expensive than coding bugs. And requirements bugs often mean you need to completely rewrite a chunk of your program.

In other words, picture that your program consists of a few modules. You write and test the first module and everything looks good. Then you write and test second and third module and things still look good. Then you go to put them together only to discover that module A's design isn't really adequate in order to integrate efficiently with module B. So now you are back, redesigning, coding and retesting module A, which you though was already done. Time will be wasted.

Better approach would be to come up with high level architecture (general module layout) for your program. Maybe you have a UI, some business logic, some communications modules and data storage.  Write a bare minimum (essentially just a skeleton code) in ALL modules and then test the whole program. Even if all it does is start up and shutdown without any useful work.  Make sure start up works. Then add one feature to the program. This feature will likely span many/all of your modules. Test to make sure the feature works. Continue doing this until your program is done.

This way you will not spend too much time in module A before understanding how the whole program comes together. You will also be able to see live UI and you will be able to interact with it, so if something needs to change you'll be able to make adjustments before too much other code is written.


答:
```<code>I have started to combine classes of similar types in single header files..
</code>```

It is good approach to implement library, but If it is your implementing client does not require the another extra classes for implementation. for example your header file contain 1 million lines of code after integrating similar type of classed then it took a long time to build.

As per my experience with library design and the standards that i follow in Microsoft technology  Library Design Guidelines. In case of .Net platform it does not matter much, but In case of c++ that i got on the apple development Dynamic Library Design Guidelines is that library should maintain these following factor of implementation.

Focused

Easy to use

Easy to maintain

Try to make your header files smaller and concise so that it will be easy to understand and increase the compile time. Sometime i prefer to have single class in single file, some experts suggest to follow this approach. You can combine classes those are much coupled to each other in single file.

Ref:

Multiple classes in a header file vs. a single header file per class

Google C++ Style Guide

Title: Combining source files, like header files

Body:
I have a project where my files have gotten out of hand because of the volume of them. I have started to combine classes of similar types in single header files because you can, and it still is good practice, now can i do the them same for those classes functions, that are declared in the source files.

Is it a good idea to combine several classes functions in a single source file, if the classes are say all sub classes of the same super class?

Body:
I have started to combine classes of similar types in single header files..

It is good approach to implement library, but If it is your implementing client does not require the another extra classes for implementation. for example your header file contain 1 million lines of code after integrating similar type of classed then it took a long time to build.

As per my experience with library design and the standards that i follow in Microsoft technology  Library Design Guidelines. In case of .Net platform it does not matter much, but In case of c++ that i got on the apple development Dynamic Library Design Guidelines is that library should maintain these following factor of implementation.

Focused

Easy to use

Easy to maintain

Try to make your header files smaller and concise so that it will be easy to understand and increase the compile time. Sometime i prefer to have single class in single file, some experts suggest to follow this approach. You can combine classes those are much coupled to each other in single file.

Ref:

Multiple classes in a header file vs. a single header file per class

Google C++ Style Guide


问:
Can Agile/Scrum be used by 1 or 2 developers?
Everything I've been reading and researching up to this point describes how Agile/Scrum works great with teams of about 4 to 6 members, maybe even more.

In my current shop, we have about 8 developers or so, but given the nature of the volume of projects and the number of departments we support, we never have more than 1 or 2 folks assigned to a given project.

Can I still use Agile/Scrum with a team of 1 or 2 developers? I'm working on making the pitch to my manager to start working with this methodology, but I need to be able to explain how to scale things back for a small developer crew, or convince them to make sure we get more members on a given project.

答:
Looking at it another way:

Why don't you consider all 8 developers members of the same Scrum team? That way you get the crosstalk effect between projects. Maybe you don't even have to commit people to specific projects??

When more people are added to your shop, you can possibly divide the team into two smaller ones.

OwnerDisplayName: Dillie-O

ContentLicense: CC BY-SA 2.5


答:
No, because it's more effective to scale horizontally than vertically

Meaning, it's better to design an architecture where you can spread requests across a number of less powerful machines; as opposed to, building one super powerful machine running code that has been optimized at a lower level.

The drive behind horizontal scaling is due to the 'nature' of the web. Websites are very IO heavy not compute heavy. There are exceptions, such as YouTube where they're encoding massive amounts of data but that can be dealt with by setting up compute nodes and an effective task management system.

For instance, You could implement a reverse-proxy server that does nothing but distributes incoming requests to other servers to fetch content. It doesn't matter where the data is returned from as long as there is a common origin for requests (and even that can be extended using advanced DNS).

At the very minimum, it's common to split the 'data layer' (ex database) from the 'web layer' (http server). Even StackOverflow has a clear separation between the two by implementing C# on the 'web layer' and a separate REST API (also C#?) to access the database.

Even when you need to tap into the raw computing power of C, many 'glue languages' like python have the built-in capability to implement C/C++ extensions.

There are a lot of ground-breaking being made in the field of scalability and fortunately, the people who are breaking new ground like to share the specifics their approach.

Basically, it comes down to:

Architecture trumps raw computing power when it comes to the web

HighScalibility.com is my favorite site to read about scalable architecture development but there are plenty more to be found on the web.

Aside:

One of the greatest bottlenecks to handling web requests is the architecture of the HTTP server. Traditional servers like Apache fork a sub-process for every request. It works but every sub-process that's added to the stack needs it's own pool of memory and will inevitably increase the overall task-switching overhead on the server.

A DDOS attack is directed to take advantage of this weakness by overloading the HTTP server to the point where it can't physically handle the load any longer and crashes.

Multi-threading has been introduced as a stopgap measure but writing 'good' multi-threaded software is hard to write and multi-threaded bugs are notoriously hard to pinpoint.

Another 'school of thought' that has become popular recently is event-driven webservers like Node.js and nginx. They rely on a simpler single-threaded model and a programming style that mitigates waiting on a function returns by implementing a fire-and-forget model. It's more difficult to program in such a manner but as long as heavy compute tasks are passed on to servers specialized for it, the numbers (ie hits/sec) they can handle (on even commodity hardware) are impressive.


问:
Developing android on android
Is there currently a way of developing android apps on an android phone? In other words, write, compile, install and run regular android java on the phone without using a pc? If not, what would make it possible, if at all? (would rooting be necessary? Or an android emulator compiled for android?)</p>

答:
It is possible with AIDE, haven't tried it personally though.

https://play.google.com/store/apps/details?id=com.aide.ui

Title: Developing android on android


答:
Android-IDE (AIDE) is the first application which allows you to develop another android application in mobile device.

AIDE (Android IDE) allows you to develop an Android project in any android based mobile phone.You don’t need any PC or any editor not even eclipse.

The main aim of AIDE is Self-contained mobile developed platform.

You can look for Meme IDE 1.14 for Windows Mobile and Android, check the detail on the link specified..

Ref:

 Android-IDE (AIDE)

Develop Android apps from within Android using AIDE (video)

Title: Developing android on android

Body: Is there currently a way of developing android apps on an android phone? In other words, write, compile, install and run regular android java on the phone without using a pc? If not, what would make it possible, if at all? (would rooting be necessary? Or an android emulator compiled for android?)</p>


问:
How can I effectively discuss language limitations with a client?
I would like to know the ideas that are being used for explaining to the client the limitations of the language used for enhancement of the existing project.

Given a scenario was that the project existed in VC++ 6.0 and the client had asked for enhancement that could include transparency (alpha) component in the color part (currently using gdi).

I found out that gdiplus library supports such feature but could not find it for MSVS 6.0 since its already being outdated (could not even find the msdn files for it) did not have support for gdiplus.

I had to explain it to my client, so created an application in the newer MSVS and included both gdi and gdiplus and drew some objects using both the libraries side by side.

So gave him an idea that the following point could be fixed if we migrate it to the newer version of code.  Since client being a developer himself understood it.

But there are cases when the clients are not developers and bearing no knowledge about programming. In such cases it is difficult to explain the problem.

答:
Take a step back and think about your requirements:

Given a scenario was that the project existed in VC++ 6.0 and the
  client had asked for enhancement that could include transparency(
  alpha) component in the color part(currently using gdi).

See that your tasks were very technical to begin with. You should generally have very technical requirements when the client is also a tech person, e.g. a developer. Like in your case.

In cases when the client is a non-technical person, you'll usually have requirements that go something like: We want the dialog box to have the round loading thingy, rounded corners and look pretty. They will rarely set you any constraints related to which library you should use, and in these cases that is completely your choice and responsibility and no explanations are satisfactory.

There are also rare cases that a very non-technical gives you very technical requirements (rare, but it happens). In these cases you should try talking to them to understand what they want instead of what they say they want and only then suggest a technology which can accomplish the goal in the best way.

Oh, yes. When you are modifying existing codebase and are facing a limitation, then you would have to explain it to your clients, technical or not. In that case, I usually use an analogy. You can't build house first and chimney later or something like that.


问:
Domain-aware code text editors
General text editors don't change greatly. Syntax highlighting and code collapsing are not big changes really. If an editor is structure or domain aware, this usually comes with a different layouts - treeviews, context-menus, drag-and-drops and so on.
So are there good example to add more domain control when editing with caret, text selection and so on?

When I think about explaining this with example, what comes to mind:

Sync control (it's when you delete first i in
...
 this automatically changes to <dv></dv>

Read-only control (it's you're at "/" at the fragment above you can't edit, but if you select
 and press Del, both are deleted

Layered navigation. Probably different modes when the caret bypasses irrelevant layers  when you press Left, Right and so on. For example if you're in text navigation for html, then all tags are bypassed

Copy-paste control. Selected fragment should contain a valid sentence for domain and the place to insert to should also be compatible with it.

These are just examples for you to recall the real world editors where you met something similar.

Probably there are editors that allows one or several things from this list, but I suppose that partial solutions is no help and even can do harm and cause inconvenience. So the question is more about complex solution intended for overall improving of productivity in the general text editors.

答:
The usual UNIX text editors (emacs, vi and its various clones) are highly extensible and can probably be configured to do most or all of the features you listed.

vim, for example, provides a range of features out-of-the box that would either allow what you describe, or achieve the same goal on a different path. For example, the it and at ('inner tag' / 'a tag') motions can be used to apply all sorts of general editing operations to an XML tag or its contents. Writing a macro that auto-closes a tag is trivial. Skipping can be achieved using tag-based motions in combination with general movement commands. vim also has configurable syntax-aware folding, and I guess getting it to fold XML properly shouldn't be too hard. If that's not enough, you can pipe any part of the current document through an external command using the ! family of commands. And finally, vim has some integration with build tools, and can be configured to parse their output to position the cursor at any error.

I am all but an emacs expert, but I'm fairly positive that emacs can do the same things, or their equivalents in the emacs paradigm.

Read-only control is a feature I would hate - it's my text, it's there, there is no reason to deny me from editing it if I so choose. Signalling that the document is wrong through aggressive syntax highlighting, and providing comfortable macros to manipulate text in a domain-specific way, is a much better choice.

But the most important reason for using a general-purpose text editor over a domain-specific tool is that you only need to learn one tool - this means that you can (and probably will) learn this one tool inside-out, and this in turn means that a tool with a crazy-steep learning curve is perfectly OK, as long as it pays off in terms of productivity. Such an expert's text editor doesn't need a graphical UI, it doesn't need to spend system resources and screen real estate for discoverability, and it can assume that I know what I'm doing instead of trying to guess where I'm going and suggesting solutions.

Title: Domain-aware code text editors


答:
Well as you are really not talking about a "language" but an upgrade of your development environment its a no brainer.

"The current version of xxxx does not support the features you want we need to upgrade to the latest version".

I know VC 6.0 for C++ to VS 2010 is a big upgrade but its still just an upgrade.

Title: How can I effectively discuss language limitations with a client?

Body:
I would like to know the ideas that are being used for explaining to the client the limitations of the language used for enhancement of the existing project.

Given a scenario was that the project existed in VC++ 6.0 and the client had asked for enhancement that could include transparency (alpha) component in the color part (currently using gdi).

I found out that gdiplus library supports such feature but could not find it for MSVS 6.0 since its already being outdated (could not even find the msdn files for it) did not have support for gdiplus.

I had to explain it to my client, so created an application in the newer MSVS and included both gdi and gdiplus and drew some objects using both the libraries side by side.

So gave him an idea that the following point could be fixed if we migrate it to the newer version of code.  Since client being a developer himself understood it.

But there are cases when the clients are not developers and bearing no knowledge about programming. In such cases it is difficult to explain the problem.


问:
Dealing with estimates as a junior programmer
I have been working for a couple of months now in a company that estimates (for the general population, not juniors specifically) tasks and then we are given the task, solve it, it goes through two tests and at the end the estimate should be somewhat met.

I am beyond stressed because some of the estimates are simply impossible for me to meet. I still don't know the entire system(because it is quite substantial) so sometimes half the time is spent finding out what i need to do and where and by the time I finish sometimes the estimate is over and there is still testing to be done (and correcting mistakes if they were any).

The second time I have to deal with a similar functionality it all works much faster, but so far I feel like I am just bad at programming.

Is there anything you did when you were just beginning that helped you get over this stage? I get so stressed when I see how little time there is to code that sometimes I can't even focus properly at what I'm doing which makes it even worse.

答:
Let me introduce you to my two friends, WAG and SWAG

Ie, the 'Wild Assed Guess' and the 'Scientific Wild Assed Guess'

Believe it or not, I didn't make these up. They're actually pretty common in business. Take a look at this article to see what I mean.

Ideally, it's best to come up with a firm estimate but if you can't, it's better to state that the estimate is rough due to incomplete data than it is to lie.

The key is, business is not computer programming. Managing expectations is more important than precision. It's important to assess the time you think it would take plus 10% as a contingency to make up for any unforeseeable problems.

If you overestimate, they will be happy when you finish with time to spare. If you underestimate, they will be either not disappointed if you meet the deadline or extremely disappointed if something goes wrong.

Business is a grey area that some people acquire an intuitive feel for over time. The fact that they're asking a junior developer to make these sorts of decisions independently says one thing. Either they don't have anyone available who is more capable of making those sort of decisions or the managers don't want to take responsibility for failures.

I'd put my money on the latter if you're working for a large organization. When a hierarchical business model grows large enough, the top is so far removed from the bottom that the higher-ups can only measure progress by what they receive on paper. It's a terrible environment because promotions are generally given for not making mistakes. But the people who get the promotions avoid failure by pushing their responsibilities on others (ie blind incompetence) and taking credit for the successes of people lower on the chain.

Unfortunately, programmers are easy targets to throw 'under the bus' because no matter how large the problem, we will try to find a solution. The key is, don't spend more time determining how to estimate the problem than you do implementing the solution.


问:
Completion time on a company where the supervisors don't know programming
We are in a small company with around 10 developers. I am the team leader and responsible for the development process.

Supervisors and salesmen are close to us since we are a small team, but have no clue on how software is developed.

When they ask me how much time I want for a change (bugfixes/features) in a product, my response is 'let me calculate it'. After giving them the schedule, they start by saying OK you can do it in XX time which differs a lot from my plan. We are using a model close to Agile basic principles and have circles per week or per three days.

Of course I argue and say that this cannot be done. They seem to have no idea on the effort we are doing. They do not want to see WHY my schedule is for that amount of time.

I know this behavior is stupid, but how can I make them see the problem?

答:
Do not show them their fault!

Try to argue better what changes you make, give them more detailed estimates.
Make a suggestion like "We can do this in your X hours instead of mine Y hours, if we will give software testing to outsource".
Or "We can do this faster, if we exclude this part of requested functionality".


问:
How do I write unit tests for robots (and other mechanical devices)?
I'm a member of my high school's robotics club, and am responsible for programming the robot.  One suggestion I keep hearing from various adults is that I should be writing unit tests to help validate my code.  The code base is getting a bit big, and I do agree that unit tests would be really helpful in helping me catch bugs quicker.

However, I'm not entirely sure how I could accomplish this.  To the best of my knowledge, unit testing is done by taking a function (or a subsystem of the code) and feeding it a set of input to make sure it comes out with the same output each time.  The code that I currently have doesn't do any heavy data crunching, but rather directly manipulates the hardware components on the robot.  Most of the complexity comes from making sure that the electronics are sound, that the code at the moment matches the actual hardware on the robot, etc.  Often times, I can only see if there's a problem by loading the code to the robot itself, and attempting to run it.

By extension, how can unit tests be written for code meant to operate any mechanical device?  It seems to me that you can only catch errors by physically observing the operation of the machine.

Or am I just misunderstanding how unit tests should work?

(If it matters, here's the code, it's written in C++, and I'm participating in FRC)

答:
I can tell you how they do it on Flight Simulators

First, you're only going to get half the answer if you ask this question to only programmers so you should probably cross post this on http://electronics.stackexchange.com while you're at it.

I haven't done any work with robots but I did spend 5 years doing hardware on flight simulators so I can tell you how their architecture works.

The hardware layer is dumb

It contains a basic interface where you can adjust simple input/output values and set interpolation breakpoints for analog signals. When you're working with 'fresh' hardware, everything will work as expected with little or no calibration but over time the parts will undergo mechanical wear and need to be adjusted.

The calibration is a simple table that contains sectioned ranged between the min/max values. To measure input on these, a servo is typically used (ex a linear potentiometer, transducer, accelerometers, etc). Or in the case of instrumentation, you just judge accuracy visually and adjust until calibrated.

The software layer is the opposite

Everything is complex and interconnected so it's important to isolate some variables to test the functionality. There's no need to give yourself a headache thinking up scenarios because it's much easier to run some realistic scenarios where you can collect data. When you run the tests, you're basically measuring the stored data against the current output.

On a flight simulator this is referred to as a QTG (Qualification Test Guide). At its core it plots the data on a 2D grid where one dimension is time and the other is the output.

Believe it or not, that's the essence of how they develop the models. A real plane is equipped with a ton of sensors and flown around doing controlled scenarios. Because all of the controls can be driven without human interaction, the tests are run (ie the sim flies itself) by the computer and the data is compared.

Even though robotics are created on a much different scale the principles are the same. The traditional approach is to completely sever the hardware and software layers so both can be tested individually. Hardware input is collected through servos, and set through an independent interface. Sofware input can be set/read by independently measuring and comparing the signaling that would otherwise go to the hardware and plotting it against known 'good' data.

The tests themselves don't necessarily need to be complex as long as the results are predictable, measurable, and reproducible.


答:
This is a huge bugbear of mine for sales/consultancy led projects and it's a tough situation. This is often an issue of how the company operates.

It is a classic case of the tail trying to wag the dog , sales guys doing whatever they can to close the sale, promising the world in features, and guaranteeing a ludicrous timescale, software development process and everything/one else be damned.

Either they will listen to you or they won't, it is not necessarily a fact they do not understand, more likely, they know fine well, but all they care about is closing the sale, getting the business and worry about deadlines later.

That being said, customers can be a pain in the backside, they want things done cheaply, and they want to know when it will be done. And they want a discount to boot.

One way to mitigate this is to have a tech guy involved in the sales meetings. Now this is not necessarily feasible in every company, but may be the only way to at least try and reign in the sales guys.

Title: Completion time on a company where the supervisors don't know programming

Body:
We are in a small company with around 10 developers. I am the team leader and responsible for the development process.

Supervisors and salesmen are close to us since we are a small team, but have no clue on how software is developed.

When they ask me how much time I want for a change (bugfixes/features) in a product, my response is 'let me calculate it'. After giving them the schedule, they start by saying OK you can do it in XX time which differs a lot from my plan. We are using a model close to Agile basic principles and have circles per week or per three days.

Of course I argue and say that this cannot be done. They seem to have no idea on the effort we are doing. They do not want to see WHY my schedule is for that amount of time.

I know this behavior is stupid, but how can I make them see the problem?


问:
Code duplication with no obvious abstraction
Have you ever encountered a case of code duplication where, upon looking at the lines of code, you couldn't fit a thematic abstraction to it that faithfully describes its role in the logic? And what did you do to address it?

It is code duplication, so ideally we need to do some refractoring, like for example making it its own function. But since the code doesn't have a good abstraction to describe it the result would be a strange function that we can't even figure out a good name for, and whose role in the logic is not obvious just from looking at it. That, to me, hurts the clarity of the code. We can preserve clarity and leave it as it is but then we hurt maintainability.

What do you think is the best way to address something like this?

答:
Without a code sample, it's difficult to say why your code has no readily identifiable abstraction. With that caveat, here's a couple ideas:

instead of creating one new function to hold the common code, break the functionality into several distinct pieces;

group small pieces together based on common data types or abstract behavior;

rewrite the duplicate code given the new pieces;

if the new code still defies a clear abstraction, break it up into small as well and repeat the process.

The largest difficulty in this exercise is that your function is likely incorporating too many unrelated behaviors at a given abstraction level, and you need to handle some of them at lower levels. You correctly surmise that clarity is key to maintaining the code, but making the behavior of the code clear (its current condition) is very different from making the intent of the code clear.

Make the how of the smaller code pieces abstract by having their function signatures identify the what, and the larger pieces should be easier to classify.


答: Say "I stand by my estimate."  And then of course hit your estimate.  When it happens three times, they'll probably trust you.</p>


答:
"When they ask me how much time I want for a change"

At that point stop them. It's not how much time you want. It's how much time you need. If they insist, give them both the time you want and the minimum you need.

It may also help to keep a very visible measure of incurred technical debt due to all the shortcuts forced upon you by Sales. Nikolay is widely optimistic that you can influence Sales by talk, when their current behavior gets them bonuses.

In fact, if Sales is really driven by such incentives, then you should take that into account when formulating your response. "Feature not committed by Engineering" is a perfectly valid reason to drop a Sales request.


答:
In my experience Sales people think that everything is a negotiation where you meet eachother somewhere in the middle. That's basically how they work. They try to sell a product to a client and ask high, the client offers low and in the end a price both parties agree on becomes the agreement.

They also take this mentality to the workfloor. They assume you're asking for too many hours so they will try to argue off some of the hours, just as in a negotiation.

Giving exact estimates, has only given me headaches.

What you can do is play along: give a higher estimate where they can shave off some during "negotiation"  and in the end, end up with the hours it really costs you to do.


答:
"After giving them the schedule, they start by saying OK you can do it in XX time which differs a lot from my plan." First of all ask them how they calculated their XX time.

Suggest to them that a record is made of your estimate and their estimate. Then you can compare the actual against the predictions and see who is more accurate.


答: As previously said, mock and stub out the hardware parts. As an example, if you have an interface to the robot, you can inherit from that interface, and then make simple stub implementations of it. Then you can have test that the stub implementation have been called as expected. If that is expected functions or expected parameters. </p>

Title: How do I write unit tests for robots (and other mechanical devices)?

Body:
I'm a member of my high school's robotics club, and am responsible for programming the robot.  One suggestion I keep hearing from various adults is that I should be writing unit tests to help validate my code.  The code base is getting a bit big, and I do agree that unit tests would be really helpful in helping me catch bugs quicker.

However, I'm not entirely sure how I could accomplish this.  To the best of my knowledge, unit testing is done by taking a function (or a subsystem of the code) and feeding it a set of input to make sure it comes out with the same output each time.  The code that I currently have doesn't do any heavy data crunching, but rather directly manipulates the hardware components on the robot.  Most of the complexity comes from making sure that the electronics are sound, that the code at the moment matches the actual hardware on the robot, etc.  Often times, I can only see if there's a problem by loading the code to the robot itself, and attempting to run it.

By extension, how can unit tests be written for code meant to operate any mechanical device?  It seems to me that you can only catch errors by physically observing the operation of the machine.

Or am I just misunderstanding how unit tests should work?

(If it matters, here's the code, it's written in C++, and I'm participating in FRC)


问:
Noobie wants to use source control, how would you guide them?
Let's say you know of an anonymous noobie that wants to be lead upon the path of righteousness.  This noobie wants to use some sort of source control tools simply for the experience of using source control tools (and possibly for whatever benefits they bring along with them).

To constrain things further (and to make this possibly even more noobie-tastic), let's say they're stuck in windows developing in visual studio.

How would you guide your neophyte?

答:
Whilst I personally use git I would send them to some articles explaining version control and source management and let them experiment.

Surely fooling around with different tools like this is what we programmers love no? I say let this newb have some fun learning which tools are best for him/her


答:
I'm working on an editor with such features. It's a plain text editor designed to edit data that resembles tables, where columns are delimited by pipes (actually, space-pipe-space). Pressing tab will move you to another "cell" like a spreadsheet, and there are commands that deal with "cells" and "rows" rather than "words" and "lines of text". It has features to align columns, and to detect contiguous rows with an equal number of columns (each row potentially can have a different number of columns). It also knows about the somewhat peculiar variable syntax, table headings and so on.

The jury is still out on how successful this type of editor is, but I think it has some potential. While power users can still configure their industrial strength editor (ie: vim, emacs) to do the same things, there's a very large segment of the population that don't such tools. So while, yes, you can do this with emacs, most users (that I'm targeting, anyway) want something less complex.

Title: Domain-aware code text editors

Body:
General text editors don't change greatly. Syntax highlighting and code collapsing are not big changes really. If an editor is structure or domain aware, this usually comes with a different layouts - treeviews, context-menus, drag-and-drops and so on.
So are there good example to add more domain control when editing with caret, text selection and so on?

When I think about explaining this with example, what comes to mind:

Sync control (it's when you delete first i in
...
 this automatically changes to <dv></dv>

Read-only control (it's you're at "/" at the fragment above you can't edit, but if you select
 and press Del, both are deleted

Layered navigation. Probably different modes when the caret bypasses irrelevant layers  when you press Left, Right and so on. For example if you're in text navigation for html, then all tags are bypassed

Copy-paste control. Selected fragment should contain a valid sentence for domain and the place to insert to should also be compatible with it.

These are just examples for you to recall the real world editors where you met something similar.

Probably there are editors that allows one or several things from this list, but I suppose that partial solutions is no help and even can do harm and cause inconvenience. So the question is more about complex solution intended for overall improving of productivity in the general text editors.


答: One editor which is in my humble opinion a beautiful example of context-sensitive editing is GNU TeXmacs. Try it out, it's open-source and shows exactly the pro's and contra's of context-aware editing.</p>

Title: Domain-aware code text editors


问:
Method size in an OOP language, for instance - in Java

Possible Duplicate:

  What should be the maximum length of function

In Java (and I think in other OOP languages too) it is recommended to keep class methods as short as possible.

While I understand this recommendation I do not understand what is a "short-sized" method and "large-sized" method.

What is a particular criteria to determine that my java method is short enough?

答:
The cyclomatic complexity of a section of source code is the count of
  the number of linearly independent paths through the source code.

Ref: http://en.wikipedia.org/wiki/Cyclomatic_complexity

I recommend that you keep that number under 10 in a single method. If it gets to 10, then it's time to re-factor.

There are tools that can evaluate your code and give you a cyclomatic complexity number.

You should strive to integrate these tools into your build pipeline.

Don't literally chase a method size, but try to look at its complexity and responsibilities. If it has more than one responsibility, then it's probably a good idea to re-factor. If its cyclomatic complexity increases, then it's probably time to re-factor.

I'm fairly certain there are other tools that give you similar feedback, but I didn't have a chance to look into this yet.


问:
What is proven as a good maximum length of a function?
Does function length affect the productivity of a programmer? If so, what is a good maximum number of lines to avoid productivity loss?

Since this is a highly opinionated topic please back up the claim with some data.

答:
From Cyclomatic complexity (Wikipedia):

The cyclomatic complexity of a section of source code is the count of
  the number of linearly independent paths through the source code.

I recommend that you keep that number under 10 in a single method. If it gets to 10, then it's time to re-factor.

There are tools that can evaluate your code and give you a cyclomatic complexity number.

You should strive to integrate these tools into your build pipeline.

Don't literally chase a method size, but try to look at its complexity and responsibilities. If it has more than one responsibility, then it's probably a good idea to re-factor. If its cyclomatic complexity increases, then it's probably time to re-factor.

I'm fairly certain there are other tools that give you similar feedback, but I didn't have a chance to look into this yet.

ContentLicense: CC BY-SA 4.0


答:
It might help to differentiate between how much time something will take and how much time will be charged.  How much time something will take is a technical decision, they have no basis to disagree with you, be stubborn.  How much the salespeople want to charge for that time is their decision and their responsibility to sell to the client.

Other than that the incentives need to be sorted out or you'll always be fighting an uphill battle.  If sales bonuses are paid not on the outright value of the sale, but on the difference between the value of the sale and the cost of delivering it then they have an incentive to listen to you.


问:
Should software developers be skilled at software design?
There is an analysis and design phase of the software development life cycle. Should software developers be skilled enough for carrying out the work performed during this phase, such as drawing workflow diagrams, data flow diagrams, ERDs, UML, and other models?

I have seen some cases where developers can code very well given a clear understanding of what is required. However, when they are asked to design a system, they stagger at times.

答:
In my opinion, by and large, any big problem is tackled by breaking it down into smaller problems.

Diagrams, assist in this task. The provide different views/details of the system. At times you are interested in how database schema will look, but other times, you are intersted in how the components will talk to each other. Perhaps, you want to see details of how a particular algorithm will work. Either ways, there is a way to depict a problem/scenario with a diagram rather than text.

Benefit of a diagram is that you don't have to have as much text. Picture bieng a thousand words and all.

For each use case, there is a different level of detail, and different kinds of things need to be thought of.

So in summary, I think it should be a pre-requisite to be able to read those diagrams well, so everyone in the team is on the same footing. The actual task of creating those diagrams, well some are more adept than others, so I would draw the line at reading them. Creating would be a bonus.

UML is a popular notation. One should be familiar with a common subset that is used more frequently. There are details in the standard, that probably only the super experts know about. One should have functional knowledge.


答:
The developers should in my opinion always be active in the design. Why? Because they are the ones implementing it. If you have dedicated designers, those designer should also code. It's kind of an eat your own dog shit thing.

It's also not necessarily the best thing to do a large upfront design. Uncle Bob talks a lot about user driven design, and user stories. By breaking the system down into user stories, the developers can more easily see what is needed for the different user scenarios, and this will improve the design, as well as the user experience in most cases. To be able to do this, the developers have to be the designers of the system!

EDIT: Got pointed out that I didn't actually answer the question.

Yes, programmers should be skilled in design, but not necessarily in the traditional large UML diagram sense.

If the team as a whole feels that diagrams are vital, everyone should be able to read it, and enough people should be skilled at making them. I'm not necessarily of the believe that large and complex diagram is what is needed to get the job done though.

Title: Should software developers be skilled at software design?

Body:
There is an analysis and design phase of the software development life cycle. Should software developers be skilled enough for carrying out the work performed during this phase, such as drawing workflow diagrams, data flow diagrams, ERDs, UML, and other models?

I have seen some cases where developers can code very well given a clear understanding of what is required. However, when they are asked to design a system, they stagger at times.


答:
A good software developer should be familiar with the work that is done at all phases of the software development life cycle, from requirements through maintenance activities, as well as the various supporting activities that happen. That's obviously a lot of topic area to cover, so I wouldn't expect one person to be an expert at all of it.

As far as design goes, I'd expect every software developer to be able to read common models, such as ERD and UML models. This includes the ability to understand what the symbols mean and how the model relates to their role in the process, such as development or testing. I'd also expect them to have enough of a working knowledge to be able to update the models to correspond to their implementation as needed, and the use of the tools used to create and maintain the models.

With respect to actually architecting or designing the system, that's something that comes with time and experience. The only way to actually get good at turning requirements into a system architecture or a high level architecture into a more detailed design is to do it, evaluate your work, and learn from any mistakes. It's not something that can be read in a book or taught in a course or two and mastered.


答:
I think that it is good to have all the developers aligned (via education, training or reading) in the various type of UML diagrams and in ERDs and various documents such as requirements (e.g. the Volere template) and details use case listings.

They should be able to read them and use them to describe what they are planning, however, I agree with Thomas that creating architect requires more than that (e.g. experience and systematic vision) and can not be taught.


答:
The design phase is a vital part of the software development process; if you cannot design software, you cannot develop software, and shouldn't be calling yourself "software developer" ("programmer" would be more appropriate).

However, designing software is not about diagrams and flowcharts. It is about figuring out solutions to a given problem on an abstract level, and planning how to translate those into an actual software product. Diagrams and flowcharts help in communicating these solutions and plans, and sometimes they help get a clearer picture, but many software developers have only superficial knowledge of UML, if any, yet they design beautiful software (and, vv., the mere fact that you're an ace at drawing flowcharts says nothing about your ability to design good software). If you can communicate and design well, any tool will be fine; the English language alone will do if nothing else is available.

TL;DR: Yes, software developers should have and maintain design skills, and no, UML e.a. are not requirements for this (though possibly helpful).


答:
To get away from their preoccupation with hours, change the game. Instead of estimating time, estimate complexity in relation to some given usecase that forms a baseline.

You mention that you have something of an Agile approach, why not try Scrum?

In other words do short Sprints, tell them that "yes in one week I will be able to develop three of your five features" then make sure you deliver on those three features. Have them prioritize the changes/features/bugs and work strictly in that order. (Of course there is more.)

Teach them about the iron triangle of time, cost, quality and scope. You fix three and the fourth is the triangle area and thus a function of the others. I would guess that it is probably more important in the end when you are delivering, how much it costs and hopefully that you deliver with quality than exactly what you are delivering.


答:
If the salesmen are also the ones who are in charge, you can say, "Ok, I can go with your schedule. Which features or responsibilities would you like me to sacrifice in order to make your deadline?" That way you're not saying "no" to the people in charge but you're not committing to impossible things. The decision is in their hands how to run the business. If they want to axe other things to make time for the changes, let them.

EDIT:
We need to respect and submit to those who are in authority, while still doing our jobs with excellence. The only way to do this is with humility. I'll work on whatever my boss wants me to work on, but I can only do so much. When you tell him like it is with an attitude of submission, he is in a better position to make better decisions and he'll want more employees like you.

Make sure these things are documented too in order to explain why the commitments are unreasonable and how the situation was resolved. It can help coworkers deal with similar situations in the future.


答: If its a persistent problem, how about seconding a sales guy onto the development team for a week or two. Give them a book about the X programming language, and tell them to do it in their estimate. 99% of the time they will fail miserably, and be loath to question your estimates again. They might also get an idea of what it takes to do software development and realise they are not helping the process.


答:
I am a young software engineer. I am graduating college in a week, but I have been working in the field for the past 2 years. I am currently at a small software company where only 2 of us are developers and our bosses don't do any of the design, or much of it. We sit and talk about it, but none of the true software design is done in these meetings, or well at least.

Being young (and technically an intern), I find it frustrating to be given projects with no specs written, no specifications to look to, just a general final desired result.

I guess my answer is software developers learn software design by having projects designed for them at first, but you should also feel you have a say in how the design happens. The designers might not understand the abilities you have or the shortcomings the developers are working with.


问:
How to correctly design NoSql database schema?
I would like to learn something more about NoSQL databases, so I've chosen to create a new project from scratch to handle football results. In my traditional relational database, I have tournaments, teams, results and class tables. All are obviously related.

What might be a good approach for designing a project like this, using a NoSQL approach instead?

答: Use the right tool for a particular job. By asking this, it's clear you don't know when NoSQL is appropriate for data storage. A lot of people are using NoSQL just because it is the "thing of the moment". Usually NoSQL databases have no schema and should be used when the data is better represented by its model. You should not use a NoSQL database to store data that is typically relational; a relational database should be used in that case. I know that when there is a need to scale the application to be capable of handling millions of transactions then NoSQL model works better (even when the data is relational), but I think that is not your case. </p>


答:
First, there are clearly defined use cases for using NoSQL over a traditionnal RDBMS. Make sure your system meets one or more of these criteria before jumping into NoSQL, or else you could run into problems.

This youtube video has been a real eye-opener for me. It is about MongoDB and data modeling. You can read more about MongoDB on their website.

Title: How to correctly design NoSql database schema?

Body:
I would like to learn something more about NoSQL databases, so I've chosen to create a new project from scratch to handle football results. In my traditional relational database, I have tournaments, teams, results and class tables. All are obviously related.

What might be a good approach for designing a project like this, using a NoSQL approach instead?


问:
For what reasons should I keep "using" section clean in C#?
Once when I was refactoring my code, I went up the IDE to the using section of my C# class, and cleaned unused namespaces and duplicate namespaces, and sorted them all.

My pair (pair programming) asked me the reason. I had no idea why I did that. I did it out of my habit to keep all of my code clean and tidy. I mean, I told him that having a cleaner code is a good idea in general, but of course that reason was not a good justification, as I won't even bother to spend my time in the using section of any C# code page.

Since many times you move a class or an enum (or a type in general) from one namespace to another namespace, and this adds new using statements to your code (either manually by going up the code window and writing the using statement yourself, or through the editor using Alt+Ctrl+F10 combination), and since these new using statements would be added to the end of using section, which makes them not sorted alphabetically, and since compiler never complaints about any of these problems, why should we care to make this section clean and tidy? What reasons might we have?

答:
My main reasons to clean up amongst the using statements are:

The more using statements the more possibility of naming conflicts which would mean you have to include parts of the namespace in the code to avoid ambiguity.

The IntelliSense is filtered based on all the assemblies in your using statements. Therefore if you clean it up from unnecessary statements you'll help yourself by helping with the accuracy of the IntelliSense.

On top of that I agree with the other answers in that it increases readability and makes it easier to get an idea of what the type(s) in the class do.


答:
Should software developers be skilled at software design?

Yes, definitely. However, design is not necessarily a big monolithic phase, nor does it have to be written down as very formalized diagrams.

The more detailed the design upfront, the more likely it is to prove false later on.

So IMO the skill of designing is not about spitting out a perfect model in abstracto. It's about making pragmatic decisions, starting small and making the design emerge, refining it as you program and discover more about the domain and technical needs.


问:
Interview assignment: how long is reasonable?
So I'm hiring for a senior developer/team lead role for an ASP.NET MVC3 project.  This is a big deal position for our team as this person will lead one of our two main products--a product that hasn't seen much developer love in a while.

So I need to ensure that my candidates do smart things with controllers, views, view models, DALs, unit tests, etc.  I use some trivial programming challenges during interviews but I want to give the folks who have trouble in whiteboard coding a chance to shine.

The best assignment I can think of: implementing a trivial log in page, is probably more than an hour of work and even if I cap it at 2 hours, it is unlikely to be 100% finished.

Is this fair?  I'm trying to strike a balance between keeping the assignment reasonable and giving the applicant a chance to show off the wide range of skills being a tech lead requires.

答:
Sounds reasonable, but you may want to include at least another page that is used after logging in from the login page.

If you expect them to do this assignment at your office during the interview, let them know ahead of time so that they can plan for it and allocate the necessary time for the interview. In my experience, interviews don't last longer than an hour, so it's only fair to let them know what to expect and how much time you will give them.

The other option is to allow them to complete your assignment at home, but that allows them to use more time and resources (i.e. get help). However, this allows you to give them a more complicated assignment that can showcase everything you expect them to know.


问:
How to Model a simple file-system by UML class diagram
I want to model a file system which contains both files and directories, and directories can contain either files or other directories.

This is what I have reached so far:

In OOSE book, however, a similar model is presented:

Now I have two questions:

I wonder why the author did not use an Interface to represent the abstract type FileSystemElement? Isn't using an interface for this type correct?

As we know, files and directories must have names with similar constraint (e.g. maximum length of 256 characters). Therefore, it would be nice if I model this in the FileSystemElement. But an interface cannot have a abstract attribute, so I have to repeat name attribute in both Directory and File classes. Is there any better workaround for this problem?

答:
Isn't using an interface for this type correct?

Using an interface in this case would work, but you would have to duplicate behavior between Directory and File (like having a maximum of 256 chars for the name). You would be better off making FileSystemElement an abstract class (assuming your language of choice supports it) Which also answers your second question : an abstract class can provide default behavior for its children. You can just declare the Name property inside the parent class, with the associated validations, etc. That way, Directory and File will inherit the property and the behavior. You won't have to redefine anything in the Directory of File class. No code duplication.