问:
Should security restrictions cause a service to return null or throw an exception?
I'm in a bit of a disagreement with a more experienced developer on this issue, and wondering what others think about it; our environment is Java, EJB 3, services, etc.

The code I wrote calls a service to get things and to create things. The problem I ran into was that I got null pointer exceptions that didn't make sense. For example, when I ask the service to create an object, I get null back; when I try to look up an object with a known valid ID, I get null back. I spent some time trying to figure out what was wrong in my code; since I'm less experienced I usually assume I've done something wrong, but it turns out the reason for the null returns was security. If the user principal using my service didn't have the right permissions for the target service, then it simply returns null. Most other services here aren't documented very well either, so apparently this is just something you have to know.

This is rather confusing as a developer writing code that interacts with the service. It would make much more sense to me if the service thew an exception that would tell me that the user didn't have the proper permissions to load this thing or to create that thing; I would then immediately know why my service wasn't working as expected.

The more experienced developer who wrote the service argued that asking for the data is not an error condition, and that exceptions should only be thrown in an error condition, not when the user doesn't have access to the data. This data is often looked up in a GUI, and for those users without the right permissions, these things simply "do not exist". So, in short: asking is not wrong, hence no exception. Get methods return null because to those users those things "don't exist". Create methods return null when the user wasn't allowed to create that thing.

Is this normal and/or good practice? I prefer using exceptions because I find it much easier to know what's going on. So I would for example also prefer to throw a NotFoundException if you asked for an object with an invalid ID, rather than returning null.

答:
I definitely think it is a bad design. Null-pointer is not a valid answer to me and it can be tricky to manage.

If the user tries to connect a service without the proper credential, I should reply with a clear and concise answer. The answer could be an exception or a special object but not null.

You should leave the null answer when the network link is broken or other unexpected critical malfunction.

Furthermore, the time you spend understanding why you got a null is a strong argument. Any piece of code should be easy to understand and use. Having a null value is not the case.


问:
Discovering elegant ways of coding
I read this thread on programmers today and thought that looked like a really elegant way of coding. I would like to discover more neat methods of coding.

What are the best ways of discovering new elegant ways of coding? (Im already aware of the standard design patterns)

答:
I would definitly recommend to read Clean Code: A Handbook of Agile Software Craftsmanship.

1 of the 10 top books for programmers, easy and pragmatic guide to clean code (design patterns are not treated in this book).

ContentLicense: CC BY-SA 3.0

Title: Discovering elegant ways of coding


答:
Returning null isn't great. It tells you nothing. To take your example, if an app is trying to look something up and the response is null for both security problems and if the item doesn't exist, then how do you tell the difference between the two?

A meaningful response may allow the application to make logical choices about what to do next or how to resolve problems.

Title: Should security restrictions cause a service to return null or throw an exception?

Body:
I'm in a bit of a disagreement with a more experienced developer on this issue, and wondering what others think about it; our environment is Java, EJB 3, services, etc.

The code I wrote calls a service to get things and to create things. The problem I ran into was that I got null pointer exceptions that didn't make sense. For example, when I ask the service to create an object, I get null back; when I try to look up an object with a known valid ID, I get null back. I spent some time trying to figure out what was wrong in my code; since I'm less experienced I usually assume I've done something wrong, but it turns out the reason for the null returns was security. If the user principal using my service didn't have the right permissions for the target service, then it simply returns null. Most other services here aren't documented very well either, so apparently this is just something you have to know.

This is rather confusing as a developer writing code that interacts with the service. It would make much more sense to me if the service thew an exception that would tell me that the user didn't have the proper permissions to load this thing or to create that thing; I would then immediately know why my service wasn't working as expected.

The more experienced developer who wrote the service argued that asking for the data is not an error condition, and that exceptions should only be thrown in an error condition, not when the user doesn't have access to the data. This data is often looked up in a GUI, and for those users without the right permissions, these things simply "do not exist". So, in short: asking is not wrong, hence no exception. Get methods return null because to those users those things "don't exist". Create methods return null when the user wasn't allowed to create that thing.

Is this normal and/or good practice? I prefer using exceptions because I find it much easier to know what's going on. So I would for example also prefer to throw a NotFoundException if you asked for an object with an invalid ID, rather than returning null.


答:
If you want to learn about elegant code, read code and lots of it.

Look at popular open source applications and frameworks - not all code would be good or elegant, but the more code of other people you are exposed to the more you will learn. Some of the code you will see will be very elegant, some horrible - both will teach you.

Title: Discovering elegant ways of coding

Body:
I read this thread on programmers today and thought that looked like a really elegant way of coding. I would like to discover more neat methods of coding.

What are the best ways of discovering new elegant ways of coding? (Im already aware of the standard design patterns)


答:
There is no single one-size-fits-all answer to the question. Whether to use exceptions or return null depends on the situation.

Instead of looking at this purely from a dogmatic point of view, look at the interface as a user interface. User interfaces should be usable. So regardless of your own opinions on the "right" way to do something, pick the method that is the most usable from the perspective of someone using your interface.

If the caller needs to know why an object isn't being returned, an exception is appropriate. If, however, the general concept is "if you don't have permission, it doesn't exist", the null is acceptable.

Specifically in your case, I'd say nulls are perfectly acceptable for looking up an item if the caller is first required to log in or connect to the server. That is when you would be told that you do or don't have permission. Once you get past the gate it's reasonable that when you search for something you don't have permission to see (or even know it exists), you should get a null.

If, on the other hand, you have no initial connection or login step, an exception makes sense. If the caller knows an item exists and they aren't getting it back, the API isn't being helpful to just return a null.

For creating an item, however, that's a different story. Presumably there could be a lot of reasons for that to fail -- no permissions, bad parameters, server out of memory, etc. If the developer is given a null for all those conditions, they have no way to determine a proper course of action.

So, to answer the question, ask yourself what the most usable solution is from the perspective of someone using the service. It may be that the way you are using it is atypical, and for the most common case a null is the right answer.

So, don't get into a religious war over this, decide what's right for this particular problem.


答:
Exceptions should only be thrown when there is an error and asking for a thing is not an error.

Asking for a thing may not be an error, but not having permissions to something you asked for is surely some sort of error. Exceptions are an alternative way of reporting exceptional conditions, to be used instead of special return values (such as null, which, as you wrote, is of absolutely no help if there are > 1 possible reasons why things could go awry (even if there is exactly 1 possible reason now, there could be 2 possible reasons in the next version, so using null as a return value indicating failure would be painting yourself into corner)). If the service doesn't report in any way why it won't do what you asked for, then it's definitely bad design.

Whether to use a special return value (e.g. negative integers are useful for functions that normally return a nonnegative integer), an exception, a global error handler or logger etc., is an implementation detail in the end. The choice depends on the language, on the situation, on conventions, and is also a question of taste. The main point is that there should be some direct way of finding out why something doesn't work. Otherwise your only option is to trash around with different options and whatever to find out what correlates with the black box's behavior, and it's waste of time.

String.substring() throws an IndexOutOfBoundsException if the index is out of bounds. I can't think of any advantages to returning null instead, even though - philosophically - one could argue that a String doesn't contain anything outside  its bounds, so null would be a logical return value then. Being logical-philosophical and being practical are obviously two different animals.


答:
If the root cause is an unauthenticated user then I prefer a hard HTTP 401 response perhaps with a redirect to a pretty-message-page (and a notification to someone that cares). Authorization-related causes are more case-by-case; there are arguments for returning HTTP errors (403, say) and arguments for returning special well-formed codes/messages in the service response.

Exceptions should only be used in exceptional cirumstances and mean that something has gone wrong. I disagree that they should be overloaded to mean "not allowed". (The same is true for the null return value: I disagree that it should be used to mean "not allowed".)


答:
It comes down to what the contract is.  If your contract says you can request something that doesn't exist, it should say what happens (null, or null object).

On the other hand, if your contract says you should call a different method first (DoesSomethingExist()) and then call the Get method, then your contract might say that you can only get things that do exist, and throw an exception if they don't.  The exception message could say something like, "Make sure to call DoesSomethingExist() first" which is a useful error message.


答:
Elegance is a subjective quality, in my opinion. It is a bit like beauty in that it is in the eye of the beholder. Different people like different things. I don't know of any objective list of characteristics that equate to elegance. Elegant code is hard to write.

That being said, it is very easy to spot unelegant code and design when faced with it. Therefore I agree with the other contributor here who recommended reading lots of code. Good design is often the result of analysis of a design's bad characteristics and smells. It seems logical that good, clean, elegant code is the result of analysis of a block of code's bad characteristics and smells.

Always write code for those coming after you.

Title: Discovering elegant ways of coding


问:
Use open-source programs in your company?
Is there any cons of making your employees use open-source programs in your company?

I am planning to start a bussiness and I wonder why companies usually work with proprietary software, as Microsoft Word to quote the most famous one. Why do not they use Open Office (or Libre Office) etc.?

From my point of view, you can save a lot of money and help the open-source community by, for instance, giving them part of your benefits in form of donations.

I do not know any (medium-big) company that does this. Probably you could give me some examples, just to prove that this model of open-source usage/collaboration works rocks.

