答:
Here are some things I've done, or have seen done:

Store as much as you can in remote repositories. Git/Mercurial/Subversion is your friend in this aspect. You can make anything a repository, and with services like Github, you can store everything, including config files, in remote repositories. Doing this gives you a central location from which to sync to and pull from (just make sure you push your latest stuff before switching machines). If you run Linux, you can probably repo your entire /home directory.

If you don't want to use repo storage services, store everything on a USB storage device. Large thumb drives, and USB hard drives are pretty cheap these days, so if you don't want to/can't use a third party storage system, then pick one up, just don't forget to take it with you!

Use software with config files and find those files so you can copy them (and don't forget your OS's configs). This may or may not be feasible, depending on what you do, but it's a very good idea to check to see if your software does. Copying config files is easier than trying to manually set up the configuration between the two machines. This is great even for utilities and OS configs, such as .bashrc for terminal, if you're not using default settings.

Use software that has a per-user, instead of per-install license. If you're not using free/open source software (Eclipse, Netbeans, etc), try to go for stuff that uses a per-user license model (such as Sublime Text). This will avoid the headache of dealing with software on multiple machines and staying kosher regarding licenses.

Use web-based tools when feasible. Things like Freshbooks, Harvest, Basecamp, and Google Apps help remove the headaches caused by multiple machines by removing the local machine to begin with (save for having a browser to access them).

Leverage your browser's syncing tools. Most, if not all, of the major browsers have syncing tools that allow you to sync your bookmarks, history, passwords, etc. between your computers (and the ones that don't very likely have addons that can). This is a huge asset, so don't be afraid to make use of it.

Script what you can. Scripting things like the download and install of your software can both speed up setup and help you not forget anything. It also helps as a "start it and forget it" type of thing, so you can do other things while the script handles the legwork of downloading and installing your software. (Note: this is very likely quite a bit easier on Linux machines, since most of your software will be in repos most likely, but it is doable on any OS, as long as you can get the installers via a commandline downloader such as curl or wget.)

Title: Productivity strategies for one developer using many PCs

Body:
In a talk about time management, a famous computer scientist said:

"One machine in your life is the right number."

He recommended a laptop with a docking station.

After trying this approach for about a month, I miss my more powerful desktop (i7 quad core hyperthread), but it is not in my technology road map (or budget) to upgrade from my old Intel Core 2 Duo (2006) notebook this year.

What strategies can help me use the desktop while at my desk and without much manual effort the notebook when I am on the go?


问:
Should I continue my self-taught coding practice or learn how to do coding professionally?
Lately I've been getting professional work, hanging out with other programmers, and making friends in the industry. The only thing is I'm 100% self-taught. It's caused my style to extremely deviate from the style of those that are properly trained. It's the techniques and organization of my code that's different.

It's a mixture of several things I do. I tend to blend several programming paradigms together. Like Functional and OO. I lean to the Functional side more than OO, but I see the use of OO when something would make more sense as an abstract entity. Like a game object. Next I also go the simple route when doing something. When in contrast, it seems like sometimes the code I see from professional programmers is complicated for the sake of it! I use lots of closures. And lastly, I'm not the best commenter. I find it easier just to read through my code than reading the comment. And most cases I just end up reading the code even if there are comments. Plus I've been told that, because of how simply I write my code, it's very easy to read it.

I hear professionally trained programmers go on and on about things like unit tests. Something I've never used before so I haven't even the faintest idea of what they are or how they work. Lots and lots of underscores "_", which aren't really my taste. Most of the techniques I use are straight from me, or a few books I've read. Don't know anything about MVC, I've heard a lot about it though with things like backbone.js. I think it's a way to organize an application. It just confuses me though because by now I've made my own organizational structures.

It's a bit of a pain. I can't use template applications at all when learning something new like with Ubuntu's Quickly. I have trouble understanding code that I can tell is from someone trained. Complete OO programming really leaves a bad taste in my mouth, yet that seems to be what EVERYONE else is strictly using.

It's left me not that confident in the look of my code, or wondering whether I'll cause sparks when joining a company or maybe contributing to open source projects. In fact I'm rather scared of the fact that people will eventually be checking out my code. Is this just something normal any programmer goes through or should I really look to change up my techniques?

答:
The advice given is quite useful, but I try to remember that my primary goal is to create 'working software' that is useful to my users.  My audience is usually NOT a group of programmers -- they are business people that are willing pay money for an automated solution (Users don't care about OO Methodologies, Frameworks, Unit Tests, code comments, etc. so don't get too hung up on it.)

I've found the ideals of the Agile Manifesto useful in my career (www.agilemanifesto.org)

Individuals and interactions over processes and tools

Working software over comprehensive documentation

Customer collaboration over contract negotiation

Responding to change over following a plan

ContentLicense: CC BY-SA 3.0


问:
How should I select continuous integration tool?
I found this cool comparison table for integration servers on Wikipedia, but I am a little uncertain how to rank the tools vs. my needs and interests.  The chart itself seems to have a lot of boxes marked unknown, so if you are comfortable updating it on Wikipedia, that could be great too.

Are there a few top performing products so I can quickly narrow down to four or five options?

Which products seems to have the largest user communities and most ongoing enhancements and integration with new tools?

Are the open source offerings best, or are there high quality tools that can be a great deal for a single user at home?

Will use of multiple systems (primary desktop, local only home network server, personal and work notebooks, multiple virtual machines spread across all) create problems and how can they be managed?

答:
Don't worry about comparisons. Start with Jenkins; it is hugely popular and extremely easy to use. Once you've used it a while you'll learn what features are important to you and what are not. My guess is, you'll end up sticking with Jenkins.

I'm sure people will debate whether or not it's the best CI server. Don't listen to them because it doesn't matter. There are probably many that are every bit as good as Jenkins -- better in some ways, maybe not as good as others. It's not so important to pick the best one; the important thing is to pick one and start learning, and Jenkins is a very good one for that.


问:
Test-Driven Development with plain C: manage multiple modules
I am new to test-driven development, but I'm loving it. There is, however, a main problem that prevents me from using it effectively.

I work for embedded medical applications, plain C, with safety issues.

Suppose you have module A that has a function A_function() that I want to test. This function call a function B_function, implemented in module B.
I want to decouple the module so, as James Grenning teaches, I create a Mock module B that implements a mock version of B_function.

However the day comes when I have to implement module B with the real version of B_function. Of course the two B_function can not live in the same executable, so I don't know how to have a unique "launcher" to test both modules.

James Grenning way out is to replace, in module A, the call to B_function with a function pointer that can have the value of the mock or the real function according to the need.
However I work in a team, and I can not justify this decision that would make no sense if it were not for the test, and no one asked me explicitly to use test-driven approach.

Maybe the only way out is to generate different a executable for each module.

Any smarter solution?
Thank you

答:
Based upon what you've described, I would suggest that's a horrible reason to use a function pointer.  It will jack up your ability to debug, analyze core dumps, and it will complicate future development / maintenance.  Function pointers have their place, but this isn't one of them.

I think you're approaching the testing from the wrong point of view.  A_func depends upon B_func's presence for it to operate.  Therefore, you can't truly test A without having the actual implementation of B in place.  Putting a mock B_func in place will only generate a limited set of tests for A_func.  By definition, you can't fully exercise A_func without the real B_func in place.

Presuming you're not dealing with a cascading series of module inclusions, the appropriate test suite would have some tests to exercise B_func and then some additional tests for exercising the variations that A_func can go through.  It's understood that you may have some redundancy between the tests for B_func and the indirect testing of B_func from A_func, but it's generally not a big deal.


问:
Is Object Oriented Programming a solution to complexity?
Do you think Object Oriented Programming is a solution to complexity. Why? This topic may be a bit controversial but my intentions to know the answer of Why from the experts here !</p>

答:
Object oriented programming manages essential and optional complexity, but does not reduce either.

I prefer the definition provided by Eric Steven Raymond in The Art of Unix Programming, because it delineates between essential, optional, and accidental complexity.
http://www.faqs.org/docs/artu/ch13s01.html#id2964646

OOP does nothing for essential or optional complexity, they are a function of the program's requirements.  It can have an effect on accidental complexity, in that you can create a more elegant design sometimes with OOP.  Sometimes however, the design is worse when using OOP.

ContentLicense: CC BY-SA 2.5


问:
Productivity strategies for one developer using many PCs
In a talk about time management, a famous computer scientist said:

"One machine in your life is the right number."

He recommended a laptop with a docking station.

After trying this approach for about a month, I miss my more powerful desktop (i7 quad core hyperthread), but it is not in my technology road map (or budget) to upgrade from my old Intel Core 2 Duo (2006) notebook this year.

What strategies can help me use the desktop while at my desk and without much manual effort the notebook when I am on the go?

答:
My advice is exactly the same set up I have for myself (I have 2 desktops, 1 netbook and 1 remote server running just nicely with this):