答:
I'm a bit of an open-source fanatic myself, but I don't really see the point in keeping it a rule to use only open-source because it shouldn't be necessary. In software development, the best solutions tend to be open-source anyway, so open-source will usually win on the grounds of merit alone. Eclipse, NetBeans, Firefox, Chrome (or Chromium, rather), Apache, Subversion, Git, the list goes on. There are exceptions, for instance when you do C# on Windows, in which case Visual Studio would probably be the best solution, but generally you'll find that the open-source tools are the best pick simply because they're the best tools available, nevermind that they're open-source.

Also keep in mind that if you set an "open-source only" rule, that you've put yourself in a box for ideological or academic reasons. That may be fine and dandy if you're into that kind of thing, but realize that this will inevitably take the focus off of the primary point of any company; to make money. - I certainly don't want to discourage you from following some ideological vision, but realize that you're constraining yourself.

You shouldn't really need a specific rule for open-source to be on top, as long as you're willing to consider open-source solutions without the typical prejudices in the first place, because the open-source solutions in development simply tend to be the best.


问:
How to become a more organized programmer?
I am a programmer that can code. But I find that I can get thing done, but not get thing do well or like most of the open source communities do. Well, I use some of the library from git hub. I find most of the programme is well structure. Also, a read me.

My question are:

Is that any common file structure or naming convention in the
community or this is just a matter of personal taste?

How to become a more organized programmer, instead of writing code
    just work. But more organized that let other easy to get in your
    project?

答:
Refactor your code till you are happy with it.

Over time you will need to refactor less and less, and eventually you will be doing it right the first time around*.

Learn by doing.

*Mostly right :)


答: Git and SourceForge. These are the two items that I use when writing a large, unorganized program. For details Google the two, as I cannot link right now for some odd reason. Sorry about that, hope this helps.</p>

Title: How to become a more organized programmer?

Body:
I am a programmer that can code. But I find that I can get thing done, but not get thing do well or like most of the open source communities do. Well, I use some of the library from git hub. I find most of the programme is well structure. Also, a read me.

My question are:

Is that any common file structure or naming convention in the
community or this is just a matter of personal taste?

How to become a more organized programmer, instead of writing code
    just work. But more organized that let other easy to get in your
    project?


答:
Bearing good software design in mind, you should think about the life of your project.

By returning null, as it has been said, you do not give any information to the client. Look what happend to you, at first you did not realize where the problem was. Moreover, if no documentation is given, this is a mess.

By throwing an exception, you can tell what went wrong. You can even customize the displayed text to be more specific if you want to.

On the other hand, by returning null you make the client investigate what it is going on.

Furthermore, you realized that there was a problem because you got elsewhere a NullPointerException. Now imagine you do not store the return of that function... You will be forced to surround each call to that function with an if else block...

From my point of view, returning null is a bad practice.


答:
Development project structure has been discussed lots of times on Stack* (1, 2), just take your pick relevant to your situation.

To get more organized, I've tried many different methods and tools for organizing code and the surrounding information:

Bug trackers like GitHub/Bugzilla/TODO text files

Wikis like GTD TiddlyWiki/GitHub

Build tools like make/Maven/rake

Project management tools like JIRA and Redmine

Editors like jEdit and vim

Merge tools like Meld and kdiff3

Version control systems like Subversion and Git (actually scratch that, just use Git and save yourself a lot of grief)

Once you've tried several of each, you might find that some fit your way of thinking better than others. But remember that there is always a better tool which you don't know about, and tools are always catching up with each other. Therefore you should always be ready to try something else, even something you've already tried and dismissed, on the basis that anything you learn can and will be used by you for the greater good.


问:
What to do with unfinished stories and tasks in SCRUM sprint?
We have unfinished tasks which are part of stories in sprint. They are not accepted by the PO.
They must be included for the next planning of sprint.
Obviously the stories must be moved, but what about the tasks? Shall they be reopened and moved for the next sprint within the stories or not?</p>

答:
The question that comes to my mind is: Does it reall matter? If it only matters because of SCRUM-purenessness I would just go with what's most convenient. Remeber: Focusing on success is more important than following processes.

I think started tasks should be finished to what extent that is possible. If tasks are really big they should of course be aborted. Aborting tasks annoys developers and wastes money.

For unstarted tasks they just move with the story...? I don't really understand the problem here.

OwnerDisplayName: dimitar

OwnerDisplayName: vidstige


答:
The approach I have used to address these issues is to address them at the next sprint planning meeting, with choices of:

Do we roll over all unfinished tasks automatically to the next iteration?

Do we review each one and re-evaluate whether we still want that in the next sprint?

Do we look at oustanding tasks before, 'with' (interleaved) or after new items that have been added?

Do we want to re-vote on outstanding items?  Sometimes I have seen items not get done because they were voted a "2" at the last Sprint Planning but turned out to be more like a 5 (for example), so sometimes the effort determination needs to be revisited.

Title: What to do with unfinished stories and tasks in SCRUM sprint?

Body:
We have unfinished tasks which are part of stories in sprint. They are not accepted by the PO.
They must be included for the next planning of sprint.
Obviously the stories must be moved, but what about the tasks? Shall they be reopened and moved for the next sprint within the stories or not?</p>

OwnerDisplayName: Michael Durrant


答:
Imagine you were using a physical Scrum board.

The uncompleted stories would remain, the completed tasks would stay in the done column or can be cleaned (your choice), and the ones in doing would remain in the doing column as well or moved in TODO (if you re-prioritize).
The only thing that will change is the Sprint number will be incremented.

This is the same thing with your Jira. Switch all your unfinished stories and task to the new sprint.

OwnerDisplayName: xsAce


答:
An experienced teams move all stories including tasks to the next iteration. Such experienced teams however do not track time as 'cost factor'.

Most of teams would like to make effort spent visible therefore they prefer to split story into two parts - tasks accepted stay in the sprint, not completed task are moved to cloned story into the next sprint.

The danger  is hiddne in incorrect velocity achieved by team. Story that has been split keeps its estimation (storypoints) however the team achived 0 for uncompleted story!

OwnerDisplayName: Dusan Kocurek


问:
Should code comments have scope?
I am asking this because I have seen places where, whoever coded initially had provided proper comments, but later on modifications were made to the code but the comments were left untouched.  I remember reading somewhere " Don't get suckered in by the comments, debug only code".

So is it a good/ relevant/ practical idea that tells the scope of the comments so as to prompt the developer for editing the comment.

Your thoughts.

答:
Definitely.  All comments have scope, whether implicit or explicit.  As a general rule, it's helpful to your successors to be reasonably explicit about scope.

Vertical space is an inexpensive way to delineate scope.

I often try to convey scope when writing comments by either:

inserting a linebreak or two before the comment, to keep it visually grouped with the block of code whose behavior it's intended to document

or defining a logical block of code, and adding the comment at the top of that block.

In C, #1 would look like:

```<code>doStuff();
doOtherStuff();

// comment explaining the intent of the following three lines
int i;
for(i=0;i<10;++i)
    doMoreStuff(i);

doOtherStuff();
</code>```

In C, #2 would look like:

```<code>doStuff();
doOtherStuff();

{
    // comment explaining the intent of the following three lines
    int i;
    for(i=0;i<10;++i)
        doMoreStuff(i);
}

doOtherStuff();
</code>```

In this second example, the extra curly brackets also help by minimizing the scope of variable i.

OwnerDisplayName: Rig Veda

Title: Should code comments have scope?

Body:
Definitely.  All comments have scope, whether implicit or explicit.  As a general rule, it's helpful to your successors to be reasonably explicit about scope.

Vertical space is an inexpensive way to delineate scope.

I often try to convey scope when writing comments by either:

inserting a linebreak or two before the comment, to keep it visually grouped with the block of code whose behavior it's intended to document

or defining a logical block of code, and adding the comment at the top of that block.

In C, #1 would look like:

doStuff();
doOtherStuff();

// comment explaining the intent of the following three lines
int i;
for(i=0;i<10;++i)
    doMoreStuff(i);

doOtherStuff();

In C, #2 would look like:

doStuff();
doOtherStuff();

{
    // comment explaining the intent of the following three lines
    int i;
    for(i=0;i<10;++i)
        doMoreStuff(i);
}

doOtherStuff();

In this second example, the extra curly brackets also help by minimizing the scope of variable i.

OwnerDisplayName: smokris


问:
Would you put your Stack Overflow profile link on your CV / Resume?
If applying for a new job, would you put your Stack Overflow profile link on your resume?

This would show the employer you're an active member of the development community and also provide an insight into your knowledge + how well you convey your ideas.

However it would feel a bit gimmicky to me?

答:
Probably Not

It's not an accomplishment but most of all because it puts everything you've ever said under scrutiny. I don't mind telling my peers that I'm ignorant about something so I can learn from them but I don't want an employer seeing that. I just can't trust someone in HR to know that someone that can admit they don't know everything is better than someone that thinks they do.

ContentLicense: CC BY-SA 2.5


问:
Reading source code to learn
As you develop as a programmer, software developer, or coder, IMHO, you begin to see different (best or worst) practices, different algorithms, and "more than one way to do it". Seeing this code can be a great learning experience for you, even though you did not write the code. But is doing this only going to confuse you?

For example, let's say you have a library in any language that was created by a colleague, and you have been using it for a while. You decide to look at the actual source code, regardless of how extensive it is, and get a better look at how this library is written. For the sake of example, the function you use most often from this library is the max function, which finds the largest of two numbers. But this function is a lot more complicated than it needs to be. The way it is written is confusing the heck out of you, and you don't know how this works.

Will this make you a better programmer, because you realize how complicated it is for such a simple function, or will it make you a worse coder because you feel less confidant?

So my question, in general, is does reading source code make you a better programmer and if so how? If not why do people still do it?.

答:
You read the code of a function and it's surprisingly complex: You could get discouraged because it's complicated and scary and it hurts your confidence. Or you could try to understand it. You might fail, but I think in general you'll still be better off doing it, as you'll probably learn something from it, and even if you learn something very small, it's still better than learning nothing at all.

I don't know many people that just sit down and start reading source code recreationally. I don't do it, I don't find it fun. Usually if I'm "reading code" it's as an example in some documentation, or it's part of an existing system I'm working on (maybe adding some features, fixing bugs, whatever). Both of these can be very good learning sources.

Title: Reading source code to learn


答:
does reading source code make you a better programmer and if so how? If not why do people still do it?

Reading it doesn't make you better, understanding it does and you do this because you work in a team and you don't always get the chance to only work on your code. Comes with the territory.

Most part of your programming time is spent not by writing code, but by reading it. So you might just start right away :D

Title: Reading source code to learn

Body:
As you develop as a programmer, software developer, or coder, IMHO, you begin to see different (best or worst) practices, different algorithms, and "more than one way to do it". Seeing this code can be a great learning experience for you, even though you did not write the code. But is doing this only going to confuse you?

For example, let's say you have a library in any language that was created by a colleague, and you have been using it for a while. You decide to look at the actual source code, regardless of how extensive it is, and get a better look at how this library is written. For the sake of example, the function you use most often from this library is the max function, which finds the largest of two numbers. But this function is a lot more complicated than it needs to be. The way it is written is confusing the heck out of you, and you don't know how this works.

Will this make you a better programmer, because you realize how complicated it is for such a simple function, or will it make you a worse coder because you feel less confidant?

So my question, in general, is does reading source code make you a better programmer and if so how? If not why do people still do it?.


问:
Meta-licensing of applications
I'm currently evaluating license management solutions for our customized and project-based applications, which are supported by a single server in the intranet of the customer. The applications use common functionality provided by the server (session handling, data synchronization, management capabilities, etc) and are installed on mobile devices. We allow our customers to run the applications on X devices and want to check on the server, whether the customer sticks to this limit (based on the sessions). We don't want licensing software to be installed on the devices itself (for example providing X serials to the customer) nor do we want to host an additional server for licensing in the intranet of the customer. If a client connects, our server should load the license for the application running on the client and verify, that there are sessions left.

The licensing managers I looked at (12 products so far) focus on the application itself and don't allow me to implement such a floating behavior as described above. For example, this software could easily be used to create a "Standard Edition" or a "Professional Edition" of our server software, which is not our intention. In XHEO DeployLX there is a "Session Limit", which allows to limit the license to the currently established sessions in ASP.NET, which comes very close to my needs.

I'm currently thinking of implementing a custom solution, which allows me to load and enforce custom-defined licenses per application on the server-side and a simple editor to define such licenses (which would contain a type and the limit itself), but I would appreciate an existing, easy to integrate commercial solution. I think it could be possible to use DeployLX for this task, but I would spend a lot of money for implementing most of the solution myself (except for the editor).

Thanks in advance for any suggestions or hints.
Gene

答:
Infralution developed a (really) cheap licensing solution that includes full source code.

We used it for one of our product as a base for our own solution that had a few specific requirements like yours. I don't like their support, but the code is fine. It iss easy to extend.

I don't see how a single problem could match your requirement AND stay light and easy to implement.

OwnerDisplayName: Gene

Title: Meta-licensing of applications


问:
How to document and teach others "optimized beyond recognition" computationally intensive code?
Occasionally there is the 1% of code that is computationally intensive enough that needs the heaviest kind of low-level optimization. Examples are video processing, image processing, and all kinds of signal processing, in general.

The goals are to document, and to teach the optimization techniques, so that the code does not become unmaintainable and prone to removal by newer developers. (*)

(*) Notwithstanding the possibility that the particular optimization is completely useless in some unforeseeable future CPUs, such that the code will be deleted anyway.

Considering that software offerings (commercial or open-source) retain their competitive advantage by having the fastest code and making use of the newest CPU architecture, software writers often need to tweak their code to make it run faster while getting the same output for a certain task, whlist tolerating a small amount of rounding errors.

Typically, a software writer can keep many versions of a function as a documentation of each optimization / algorithm rewrite that takes place. How does one make these versions available for others to study their optimization techniques?

Related:

Clean readable code vs fast hard to read code. When to cross the line?

答:
Short answer

Keep optimisations local, make them obvious, document them well and make it easy to compare the optimised versions with each other and with the unoptimised version, both in terms of source code and run-time performance.

Full answer

If such optimisations really are that important to your product, then you need to know not only why the optimisations were useful before, but also provide enough information to help developers know whether they will be useful in the future.

Ideally, you need to enshrine performance testing into your build process, so you find out when new technologies invalidate old optimisations.

Remember:

The First Rule of Program Optimisation: Don't do it.

The Second Rule of Program Optimisation (for experts only!): Don't do it yet."

— Michael A. Jackson

In order to know whether now is the time requires benchmarking and testing.

As you mention, the biggest problem with highly optimised code is that it is difficult to maintain so, as far as possible, you need to keep the optimised portions separate from the unoptimised portions. Whether you do this through compile time linking, runtime virtual function calls or something in between shouldn't matter. What should matter is that when you run your tests, you want to be able to test against all of the versions you are currently interested in.

I would be inclined to build a system in such a way that the basic unoptimised version of the production code could always be used to understand the intent of the code, then build different optimised modules alongside this containing the optimised version or versions, explicitly documenting wherever the optimised version differs from the base-line. When you run your tests (unit and integration), you run it on the unoptimised version and on all current optimised modules.

Example

For instance, lets say you have a Fast Fourier Transform function. Maybe you have a basic, algorithmic implementation in fft.c and tests in fft_tests.c.

Then along comes the Pentium and you decide to implement fixed point version in fft_mmx.c using MMX instructions. Later the pentium 3 comes along and you decide to add a version which uses Streaming SIMD Extensions in fft_sse.c.

Now you want to add CUDA, so you add fft_cuda.c, but find that with the test dataset that you've been using for years, the CUDA version is slower than the SSE version! You do some analysis and end up adding a dataset that's 100 times bigger and you get the speed-up you expect, but now you know that the set-up time for using the CUDA version is significant and that with small datasets you should use an algorithm without that set-up cost.

In each of these cases you are implementing the same algorithm, all should behave in the same way, but will run with differing efficiencies and speeds on different architectures (if they will run at all). From the code point of view though, you can compare any pair of source files to find out why the same interface is implemented in different ways and usually, the easiest way will be to refer back to the original unoptimised version.

All of the same goes for a OOP implementation where a base class which implements the unoptimised algorithm, and derived classes implement different optimisations.

The important thing is to keep the same things which are the same, so that the differences are obvious.


问:
What should I learn after Python?
I am 12 years old and have mastered the basics of Python with Learn Python The Hard Way by Zed Shaw (I think) and it has done me well. What should I do next? Do you have any recommended books or good website tutorials? What do you need to know before learning C? </p>

答:
If you want to learn C (which is a good thing IMO - you learn quite much about memory management etc.), have a look at http://c.learncodethehardway.org/ - it's much better than those "hey, you never programmed but i'll teach you $language" tutorials. If you have some knowledge, start a small project you can practice on. For me it was writing an IRC bot from scratch and modifying irc services (srvx). The existing codebase of the latter made it rather easy to get started (IMO the first days/weeks of a project are the hardest and most annoying), in the from-scratch project I then implemented algorithms/data structures known from the other project on my own, improving my knowledge of them.

However, I'd suggest you to improve your Python knowledge - while having knowledge of many languages is useful, mastering a language will allow you to write better and more complex programs and in the future long-term experience with a language will most likely be useful in job applications.

Depending on what you do with Python, you might want to get started with web development - obviously with a python backend. That means learning HTML5 (stay away from w3schools.com and WYSIWYG editors!) and modern JavaScript (If a tutorial still handles netscape, it is not "modern". If a tutorial passes a string to setTimeout, it is simply bad. Having a look at jQuery is also a good thing - jQuery-based code has good chances to use modern techniques).

While very common I really suggest you to stay away from PHP! The majority of examples and tutorials about it is extremely low-quality and with PHP you risk getting used to really bad coding practices!

In case you consider learning Java (you did not mention it in the question but in the tags): If you plan studying computer science in the future chances are good that you'll have to use it at university. However, with good programming skills - which you are likely to get if you started programming at such a young age and continue with it - it will be easy to get into so I would certainly stay away from it right now. If you want to work with a high-level compiled language, better learn C#. It is similar but has lots of syntactic sugar, i.e. language elements that make the developer's life easier, and with Visual C# Express Edition Microsoft has a very good, yet free, IDE available. If you feed google with "C# for kids" you even find some books about it targeted at a young audience - depending on your knowledge they might be way too basic for you though.