web browser use either Firefox (with Firefox sync) or Google chrome (with it's google account) to keep history, bookmarks and preferences consistent.

unison this is a free (as in freedom) tool to keep things many systems syncronized. I find it works like a charm. The perfect setup would be to have a server running it but it also works fine if you have an external HD that you move around (I used that before). And you don't have to keep them always syncronized. I found it to be quite good to make a guess about when updating files. And it's also very flexible. For example, you can have your desktops syncing some directories (such as Pictures and Videos) that are not syncing with a netbook (maybe you don't have a lot of space there).

do not use SVN if you have many version control systems either use mercurial or git. SVN works with file locks and some other magic inside the .svn directories and will not work when you use unison (or other sync tools) to keep the files between systems synchronized. Of course if you always makes a commit then on the other systems you only have to update the repo and there's no problem. But I'm not always ready to make a commit when have to go from one to another system.


答:
Actually, I think working on many PCs can increase your productivity (albeit not without an initial investment).

The reason for this is complex, but you can sum it up this way:

You are forced to think about creating a good development environment, independent of your PC.

I'd argue in better-organized companies this is the case and there are documented instructions about setting up a new computer up to speed with the tools required for the project developed.

In order to achieve what you want, you should decouple your process from the machine as much as possible.

So, a couple of tips:

1. Always use version control.

This applies to both code and data. Tools for the code and data differ, of course.
You might want to favor distributed tools, since this gives you more flexibility.

2. Document the process of setting up the development environment

This is pretty straight-forward, although admittedly it's also time-consuming. However the importance is utmost: if you suddenly have to setup a new machine, this is immensely helpful.

3. Create a VM containing a ready development machine

This is rather an emergency response step, but it's very good to do that, too. This way, you can just start coding when presented with a new PC, which can save you much time if you're in a hurry.

4. Have a dedicated deployment / continuous integration server.

This way you can assert that the code works on the deployment machine as well as yours. There are many service providers for this, plus dedicated virtual servers are not very expensive anymore.

5. Use a cross-platform IDE (if possible) and learn how to cross-compile and cross-debug (if applicable).

Again, allows you to work in an even more unfriendly environment, plus this is the only way you can catch some of the more persistent bugs. It allows you to do stuff like leave your work machine on when leaving the office and debugging on it from home, even if you can't run the project locally.

6. Make yourself comfortable with SSH, VNC, SCP and RDP.

You're going to need at least one of these, since there's always some mixup when a deadline is approaching: a file you've forgotten to upload to the server and is on a PC in another city, or you need to fix something on a remote machine, etc.

Think of #6 as a last resort; you shouldn't depend on anything you don't have easy access to for your work, except in unforeseen cases, and SSH is not easy access.

Accidentally, you might notice some of these tips are considered good practices in general; I believe them to be such. This is all a matter of organization and improving it will save you time, eventually.


问:
How to Convert HTML to PDF Using PHP?
PDF or Portable Document Format is a popular file type that is often used for online documents. It's great for distributing downloadable written content, and is frequently used by governments and businesses alike. Because it's a format that's familiar to all, many applications allow the user to convert other document types to the PDF format. PHP is one programming language that has a built-in ability to convert to PDF. PHP scripts can be used to transform file types such as HTML into PDF files.</p>

答:
Try dompdf, it looks like what you need:

dompdf is an HTML to PDF converter. At its heart, dompdf is (mostly) CSS 2.1 compliant HTML layout and rendering engine written in PHP. It is a style-driven renderer: it will download and read external stylesheets, inline style tags, and the style attributes of individual HTML elements. It also supports most presentational HTML attributes.

Also, one of the answers for This Stack Overflow question suggests wkhtmltopdf:

Simple shell utility to convert html to pdf using the webkit rendering engine, and qt.

So your PHP code could call it. However, has some problems:

It needs a patched Qt for some features

It needs the X.org stack in the server-side

Or you could combine html2ps (HTML to PostScript) and ps2pdf (PostScript to PDF).

Title: How to Convert HTML to PDF Using PHP?


问:
How to learn to make better estimates?
I suck at estimates. When someone asks me how long something will take, I don't even dare to make a guess since I will be completely off the mark. Usually I'm way too optimistic, and should probably multiply my guess with some large X factor...

How can I learn to make better estimates? It's not taught at my uni, and even though we have deadlines for all laborations I never think about how long something will actually take. Which I should. For everyone's sake (especially mine).

答:
Learn your own bias. If your last estimate has been too low by factor two, next time, double your initial estimate. (Of course, Hofstadter's law makes it hard to do that right...)

It's also always a good idea to remember how much work was needed after the initial release of the previous work, and add that to the next estimate. E.g. your last task took 2 months to complete, but after going live, support, hotfixes and additional changes have cost you another month, so, next time estimate 3 months for a similar task.

Title: How to learn to make better estimates?


问:
Specific reasons for still using Subversion?
I want to choose a version control system for my company. So far I know I have Git, Subversion and Mercurial.

These days I see that Git is the most used, so I'm left wondering: would there be any specific reason to still use Subversion, or should I go directly to Git?

答:
SVN is not dead at all.  It's is still in extremely wide use, and it's not going anywhere anytime soon.  SVN is much simpler to use than distributed version control, especially if you're not actually running a distributed project that needs distributed version control.

If you only have one central repository (which is all your company will need if they're still small enough to get by without source control so far), it's much simpler to use SVN to interact with it.  For example, with SVN you can pull changes from the repository, or commit your local changes to it, with a single operation, whereas HG and Git require two or three steps to do the equivalent work.

And with the recent revisions, SVN has fixed a lot of the performance issues that made people prefer HG and Git.  It's significantly faster now than it was a couple years ago, and at this point, there's really no good reason to look at HG or Git for your project unless you actually need the advanced features of distributed version control.


答:
I just solved this for myself.

I have laptop for development and couple weeks ago it crashed. Well. I learned that even I have backups, svn, etc pain was huge just because I was so hardware dependent. To restore dev environment on different machine takes time. Even with on-site mintenance plan I was down for 4 days.

Long story short I bought pretty beefy desktop and run VMWare on it. Performance is better than it was on laptop and my whole system is in one folder which I backup daily. It is on separate SSD and when I need to go somewhere I just put it in dvd bay on my laptop. Slow but ok for travel.

This way I have backup, independence from hardware and backup hardware in case laptop or desktop ever fails


问:
Is functional programming a superset of object oriented?
The more functional programming I do, the more I feel like it adds an extra layer of abstraction that seems like how an onion's layer is- all encompassing of the previous layers.

I don't know if this is true so going off the OOP principles I've worked with for years, can anyone explain how functional does or doesn't accurately depict any of them: Encapsulation, Abstraction, Inheritance, Polymorphism

I think we can all say, yes it has encapsulation via tuples, or do tuples count technically as fact of "functional programming" or are they just a utility of the language?

I know Haskell can meet the "interfaces" requirement, but again not certain if it's method is a fact of functional? I'm guessing that the fact that functors have a mathematical basis you could say those are a definite built in expectation of functional, perhaps?

Please, detail how you think functional does or does not fulfill the 4 principles of OOP.

Edit:
I understand the differences between the functional paradigm and object oriented paradigm just fine and realize there are plenty of multiparadigm languages these days which can do both. I am really just looking for definitions of how outright fp (think purist, like haskell) can do any of the 4 things listed, or why it cannot do any of them. i.e. "Encapsulation can be done with closures" (or if I am wrong in this belief, please state why).

答:
Functional programming isn't a layer above OOP; it's a completely different paradigm.  It's possible to do OOP in a functional style (F# was written for exactly this purpose), and on the other end of the spectrum you have stuff like Haskell, which explicitly rejects the principles of object orientation.

You can do encapsulation and abstraction in any language advanced enough to support modules and functions.  OO provides special mechanisms for encapsulation, but it's not something inherent to OO.  The point of OO is the second pair you mentioned: inheritance and polymorphism.  The concept is formally known as Liskov substitution, and you can't get it without language-level support for object-oriented programming.  (Yes, it's possible to fake it in some cases, but you lose a lot of the advantages that OO brings to the table.)

Functional programming doesn't focus on Liskov substitution.  It focuses on increasing the level of abstraction, and on minimizing the use of mutable state and routines with "side effects", which is a term functional programmers like to use to make routines that actually do something (as opposed to simply calculating something) sound scary.  But again, they're completely separate paradigms, that can be used together, or not, depending on the language and the skill of the programmer.


答:
"If you have a task that can be done on six hours, it is better to write a tool that does it in 20 minutes, even when creating the tool takes six hours?"

Distributed Version control is a different beast to tackle. It requires substantial learning for each developer. If you have the buffer to accommodate the learning process for each developer, you should move to a good distributed version control system. Once the learning phase is over Distributed Version Control is much better than Centralized Version Control.

Distributed Version Control seems to be an eventuality. It is here to stay for a very long time, it is better that we adapt to it sooner than later. I remember the same discussion when SVN was new and people were used to CVS, lots of arguments were given for not using SVN, but eventually SVN became the most popular version control system.

If the company is well established with a lot of source code in the existing version control system, moving to a new system is a big task, but if the company is small or starting up, moving to a new version control is very easy. But if you stick to an older version control (in a new setup) you will hit the bottleneck somewhere in future where you will have to eventually plan a version control migration anyway.

I have seen a lot of pro SVN comments, but all of them tend to be of the nature "SVN is not bad" rather than "SVN is better". So I would strongly recommend that you choose a Distributed Version Control (such as Git) for your project.

EDIT
Advantages of GIT over SVN

No dedicated server required Actually, both can be used w/o a server.

Can continue development even without a network connection.

Branch management is much easier.

Better support from CI tools such as Bamboo

Someone mentioned tooling (for visual studio) as a reason to stick to SVN. http://gitscc.codeplex.com/ provides GIT support for Visual Studio.

Title: Specific reasons for still using Subversion?

Body:
I want to choose a version control system for my company. So far I know I have Git, Subversion and Mercurial.

These days I see that Git is the most used, so I'm left wondering: would there be any specific reason to still use Subversion, or should I go directly to Git?


问:
Name for this antipattern? Fields as local variables
In some code I'm reviewing, I'm seeing stuff that's the moral equivalent of the following:

```<code>public class Foo
{
    private Bar bar;

    public MethodA()
    {
        bar = new Bar();
        bar.A();
        bar = null;
    }

    public MethodB()
    {
        bar = new Bar();
        bar.B();
        bar = null;
    }
}
</code>```

The field bar here is logically a local variable, as its value is never intended to persist across method calls. However, since many of the methods in Foo need an object of type Bar, the original code author has just made a field of type Bar.

This is obviously bad, right?

Is there a name for this antipattern?

答:
Going against the grain here but while I don't consider the given example to be good coding style as is in its current form, the pattern does exist while doing unit testing.

This fairly standard way of doing unit testing

```<code>public class BarTester
{
    private Bar bar;

    public Setup() { bar = new Bar(); }
    public Teardown() { bar = null; }

    public TestMethodA()
    {
        bar.A();
    }

    public TestMethodB()
    {
        bar.B();
    }
}
</code>```

is just a refactoring of this equivalent of OP's code

```<code>public class BarTester
{
    private Bar bar;

    public TestMethodA()
    {
        bar = new Bar();
        bar.A();
        bar = null;
    }

    public TestMethodB()
    {
        bar = new Bar();
        bar.B();
        bar = null;
    }
}
</code>```

I would never write code as given by OP's example, it screams refactoring, but I consider the pattern to be neither invalid nor an antipattern.

Body:
Going against the grain here but while I don't consider the given example to be good coding style as is in its current form, the pattern does exist while doing unit testing.

This fairly standard way of doing unit testing

public class BarTester
{
    private Bar bar;

    public Setup() { bar = new Bar(); }
    public Teardown() { bar = null; }

    public TestMethodA()
    {
        bar.A();
    }

    public TestMethodB()
    {
        bar.B();
    }
}

is just a refactoring of this equivalent of OP's code

public class BarTester
{
    private Bar bar;

    public TestMethodA()
    {
        bar = new Bar();
        bar.A();
        bar = null;
    }

    public TestMethodB()
    {
        bar = new Bar();
        bar.B();
        bar = null;
    }
}

I would never write code as given by OP's example, it screams refactoring, but I consider the pattern to be neither invalid nor an antipattern.


答:
No; OOP may be seen as a superset of procedural programming and differs fundamentally from functional paradigm because it has state represented in the instance fields. In functional paradigm the variables are functions which are applied on the constant data in order to obtain the desired result.

Actually you can consider functional programming a subset of OOP; if you make all of your classes immutable you may consider you have some kind of functional programming.

Title: Is functional programming a superset of object oriented?

Body:
The more functional programming I do, the more I feel like it adds an extra layer of abstraction that seems like how an onion's layer is- all encompassing of the previous layers.

I don't know if this is true so going off the OOP principles I've worked with for years, can anyone explain how functional does or doesn't accurately depict any of them: Encapsulation, Abstraction, Inheritance, Polymorphism

I think we can all say, yes it has encapsulation via tuples, or do tuples count technically as fact of "functional programming" or are they just a utility of the language?

I know Haskell can meet the "interfaces" requirement, but again not certain if it's method is a fact of functional? I'm guessing that the fact that functors have a mathematical basis you could say those are a definite built in expectation of functional, perhaps?

Please, detail how you think functional does or does not fulfill the 4 principles of OOP.

Edit:
I understand the differences between the functional paradigm and object oriented paradigm just fine and realize there are plenty of multiparadigm languages these days which can do both. I am really just looking for definitions of how outright fp (think purist, like haskell) can do any of the 4 things listed, or why it cannot do any of them. i.e. "Encapsulation can be done with closures" (or if I am wrong in this belief, please state why).


问:
Is it a bad practice to quit a company only to begin as a consultant?
Like the title says; is it a bad practice to quit a company after a few years, only to begin as a consultant for the same 'customer'?

I've been lucky enough to come in to a company in the oil business from the beginning, developing software for relatively new and unused technology.  Long before I even got this job, I've wanted to start my own consulting firm. Is it morally wrong of me to quit my job after a few years, only to hire myself out as a 'specialist' or consultant on our systems?

答:
Leaving a company and becoming a consultant can be rewarding, both personally and financially. However, it is not necessarily simple.

First, consider whether consulting on the product breaks any Non-Disclosure Agreements (NDAs) or non-compete clauses in your contract. Whether these are enforceable or not does not help you when you are facing down lawyers. The customer may also have a clause in their contract stating they cannot hire anyone from your company or vice versa.

Second, that being a consultant is different to being a developer. You are using the product rather than writing it. Forget the nice IDEs you are used to and start thinking of batch files/scripts, database migrations and other less glamorous things.

Third, your knowledge of the product is going to atrophy over time. You will not have access to the source code and, as improvement and modifications occur, you will not know what they are until you use the product like everyone else. You may have friends on the development staff but do not expect them to give you the inside scoop on everything forever.

Lastly, being tied to a single customer can be dangerous. That customer may go out of business or stop using your product. You will need to start networking more and expanding your list of contacts. You may enjoy this or not but you have to be good at it to succeed.

That said, many people become consultants. Some people find development does not give them the same buzz and want to focus on the broader (and potentially more lucrative) customer problems. Some just have interests in many areas and consulting is a way of satisfying all of them. Assuming you are OK with the issues given above, this is a perfectly acceptable and reasonable route to take.


问:
Emailing Service: To or Bcc?
I'm busy coding a reusable e-mail service for my company. The e-mail service will be doing quite a few things via injection through the strategy pattern (such as handling e-mail send rate throttling, switching between Smtp and AmazonSES or Google AppEngine for e-mail clients when daily quotas are exceeded, send statistics tracking (mostly because it is neccessary in order to stay within quotas) to name a few).

Because e-mail sending will need to be throttled and other limitations exist (ex. max recipient quota on AmazonSES limiting recipients to 50 per send), the e-mails typically need to be broken up.

From your experience, would it be better to send bulk (multiple recipients per e-mail) or a single e-mail per recipient?

The implications of the above would be to send to a 1000 recipients, with a limit of 50 per send, you would send 20 e-mails using BCC in a newsletter scenario. When sending an e-mail per recipient, it would send 1000 e-mails. E-mail sending is asynchronous (due to inherit latency when sending, it's typically only possible to send 5 e-mails per second unless you are using multiple client asynchronously).

Edit

Just for full disclosure, this service won't be used by or sold to spammers and will as far as possible automatically comply with national and international laws.

>Closed<

Thanks for all the valuable feedback. The concerns regarding compliance towards laws, user experience (generic vs. personalized unsubscribe) and spam regulation via ISP blacklisting does make To the preferred and possibly the only choice when sending system generated e-mails to recipients.

答:
This largely depends on the type of email you are sending.

For example, a single recipient per email is a good idea for bulk mail such as customer mailings because it allows you to embed a personalized unsubscribe link for that specific email address.

If these are bulk mailings to employees, on the other hand, you may not need anything like that.

Title: Emailing Service: To or Bcc?


答:
Whether one 'To' recipient per email is appropriate really depends on your use-case and what other features you want to offer.

If you want recipients to be able to unsubscribe from these bulk emails, then I recommend you include a link specific to one recipient. While you could provide two-stage unsubscription (that is, the recipient clicks a generic unsubscribe link and then enters their email address to confirm), I can't understate how incredibly annoying that is to a user.

On that subject, in some countries there is a legal requirement to include an unsubscribe link when bulk-emailing, so remember to always have that.

Further, if you want each recipient's emails personalised in some way then you also want one To recipient per email, rather then 50 in the Bcc field. Personalisation is not always just their name in the salutation, it could say be a team meeting time and venue if it's internal email to various different company teams, or a special offer tailored to certain people on your mailing list.

Finally, if you want to monitor behaviour (that is, track opens, link clicks, forwards, facebook liking and so on) you also want one To recipient per email.

If all you want to do is send emails, you're right, you could choose many Bcc recipients and probably get away with it. If you want anything more, I'd certainly recommend you send to one To recipient.

Edit

I forgot to mention also that you need to protect the sending reputation of the IP addresses your sending servers use. A lot of anti-spam software, along with mail servers in general maintain black lists of banned sending IPs. If you send ten emails to 50 people each, and only 1 person marks that as spam, some lists will interpret that as you having a 10% spam rate (1 in 10 emails has been marked as spam). That's incredibly big and will likely very quickly have your IPs blacklisted immediately. Again, go for one 'To' recipient per email.

Title: Emailing Service: To or Bcc?

Body:
I'm busy coding a reusable e-mail service for my company. The e-mail service will be doing quite a few things via injection through the strategy pattern (such as handling e-mail send rate throttling, switching between Smtp and AmazonSES or Google AppEngine for e-mail clients when daily quotas are exceeded, send statistics tracking (mostly because it is neccessary in order to stay within quotas) to name a few).

Because e-mail sending will need to be throttled and other limitations exist (ex. max recipient quota on AmazonSES limiting recipients to 50 per send), the e-mails typically need to be broken up.

From your experience, would it be better to send bulk (multiple recipients per e-mail) or a single e-mail per recipient?

The implications of the above would be to send to a 1000 recipients, with a limit of 50 per send, you would send 20 e-mails using BCC in a newsletter scenario. When sending an e-mail per recipient, it would send 1000 e-mails. E-mail sending is asynchronous (due to inherit latency when sending, it's typically only possible to send 5 e-mails per second unless you are using multiple client asynchronously).

Edit

Just for full disclosure, this service won't be used by or sold to spammers and will as far as possible automatically comply with national and international laws.

>Closed<

Thanks for all the valuable feedback. The concerns regarding compliance towards laws, user experience (generic vs. personalized unsubscribe) and spam regulation via ISP blacklisting does make To the preferred and possibly the only choice when sending system generated e-mails to recipients.


答:
Client tooling hasn't been mentioned yet. You can certainly do everything with a command line script but having GUI integration can be a real productivity boost.

We work mostly with Visual Studio; integration into the IDE is definitely better with SVN than with Git right now. This may change in the future, but I'd certainly weigh this into your decision just as much as the version control functions.

Just like everything else, a version control system isn't a goal in itself, just a tool to get you where you're going. Pick the one that's going to get you there fastest based on your situation.


答:
I'm a Git fan. Recently I had to admit that one of the downsides of Git is that it identifies versions with hashes as opposite to svn's release numbers. The release number can be easier passed on by phone or something like that.

And that's the only pro I can imagine. If you really want to rely on that feature you can have it in a distributed and/or centralized VCS Bazaar. In Git there are tags that can serve the purpose.

Anyway I just couldn't imagine developing without quick branch switching, and stashing. These two features alone beat SVN, where as far I remember the same task required creating and checking out a whole tree into separate directories to achieve the same goal.

Those so called "advanced features of distributed version control" come with the time, and you don't have to learn them at the very beginning. Don't be scared of them. They are here to help you, not to get in the way. And there's no problem to set up a central repository for a DVCS.


问:
How to make a PHP function triggered automatically at a user defined time
I am developing an internal system for a company with PHP using Zend framework. I need one of its functions to execute on a time specified by user.

My research on this matter found me several ways of doing this using CPanel Cron jobs and setting up scheduled tasks on the server. But in this scenario, I don't have a CPanel and I already use scheduled tasks. But my challenge is to provide an interface for the user to specify the time to trigger the function.

答:
cron is an external program, you can call it from PHP via exec() or shell_exec() (their only difference is how they handle output).

You'll probably want to build a friendly user interface around it, and be extremely strict with what ends up getting executed, but that's about it.


答:
I find the following intuition useful to compare OOP and FP.

Rather than considering FP as a superset of OOP, think of OOP and FP as two alternative ways of looking at a similar underlying computation model in which you have:

Some operation that is executed,

some input arguments to the operation,

some fixed data / parameters that can influence the definition of the operation,

some result value, and

possibly a side-effect.

In OOP this is captured by

A method that is executed,

the input arguments of a method,

the object on which the method is invoked, containing some local data in the form of member variables,

the method's return value (possibly void),

the method's side-effects.

In FP this is captured by

A closure that is executed,

the input arguments of the closure,

the captured variables of the closure,

the closure's return value,

the closure's possible side effects (in pure languages like Haskell, this happens in a very controlled way).

With this interpretation, an object can be seen as a collection of closures (its methods) all capturing the same non-local variables (the object's member variables common to all closures in the collection). This view is also supported by the fact that in object-oriented languages closures are often modeled as objects with exactly one method.

I think the different points of view originate from the fact that the object-oriented view is centered on the objects (the data) while the functional view is centered on the functions / closures (the operations).


答:
FP like OO isn't a well defined term. There are schools with different, sometimes conflicting, definitions. If you take what they have in common, you get down to:

functional programming is programming with first class functions

OO programming is programming with inclusion polymorphism combined with at least a restricted form of dynamically resolved overloading. (A side note: in OO circles polymorphism is usually taken to mean inclusion polymorphism, while FP schools it usually means parametric polymorphism.)

Everything else is either present elsewhere, or absent in some cases.

FP and OO are two abstractions building tool. They each have their own strengths and weaknesses (for instance they have a different preferred extension direction in the expression problem), but none is intrinsically more powerful than the other. You can build an OO system over a FP kernel (CLOS is one such system). You can use an OO framework to get first class functions (see the way lambda functions are defined in C++11 for instance).


问:
Binding in the view or the controller?
I've seen 2 different approaches with MVC on the web.

One, like in ExtJS, is to bind the callbacks to the view via the controller. Finding every element on the view and adding the functionallity.

The other, like in angular.js and in the lift framework, is to bind in the views and just write the functionallity in the controller.

Which is better and cleaner?

The ExtJS approach has dumb views and all the logic in the controller which seems clean to me. I had problems with global IDs for GUI-elements or relative navigation to GUI-elements in this approach. When I changed the view, the controller couldn't find the buttons anymore or I had multiple instances of one button with the same ID on a single application, because of the global ID.

But I solved this with IDs that are only global in a view and can be on the application multiple times. So I could mess with the (dumb) views layout and design and the functionality wouldn't break.

The angular.js approach with the bindings in the view doesn't have the problem with global IDs. Also, the person who changes something in the view layout has to know the IDs anyway, so the controller can put the data at the right spot.

So if I write

```<code>ng-click="doThis()" />
</code>```

for angular.js and implement doThis()

or

```<code>lid="buttonwhichdoesthis" />
</code>```

for extjs and find the element with the local id and add doThis() as the handler on the controller side, it seems to not be so different.

The only thing is, the second one has one more layer of indirection, which seems cleaner.

The first one seems less effort.

答:
From my own point of view: neither of them is better the other one. They are just two different ways of achieving the same purpose.

I'm pretty use to work with different MVC frameworks based in Java as Spring MVC, JSF and GWT. The two former ones are as the angular.js you mentioned, they bind operations with the views and everything is executed on the server side (even UI rendering) whilst the latter, GWT, is JavaScript based and all the UI work is performed on the client side, then bound through means of callbacks to server-side calls to perform those other server-side tasks as data processing and so on.

I prefer to work with server-side frameworks and perform small AJAX calls from the UI to update specific parts of the application view. But I thing that's a personal preference.

Title: Binding in the view or the controller?

Body:
I've seen 2 different approaches with MVC on the web.

One, like in ExtJS, is to bind the callbacks to the view via the controller. Finding every element on the view and adding the functionallity.

The other, like in angular.js and in the lift framework, is to bind in the views and just write the functionallity in the controller.

Which is better and cleaner?

The ExtJS approach has dumb views and all the logic in the controller which seems clean to me. I had problems with global IDs for GUI-elements or relative navigation to GUI-elements in this approach. When I changed the view, the controller couldn't find the buttons anymore or I had multiple instances of one button with the same ID on a single application, because of the global ID.

But I solved this with IDs that are only global in a view and can be on the application multiple times. So I could mess with the (dumb) views layout and design and the functionality wouldn't break.

The angular.js approach with the bindings in the view doesn't have the problem with global IDs. Also, the person who changes something in the view layout has to know the IDs anyway, so the controller can put the data at the right spot.

So if I write

```<code><a ng-click="doThis()" />
</code>```

for angular.js and implement doThis()

or

```<code><a lid="buttonwhichdoesthis" />
</code>```

for extjs and find the element with the local id and add doThis() as the handler on the controller side, it seems to not be so different.

The only thing is, the second one has one more layer of indirection, which seems cleaner.

The first one seems less effort.


问:
Learning Zend Framework 1 or 2?
I have programmed for a few years in php and now I'm going to learn zend framwork.
Zend is very popular and there are a lot of tutorials, books and documentation out there. But I saw in the last months that there is a second version of Zend, but it's not so used and popular, not yet.

I think it is better to start with a new version, but I don't know what to do now, as when I see job offers many people require the first version.
Which version do you suggest me?

答:
You should learn both, but I'd personally put more emphasis on ZF2.

ZF2 is the package that will have the longest lifespan ahead of it, whilst ZF1 is probably going to go into maintained mode once ZF2 is generally available, so if you limit yourself to ZF1 you'll eventually have to learn ZF2 anyway if you want to maintain your employability.  If you only learn ZF1, you're dooming yourself to the life of a maintainance engineer keeping legacy codebases in working order.

Having said that, it would be unwise to ignore ZF1 as nearly all Zend Framework applications currently deployed will use that.

Title: Learning Zend Framework 1 or 2?


问:
What to do when you inherit an unmaintainable codebase?

Possible Duplicate:

  Techniques to re-factor garbage and maintain sanity?

  I've inherited 200K lines of spaghetti code — what now?

I'm currently working at a company with 2 other PHP developers aside from me, and 1 junior developer.

The senior developer who originally built the system we're all working on has resigned and will only be here for a matter of weeks.  The other developer, who is the only other guy who knows anything about the system, is unhappy here and is looking for a new job.  I'm very real danger of being left behind as the only experienced developer on this codebase.

Since I've joined this company I've tried to push for better coding standards, project documentation, etc and I do think I've made some headway, but the vast majority of the code is simply unmaintainable and uncommented.  A lot of this has to do with the need to get things done fast at points in the project before I joined, but now the technical debt is enormous, even with the two developers who do understand the system on board.  Without them, it will simply be impossible to do anything with it.  The senior developer is working on trying to at least comment all his code before he leaves but I think the codebase is simply too vast to properly document in the remaining time.  Besides, when he does comment it still doesn't make things as clear as it could.

If the system was better organized and documented I could probably start refactoring it incrementally, but the whole thing is so tightly coupled that it's very difficult to make any changes in one module without having unintended knock-on effects in other modules.  Naturally, there's no unit tests either, and I honestly don't think this codebase could possibly be unit tested anyway given how it's implemented.

There also never seems to be enough time to get things done even with 3 developers and 1 junior developer.  With one developer and one junior, neither of which had significant input into the early design of the system, I don't see how we could possibly get anything done with keeping the current system working, implementing new features as needed and developing a replacement for the current codebase that is better organized.

Is there an approach I can take to cope with this situation, or should I be getting my own CV in order as well at this point? If it was just me and the junior designer who would be left I'd go for the latter option almost without question.  However, there's a team of front-end developers and content managers as well, and I'm worried what would become of them if I left and put them in a position where there would be no developers at all.  The department might just be closed down altogether under such circumstances, and then I'd have their unemployment on my conscience as well!

答:
The similarity your situation has with what I've experienced about 3 years ago is frightening:

same setup: undocumented, cowboy coding

the "senior" guy that made the thing is gone

the remaining guys know something about the existing code base but not a lot.

thought the thing was presented as "working" and my job was introduced as "just add some extra features, no major recoding", it was clear that nothing was doable without a major re-hauling.

I don't know what the best approach to this is, but I can tell you how I've dealt with the thing:

first off, the cowboy coding environment and lack of documentation (and testing, in my case) was considered a good thing by everybody, so proposing to change that in the sense where some time was spent doing docs, implementing a test infrastructure etc was denied right from the start. What I ended up doing is implementing all this "on the down low". Without actually declaring it as a task, I've tried spending 1-2 hours a day (for like, the first 2-3 weeks) just organizing the code, putting it on svn, making some docs, and some basic unit and integration testing. Functional tests, CI and higher order organizational stuff was out of the question in such a setup, so that was left aside, but at least some advancement was done.

second, and again, without really declaring it as such, I've accepted my "just add a new feature, nothing more" tasks as is, but instead re-hauled the whole module that was impacted by that task (in order to make the task implementable). I've simply demanded some extra time, but without actually declaring it, remade the existing, production code first, and then added the extra features. The up side here was that the original code, even though it was in production for a while, was so bad and un-performant, that a simple, common sense refactoring made it substantially faster and that gained me the approval for the extra time I demanded.

finally, about 2-3 months of this, I started looking for a different job, because it was clear that this was not something I wanted to do on the long run. Long story short, I've quit this job after about 5 months, in which time I managed to implement a decent portion of the functionality that was demanded of me, but not all.

Now, here's what I've learned from it all: sure, if possible avoid such jobs, it's better to work in a clean, structured environment, where the software development process is recognize for what it is and treated with respect. On the other hand, I cannot deny that my short period of working in such conditions taught me A LOT about how to deal with issues in such an under-pressure environment. It also made me appreciate even more all the protocols and methodology needed for good software development.

So in short, if you can afford a few months of this, do it, it will be an interesting experience (just as long as you have a clear way out in the near future). If not, just leave it as soon as possible and be done with it.


问:
Object Oriented Programming Language performance ranking
After reading this post about ideal programming language learning sequence, I am wondering what would have been the answers if the question was performance -instead of learning- oriented ?

Since there are many programming languages I chose to ask the question for OOL to be the least subjective. But any thought or comparison about no-OOL are appreciated :D

If we omit the programming effort, time and costs. What is your ranking of the most powerful object oriented languages ?

答:
Omitting development effort, time, and cost you are going to get the most performance from a languages that are statically typed and compiled.  Dynamic interpreted (or Just in time compiled a.k.a. JIT) languages on the other hand generally are expected to reduce development effort, time, and cost.  Additionally however they are expected to reduce deployment effort, time, and cost.

C++ is going one of the obvious winners here and is used extensively in the game development community for that reason.

Scalable solutions however seem to benefit from the reduced deployment costs of dynamic and interpreted languages.  So while one box may run slower than equivalent C++ code, a cloud of interpreters or virtual machines may have the advantage assuming equal deployment budgets.  Java is one example, but clouds of Ruby or particularly Scala may be more indicative of this trend.


答:
would there be any specific reason to use Subversion those days

Apart from tooling support in IDEs (which I don’t use) – not really, no. Of course SVN may be more familiar but that’s about the only reason, and I’ve found both Hg and Git very easy (and very fast) to learn.

Yes, there are all those complex guides out there which describe how Git is trivial once you understand that branches are just homeomorphic endofunctors mapping submanifolds of a Hilbert space.1

I don’t understand that. But you know what? It doesn’t matter. You don’t need to know any of that stuff to use Git.

For the most part, Git and Hg are easy to use and they have definitive advantages over SVN. The elephant in the room is of course branching: branches just work in Git and Hg. By contrast, in SVN they are painful at best and broken at worst (merging multiple heads).

Of course you can still use SVN. You can also still use Windows XP. However, the majority of users who have tried both agree that one of the alternatives is vastly superior.

1 Yes I get that this is a joke. I think.


答:
There are several approaches to this, but fundamentally a lot will depend on management support - and if you haven't got management that understands what differences a testable, solid, documented codebase means, then maybe polishing your CV would be the best route.

Do you have parallel environments? The first thing I would suggest would be putting in place a regression testing framework - taking a regular snapshot of the production data and using that in for a parallel dev/UA environment. Then start testing refactored, new or edited code there before release into production.

If you can't unit/integration/system test from scratch, then you should at least start to test properly any new/changed code - and you'll need the parallel environment for that. Then at least you'll start to build up some confidence in the changes that you are making.

Once you've got some testing in place, then maybe try to get some coverage tools so you can start to guess at the extent of your problems.

Investigate automated documentation too - I'm currently in a .net world and being able to enable automated documentation and then have missing documentation marked as warnings, but optionally to have warnings treated as errors, so builds will fail when documentation is absent, is a real help in finding holes. It doesn't help with creating good comments, but something is generally better than nothing.

And push back to management - every developer will tell you they don't have enough time to get things done, but if you can start baking in time to your estimates to include testing and documentation, even if it just turns "later today" into "tomorrow lunchtime" or similar, then you'll be reaping the dividends soon enough.

You'll also be teaching the junior some good practices and if you're both still around in a few years, that'll be a huge win too.

Title: What to do when you inherit an unmaintainable codebase?

Body:
Possible Duplicate:

  Techniques to re-factor garbage and maintain sanity?

  I've inherited 200K lines of spaghetti code — what now?

I'm currently working at a company with 2 other PHP developers aside from me, and 1 junior developer.

The senior developer who originally built the system we're all working on has resigned and will only be here for a matter of weeks.  The other developer, who is the only other guy who knows anything about the system, is unhappy here and is looking for a new job.  I'm very real danger of being left behind as the only experienced developer on this codebase.

Since I've joined this company I've tried to push for better coding standards, project documentation, etc and I do think I've made some headway, but the vast majority of the code is simply unmaintainable and uncommented.  A lot of this has to do with the need to get things done fast at points in the project before I joined, but now the technical debt is enormous, even with the two developers who do understand the system on board.  Without them, it will simply be impossible to do anything with it.  The senior developer is working on trying to at least comment all his code before he leaves but I think the codebase is simply too vast to properly document in the remaining time.  Besides, when he does comment it still doesn't make things as clear as it could.

If the system was better organized and documented I could probably start refactoring it incrementally, but the whole thing is so tightly coupled that it's very difficult to make any changes in one module without having unintended knock-on effects in other modules.  Naturally, there's no unit tests either, and I honestly don't think this codebase could possibly be unit tested anyway given how it's implemented.

There also never seems to be enough time to get things done even with 3 developers and 1 junior developer.  With one developer and one junior, neither of which had significant input into the early design of the system, I don't see how we could possibly get anything done with keeping the current system working, implementing new features as needed and developing a replacement for the current codebase that is better organized.

Is there an approach I can take to cope with this situation, or should I be getting my own CV in order as well at this point? If it was just me and the junior designer who would be left I'd go for the latter option almost without question.  However, there's a team of front-end developers and content managers as well, and I'm worried what would become of them if I left and put them in a position where there would be no developers at all.  The department might just be closed down altogether under such circumstances, and then I'd have their unemployment on my conscience as well!


问:
Understanding the static keyword
I have some experience in developing with Java, Javascript and PHP.

I am reading Microsoft Visual C# 2010 Step by Step which I feel it is a very good book on introducing you to the C# language.

I seem to be having problems in understanding the static keyword. From what I understand this far if a class is declared static all methods and variable have to be static. The main method always is a static method so in the class that the main method exists all variables and methods are declared static if you have to call them in the main method. Also I have noticed that in order to call a static method from another class you do not need to create an object of that you can use the class name.

But what is the actual purpose of the static keyword? When should I declare static variable and methods?

答:
Looking at it this way helps me:

Every type has a static instance.

The static instance is created at the first time you access the type -- either through the static instance or creating another instance.

You can create as many non-static instances as you like, but there is only one static instance.

Anything within a class that is declared as static belongs to the static instance, and thus doesn't have access to any other instances you create. But the other instances DO have access to the static instance.

If a class is declared as static then you cannot create other instances, only the static instance can ever exist.

You can declare a static constructor for the static instance just like a constructor for a normal instance (but by declaring it static).

As for when to use the static keyword:

Any method that doesn't need access to local properties can and probably should be declared static.

Helper classes that don't have any state whatsoever (which should be rare anyway) and that will never be mocked can be declared static. Whether they should is another matter; use this functionality sparingly.

Properties and fields that must be accessed by all instances of a class must be declared static. But use this only when there is no other option.

Title: Understanding the static keyword


答:
Since I've joined this company I've tried to push for better coding standards, project documentation, etc

If you're going to be the sole experienced developer left on the project this seems like a golden opportunity to introduce better coding practice.

Be open with the management team and explain the situation you're in, explain to them that you need time to work through the existing code-base before you continue kludging away on top of it.

It may seem daunting to tackle the code line by line without any comments, but afterwards your understanding of exactly how the software works will increase considerably, and you will find future additions a breeze to implement!

And lastly... sometimes a new job can be just the ticket, but 3 months into it you might find yourself in exactly the same position but with less influence over issues that matter (i.e. coding standards!).


答:
There is no easy answer to the question.

From what you have written, the biggest problem appears to be one of project management. Too many tasks were performed too quickly. You can implement the world's best coding standards, automated tests and so on but if this practice continues, it will all be for naught. You need to change the thinking from a features and deadlines first and quality a distant third to a quality first, pick either features or deadlines for second or third mentality.

You need to talk with your management to improve this. It may not all be your immediate management's fault. Maybe business conditions are changing or customers are being difficult, but it is something you need to address. If you cannot address this, walk away. Companies need good developers more than developers need bad companies.

Assuming you can get some commitment for that, start with a small piece of the product, such as one you need to modify or extend and make it better. Whenever you have a coding task, pad the estimate a bit and spend a bit of time fixing or improving something.

At the same time, start enforcing better practice such as code reviews, use automated unit tests and so on. This is mandatory for all developers, especially the senior ones.

Michael Feathers has a great book, Working Effectively with Legacy Code, on refactoring code to make it more testable. I am unfamiliar with PHP tools but there is surely an equivalent of the .NET StyleCop to enforce coding standards. Also identify whether components of the system can be replaced by third-party libraries. This offloads the maintenance burden from you and likely increases the code quality.

Also consider gathering some metrics. It may be worthwhile tracking how much of the code base has been cleaned up, perhaps a percentage of the code or number of components. One way to demonstrate the benefit of the work to management is compare defect detection rate and number in old code with the cleaned up code. Another is to look at the time taken to complete modifications to the old and new code.

Once this has been successful for a few components, work with the other developers on the overall system design. How should the system actually work? This may be difficult, particularly if the product is changing rapidly, but a high level design for the system is something to aspire to with the incremental changes. Without it, the quality of individual components may improve but the system will be a mess.

You should then be in a situation to reassess where you are.

One last point I want to address is your indebtedness to other developers. From what you have written, the state of the product is not your fault. Software developers tend to feel a strong bond to one another and is one of the reasons many of us love the industry. Fixing a broken product will look good on the CV. Drowning in negativity and futility will drive you crazy and burn you out. You have to know where to draw the line and trust others to look after themselves.


答:
Here's Joshua Bloch's way of explaining it, which I find brilliant like most of what he says (yes I'm a Joshua Bloch fan boy :) ). This is quoted from memory.

Imagine that a class is the equivalent of a blue-print for a house. Imagine then that a house is to the blue-print as an instance of the class is for the class. You can have one class (blue-print) and multiple instances (houses) created from it.

Now, common sense dictates that most of the functions/behaviors that a house (instance) can have/do, even though they are declared in the blue-print, cannot be used until an actual house (instance) is made out of that blue-print (class). Like, your blue-print might contain in it the place where the light switches and the light bulbs should go, but you have no way of making those work on the blue-print, you have to actually build the house in order to be able to switch the light switch on and off and have certain light bulbs go on and off.

However, you might have some behavior that is applicable to the blue-print directly, and which you could use/access directly on the blue-print without needing to make an actual house out of that blue-print. Imagine that your blue-print has a button that, upon pressing, will display the footprint of the house contained in that blue-print (by calculating all the lengths of the walls and such). Obviously you COULD build a house first, then go around measuring its footprint, but you can do this with he blue-print alone, so it would be more helpful to have this behavior implemented in the blue-print. Such a blue-print embedded button that calculates the footprint of the house is the equivalent of having a static function in a class.

Title: Understanding the static keyword

Body:
I have some experience in developing with Java, Javascript and PHP.

I am reading Microsoft Visual C# 2010 Step by Step which I feel it is a very good book on introducing you to the C# language.

I seem to be having problems in understanding the static keyword. From what I understand this far if a class is declared static all methods and variable have to be static. The main method always is a static method so in the class that the main method exists all variables and methods are declared static if you have to call them in the main method. Also I have noticed that in order to call a static method from another class you do not need to create an object of that you can use the class name.

But what is the actual purpose of the static keyword? When should I declare static variable and methods?

ContentLicense: CC BY-SA 4.0


问:
Why is it you never get as much done as you'd planned?
I always start the day thinking "I'll easily get this done by the end of the day" and set what looks like a realistic target.

So why do I never hit it? The task always ends up taking 3x longer due to unforeseen bugs, last minute changes etc.

Is it just me?  I don't seem to be getting any better predicting what can be done in a day.

答:
Hard to believe that nobody has mentioned Hofstadter's law yet.

I think the real answer is that your planning always assumes a best-case scenario, as if everything worked immediately an no interruption ever occured. In real life, you start coding, then the telefone rings, you are distracted for 5 minutest, spend another 15 minutes on stackoverflow or programmers.stackexchange to calm down and refocus, do some coding, run into an unexpected behaviour of some API, do some googling, spend 2 hourse to test the possible solutions etc.

In other word: "best-case" only happens in your dreams.


问:
Code testing practice
So now I have come to the conclusion like many others that having some way of constantly testing your code is good practice since it enables fewer people to be involved (colleges and customers alike) by simply knowing what's wrong before someone else finds out the hard way.

I've heard and read some about Unit Testing and understand what it's supposed to do and all. The there are so many different types of bugs. It can be everything from web browser not being able not being able to send correct values, javascript failing, a global function messing up a piece of code somewhere to a change that looked good when testing it out but fails in some special case which was hard to anticipate. My simply finding these errors I learn to rarely repeat them again, but there seems to always be new bugs to be found and learnt from.

I would guess maybe the best practice would be to run every page and it's functions a couple of times, witness the result and repeat this in Firefox, Chrome and Internet Explorer (and all smartphones apparently) to make sure it works as intended. However this would take quite some time to do consider I don't work with patches/versions and do little fixes here and there a couple of times per week.

What I prefer would be some kind of page I can just load that tests as much things as possible to make sure the site works as intended. Basicly just run a lot of cURL's with POST-values and see if I get expected result. But how would I preferably not increase the IDs of every mysql rows if I delete these testing rows? It feels silly to be on ID 1000 with maybe 50 rows in total.

If I could build a new project from scratch I would probably implement some kind of smooth way to return a "TRUE" on testing instead of the actual page. But this solution would for the moment being have to be passed on existing projects.

My question

What would you recommend to be the best way to test my site to make sure that existing functions does their job upon editing the code? Should I consider to implement a lot of edits first, then test manually the entire code to make sure it still works? Is there any nice way of testing codes without "hurting" the ID columns?

Extra thoughs

Would it be a good idea to associate all of my files to the different parts of my site which they affect? For instance if I edit home.php I will through documentation test if my homepage's start works as intended since it's the only part of my site it should affect.

答:
ID's should not be a problem for you. You can always drop the database and recreate it when you need to.

Unit testing is something a little different than what you are after. Unit testing only makes sure that a unit of code does work right. That is all.

You need to do integration testing to make sure all units work right when integrated together.

You also can do automated GUI testing to simulate your operations like pushing a button on web browser.

Title: Code testing practice


答:
If you quit and the department shuts down I wouldn't hold you responsible at all, assuming you are a recent addition to the company. But on the other hand, if you've been there more than say 6 months and there's anyone (at least, anyone important) who doesn't know what you think about the current standards then I'd hold you partially responsible.

It's not enough to simply say "we should comment our code" to your fellow developers. If the code is unmaintainable then it's your responsibility - i.e. part of your job - to ensure that everyone knows it from colleagues and teammates to management and support. If they don't care, then you either accept it or leave.

You didn't leave, so you implicitly accepted it. You don't say that you've been testing or commenting your own code, so I can only assume that you haven't. Now all that "technical debt" is coming home to roost. You have three options:

cut-and-run, find a new job. Presumably you'll do this on the sly whilst still working at the current job until something comes up. This is what you'd do if you think the problem is insurmountable, too risky, or too much hard work. Start looking immediately, because if the code is as you say then things might get ugly very quickly.

step up, position yourself as the new senior dev and fix the mess. You have the opportunity to prove yourself, if you are up to it. But I would attach some dependencies that have to happen before you invest yourself into the task

your management must understand that you are in a fix, things have not been done correctly and processes must change. You might have a hard time here if you have been part of the problem - if you've been there for a while then without a doubt your boss will say 'so why didn't you let me know this was happening?'

you get a promotion to senior dev, which should mean you get the authority to make things happen the way that you want. If they don't trust that you can do the job this won't happen.

do nothing. Just turn up and get paid like you've been doing so far, they'll hire someone else to be the senior dev who will be responsible for fixing the problem, don't stress it.


答:
Code can always be manipulated into a testable state... It just depends on if you have the time!

I advise a read of Working Effectively with Legacy Code which will help you identify strategies for getting tests in place.

The temptation is to throw the whole lot away and re-start from scratch... This is nearly always the wrong thing to do (so says Joel Spolsky, so it must be true!).


答:
Look at a browser based testing framework like Selenium and Watin as Yannis suggested. You can use this to automate human-like interaction with your web pages, things like "check the heading is "X" when the page loads, enter "Test" in the text box, submit using the "OK" button and check the resulting page's heading has changed to "Y".

Like all automated unit tests, it becomes repeatable and faster to execute. If you change home.php, in the example you give above, just run the tests over the whole website and make sure there are no flow on affects. Most testing frameworks support the commonly browsers and even run them in parallel on multiple computers.

If you are interested in performance by YSlow can help identify performance issues (although I have not used it in some time). There are link validators, SSL security validators, security analysis tools and many other tools out there.

Do not forget traditional automated unit testing on your back end. It can help isolate errors rather than just saying this page didn't load correctly, for example.

If you are worried about polluting your production database with test data, this may or may not be a good idea in the first place. The risk that your tests could interfere with customers and their data, particularly if there are financial transactions or personally identifiable information (PII) involved, is something you and your management have to weigh up but I would recommend using a separate but identical staging or test environment instead. If you must run tests on a production system, make sure your test data is easily segregated from customer data and purge it after the test run.

Title: Code testing practice

Body:
So now I have come to the conclusion like many others that having some way of constantly testing your code is good practice since it enables fewer people to be involved (colleges and customers alike) by simply knowing what's wrong before someone else finds out the hard way.

I've heard and read some about Unit Testing and understand what it's supposed to do and all. The there are so many different types of bugs. It can be everything from web browser not being able not being able to send correct values, javascript failing, a global function messing up a piece of code somewhere to a change that looked good when testing it out but fails in some special case which was hard to anticipate. My simply finding these errors I learn to rarely repeat them again, but there seems to always be new bugs to be found and learnt from.

I would guess maybe the best practice would be to run every page and it's functions a couple of times, witness the result and repeat this in Firefox, Chrome and Internet Explorer (and all smartphones apparently) to make sure it works as intended. However this would take quite some time to do consider I don't work with patches/versions and do little fixes here and there a couple of times per week.

What I prefer would be some kind of page I can just load that tests as much things as possible to make sure the site works as intended. Basicly just run a lot of cURL's with POST-values and see if I get expected result. But how would I preferably not increase the IDs of every mysql rows if I delete these testing rows? It feels silly to be on ID 1000 with maybe 50 rows in total.

If I could build a new project from scratch I would probably implement some kind of smooth way to return a "TRUE" on testing instead of the actual page. But this solution would for the moment being have to be passed on existing projects.

My question

What would you recommend to be the best way to test my site to make sure that existing functions does their job upon editing the code? Should I consider to implement a lot of edits first, then test manually the entire code to make sure it still works? Is there any nice way of testing codes without "hurting" the ID columns?

Extra thoughs

Would it be a good idea to associate all of my files to the different parts of my site which they affect? For instance if I edit home.php I will through documentation test if my homepage's start works as intended since it's the only part of my site it should affect.


答: Apart from the problems already mentioned, using this approach in environment without automatic garbage collection (e.g. C++) would lead to memory leaks, as the temporary objects are not freed after use. (While this may seem to be a bit far fetched, there are people out there who would just change 'null' to 'NULL' and be happy that the code compiles.)</p>

Title: Name for this antipattern? Fields as local variables

Body:
In some code I'm reviewing, I'm seeing stuff that's the moral equivalent of the following:

```<code>public class Foo
{
    private Bar bar;

    public MethodA()
    {
        bar = new Bar();
        bar.A();
        bar = null;
    }

    public MethodB()
    {
        bar = new Bar();
        bar.B();
        bar = null;
    }
}
</code>```

The field bar here is logically a local variable, as its value is never intended to persist across method calls. However, since many of the methods in Foo need an object of type Bar, the original code author has just made a field of type Bar.

This is obviously bad, right?

Is there a name for this antipattern?


答:
It depends on who you ask for a definition of OOP. Ask five people and you’ll likely get six definitions. Wikipedia says:

Attempts to find a consensus definition or theory behind objects have not proven very successful

So whenever somebody gives a very definitive answer, take it with a grain of salt.

That said, there’s a good argument to be made that, yes, FP is a superset of OOP as a paradigm. In particular Alan Kay’s definition of the term object-oriented programming doesn’t contradict this notion (but Kristen Nygaard’s does). All Kay was really concerned with was that everything is an object, and that logic is implemented by passing messages between object.

Maybe more interestingly for your question, classes and objects can be thought of in terms of functions and closures returned by functions (which act as classes and constructors at once). This comes very close to prototype-based programming, and in fact JavaScript allows doing precisely that.

var cls = function (x) {
    this.y = x;
    this.fun = function () { alert(this.y); };
    return this;
};

var inst = new cls(42);
inst.fun();
```

(Of course JavaScript allow mutating values which is illegal in purely functional programming but nor is it required in a strict definition of OOP.)

The more important question though is: Is this a meaningful classification of OOP? Is it helpful of thinking of it as a subset of functional programming? I think that in most cases, it isn’t.

Body:
It depends on who you ask for a definition of OOP. Ask five people and you’ll likely get six definitions. Wikipedia says:

Attempts to find a consensus definition or theory behind objects have not proven very successful

So whenever somebody gives a very definitive answer, take it with a grain of salt.

That said, there’s a good argument to be made that, yes, FP is a superset of OOP as a paradigm. In particular Alan Kay’s definition of the term object-oriented programming doesn’t contradict this notion (but Kristen Nygaard’s does). All Kay was really concerned with was that everything is an object, and that logic is implemented by passing messages between object.

Maybe more interestingly for your question, classes and objects can be thought of in terms of functions and closures returned by functions (which act as classes and constructors at once). This comes very close to prototype-based programming, and in fact JavaScript allows doing precisely that.

var cls = function (x) {
    this.y = x;
    this.fun = function () { alert(this.y); };
    return this;
};

var inst = new cls(42);
inst.fun();

(Of course JavaScript allow mutating values which is illegal in purely functional programming but nor is it required in a strict definition of OOP.)

The more important question though is: Is this a meaningful classification of OOP? Is it helpful of thinking of it as a subset of functional programming? I think that in most cases, it isn’t.


答:
Any time you care deeply about performance, you generally want to get as close to the metal as you can.  In most languages, you can write out performance critical segments in C code.  C programmers can drop down to assembly language for the really critical stuff.  So if I'm writing some C# code, but I really need a tight performance on an inner loop, I can write some C or C++ code and use interop to call that code.  If I need even more performance, I can write assembly in my C library.  Going lower than assembly is possible, but who wants to write machine code these days?

However, and this is the big consideration, dropping close to the metal is only high-performance for small, tight goals.  If I was writing a 3D renderer, I might do the floating point math and rendering in C, (using a library to execute it on the video card.)  But performance problems are also architectural, and performance issues from large-scale problems are often better solved in a high level language.

Look at Erlang: Ericsson needed a language to do massive parallel work easily, because doing parallel processing was going to get them way more performance than any tightly optimized C routines running on one CPU core.  Likewise, having the fastest code running in your loop is only performance enhancing if you can't remove the loop entirely by doing something better at the high level.

You can do huge system, high level programming in C, but sometimes the greater expressiveness of a more powerful language will show opportunities for architectural optimizations that wouldn't be obvious otherwise.

Title: Object Oriented Programming Language performance ranking

Body:
After reading this post about ideal programming language learning sequence, I am wondering what would have been the answers if the question was performance -instead of learning- oriented ?

Since there are many programming languages I chose to ask the question for OOL to be the least subjective. But any thought or comparison about no-OOL are appreciated :D

If we omit the programming effort, time and costs. What is your ranking of the most powerful object oriented languages ?


问:
Dealing with Fanboys
We've all probably met someone like this, that developer who just knows that his language is the one true language and won't shut up about it. How do you deal like someone like this? I don't want to offend anyone (especially since the fanboy in my workplace is the senior developer). But I want to be able to use my own choice of scripting language when I have to write a throwaway script that never makes it to the repository and no one else need know existed.

Thoughts that I had to dealing with this:

Laugh it off - "Haha yeah maybe language X is a bit easier, I guess I'm a masochist!"

Go with it - I'd really prefer to avoid this as I can't afford the drop in productivity associated with picking up a new language.

Hide my language - Become a closet programmer and hide my monitor whenever I'm scripting or automating something.

What would you suggest for this situation?

答:
Does he decide what you use based on company policy? Appeal your case to him; if he still decides against it, shut up and do your work with the tools your boss says you should use.

You work there, not play there. Ultimately it's out of your hands.

Even if he's not your boss, I would consider all the angles here. Would you like it if he knew Fortran and one day you inherited all his code. You'd have to learn a brand new language from scratch on the fly, that's terribly stressful. Now picture his side, you might write your scripts using Cobol and he may not know Cobol.

Use something the majority of your team knows.

Title: Dealing with Fanboys


答:
Show that in a specific context, another language is a more pragmatic choice.

If the person is passionate about C++ and you're working on a web application project, it wouldn't be too difficult. In the same way, some contexts are very inclined towards functional programming and using a non-functional language would be not very wise.

Notes:

Avoid situations where both your and his preferred language are very similar.

For example, I would hardly imagine a context where Java would be "better" than C#, or C#, "better" than Java.

Remember that the choice of a language is very often subjective and is explained more by the previous experience of a developer rather than some evidence-based elements.

For example if I'm asked to do an application relative to financial sector, I would still use C# rather than Haskell, even if I find Haskell more appropriate and truly exciting. The reason of this choice is that I have years of experience with C#, but when it comes to Haskell, I've only read a few tutorials and never used it professionally.

Title: Dealing with Fanboys

Body:
We've all probably met someone like this, that developer who just knows that his language is the one true language and won't shut up about it. How do you deal like someone like this? I don't want to offend anyone (especially since the fanboy in my workplace is the senior developer). But I want to be able to use my own choice of scripting language when I have to write a throwaway script that never makes it to the repository and no one else need know existed.

Thoughts that I had to dealing with this:

Laugh it off - "Haha yeah maybe language X is a bit easier, I guess I'm a masochist!"

Go with it - I'd really prefer to avoid this as I can't afford the drop in productivity associated with picking up a new language.

Hide my language - Become a closet programmer and hide my monitor whenever I'm scripting or automating something.

What would you suggest for this situation?


答:
The answer is you do not deal with it. Arguing with them just drags the arguer down to their level (where they beat you with experience) and is ultimately unconstructive because they are close minded.

Ignore any arguments they give for or against their language and make up your own mind. Use the usual techniques like avoid eye contact, answer monosylabically and move onto a new subject when silence ensures. Train them to annoy the person next to you instead.

The challenge here is the fan boy associates the language with his or her identity and any negativity associated with that language is personal. Do not attack or defend. Just ignore.

Title: Dealing with Fanboys


答: You should try fogging.  This means to agree with everything the fanboy says (in part or whole), but do your own thing unless explicitly instructed to do otherwise.</p>

Title: Dealing with Fanboys


答:
Few things are jumping out of the question.

Is it really a throwaway script? If it is, it's strange that it's
being discussed.

Are you sure throwaway script will stay as is? A lot of production
stuff has been a throwaway script at some time.

Are you going to rewrite the script if it's promoted and needs
integration in the system?

Is the language choice purely syntactical or is it a language from
another sphere?

I kinda understand the fan-boy part, because from one side, I am behaving kinda like a fan-boy sometimes, while protecting my few languages of choice. And I've also dealt with other fan-boys who try to bring new stuff in.

My view on this situation is like this:

If it's a new language, it belongs in a garbage bin.

If it's an industry proven language, it can be used if it's
specialized for the task.

If it's a very unpopular language, it belongs in a garbage bin, even if
it's super cool and super fast.

It's because no one knows how to write safe and fast software in an unknown language, and it has all the gotchas developers have to learn. The stupid script will have to be supported over 20 years or rewritten. Over 20 years, at least 50 developers change in an average shop. If each one writes few fancy scripts in a new language, you need 50 language runtimes, 50 different expertises on the team, and the codebase has buggy code in 50 languages. And some of the languages are no longer supported on Windows or Linux. And needs that unpatched 10 years old custom server, with no spare parts available, 24/7.

Also, no one really wants to support dead languages like VB, Silverlight, D, etc., when the code-base will probably outlive the language itself.

Title: Dealing with Fanboys


答:
Very few things at a job are truly throwaway scripts.  I wind up putting many such things on the wiki or in the repository anyway in case needed again.

Even things I think are beneath the level of sharing, my teammates often feel differently.  For example, I have a rgrep alias in my .profile.  It's just a find statement with a parameter since I don't have access to real rgrep on that server.  A teammate got wind and wanted it on the wiki..  Yes, the one line statement.  Obviously we didn't have a debate about implementation language - it had to be UNIX.  But it highlights the need to do things others on the team can understand.

Another spin is that it is possible the senior developer has a reason you don't know about for using that language.  Have you asked?

Maybe try making the same script in both languages once to show why yours is better.

Title: Dealing with Fanboys


答:
Murphy's Law of Time Management:  To figure out how long something will take, figure out how long it should take and double it.

Then, move up to the next higher unit of time.  Thus, we allocate two weeks for a one-day project.

Title: How to learn to make better estimates?

Body:
I suck at estimates. When someone asks me how long something will take, I don't even dare to make a guess since I will be completely off the mark. Usually I'm way too optimistic, and should probably multiply my guess with some large X factor...

How can I learn to make better estimates? It's not taught at my uni, and even though we have deadlines for all laborations I never think about how long something will actually take. Which I should. For everyone's sake (especially mine).


问:
Why does java.util.ArrayList allow to add null?
I wonder why java.util.ArrayList allows to add null.  Is there any case where I would want to add null to an ArrayList?

I am asking this question because in a project we had a bug where some code was adding null to the ArrayList and it was hard to spot where the bug was. Obviously a NullPointerException was thrown but not until other code tried to access the element. The problem was how to locate the code that added the null object. It would have been easier if ArrayList threw an exception in the code where the elements was being added.

答:
Null may be a valid value for an element of a list.  Say your list contains elements which represent some optional data about a list of users and is stored in the same order as the users.  If the extra data is populated then your list will contain the additional data otherwise the slot corresponding to a user will be null.  (I'm sure there are better examples, but you get the idea)

if you don't want to allow nulls to be added then you could wrap the array list with your own wrapper which threw when null was added.


答:
ArrayList allows null by design.  It is intentional.  From the javadoc:

"[ArrayList is a] resizable-array implementation of the List interface. Implements all optional list operations, and permits all elements, including null."

The answer to "why" is that if it didn't the ArrayList wouldn't be usable in cases where it is necessary to put a null in the list.  By contrast, you can prevent an ArrayList from containing nulls by either testing values before adding them or using a wrapper that prevents this happening.

Is there any case where I would want to add null to an ArrayList?

Obviously, any case where null has a distinct meaning.  For instance it might mean that the value at a given position in the list has not been initialized or supplied.

It would have been easier if the ArrayList had thrown an exception in the code where the elements was being added.

You could easily implement that behaviour by creating a wrapper class.  However, this is not the behaviour that most programmers / applications need.

Title: Why does java.util.ArrayList allow to add null?

Body:
I wonder why java.util.ArrayList allows to add null.  Is there any case where I would want to add null to an ArrayList?

I am asking this question because in a project we had a bug where some code was adding null to the ArrayList and it was hard to spot where the bug was. Obviously a NullPointerException was thrown but not until other code tried to access the element. The problem was how to locate the code that added the null object. It would have been easier if ArrayList threw an exception in the code where the elements was being added.


答:
This design decision appears mostly driven by naming.

Name ArrayList suggests to reader a functionality similar to arrays - and it is natural for Java Collections Framework designers to expect that vast majority of API users will rely on it functioning similar to arrays.

This in particular, involves treatment of null elements. API user knowing that below works OK:

```<code>array[0] = null; // NPE won't happen here
</code>```

would be quite surprised to find out if similar code for ArrayList would throw NPE:

```<code>arrayList.set(0, null); // NPE => WTF?
</code>```

Reasoning like above is presented in  Collections > Implementations > List Implementations">JCF tutorial stressing points that suggest close similarity between ArrayList and plain arrays:

ArrayList... offers constant-time positional access and is just plain fast...

If you would want a List implementation disallowing nulls, it would better be called like NonNullableArrayList or something like that, to avoid confusing API users.

Side note there is an auxiliary discussion in comments below, along with additional considerations supporting the reasoning laid out here.

Body:
This design decision appears mostly driven by naming.

Name ArrayList suggests to reader a functionality similar to arrays - and it is natural for Java Collections Framework designers to expect that vast majority of API users will rely on it functioning similar to arrays.

This in particular, involves treatment of null elements. API user knowing that below works OK:

array[0] = null; // NPE won't happen here

would be quite surprised to find out if similar code for ArrayList would throw NPE:

arrayList.set(0, null); // NPE => WTF?

Reasoning like above is presented in JCF tutorial stressing points that suggest close similarity between ArrayList and plain arrays:

ArrayList... offers constant-time positional access and is just plain fast...

If you would want a List implementation disallowing nulls, it would better be called like NonNullableArrayList or something like that, to avoid confusing API users.

Side note there is an auxiliary discussion in comments below, along with additional considerations supporting the reasoning laid out here.