Most important, however, is that you shouldn't become a pure geek/nerd at this age. Don't forget there's a real life, too. Computers and especially programming are awesome, but hanging out with friends is nice, too.

OwnerDisplayName: Shameer

Title: What should I learn after Python?


问:
Why are part-time jobs in programming an anomaly?
I've recently quit my full time developing job at mega-corp, and I decided that I'll look for a part time job. Since then I've talked to half a dozen potential employers, and every one of them had the same reaction when I said the magic words "part-time" - they all closed up and became suspicious. Now, I understand that it might just be me, so as control I asked every one of them what if I were willing to work full time, and they all said I would probably get an offer.

My question is two fold:

Why, as an employer, would you give up a competent, even great, developer, simply because he wants to work 3 days a week and not 5?

How do I sell the story of part time job better? I usually just list my reasons which are that I prefer that balance currently in my life and that I want to work on my own projects, but it leaves them even more suspicious - am I going to start something myself and quit? Am I just lazy?

答:
That's probably a form of supplier induced demand. As long as there are lots of programmers willing to dedicate their whole day (and night) time to work, there is no reason for the employer to accept any extra-effort with uncertain extra-outcomes by following uncommon employment policies.
So unless a growing fraction of developers starts recognizing the benefits of part-time employment and start demanding it from their employers, it is unlikely that these change their policy for those reasons stated in the other posts.

I think this isn't a specific programmers issue. Most employments that are traditionally assigned to the male gender are full-time by definition. Because, traditionally, men care for the cash flow and women care for the family. While women nowadays also claim to get a work-life, the male role model is yet a full-time work, spare-time private projects model.
So, up to now the emancipation of women came at the cost of the family aspect of life.
Decreasing birth rates and increasing public child care tell a story.

The point of this, the emancipation of men, that will allow men to prefer family over the job, is the next step of the emancipation of women.
To relate back to part-time programmers: this is a matter of role models and society, and not a question of what extras the employers are willing to grant to their employees.
I think in a healthy society there will be an equilibrium state where both (or all, whatever) genders are equally doing a bit of work, and a bit of family, and a bit of private projects.

Related links (to be continued):

http://www.ted.com/talks/anne_marie_slaughter_can_we_all_have_it_all


问:
What language should I use for making a cross platform library?
I want to build a SyncML parsing library (no UI) which should be able to build up messages based on information provided by the host application, fed in by the library's methods. Also, the library should to be able to do callbacks to methods in the host application.

I want to be able to compile this and have it available on as many platforms as possible: Windows, Windows Phone 7 OS, OSX, iOS, Linux, Android, BlackBerry. Basically as many platforms as possible.

The priority is to have this available on mobile devices.

Questions:

What setup should I use? (programming languages, compilers, IDE etc.)

How would I compile this library for these different platforms and how would I connect to it?

Any other info? e.g. articles that cover the subject of cross-platform development?

I haven't done this sort of a cross-platform project before, so any available information to put me in the right direction would be welcomed.

Myself, I have a background in C#/.NET and Objective-C.

答:
.NET is hardly available on many platforms, and Objective-C is even worse, plus .NET is kinda slow and ObjC has basically no support outside Apple. C as a language is basically not even worth considering unless some external factor makes you use it.

The only result viable language is C++.


问:
Is it out of line to give unsolicited constructive criticism to a programmer?
I recently started work at new office that uses a proprietary program written by a solo developer. He's occasionally around as part-time tech support, but the company has signed off on this software and he's no longer being paid to develop it.

As a user of his software there are many issues that leap out to me as a source of concern:

very simple to directly view the DB as a low-privilege user

passwords stored as plaintext

dictionary admin passwords

app uses the DB root account

DB doesn't meet 1NF (eg. appointment1, appointment2, etc.)

I feel like these are serious issues and that if I were him I'd want them pointed out to me, but I'm not a qualified programmer (I'm a social worker) and I don't know if it would be rude of me to just buttonhole him and start blabbering about salted hashes and normal forms, especially when this is no longer a paid task of his.

Is it out of line? If not, how would you broach it?

Edit - more info prompted by comments:

The application holds sensitive data.

It's for internal use, but it's running on lots of machines in several cities and many visitors come through our offices.

My concerns are for the developer's future projects as well as this specific one.

答:
What is your intent in telling the programmer that his code needs improvement?

Are you trying to get him to be a better programmer?  Then yes, you're out of line, it's not your place to tell him that his programming skills are subpar.

If your goal is to raise security concerns about the code, then yes, that can be appropriate, but not with the programmer.  Talk to whoever is in charge of the application and ask if they're interested in some concerns you have.  Do not just go and say "Hey, you know that app that maintains the records about foo?  It sucks, and here's why."  Describe the problem separate from the issues of how it got to be that way, and who did it.

Consider if you noticed that the overhead door to the warehouse was secured at night with a piece of twine.  You wouldn't say "Your security sucks, and whoever set it up is an idiot, and if you don't fix it now, you're screwed."  Even if you knew all the backstory about how it got to be that way, you'd leave all that out.

Instead, you'd say "I saw something that I thought I should point out.  I saw that the warehouse door is closed with twine, and I'm afraid that wouldn't be strong enough to keep out a determined burglar." It's entirely focused on the problem you see, and doesn't get into the drama of how it got to be that way.

And if you say "Hey, I've got security concerns" and they say "Yeah, it's OK, it's internal, it's no big deal," then let it drop.  You've done your job.


答: The most useful thing to learn is different algorithms and how different languages work. Then you can turn your hand to any language.  It is quite likely to by the time you are working full time, you could be programming a language which doesn't exist yet. I have been programming Java for 12 years.  It didn't exist until 10 years after I started programming.</p>

Title: What should I learn after Python?

Body: I am 12 years old and have mastered the basics of Python with Learn Python The Hard Way by Zed Shaw (I think) and it has done me well. What should I do next? Do you have any recommended books or good website tutorials? What do you need to know before learning C? </p>


问:
When does the "Do One Thing" paradigm become harmful?
For the sake of argument here's a sample function that prints contents of a given file line-by-line.

Version 1:

```<code>void printFile(const string & filePath) {
  fstream file(filePath, ios::in);
  string line;
  while (std::getline(file, line)) {
    cout << line << endl;
  }
}
</code>```

I know it is recommended that functions do one thing at one level of abstraction. To me, though code above does pretty much one thing and is fairly atomic.

Some books (such as Robert C. Martin's Clean Code) seem to suggest breaking the above code into separate functions.

Version 2:

```<code>void printFile(const string & filePath) {
  fstream file(filePath, ios::in);
  printLines(file);
}

void printLines(fstream & file) {
  string line;
  while (std::getline(file, line)) {
    printLine(line);
  }
}

void printLine(const string & line) {
  cout << line << endl;
}
</code>```

I understand what they want to achieve (open file / read lines / print line), but isn't it a bit of overkill?

The original version is simple and in some sense already does one thing - prints a file.

The second version will lead to a large number of really small functions which may be far less legible than the first version.

Wouldn't it be, in this case, better to have the code at one place?

At which point does the "Do One Thing" paradigm become harmful?

答:
As other posters have commented, doing one thing is a matter of scale. </p>

<p>I would also suggest that the One Thing idea is to stop people coding by side effect. This is exemplified by sequential coupling where methods have to be called in a particular order to get the 'right' result. </p>

OwnerDisplayName: Petr

Body:
As other posters have commented, doing one thing is a matter of scale.

I would also suggest that the One Thing idea is to stop people coding by side effect. This is exemplified by sequential coupling where methods have to be called in a particular order to get the 'right' result.


答:
You won't always have the platter when it comes to source code. Some people write elegant code in a manner that everyone can consume them but some write in a manner that even they can't understand it later.

Either way, you will have something to learn from. If the code is written well, you can take it into your stride or else if the code is very complicated, you will have your mind rolling to learn how this can be achieved in a better and cleaner manner.

Conclusion:- Never shy away from the code you are dealing with

Title: Reading source code to learn


问:
Is it better to use preprocessor directive or if(constant) statement?
Let's say we have a codebase that is used for many different costumers, and we have some code in it that is relevant only for costumers of type X. Is it better to use preprocessor directives to include this code only in costumer of type X, or to use if statements? To be clearer:

```<code>// some code
#if TYPE_X_COSTUMER  = 1
// do some things
#endif
// rest of the code
</code>```

or

```<code>if(TYPE_X_COSTUMER) {
    // do some things
}
</code>```

The arguments I can think about are:

Preprocessor directive results in smaller code footprint and less branches (on non-optimizing compilers)

If statements results with code that always compiles, e.g. if someone will make a mistake that will harm the irrelevant code for the project he works on, the error will still appear, and he will not corrupt the code base. Otherwise he will not be aware of the corruption.

I was always been told to prefer the usage of the processor over the usage of the preprocessor (If this is an argument at all...)

What is preferable - when talking about a code base for many different costumers?

答:
Long story short: the fears about preprocessor directives are basically 2, multiple inclusions and maybe less readable code and a more criptic logic.

If your project is small with almost no big plan for the future, i think that both options offers the same ratio between pros and cons, but if your project is going to be huge, consider something else like the writing of a separate header file if you still want to use preprocessor directives, but keep in mind that this kind of approach usually makes the code less readable and be sure that the name of that constants means something for the business logic of the program itself.


问:
Is COBOL still worth learning?
Does learning COBOL still make sense?</p>

答:
If you want to have a job as a COBOL programmer, then sure, go ahead and learn it.

For any other reason, like trying to learn something useful that might help you with modern programming techniques, no, don't bother.

Title: Is COBOL still worth learning?


答:
I think there is one advantage of using a #define that you didn't mention, and that is the fact that you can set the value on the command line (thus, set it from your one-step build script).

Other than that, it is generally better to avoid macros. They don't respect any scoping and that can cause problems. Only very dumb compilers can't optimize a condition based on a compile-time constant. I don't know if that is a concern for your product (for example it might be important to keep the code small on embedded platforms).

Title: Is it better to use preprocessor directive or if(constant) statement?

Body:
Let's say we have a codebase that is used for many different costumers, and we have some code in it that is relevant only for costumers of type X. Is it better to use preprocessor directives to include this code only in costumer of type X, or to use if statements? To be clearer:

```<code>// some code
#if TYPE_X_COSTUMER  = 1
// do some things
#endif
// rest of the code
</code>```

or

```<code>if(TYPE_X_COSTUMER) {
    // do some things
}
</code>```

The arguments I can think about are:

Preprocessor directive results in smaller code footprint and less branches (on non-optimizing compilers)

If statements results with code that always compiles, e.g. if someone will make a mistake that will harm the irrelevant code for the project he works on, the error will still appear, and he will not corrupt the code base. Otherwise he will not be aware of the corruption.

I was always been told to prefer the usage of the processor over the usage of the preprocessor (If this is an argument at all...)

What is preferable - when talking about a code base for many different costumers?


答:
It is very beneficial to read some interresting codes of my collegues. But not programs as a whole, because the most of all programs is just a boilerplate code. The best you can do, is read blogs of good programmers, because they will show you the interresting part and even tell you, why they used such a construction - you will learn to thing their way. And this the most important thing - not the code itself, but the thoughts behind it.

I think I need not to add that even better is to argue with your colleagues and friends programmers how to solve some issue - you will find many new thoughts and together you might event devise approach, which is new to both (all) of you.

Title: Reading source code to learn


问:
Handling Indirection and keeping layers of method calls, objects, and even xml files straight
How do you keep everything straight as you trace deeply into a piece of software through multiple method calls, object constructors, object factories, and even spring wiring.  I find that 4 or 5 method calls are easy to keep in my head, but once you are going to 8 or 9 calls deep it gets hard to keep track of everything.  Are there strategies for keeping everything straight?

In particular, I might be looking for how to do task x, but then as I trace down (or up) I lose track of that goal, or I find multiple layers need changes, but then I lose track of which changes as I trace all the way down.  Or I have tentative plans that I find out are not valid but then during the tracing I forget that the plan is invalid and try to consider the same plan all over again killing time....

Is there software that might be able to help out?  grep and even eclipse can help me to do the actual tracing from a call to the definition but I'm more worried about keeping track of everything including the de-facto plan for what has to change (which might vary as you go down/up and realize the prior plan was poor).

In the past I have dealt with a few big methods that you trace and pretty much can figure out what is going on within a few calls.  But now there are dozens of really tiny methods, many just a single call to another method/constructor and it is hard to keep track of them all.

答:
If you have your project covered by unit tests and integration test, you shouldn't need to hold the whole picture in your mind.

Using test-driven development and XP practices - well named methods (semantic names), you should work easily at each level of abstraction.

In case you need add new functionality to your project, you simply write new test and try to get that test working as quickly as possible. If there is no possibility to add the functionality (for some structural reason - unaccessible extension points...), refactor your code (repeatedly check your changes don't brake the code running your test suite).

Try to give your test cases semantic names:

```<code>@Test
public void shouldReturnSumOfSuppliedNumbers() {
     // test code here
}
</code>```

will give you more information than:

```<code>@Test
public testSum() {
     // test code here
}
</code>```

Body:
If you have your project covered by unit tests and integration test, you shouldn't need to hold the whole picture in your mind.

Using test-driven development and XP practices - well named methods (semantic names), you should work easily at each level of abstraction.

In case you need add new functionality to your project, you simply write new test and try to get that test working as quickly as possible. If there is no possibility to add the functionality (for some structural reason - unaccessible extension points...), refactor your code (repeatedly check your changes don't brake the code running your test suite).

Try to give your test cases semantic names:

@Test
public void shouldReturnSumOfSuppliedNumbers() {
     // test code here
}

will give you more information than:

@Test
public testSum() {
     // test code here
}


答:
Do your customers have access to your code? If yes, then preprocessor could be a better option.
We have something similar and we use compile time flags for various customer (or customer specific features). Then a script could extract customer specific code and we ship that code. The customers are not aware of other customers or other customer specific features.</p>


问:
The equivalent of a "Memorandum of Understanding" for programmers?
When one business acquires another, they use a Memorandum of Understanding, which is basically an agreement outlining the duties of each party, etc.

I am about to begin a massive web development project for a client - What is the equivalent agreement I would use with them?

答:
There are basically two types of contracts between a service provider and a client :-

Service Contract : Also sometimes referred as service-level agreement (SLA) is an agreement in which the level of service is formally defined. In practice, the term SLA is sometimes used to refer to the contracted delivery time (of the service) or performance. As an example, software providers will commonly include service level agreements within the terms of their contracts with customers to define the level(s) of service/product being provided in plain language terms.

Non-Disclosure Agreement(NDA) (This is optional) confidentiality agreement (CA), confidential disclosure agreement (CDA), proprietary information agreement (PIA), or secrecy agreement, is a legal contract between at least two parties that outlines confidential material, knowledge, or information that the parties wish to share with one another for certain purposes, but wish to restrict access to or by third parties.

OwnerDisplayName: RD.


问:
Move a player to another team, with players stored in one arraylist and teams in another using java
Basically I have a team class, which has an array list that store the players in. In the driver class there's an arraylist that stores the teams.

Anyhow I've worked out how to add a player to a specific team and likewise remove a player from said team. Where I'm hitting problems is when I try to transfer one player to another.

My understanding is to scan through the first team, and get the player. Then somehow add this player to another, by scanning through the chosen team and add to it?

I've tried this way but it seems to replace the original player with the new player in both teams.

My other approach would be to somehow return the parameters of the player object, create another with the return parameters, remove the original then add the new instance in the other team?

Really not quite generally how I can go about this, been trying all afternoon!

If someone could offer me a general idea, then I can go off and apply the understanding to practice.

答:
ArrayList has methods to find the location of an object, remove an object and add an object. As far as I can see, your question can be solved like this:

```<code>Given an object (or team player in question)
    1. Find the location (indexOf) of that object in first ArrayList
    2. Remove it from there (remove) and store the returned object
    3. Add it in the second ArrayList (add)
</code>```

where the terms in the brackets are the methods from ArrayList APIs which you can find here and figure out the arguments which they take.

Hope that's what you meant.

Body:
ArrayList has methods to find the location of an object, remove an object and add an object. As far as I can see, your question can be solved like this:

Given an object (or team player in question)
    1. Find the location (indexOf) of that object in first ArrayList
    2. Remove it from there (remove) and store the returned object
    3. Add it in the second ArrayList (add)

where the terms in the brackets are the methods from ArrayList APIs which you can find here and figure out the arguments which they take.

Hope that's what you meant.

OwnerDisplayName: Salil


答:
Great question.

There's some good answers hereabouts too, but overwhelmingly they appear to be taking the employers' perspective, so let me redress that a little.

Firstly, I think it is great that you are wanting to take a better work/life balance than an ordinary 9-6 job will offer you. We who live in advanced capitalist economies often need reminding that our society has created a 'normal' workaholism that takes from most people most of their useful waking hours. You may therefore need a bit of encouragement in your quest, and I would start with recommending How to Be Idle by Tom Hodgkinson. In it he argues for a de-stressed society that lives cheaply, works less, makes more merriment and relies less on expensive/pre-packaged food and entertainment (I believe his How To Be Free is on similar lines, and I forget which one it was that I have read).

I'd also say that you shouldn't mention your part-time intentions until you've got through first-stage interview. You can then ask at second stage interview, or via email/telephone contact, if your application progresses.

Consider also only asking for four days/week. For some reason, I sense there is quite a gulf between three and four - maybe because Friday tends to be a wind-down day, and a good programmer cannot be expected to run at full productivity five days a week anyway. So I think you'd be more likely to get a nod if you start asking small.

Also, would you consider taking a flexitime job on with full-time hours? That would be nine-ish hours per day rather than seven-ish, but would mean that your employer gets the benefit of a full-time developer whilst giving you the win you're after. That of course presumes you'd be happy with just one extra day off per week. Incidentally, some while back I noticed a tasty-looking advert on StackExchange for a four-day week dev based in San Francisco - so they are out there (edit: I wanted to link to it but cannot find it - it is probably gone!).

That last point brings me to my next one: apply to small companies or start-ups. Small firms don't often have the budget to pay good developers handsomely, so they may offer non-remuneration benefits instead. Also, there are less layers of middle-management to get unusual requests rubber-stamped.

My path has been somewhat similar to yours - I used to work for a large company as a PHP/Oracle web programmer, and they insisted on my commuting to the office every day, resulting in 300 miles per week of pointless mileage. I requested flexitime and home-working at various strategic points (reviews and the like) and they were repeatedly "considered" and turned down. I enjoyed the job and the people, but a couple of years later, I gave up asking, found a small UK company that offered both flexitime and telecommuting, and resigned from the corporate job. It is my hope that in leaving over it, I have very slightly improved the chances of others who want to do the same.

So, I wish you the best of luck - if you are successful in this endeavour, you also may help out other developers who feel the same as you do. If you get there, do document somewhere on the web some tips to help others!

Edits: an interesting article and comments on this topic, and another from 37signals. Here is how companies can set up four-day working weeks. Less on-topic but very interesting - remote working by the chap who set up this very website!

Title: Why are part-time jobs in programming an anomaly?

Body:
I've recently quit my full time developing job at mega-corp, and I decided that I'll look for a part time job. Since then I've talked to half a dozen potential employers, and every one of them had the same reaction when I said the magic words "part-time" - they all closed up and became suspicious. Now, I understand that it might just be me, so as control I asked every one of them what if I were willing to work full time, and they all said I would probably get an offer.

My question is two fold:

Why, as an employer, would you give up a competent, even great, developer, simply because he wants to work 3 days a week and not 5?

How do I sell the story of part time job better? I usually just list my reasons which are that I prefer that balance currently in my life and that I want to work on my own projects, but it leaves them even more suspicious - am I going to start something myself and quit? Am I just lazy?


答:
As for many questions, the answer of this question is it depends. Instead of saying which is better i have rather given examples and goals where a one is better than other.

Both preprocessor and constant have their own places of appropriate usage.

In case of pre-processor, the code is removed before the compile time. Hence, it is best suited for situations where code is expected not be compiled. This can affect the module structure, dependencies, and it may allow selecting best code segments for performance aspects. In following cases, one must divide code by use of preprocessor only.

Multi-platform code:

For example, when code is compiled under different platforms, when code has dependency on specific version numbers of OS (or even the compiler version - though this is very rare). For example when you are dealing with little-endien big-endien counterparts of code - they must be segregated with preprocessors rather than constants. Or if you are compiling code for Windows as well Linux and certain system calls are very different.

Experimental Patches:

Another case where this makes is to have a justified is some experimental code which is risky or certain major modules that needs to be omitted which will have significant linking or performance difference. The reason why one would want to disable the code via preprocessor rather than hiding under if() is because we might not be sure of bugs introduced by this specific change set and we are running under experimental basis. If it fails, we must do nothing else but disable that code in production than rewrite. Some time it is ideal to use #if 0  to comment out the entire code.

Dealing with dependencies:

Another reason where you may want to generate For example, if you don't want to support JPEG images, you can help get rid of compiling that module/stub and eventually library will not (statically or dynamically) link to that module. Sometimes packages run ./configure to identify availability of such dependency and if libraries are not present, (or user doesn't want to enable) such functionality is disabled automatically without linking with that library. Here it is always beneficial if these directives are auto generated.

Licensing:

One very interesting of example of preprocessor directive is ffmpeg. It has codecs which can potentially infringe patents by its use. If you download the source and compile to install, it asks you if you want or keep away such stuff.
Keeping codes hidden under some if conditions still can land you in court!

Code copy-paste:

A.k.a macros. This is not an advice to over use macros - just that macros have much more powerful way to apply copy-past equivalent. But use it with great care; and use it if you know what you are doing. Constants of course, cannot do this. But one can use inline functions as well if that is easy to do.

So when do you use constants?

Almost everywhere else.

Neater code flow:

In general, when you use constants, it is almost indistinguishable from regular variables and hence, it is better readable code. If you write routine that is 75 lines- have 3 or 4 lines after every 10 lines with #ifdef is VERY unable to read. Probably given a primary constant governed by #ifdef, and use it in a natural flow every where.

Well indented code:
All preprocessor directive, never work well with otherwise well indented code. Even if your compiler does allow indentation of #def, Pre-ANSI C preprocessor did not allow for space between the start of a line and the "#" character; the leading "#" had to always be placed in the first column.

Configuration:

Another reason why constants/ or variables make sense is that they can easily evolve from being either linked to globals or in future can be extended to be derived from configuration files.

One last thing:

Never USE preprocessor directives #ifdef to #endif
crossing the scope or { ... }. i.e. start of #ifdef or end of #endif on different sides of { ... }. This is extremely bad; it can be confusing, it can be sometime dangerous.

This of course, is not an exhaustive list, but shows you stark difference, where which method is more apt to use. It is not really about which is better, it is alway more of which one is more natural to use in given context.


答:
I have a special section on my CV that shows potential employers that I communicate effectively and work well with others. The section before that lists my involvement / accomplishments in various free/open source projects.

You need something to show that you not only know what you're doing, but can get along well with a team of your peers. While yes, you can articulate this in an interview, you need to help make sure that you actually get the call in the first place.

A number of people maintain that a reasonably high reputation score on Stack Overflow generally shows that you are not only knowledgeable, but also an effective communicator.

I have found many cases where this theory is directly contradicted. There are more than a few people on SO that have 12k + reputation and are consistently and incredibly rude.

When I hire someone, I do ask if they read blogs, participate on programming related web sites, etc and I generally research their participation on whatever they mention.

A more 'general' synopsis of spare time activities is better, for instance:

Regular participant on the Stack Overflow Q&A Site

Regular editor of CS related articles on Wikipedia

Member of the League For Programming Freedom

Contributing / Voting member of Software In The Public Interest

Founder of Programmers For The Ethical Treatment Of Unicorns (PETU)

Just show the hiring manager that you actually enjoy programming so much that you do it in your spare time and that you get along with others. There's no reason to draw attention to a single activity just because it features a numerical score.

Title: Would you put your Stack Overflow profile link on your CV / Resume?

Body:
If applying for a new job, would you put your Stack Overflow profile link on your resume?

This would show the employer you're an active member of the development community and also provide an insight into your knowledge + how well you convey your ideas.

However it would feel a bit gimmicky to me?


问:
Why is trailing whitespace a big deal?
Trailing whitespace is enough of a problem for programmers that editors like Emacs have special functions that highlight it or get rid of it automatically, and many coding standards require you to eliminate all instances of it. I'm not entirely sure why though. I can think of one practical reason of avoiding unnecessary whitespace, and it is that if people are not careful about avoiding it, then they might change it in between commits, and then we get diffs polluted with seemingly unchanged lines, just because someone removed or added a space.

This already sounds like a pretty good reason to avoid it, but I do want to see if there's more to it than that. So, why is trailing whitespace such a big deal?

答:
Reasons that it's important to me:

When I hit the "End" key, I expect the cursor to go to the end of the line (depending what editor I'm using and how it's configured) and I expect to be able to start typing right away. If the cursor gets there and I have to delete 3 or 4 characters, it's annoying. Especially if it's inconsistent throughout the file(s).

When I have string literals that span multiple lines, trailing whitespace can make the output string look incorrect when it's used.

While not strictly programming, whitespace can seriously mess up data entry, if there's trailing/leading in a file that will be parsed and used as input to something else. This happens the most when a clean, generated input file gets dirtied by someone editing it in Excel or something and then trailing whitespace (and other formatting issueS) can creep in.

Title: Why is trailing whitespace a big deal?


答:
I recently spent a day looking for a bug that turned out to be an unexpected trailing
whitespace in data.</p>

Title: Why is trailing whitespace a big deal?

Body:
Trailing whitespace is enough of a problem for programmers that editors like Emacs have special functions that highlight it or get rid of it automatically, and many coding standards require you to eliminate all instances of it. I'm not entirely sure why though. I can think of one practical reason of avoiding unnecessary whitespace, and it is that if people are not careful about avoiding it, then they might change it in between commits, and then we get diffs polluted with seemingly unchanged lines, just because someone removed or added a space.

This already sounds like a pretty good reason to avoid it, but I do want to see if there's more to it than that. So, why is trailing whitespace such a big deal?


答:
You may think of yourself as a programmer who wants to work 3/5 of a week. If you are applying for jobs at a company large enough to have a HR department then here are a few of your problems:

It's a tight market and you are responding to a full-time position with a counter-offer for part-time work. Resumes are being thrown away for lack of "optional" requirements and you just wasted their time by interviewing for a job (full-time) that you didn't intend to take. From their point of view - you lied.

As previously mentioned they have a 1.0 programming unit requirement and you are 0.6 programming unit - bad fit.

If they hire full-time employees and full-time contractors you don't fit HR systems - payroll, insurance eligibility, real estate (do you get 3/5 of a desk? do they waste 2/5 of a desk?).

From the manager's point of view you are just as big a headache - dress code, email appropriateness, late arrivals, sexual harassment - as everyone who is doing 166% of the work you do.

The previous comments about project complexity (and things like company limits on the number of direct reports) hold true. Imagine a project that requires 1 developer. Now imagine running that project with five 1/5 developers. It's an exaggeration but it points up the issue.

If the ad or referrer doesn't say "part-time", don't bother. You're wasting everyone's time. You might consider a serial part-time career. Work for nine months then take three off. You'll need to find something to put on your resume to cover the three months though.


答:
When I select program source code in order to copy and paste it (or delete it) I find it a bit annoying to see all the irregular extra white space at the end of lines: since I have to read the code while I am selecting it, the trailing white space is an unneeded noise. Example (dots represent the white space):

```<code>if (fp)........
{....
    fclose(fp);.
}
else
{.....
    prinft("File is NULL\n");
}..
</code>```

This example is artificial, but I have seen a lot of code that looks like this.

Title: Why is trailing whitespace a big deal?

Body:
When I select program source code in order to copy and paste it (or delete it) I find it a bit annoying to see all the irregular extra white space at the end of lines: since I have to read the code while I am selecting it, the trailing white space is an unneeded noise. Example (dots represent the white space):

if (fp)........
{....
    fclose(fp);.
}
else
{.....
    prinft("File is NULL\n");
}..

This example is artificial, but I have seen a lot of code that looks like this.


答:
I really hate trailing whitespace, but the exact reason is a bit vague.

I guess the origin of that feeling is not in programming, but in the desktop publishing field. Have you ever got a document typed by someone else that needed to be typeset into a publication? In all modern publications, especially when using columns, it is custom to have sentences follow each other sequentially within one paragraph, not starting a new line for each sentence. Well, when there is trailing whitespace, it takes a lot more effort to get it right (lots of search and replace actions that eliminate double spaces, etc...).

Other reasons (in programming), not good reasons, I know, but they bother my subconscious psyche in such aggravating intense manner that they compel me to eliminate it:

It takes more storage space than necessary

The parser will have to skip an extra character for no good reason when compiling

Some editors might add an extra blank line when WordWrap is on and the
trailing space doesn't fit

Yes, yes I know! I know, these are junk reasons. I'm not a perfectionist, but... well maybe I am?

The last reason I can think of is inconsistent cursor movement. It feels like the cursor is hanging in thin air at the end of a line, every step to the right may cause it to either drop or to hover further to an unknown extent, it just feels unsteady (like those invisible or disappearing blocks that Super Mario used to jump on).

Probably I can be diagnosed with trailspacefobia?

Title: Why is trailing whitespace a big deal?

ContentLicense: CC BY-SA 4.0


答: You might want to try Java - Java Runtime Environment (the virtual machine) is cross platform, Java may be used in mobile devices with Android (or with Java ME) and .NET is very simillar to it.</p>

Title: What language should I use for making a cross platform library?

Body:
I want to build a SyncML parsing library (no UI) which should be able to build up messages based on information provided by the host application, fed in by the library's methods. Also, the library should to be able to do callbacks to methods in the host application.

I want to be able to compile this and have it available on as many platforms as possible: Windows, Windows Phone 7 OS, OSX, iOS, Linux, Android, BlackBerry. Basically as many platforms as possible.

The priority is to have this available on mobile devices.

Questions:

What setup should I use? (programming languages, compilers, IDE etc.)

How would I compile this library for these different platforms and how would I connect to it?

Any other info? e.g. articles that cover the subject of cross-platform development?

I haven't done this sort of a cross-platform project before, so any available information to put me in the right direction would be welcomed.

Myself, I have a background in C#/.NET and Objective-C.


答:
This is not one choice but many. While it is tempting to find one thing that goes everywhere, it is not always the best way to do.

For example, while it may be possible to squeeze a C++ code in Windows mobile platform, anything .NET will always be easier here than its' counter part from the point of view of support.

Similarly, one needs to make a major choice whether you want it to be native or under run time and are you strictly limited to Web centric or more generic powerful one? For example, Adobe Runtime is more omnipresent but it will limit to what you can do compared to with core programming languages.

Most important thing i guess, is the type and level of GUI you want to built.

Now comming to most promissing choices.

a.  For Symbian, Blackberry, Android, BREW and Bada (samsung) Java/J2ME is the commonest way. Though, you might be better of with C/C++ in many cases, for native core stuff in some platform.

b. For Windows .NET with any supported language would be good.

c. For iOS - there is no choice but Objective C. This is NOT very much C++ so i won't count it as a objective

Here is a wiki reference which shows set of all platforms that shows you all options and where they apply.

Thanks to your question, i learned from the above wiki link that there are now SDKs, that try to solve above problem. The two that comes closest are:

Marmalade : http://www.madewithmarmalade.com/marmalade/supported-platforms
this interestingly support almost all platforms. Windows is just about getting added to make complete circle.

Particle Code : http://www.particlecode.com/

I have not used them yet, but sounds interesting work.


问:
PHP rand function (or not so rand)
I was testing PHP rand function to write on a image. Of course the output shows that it's not so random. The code I used:

```<code><?php
header('Content-Type: image/png');
$lenght = 512;
$im = imagecreatetruecolor($lenght, $lenght);
$blue = imagecolorallocate($im, 0, 255, 255);
for ($y = 0; $y < $lenght; $y++) {
    for ($x = 0; $x < $lenght; $x++) {
        if (rand(0,1) == 0) {
            imagesetpixel($im, $x, $y, $blue);
        }
    }
}
imagepng($im);
imagedestroy($im);
?>
</code>```

My question is, if I use image width/lenght (variable $lenght in this example) number like 512, 256 or 1024, it is very clear that it's not so random. When I change the variable to 513 for an example, it is so much harder for human eye to detect it. Why is that? What is so special about these numbers?

512:

513:

Edit: I'm running xampp on Windows to test it.

答:
This is a known bug which isn't related to PHP, but inherant to the windows API used by PHP. The random function of this API is very bad.

This problem will not exist on Linux or MacOS (or any other system).

You can learn more about this here: http://cod.ifies.com/2008/05/php-rand01-on-windows-openssl-rand-on.html

If it is more visible with some value, this is mostly because of the dimensions of the image, and the clear lines formed by the pattern. This is definitively linked to our perception, some patterns looks more random than others.

The human brain random function is very buggy. What we see as random or not isn't reliable at all. This is a known phenomenon but off topic here.

Title: PHP rand function (or not so rand)


问:
How do you avoid name similarities between your classes and the native ones?
I just ran into an "interesting problem", which I would like your opinion about:

I am developing a system and for many reasons (meaning: abstraction, technology independence, etc) we create our own types for exchanging information.

For instance: if there is a method which is called SendEmail and is invoked by the business logic, it way have a parameter of type OurCompany.EMailMessage, which is an object which is completely technology independent and contains only "business relevant data" (for instance, no information abut head encoding).

Inside the SendEmail function, we get this information from our EMailMEssage object and create a MailMessage (this one is technolgy specific) object so it can be sent over the network.

As you can already notice, our class has a very similar name to the "native" language class. The problem is: this is exactly what they are, email messages, so it is hard to find another meaningful name for them.

Do you have this problem often? How do you manage it?

Edit: @mgkrebbs just commented about using fully qualified names. This is our current approach, but a little bit too verbose, IMHO. I would like something cleaner, if possible.

答:
Do you have this problem often? How do you manage it?

It really depends on the language you use. In c++ and java, this problem is solved by using namespaces. I am using c++, and it happens that I got different classes with the same name. It's not a problem, since they are in different namespaces.

In other languages, there are no ways around but providing different names.


答:
This is a problem about the namespace you are going to use for your project.

Basically a namespace is the collection of the keywords provided by all your classes and/or all the classes you want to use in your project ( including the standard classes usually provided with the language/compiler/IDE ).

Since a namespace is a collection, some basically rules are applied to prevent the making of a mess of terms without any related behaviour, and some languages like the C# also allows you to define your own namespace as usually and also use it in other classes.

Do not confuse the namespace with the basic keyword of the language, they are both a collection of keywords but with a big difference between the two: you can modify a namespace but you usally can't modify the basic keywords of a language.
The sum between the namespace you have used in your project and the basic keywords of the language you use gives you the total amount of keywords.

The topic is heavily discussed on the net, i can suggest a basic search with the terms "namespace [your language]" o something like that.
I'm not directly answering your question simply because you can have different approach for different languages.

Title: How do you avoid name similarities between your classes and the native ones?

Body:
I just ran into an "interesting problem", which I would like your opinion about:

I am developing a system and for many reasons (meaning: abstraction, technology independence, etc) we create our own types for exchanging information.

For instance: if there is a method which is called SendEmail and is invoked by the business logic, it way have a parameter of type OurCompany.EMailMessage, which is an object which is completely technology independent and contains only "business relevant data" (for instance, no information abut head encoding).

Inside the SendEmail function, we get this information from our EMailMEssage object and create a MailMessage (this one is technolgy specific) object so it can be sent over the network.

As you can already notice, our class has a very similar name to the "native" language class. The problem is: this is exactly what they are, email messages, so it is hard to find another meaningful name for them.

Do you have this problem often? How do you manage it?

Edit: @mgkrebbs just commented about using fully qualified names. This is our current approach, but a little bit too verbose, IMHO. I would like something cleaner, if possible.


答:
Well my old development team use to append the acronym of the application in each customized class. We had for example ABCEmail class.

I think it is more straightforward than relying on namespace but can be also a complementary solution to the usage of the namespace.

Last but not least, since you are creating a new object, it means that the native object does not answer your needs so your name of your Email File could be CustomizedEmail, AdvancedEmail ...etc


答:
You haven't specified the sector you're looking in, but I suspect there's two main reasons:

Suspicion about what you're doing the rest of the time (are you there to steal data, ideas, or other intellectual property (IP))

Concerns that other employees will also want to work part-time (and the difficulty of denying parity)

There is a per-employee overhead in any business, and whilst one part-time postion may not break the bank, the overhead from a 20-person team turning into a 40-person team could be prohibitive (if no more hours are being worked) - there'd also be additional management costs coordinating such an environment.


问:
Use open-source programs in your company?
Is there any cons of making your employees use open-source programs in your company?

I am planning to start a bussiness and I wonder why companies usually work with proprietary software, as Microsoft Word to quote the most famous one. Why do not they use Open Office (or Libre Office) etc.?

From my point of view, you can save a lot of money and help the open-source community by, for instance, giving them part of your benefits in form of donations.

I do not know any (medium-big) company that does this. Probably you could give me some examples, just to prove that this model of open-source usage/collaboration works rocks.

答:
I love FOSS, but be honest - it's a mere child's play! There are so many small but annoying bugs in it, that's absolutely unbelievable. Take what you want: Gnome, OpenOffice, Firefox, ... it doesn't matter. Instead of improving the software, they add more and more features. It's the same silly strategy as with closed source.
In fact, the question is not "either or", but "as well as". You can have both worlds on one computer on one screen. I use VirtualBox. It's great. You can have a Linux application in one window and a Windows application in an other window on the same screen. Even cut and paste between the applications works. Also hardware access is absolutely no problem. Forget dual-boot. That's not the solution. Try virtualization instead and chose the program that suites the task at hand best. A well-equipped up-to-date machine is sufficient to work fluently. </p>


问:
Would you put your Stack Overflow profile link on your CV / Resume?
If applying for a new job, would you put your Stack Overflow profile link on your resume?

This would show the employer you're an active member of the development community and also provide an insight into your knowledge + how well you convey your ideas.

However it would feel a bit gimmicky to me?

答:
I haven't yet put my profile on my CV, mostly because I haven't thought of it while updating. It seems though that it's consistently quite high in google searches on my name, so people in the know will have no problem being led towards it.

PS. I just created my stackexchange.com profile, have had my stackoverflow.com profile for a few years.

OwnerDisplayName: avocade


问:
Reading source code to learn
As you develop as a programmer, software developer, or coder, IMHO, you begin to see different (best or worst) practices, different algorithms, and "more than one way to do it". Seeing this code can be a great learning experience for you, even though you did not write the code. But is doing this only going to confuse you?

For example, let's say you have a library in any language that was created by a colleague, and you have been using it for a while. You decide to look at the actual source code, regardless of how extensive it is, and get a better look at how this library is written. For the sake of example, the function you use most often from this library is the max function, which finds the largest of two numbers. But this function is a lot more complicated than it needs to be. The way it is written is confusing the heck out of you, and you don't know how this works.

Will this make you a better programmer, because you realize how complicated it is for such a simple function, or will it make you a worse coder because you feel less confidant?

So my question, in general, is does reading source code make you a better programmer and if so how? If not why do people still do it?.

答:
Reading source code is difficult for many people. It takes large amount of effort to learn to do it properly so that you ignore the irrelevant details, and concentrate on the important stuff. The time frame for learning this stuff is like 10-20 years. You can't expect people who have written code for short amount of time to know how to read code properly.

On the other hand, it's a skill that can be learned. It requires concentrated effort during several years to learn to do it. It does help tremendously once you learn it. It's like finding problems in the code that were completely impossible to find before -- sometimes even finds problems in modules which you have never even seen the code.

Title: Reading source code to learn


问:
Is reference to bug/issue in commit message considered good practice?
I'm working on a project where we have the source control set up to automatically write notes in the bug tracker. We simply write the bug issue ID in the commit message and the commit message is added as a note to the bug tracker.

I can see only a few downsides for this practice. If sometime in the future the source code gets separated from the bug tracking software (or the reported bugs/issues are somehow lost). Or when someone is looking in the history of commits but doesn't have access to our bug tracker.

My question is if having a bug/issue reference in the commit message is considered good practice? Are there some other downsides?

答:
We have adopted this practice and it works very well for us. The tight integration between version control system (VCS) and other systems we use, e.g. continuous integration, bug tracker, etc. is extremely valuable. If we ever change anything in the future we certainly will have to assess the side effects, including the links between the VCS and bug tracking system.

In general I would see this as good practice. For some tracking systems there are additional options and tools available, for example bugtraq properties for Subversion (SVN). This suggests that quite a few people see value in this practice.


答:
Your question is very good. How about if you prefix your method with a prefix such as U (or u) or cls (short for class)? For examples:

clsEMailMEssage
or
uEMailMEssage

This does not require a lot of typing and you could immediately tell that the type is 'yours'.

Edit - In response of the first 2 comments:

I would like to point the reader's attention to the fact that: Not all Hungarian notations are created equal. We should distinguish between System Hungarian and Apps Hungarian, I assume that the suggestion above follows the Apps Hungarian type, which is not harmful.

The harm associated with System Hungarian notation such as in naming an ID an intID is not present in the above suggestion.

For more on this, have a look at: Making Wrong Code Look Wrong - Joel On Software


问:
Local versioning system especially designed for documents
I have to work on some docs, I need a software that can trace all the modifications that I will make to a specific file or project (group of files): is there something like that?

The important thing is that I have to do that with a single machine so I do not need a distributed solution, I only have to work with txt files with UTF-8 charset and pdf files.

答:
You can use a DVCS anyway.

DVCS works great with a local repository that stays only on your local machine.

 You don't have to distribute, i.e. push or pull to or from other machines.

EDIT:

The most known and used DVCS are Git (as already suggested in the accepted answer) and Mercurial.


答:
I use git to track my local files.

```<code>git init .
git add myfile1.txt myfile2.txt
git commit -m "Added first two files"
...
</code>```

You can track everything on your local repo without needing an external one.

Title: Local versioning system especially designed for documents

Body:
I have to work on some docs, I need a software that can trace all the modifications that I will make to a specific file or project (group of files): is there something like that?

The important thing is that I have to do that with a single machine so I do not need a distributed solution, I only have to work with txt files with UTF-8 charset and pdf files.

Body:
I use git to track my local files.

git init .
git add myfile1.txt myfile2.txt
git commit -m "Added first two files"
...

You can track everything on your local repo without needing an external one.


答:
This is very common practice, and I have found it extremely convenient.  I use TRAC, so I can read the code history and navigate to the task that drove the change, or read the task history and navigate to the code changes.  </p>

<p>"If sometime in the future..."  If you separate the code from the bug tracker, then the old revision history probably won't be of further interest.</p>

Title: Is reference to bug/issue in commit message considered good practice?

Body:
I'm working on a project where we have the source control set up to automatically write notes in the bug tracker. We simply write the bug issue ID in the commit message and the commit message is added as a note to the bug tracker.

I can see only a few downsides for this practice. If sometime in the future the source code gets separated from the bug tracking software (or the reported bugs/issues are somehow lost). Or when someone is looking in the history of commits but doesn't have access to our bug tracker.

My question is if having a bug/issue reference in the commit message is considered good practice? Are there some other downsides?

Body:
This is very common practice, and I have found it extremely convenient.  I use TRAC, so I can read the code history and navigate to the task that drove the change, or read the task history and navigate to the code changes.

"If sometime in the future..."  If you separate the code from the bug tracker, then the old revision history probably won't be of further interest.


答:
If you want to make really, really sure that no information is lost even if you may use a different bug tracker in the future or your bug tracker data somehow disappears, why not just put both the issue ID and a short explanation about the bug into the commit message?

Fix bug #123: app crashed after login

Then you still have the link from the history of commits to the bug tracker - and if the bug tracker should ever be not available, you can still see in the history what this particular bug was about.


答:
Think about the kinds of problem domains you want to work in.  Typically those domains have a set of languages that are generally used for the purpose.  If COBOL matches that then go ahead.

There is no way I would touch either cobol or the problem domain(s) that use it heavily with a 10 foot pole.  I'd rather flip burgers.

Also consider if the language offers some bonus/improvment to your programming ability/concepts.  I can't think of anything COBOL can do/implements/features that isn't done better or can be demonstrated better in another language.

You and others may feel differently.

Title: Is COBOL still worth learning?

Body: Does learning COBOL still make sense?</p>


答: I use this practice too and I consider it a very good one. But besides the issue ID, I add a short description of the bug / feature (usually the title from the bug tracking system). This often helps save time because I don't have to lookup in the bug tracking system (beacuse I recognise the change) AND, like you said, if somehow I lose the bug tracking system, I'm not completly lost.</p>