问:
What to bring to a programming interview?
I have just completed my Master's degree in Computer Science and have gotten my first job interview as a developer.  I do not have much experience in large scale development projects, but I am hoping my university education counts for something.

I am wondering, what materials should I bring that would impress my interviewers?  What do most interviewers expect, especially from a new graduate?

**Edit:

The job interview went OK, except I forgot my pants.

Thanks for all the great advice!

答:
Take some sample code from projects you've worked on and are proud of.

This code should show how you've solved some sort of problem or how you were able to overcome obstacles during development.

OwnerDisplayName: ddrum

OwnerDisplayName: John Boker


答: A calm mind and open heart.</p>

ContentLicense: CC BY-SA 2.5

Title: What to bring to a programming interview?

Body:
I have just completed my Master's degree in Computer Science and have gotten my first job interview as a developer.  I do not have much experience in large scale development projects, but I am hoping my university education counts for something.

I am wondering, what materials should I bring that would impress my interviewers?  What do most interviewers expect, especially from a new graduate?

**Edit:

The job interview went OK, except I forgot my pants.

Thanks for all the great advice!

Body: A calm mind and open heart.

OwnerDisplayName: ewakened


答: A notepad!  Think of some questions/concerns ahead of time, and take some notes when they describe the job to you.</p>

OwnerDisplayName: devin


答:
Calm and confidence. Don't bring any code, I can tell you that based on my experience in interviewing others.

If you can't talk confidently about what you've achieved, code's just going to get in the way.

In fact, don't bring any external materials unless asked (except something for writing down details). Just show up, answer questions honestly, show a passion (or at least an interest) for the sort of work you're interviewing for, and I believe you're 80% of the way there.


答:
A notepad and pen are good, but bring some humility and enthusiasm - that will impress the interviewer the most ;-)

And pants - remember to wear pants.

OwnerDisplayName: Steven A. Lowe


答:
Frankly, I would suggest taking nothing at all. It won't affect the interviewer's opinion of you at all if you turn up with nothing. - My opinion from experience

If you must take something to an interview, take some CDs of projects you have worked on in the past for the interviewers to look at later.

OwnerDisplayName: Nick Grubb


答:
Your resume

Perhaps a laptop with some work on it that you may demonstrate if the conversation ever comes up.

A shortlist of links of pages you might have contributed to, if applicable

Energy.. its amazing how many people I interviewed with no energy/motivation whatsoever..

I don't say you should take it with you to impress anyone, but don't be afraid to have something non-interview-related with you, like a newspaper if its something you usually have.

Whatever you take with you, take it in an organized fashion, just proving you are organized with the stuff you carry with you gives out a few + points

OwnerDisplayName: Ric Tokyo


答:
I agree with the others, don't burden yourself with anything except maybe a small notepad.  Maybe a book to read because you might be left sitting around waiting.  Just show up, be confident, answer questions honestly.  You might want to bring a cheat sheet of questions to ask them about what the job will be like, if that sort of thing helps you.  Remember, you're interviewing them as much as they're interviewing you.  Worry more about meeting and getting along with the people then being grilled about technical questions.

I disagree about code.  Don't bring code, but make sure they already have a sample of your code on some real project.  Make sure it's code you're allowed to show people, so no code from a previous job.  Open Source code from a real project is ideal.  Realistic code samples answer a lot of questions about what sort of programmer you're going to be, and it shows you're not just a 9-to-5 programmer.  That you're going to expand your skills outside of work.

You should spend most of your time preparing by investigating the company, what they do and how they do it.  Bone up on whatever it is they do so you're not completely blind sided, even if it's just reading a few Wikipedia articles.  This will also let you show honest interest and ask more questions, which is good.

Finally, get a good night's sleep, eat a good meal before hand, err on the side of being early, go to the bathroom before heading in, and turn off your cell phone.

OwnerDisplayName: Schwern


答:
Bring one printed copy of your resume for each person you'll be interviewing with, plus another copy for yourself. Chances are, they've already printed and distributed your resume, but it never hurts to have a few extra copies handy. I once had an interviewer ask for a copy of my resume, and I had to say "Sorry, I didn't bring it." I felt like an idiot and never repeated that mistake.

Other than that, bring a pad of paper and a pen. Sometimes, interviews will be conducted in rooms without whiteboards, and sometimes you just need to draw a quick diagram to explain an idea. If you have paper and a pen, you're golden.

Things to NOT bring: cell phone, laptop, sample code (brief rant: I wish it was acceptable in the industry to bring sample code; I hate writing whiteboard code, but I have thousands upon thousands of lines of code in my personal portfolio that I'd be proud to show).

If possible, I also try to keep my pockets completely empty. I leave my wallet in the car, and I remove my car key from its usual keyring, carrying only the single key. For some reason, having stuff in my pockets is a distraction during an interview, so I prefer to travel light.

OwnerDisplayName: benjismith


答:
Just knowledge and nothing else.

Although maybe a cool gadget will make a slightly better impression in interviewers eyes but I wouldn't count on that.

No one is going to look at the code, they won't be sure it's you who wrote it anyway. And they will have paper and pen ready for you, that's for sure.

OwnerDisplayName: vava


答: Breath mints, nothing ruins first impressions more than gagging when a candidate speaks first to you!</p>

OwnerDisplayName: ninesided


答:
From my experience hiring coders:

Be ready to undergo a coding test

Wear a suit that fits!

OwnerDisplayName: Chris KL


答:
Bringing along code (of some form) that you consider "good code" and then being able to explain clearly why you think it is good, is one of the best ways to prove and demonstrate that you are passionate about your work and are willing to stand by it.

This may be code you worked on yourself or could actually be open souce code for example that you happen to admire for certain aspects.

Of course many companies will not specifically request code at an interview, that doesn't mean you can't have it with you anyway.  Some interviewers might not even think to ask, but would be interested in seeing it anyway.  Offer it, but just don't force it on the interviewer if there is little interest.

As Joel and Jeff have spoken about on the podcast/blogs, "Why would you hire someone to be a programmer and not want to check that they can actually write decent code?".

In fact, the way in which the interviewers respond to your code, their level of enthusiasm and the depth of the questions they ask you about it, are very insightful in helping you to decide if you this company is for you.

Sadly I've never been asked to present/discuss some code in an interview.  The nearest I've come to is a basic (very) coding test.

However, from what I've seen, software companies should ask for code at interviews more often, software quality could only improve by at least eliminating people who "would be better in another career".

OwnerDisplayName: Ash


答: Just bring copies of your resume.  On-site interviews that I have been through usually last 1/2 - 1 day with multiple interviewers.</p>

OwnerDisplayName: bob


答: Be specific to the interview -- try to gather some info about the job you're applying to and present relevant facts to the interviewer, i.e. if it's a Rails development shop they probably won't get too excited about that Gtk+ Widget you wrote, but that could change if the code repository is available on GitHub.  </p>

OwnerDisplayName: pantulis


答:
Courage. The courage to decline the position if your would-be boss or your would-be peers treat you rudely or unprofessionally on the interview. Be confident and be perceptive.

Now, more practically, I would say you need to bring a pen. And that's about it.

OwnerDisplayName: Jeremy Ricketts


答:
Re: bringing code or not bringing code. The one sure thing about interviews is they'll want your resume (if you haven't already provided it). everything else is up to the interviewer.

Interview 101 - when arranging the interview, you ask "Is there anything you'd like me to bring, some example code perhaps?"

Let them tell you, don't try to guess.

OwnerDisplayName: nailitdown


答:
Honesty and modesty.

Dress appropriate for the job (ie: don't wear a nice suit for a mechanical engineering job)

Ask the employer what they would like you to bring. You need the job, so find out what you need

Be ready for an on the spot code-test. If this happens, don't try and impress the employer with something fancy but doesn't actually work. Make it functional, what they want, nothing more, nothing less.

Be yourself.

And best wishes to you! I hope you get the job you want!

OwnerDisplayName: ddrum

OwnerDisplayName: danderson


答: Bring some questions to show interest in the employer and their business!</p>

OwnerDisplayName: Niklas Winde


问:
What does 'opinionated software' really mean?
I've seen a lot of other framework/library developers throw the phrase 'we write opinionated software' around, but in practical terms, what does that really mean? Does it mean that the author of the 'Opinionated Framework X' says that because they write code a certain way, you should be writing the same type of code that they write?

Isn't that a bit pretentious?

答: The framework is saying "I know the one true way to do this thing, and I'll fight you if you try it any other way".  Opinionated. </p>

ContentLicense: CC BY-SA 3.0


答:
The answer depends entirely on the type of company you're interviewing with.

I can only really answer for the company I work for (a fairly relaxed agency) - but if you wear a suit to one of our interviews, we'll be wondering whether you're a fit for the culture.

As for taking 'things' - nothing that you wern't asked to bring, unless you don't have an option (eg travelling to the interview by public transport).

The only exception is, as others have said, to bring a bring a few copies of your resume - at least two.

Knowing your stuff is the key thing to 'bring' to the interview. Do your research about the role and the company.

Be up-front when you don't know an answer.
Ask clarifying questions if you don't understand the question.

Interviewers shouldn't (imo) be asking trick questions, but they might ask you to give an example of how you would implement something. Listen to the stated requirements carefully.

Be prepared for a code review.

OwnerDisplayName: Will


答:
Bring nothing but yourself unless asked to.

Don't worry about a lack of track record. If I were interviewing you, I'd home in on how you approached your masters project: How you dealt with difficulties as they came up. I'd try to get a feel for how quickly you acquired skills and techniques. More than anything else, I'd be keen on seeing how good you were at finding things out without help.

One of the most tiresome sort of people I've ever had in a programming team are those who aren't self-motivating, and who don't 'take ownership'. When they finish allotted tasks, they sit there inert, or trawling social sites under the apparent impression that this is acceptable behavior. If you show that you can take initiative, work under only light supervision, have the social skills necessary for team-work, and will stick at tasks then you are every team-leader's dream.

OwnerDisplayName: Phil Factor


答: Give your name on stackoverflow, they will see how high your reps is ! :D</p>

OwnerDisplayName: Nicolas Dorier


问:
How can I deal with the cargo-cult programming attitude?
I have some computer science students in a compulsory introductory programming course who see a programming language as a set of magic spells, which must be cast in order to achieve some effect (instead of seeing it as a flexible medium for expressing their idea of solution).

They tend to copy-paste code from previous, similar-looking assignments without considering the essence of the problem.

Are there some exercises or analogies to make these students more confident that they can, and should, understand the structure and meaning of each piece of code they write?

答: Make them do the assignment in front of you in the classroom with no Internet access provided (have the school cut it off, allow no phone use as well during class). At least do this for tests. There is no reason at all that they should be using the Internet for basic programming expercises. The book should be a sufficient resource for intro exercises. Allow Internet usage once you are in an advanced class and they already have learned how to think. </p>


答:
Unfortunately, thats the way a lot of people's brains work.  So go into this understanding that there are people who you cant 'cure' of this.  There are a lot of people who are unable to work at the level of mental precision necessary for programming.  Some people are simply not designed for it.  I'm not saying give up on the students - I'm saying dont assume you are failing if not everyone picks it up.

Without knowing more about the context of the class, I'd say focus more with these problem students on the very basic structures - simple if/thens, loops, etc.  Simple routines to print out odd numbers, every tenth number, etc.  Nothing more than 10 lines of code each.  If they are 'magic thinking' they obviously havent mastered those basics yet.  Have them do a lot of different simple routines until they grasp whats going on.  Someone else mentioned writing the code out on paper - I think that'd also be a great way to do these simple routines.

You also might consider having them learn flow charting.  For some people, being able to see the flow of an algorithm, and then how that connects to code, may be helpful to them connecting the code to the flow.

Title: How can I deal with the cargo-cult programming attitude?

Body:
I have some computer science students in a compulsory introductory programming course who see a programming language as a set of magic spells, which must be cast in order to achieve some effect (instead of seeing it as a flexible medium for expressing their idea of solution).

They tend to copy-paste code from previous, similar-looking assignments without considering the essence of the problem.

Are there some exercises or analogies to make these students more confident that they can, and should, understand the structure and meaning of each piece of code they write?


答:
Some food in your belly.

One time I went for an interview that lasted for 4-5 hours and I did not eat much beforehand because of nervousness. My stomach started crumbling and hurting halfway through the interview and it was not comfortable at all.

So eat food beforehand that will give you energy and stays with you for hours but does not weigh you down. A light lunch an hour before should do. If you only want to snack, some almonds and a little protein shake will do.


问:
Self-documenting code vs Javadocs?
Recently I've been working on refactoring parts of the code base I'm currently dealing with - not only to understand it better myself, but also to make it easier for others who are working on the code.

I tend to lean on the side of thinking that self-documenting code is nice. I just think it's cleaner and if the code speaks for itself, well... That's great.

On the other hand we have documentation such as javadocs. I like this as well, but there's a certain risk that comments here gets outdated (as well as comments in general of course). However, if they are up-to-date they can be extremely useful of say, understanding a complex algorithm.

What are the best practices for this? Where do you draw the line between self-documenting code and javadocs?

答:
I think that with javadocs, things are the same as with any documentation at all - main rule is:

follow the audience

Do many people read your javadocs? If yes, it makes good sense to invest efforts into getting it right.

Do your readers tend to skip reading code in favor of studying javadocs? If yes, it makes twice as much sense to spend efforts on writing it well.

This is exactly the case with JDK documentation. Guess Sun/Oracle spent a lot efforts on these and they seem to have a nice payback in API docs being used a lot by community.

Now, is it your case? If not, think twice whether efforts invested into javadocs are justified.

As already pointed above, listen to the audience to find out the way.

If you hear active complaints about insufficient documentation, consider investing into improving it.

If, on the other hand, all you hear is developers whining about braindead rules forcing them to waste time on useless typing, well, then chances are high that your javadocs efforts are like investing into subprime mortgages. Think of better investments instead.

Title: Self-documenting code vs Javadocs?


问:
Elegant ways to handle if(if else) else
This is a minor niggle, but every time I have to code something like this, the repetition bothers me, but I'm not sure that any of the solutions aren't worse.

if(FileExists(file))
{
    contents = OpenFile(file); // <-- prevents inclusion in if
    if(SomeTest(contents))
    {
        DoSomething(contents);
    }
    else
    {
        DefaultAction();
    }
}
else
{
    DefaultAction();
}
```

Is there a name for this kind of logic?

Am I a tad too OCD?

I'm open to evil code suggestions, if only for curiosity's sake...

答:
Of course you can only go so far in scenarios like these, but here's a way to go:

interface File<T> {
    function isOK():Bool;
    function getData():T;
}

var appleFile:File<Apple> = appleStorage.get(fileURI);
if (appleFile.isOK())
    eat(file.getData());
else
    cry();
```

<p>You may want additional filters. Then do this:</p>

<pre class="lang-cs prettyprint-override"><code>var appleFile = appleStorage.get(fileURI, isEdible);
//isEdible is of type Apple->Bool and will be used internally to answer to the isOK call
if (appleFile.isOK())
    eat(file.getData());
else
    cry();
</code>```

Although this might make sense just as well:

function eat(apple:Apple) {
     if (isEdible(apple))
         digest(apple);
     else
         die();
}
var appleFile = appleStorage.get(fileURI);
if (appleFile.isOK())
    eat(appleFile.getData());
else
    cry();
```

Which is the best? That depends on the real world problem you're facing.

But the thing to take away is: you can do a lot with composition and polymorphism.

Title: Elegant ways to handle if(if else) else

Body:
Of course you can only go so far in scenarios like these, but here's a way to go:

interface File<T> {
    function isOK():Bool;
    function getData():T;
}

var appleFile:File<Apple> = appleStorage.get(fileURI);
if (appleFile.isOK())
    eat(file.getData());
else
    cry();

You may want additional filters. Then do this:

var appleFile = appleStorage.get(fileURI, isEdible);
//isEdible is of type Apple->Bool and will be used internally to answer to the isOK call
if (appleFile.isOK())
    eat(file.getData());
else
    cry();

Although this might make sense just as well:

function eat(apple:Apple) {
     if (isEdible(apple))
         digest(apple);
     else
         die();
}
var appleFile = appleStorage.get(fileURI);
if (appleFile.isOK())
    eat(appleFile.getData());
else
    cry();

Which is the best? That depends on the real world problem you're facing.

But the thing to take away is: you can do a lot with composition and polymorphism.


问:
What is the supposed productivity gain of dynamic typing?
I often heard the claim that dynamically typed languages are more productive than statically typed languages. What are the reasons for this claim? Isn't it just tooling with modern concepts like convention over configuration, the use of functional programming, advanced programming models and use of consistent abstractions - all of which could be used in statically typed languages as well? Admittedly there is less clutter because the (for instance in Java) often redundant type declarations are not needed, but you can also omit most type declarations in statically typed languages that use type inference, without losing the other advantages of static typing. And all of this is available for modern statically typed languages like Scala as well.

So: what is there to say for productivity with dynamic typing that really is an advantage of the type model itself?

Clarification: I'm more interested in big / medium sized projects than in quick hacks. :-)

答:
One advantage I've found with most dynamic languages is that they make it easier to write more generic code. It's much easier to write at a higher level of abstraction when you don't have to fight the type system to do so.

You don't have to think about it as much--writing code that does something nontrivial with any object in Java is difficult and probably requires reflection which is basically dynamically typed; with something like JavaScript, writing a function that does something interesting to all objects is second nature. A perfect example would be a function I recently wrote that takes an object and replaces all of its methods with ones that do the same thing but also fire off an event. I have no idea how to approach something like this in Java. However, I'm not sure how much of this is due to the type systems and how much is due to other language differences.

However, I've recently started using Haskell. Haskell lets me write abstract, generic code as easily as any dynamically typed language I've used. My Java/JavaScript example above makes no sense in Haskell because it doesn't have objects, methods, events or even much mutation, but other sorts of generic code are really easy to write.

In fact, Haskell can write some generic code that dynamically typed languages can't; a perfect example is the read function which is basically the opposite of toString. You can get an Int or a Double or whatever type you want (as long as it's in a certain type class). You can even have polymorphic constants, so maxBound can be the maximum Int, Double, Char...etc., all depending on what type it's supposed to be.

My theory now is that the productivity gain from using a dynamic language is always in comparison to languages like Java with less capable, more verbose and less flexible type systems.

However even Haskell's type system has some annoying issues that you would not have in a dynamically typed language. The biggest one I've been annoyed about is the way numbers are handled; for example, you have to mess around with the type system to use length (of a list) as a double, something you would have no issues with without a type system. Another annoying thing I've run into is working with Word8 (an unsigned int type) and functions which expect Int.

So, ultimately, having no type system makes it easier to write generic code without thinking too much and also avoids annoying pitfalls of type systems. You never have to fight the type system in a dynamic language, but you can't rely on it either.

ContentLicense: CC BY-SA 4.0


答: I just want to comment on the concern that Javadoc comments might get outdated. While @JonathanMerlet is right in saying that the Javadoc should be stable, you can also help by reviewing Javadoc and comments as well as code during peer review. Do the comments match with what the code is doing? If not, which is incorrect, and insist the developer fix it. Try to encourage other developers to do the same. This helps keep not only external documentation (Javadoc comments) up-to-date, but also any regular code comments as well. This helps developers who come along after your refactoring understand the code more quickly and easily, and makes maintaining it much simpler in the future. </p>

Title: Self-documenting code vs Javadocs?

Body:
Recently I've been working on refactoring parts of the code base I'm currently dealing with - not only to understand it better myself, but also to make it easier for others who are working on the code.

I tend to lean on the side of thinking that self-documenting code is nice. I just think it's cleaner and if the code speaks for itself, well... That's great.

On the other hand we have documentation such as javadocs. I like this as well, but there's a certain risk that comments here gets outdated (as well as comments in general of course). However, if they are up-to-date they can be extremely useful of say, understanding a complex algorithm.

What are the best practices for this? Where do you draw the line between self-documenting code and javadocs?


问:
Single responsibility principle - am I overusing it?
For reference - http://en.wikipedia.org/wiki/Single_responsibility_principle

I have a test scenario where in one module of application is responsible for creating ledger entries. There are three basic tasks which could be carried out -

View existing ledger entries in table format.

Create new ledger entry using create button.

Click on a ledger entry in the table (mentioned in first pointer) and view its details in next page. You could nullify a ledger entry in this page.

(There are couple more operation/validations in each page but fore sake of brevity I will limit it to these)

So I decided to create three different classes -

LedgerLandingPage

CreateNewLedgerEntryPage

ViewLedgerEntryPage

These classes offer the services which could be carried out in those pages and Selenium tests use these classes to bring application to a state where I could make certain assertion.

When I was having it reviewed with on of my colleague then he was over whelmed and asked me to make one single class for all. Though I yet feel my design is much clean I am doubtful if I am overusing Single Responsibility principle

答:
Let's examine these classes:

LedgerLandingPage: The role of this class is to show a list of ledgers. As the application grows, you will probably want to add methods for sorting, filtering, highliting and transparently fuse in data from other data sources.

ViewLedgerEntryPage: This page shows the ledger in detail. Seems pretty straight forward. As long as the data is straight forward. You can nullify the ledger here. You could also want to correct it. Or comment it, or attach a file, receipt or external booking number or whatever. And once you allow editing, you definitely want to show a history.

CreateLedgerEntryPage: If the ViewLedgerEntryPage has full editing capability, the responsibility of this class can possibly be fulfilled by editing a "blank entry", which may or may not make sense.

Theses examples may seem a little far fetched, but the point is, that from a UX we're talking features here. A single feature is definitely a a distinct, single responsibility. Because the requirements to that feature can change and the requirements of two different features can change into two opposing directions, and then you wish you had stuck with the SRP from the beginning.

But conversely, you can always slap a facade onto three classes, if having a single interface is more convenient for whatever reason you can think of.

There is such a thing as SRP overuse: If you require a dozen classes to read the contents of a file, it's rather safe to assume you're doing just that.

If you look at the SRP from the other side, it actually says, that a single responsibility should be taken care of by a single class. Please note however, that responsibilities exist only within abstraction levels. So it makes perfectly sense for a class from a higher abstraction level to carry out its responsibility by delegating work to lower level component, which is best achieved through dependency inversion.


问:
Struggling with the Single Responsibility Principle
Consider this example:

I have a website. It allows users to make posts (can be anything) and add tags that describe the post. In the code, I have two classes that represent the post and tags. Lets call these classes Post and Tag.

Post takes care of creating posts, deleting posts, updating posts, etc.
Tag takes care of creating tags, deleting tags, updating tags, etc.

There is one operation that is missing. The linking of tags to posts. I am struggling with who should do this operation. It could fit equally well in either class.

On one hand, the Post class could have a function that takes a Tag as a parameter, and then stores it in a list of tags. On the other hand, the Tag class could have a function that takes a Post as a parameter and links the Tag to the Post.

The above is just an example of my problem. I am actually running into this with multiple classes that are all similar. It could fit equally well in both. Short of actually putting the functionality in both classes, what conventions or design styles exist to help me solve this problem. I am assuming there has to be something short of just picking one?

Maybe putting it in both classes is the correct answer?

答:
Personally, I wouldn't add that functionality to either of them.

To me, both Post and Tag are data objects, so shouldn't be handling database functionality. They should simply exist. They're meant to hold data, and be used by other parts of your application.

Instead, I'd have another class that is responsible for your business logic and data pertaining to your web page. If your page is displaying a post and allowing users to add tags, then the class would have a Post object, and contain functionality to add Tags to that Post. If your page is displaying tags and allowing users to add posts to those tags, it would contain a Tag object and have functionality to add Posts to that Tag.

That's just me though. If you feel that you must handle database functionality in your data objects, then I'd recommend pdr's answer


问:
What are the relative merits for implementing an Erlang-style "Continuation" pattern in C#
What are the relative merits (or demerits) for implementing an Erlang-style "Continuation" pattern in C#. I'm working on a project that has a large number of Lowest priority threads and I'm wondering if my approach may be all wrong.

It would seem there is a reasonable upper limit to the number of long-running threads that any one Process 'should' spawn. With that said, I'm not sure what would signal the tipping-point for too many thread or when alternate patterns such as "Continuation" would be more suitable.

In this case, many of the threads do a small amount of work and then sleep until woken to go again (Ex. Heartbeat, purge caches, etc...). This continues for the life of the Process.

答:
A thread model is really more for when a task is continually running.  What you're describing is more of an event model.  In response to a timer elapsing, you run through a function once, then the timer is reset.  You only have enough threads to handle whatever events are running at any given moment, and you can have a ton of pending timers without even noticing.

Continuations are kind of a workaround to allow you to retain state in functional programming, but retaining state is what objects are all about.  Store whatever you need in a field, and it will be available to you the next time the event fires.


答:
Alistair Cockburn talks about the concept of Shu-Ha-Ri and how it applies to programming, http://alistair.cockburn.us/Shu+Ha+Ri. I think it may be important to bear in mind where your students are in this continuum.  First that will help ease some of your frustration. Copy/imitate is a very natural response and accepted mode when you are first starting to learn something.  Second, it may help you get some ideas of how to move forward. For example, you may want to consider choosing a problem that can be solved in multiple ways (loops vs. recursion, console vs. web/gui) then explicitly have them first solve it one way, then another way -- bonus they can learn about legitimate code reuse, componentization, creating reusable libraries, etc.

Another successful way that I've seen used is to have a series of projects that build on one another, making a default, working version available at each step after assignments have been handed in to prevent people from falling behind.  Each step of the process should introduce something new.  I'll grant you that this may be easier to do in a design class than a programming class, but it should still be doable.  One nice thing about this is that you explicitly give them a good (hopefully) implementation to compare against theirs at each step.  Expose this comparison as an assignment, i.e., do a mini-code review of their own code against their effort.  You might want to make this one of several extra credit options.

While I'm typically not big on "comments," you might want to make documentation of the code one of the grade items.  Have them produce a "Theory of Operation" document for each project that describes their approach, how each component fits in, and how they together solve the problem.  Normally, I'd want the code to do much of this on its own, but it would drive them to put their thinking caps on and put it to paper.

Lastly, you might want to get creative and have your students review each other's code and give it an evaluation.  Put peer pressure to work for you. Allow this to become part of the grade or extra credit for the highest rated code (and docs).


答:
I'd extract it to a separate method and then:

if(!FileExists(file))
{
    DefaultAction();
    return;
}

contents = OpenFile(file);
if(!SomeTest(contents))
{
    DefaultAction();
    return;
}

DoSomething(contents);
```

<p>which also allows for</p>

<pre class="lang-cs prettyprint-override"><code>if(!FileExists(file))
{
    DefaultAction();
    return Result.FileNotFound;
}

contents = OpenFile(file);
if(!SomeTest(contents))
{
    DefaultAction();
    return Result.TestFailed;
}

DoSomething(contents);
return Result.Success;
</code>```

then possibly you could remove the the DefaultAction calls and leave executing the DefaultAction for the caller:

Result OurMethod(file)
{
    if(!FileExists(file))
    {
        return Result.FileNotFound;
    }

    contents = OpenFile(file);
    if(!SomeTest(contents))
    {
        return Result.TestFailed;
    }

    DoSomething(contents);
    return Result.Success;
}

void Caller()
{
    // something, something...

    var result = OurMethod(file);
    // if (result == Result.FileNotFound || result == Result.TestFailed), or just
    if (result != Result.Success)
    {
        DefaultAction();
    }
}
```

I like Jeanne Pindar's approach as well.

Title: Elegant ways to handle if(if else) else

Body:
This is a minor niggle, but every time I have to code something like this, the repetition bothers me, but I'm not sure that any of the solutions aren't worse.

if(FileExists(file))
{
    contents = OpenFile(file); // <-- prevents inclusion in if
    if(SomeTest(contents))
    {
        DoSomething(contents);
    }
    else
    {
        DefaultAction();
    }
}
else
{
    DefaultAction();
}
```

Is there a name for this kind of logic?

Am I a tad too OCD?

I'm open to evil code suggestions, if only for curiosity's sake...

Body:
I'd extract it to a separate method and then:

if(!FileExists(file))
{
    DefaultAction();
    return;
}

contents = OpenFile(file);
if(!SomeTest(contents))
{
    DefaultAction();
    return;
}

DoSomething(contents);

which also allows for

if(!FileExists(file))
{
    DefaultAction();
    return Result.FileNotFound;
}

contents = OpenFile(file);
if(!SomeTest(contents))
{
    DefaultAction();
    return Result.TestFailed;
}

DoSomething(contents);
return Result.Success;

then possibly you could remove the the DefaultAction calls and leave executing the DefaultAction for the caller:

Result OurMethod(file)
{
    if(!FileExists(file))
    {
        return Result.FileNotFound;
    }

    contents = OpenFile(file);
    if(!SomeTest(contents))
    {
        return Result.TestFailed;
    }

    DoSomething(contents);
    return Result.Success;
}

void Caller()
{
    // something, something...

    var result = OurMethod(file);
    // if (result == Result.FileNotFound || result == Result.TestFailed), or just
    if (result != Result.Success)
    {
        DefaultAction();
    }
}

I like Jeanne Pindar's approach as well.


答:
The whole of all modern language features is so big, that static vs. dynamic typing alone doesn't carry much weight.

The rule is, the better your language features, the shorter your code. That's quite simple. Java shows how static typing can go awfully wrong, which gives its opponents much to feed on. Poorly designed language features generally come with a cost, and static typing in Java is firstly a mandatory feature (otherwise most people probably wouldn't even use it) and secondly poorly executed.

This is why in comparison most dynamic languages shine, even though I would argue that PHP doesn't really make your life better in the grand total (at least until recently), because of many other quirks unrelated to type systems.

On the other hand you have a lot of languages with expressive type systems that don't get in your way and that even aren't mandatory. And some of them even allow embedding untyped code, whenever you need to escape the type system.

Personally, I use haXe, which is a language with type inference, both nominal and structural subtyping, optional untyped code, first class function types, algebraic datatypes and (not quite mature but extremely powerful) lexical macros, all the while avoiding arcane syntax. After using haXe for about 3 years now, I have come to a simple conclusion:

Programming becomes far easier, when your language doesn't lock you into religious choices about paradigms but tries to just be a good tool. There's a number of static and dynamic languages and mixed languages, that succeed at that. Some of them are easy to learn, most hard to master.

Their power comes from the way their individual features can be composed to easily create simple solutions to complex problems. This precludes a certain orthogonality that can only be achieved through a delicate balance of inclusion or omission of all language features explored so far. If you tried to add static typing to Ruby, you would cripple it, if you tried to take it away from Haskell, you would crush it. In contrast to that: if you took it away from C, people would hardly notice and if you took it away from Java, some might thank you.

From my personal experience, I can tell you this: I like Ruby. It broadened my horizons and the way I design systems. IMHO it should be used to teach people programming in the first place. It is unobtrusive, powerful, concise, fun. I understand why somebody coming from an orthodox language will enjoy it.

On the long run however, static typing permits to defer work to the static analyzer and with type inference this comes basically at no cost. The result is code that is easier to maintain and often runs faster.

But again, static typing alone can't do a thing. It's a matter of combination. I think somewhere between F#, Scala, Nemerle, OCaml or haXe you can find your very own optimum. But that ultimately depends on you, because the language should allow you to embed your thoughts without effort, instead of forcing you to bend them around it. And after all, nothing yields more productivity gain, than if programming is fun.

Title: What is the supposed productivity gain of dynamic typing?

Body:
I often heard the claim that dynamically typed languages are more productive than statically typed languages. What are the reasons for this claim? Isn't it just tooling with modern concepts like convention over configuration, the use of functional programming, advanced programming models and use of consistent abstractions - all of which could be used in statically typed languages as well? Admittedly there is less clutter because the (for instance in Java) often redundant type declarations are not needed, but you can also omit most type declarations in statically typed languages that use type inference, without losing the other advantages of static typing. And all of this is available for modern statically typed languages like Scala as well.

So: what is there to say for productivity with dynamic typing that really is an advantage of the type model itself?

Clarification: I'm more interested in big / medium sized projects than in quick hacks. :-)


问:
Online Advertising And Marketing Your Services?
I have been working on freelance sites for a good 4 or 5 years, bending over backwards to build a decent portfolio and generate great ratings. I take huge pride in my work (web applications).

I'm completely lost because when I think what would happen if I suddenly lost my freelance account it isn't a pretty picture. I have literally no idea where else I could advertise my services apart from google paid advertising.

Any suggestions? I'd of course be more than willing to pay for marketing and such. I've been searching google for ages and can't find much advice on where to advertise to secure good clients for web development work.

I say good clients because I mean actual business owners, not somebody else who is outsourcing to me (where do they find clients?). I'd appreciate any help.

答:
It sounds like the first thing you need to do is make yourself a web application that has your portfolio on it if you don't already have one, so if whatever site you are using loses your portfolio you still have all the information available. I would also consider creating an LLC or private corporation or something as well. Then take your website you create and make sure you make it available to people looking you up everywhere you frequent, your SE profile, your freelancer profiles, other forums profiles/post signatures...

Essentially do for yourself what I assume you have done for many of your clients.


问:
Clang warning flags for Objective-C development
As a C & Objective-C programmer, I'm a bit paranoid with the compiler warning flags.

I usually try to find a complete list of warning flags for the compiler I use, and turn most of them on, unless I have a really good reason not to turn it on.

I personally think this may actually improve coding skills, as well as potential code portability, prevent some issues, as it forces you to be aware of every little detail, potential implementation and architecture issues, and so on...

It's also in my opinion a good every day learning tool, even if you're an experienced programmer.

For the subjective part of this question, I'm interested in hearing other developers (mainly C, Objective-C and C++) about this topic.

Do you actually care about stuff like pedantic warnings, etc? And if yes or no, why?

Now about Objective-C, I recently completely switched to the LLVM toolchain (with Clang), instead of GCC.

On my production code, I usually set this warning flags (explicitly, even if some of them may be covered by -Wall):

-Wall

-Wbad-function-cast

-Wcast-align

-Wconversion

-Wdeclaration-after-statement

-Wdeprecated-implementations

-Wextra

-Wfloat-equal

-Wformat=2

-Wformat-nonliteral

-Wfour-char-constants

-Wimplicit-atomic-properties

-Wmissing-braces

-Wmissing-declarations

-Wmissing-field-initializers

-Wmissing-format-attribute

-Wmissing-noreturn

-Wmissing-prototypes

-Wnested-externs

-Wnewline-eof

-Wold-style-definition

-Woverlength-strings

-Wparentheses

-Wpointer-arith

-Wredundant-decls

-Wreturn-type

-Wsequence-point

-Wshadow

-Wshorten-64-to-32

-Wsign-compare

-Wsign-conversion

-Wstrict-prototypes

-Wstrict-selector-match

-Wswitch

-Wswitch-default

-Wswitch-enum

-Wundeclared-selector

-Wuninitialized

-Wunknown-pragmas

-Wunreachable-code

-Wunused-function

-Wunused-label

-Wunused-parameter

-Wunused-value

-Wunused-variable

-Wwrite-strings

I'm interested in hearing what other developers have to say about this.

For instance, do you think I missed a particular flag for Clang (Objective-C), and why?

Or do you think a particular flag is not useful (or not wanted at all), and why?

EDIT

To clarify the question, note that -Wall only provides a few basic warnings.

They are actually a lot more warning flags, not covered by -Wall, hence the question, and the list I provide.

答:
I typically go with Xcode's default settings for a new project; it provides a good balance of helpful vs. annoying. Any specific list of warnings and other compiler options will be based largely on either personal preference or project requirements, so I don't think there's a lot of value in trying to go through your list and argue for or against specific warnings. If it works for you, great. If you find that you've made some error that the compiler should be able to detect and you'd like help with that in the future, look for a compiler option to warn about that and turn it on.

One thing that many programmers advocate is turning on the "Treat Warnings as Errors" (-Werror) option to prevent builds from completing with success if there are any warnings.

OwnerDisplayName: Macmade


答:
How about this solution:

content = NULL; //I presume OpenFile returns a pointer
if(FileExists(file))
    contents = OpenFile(file);
if(content != NULL && SomeTest(contents))
    DoSomething(contents);
else
    DefaultAction();
```

I made the assumption that OpenFile returns a pointer, but this could work also with value type return by specifying some default value not returnable (error codes or something like that).

Of course I don't expect some possible action via the SomeTest method on NULL pointer (but you never know), so this could be also seen as an extra check for NULL pointer for the SomeTest(contents) call.

Title: Elegant ways to handle if(if else) else

Body:
How about this solution:

content = NULL; //I presume OpenFile returns a pointer
if(FileExists(file))
    contents = OpenFile(file);
if(content != NULL && SomeTest(contents))
    DoSomething(contents);
else
    DefaultAction();

I made the assumption that OpenFile returns a pointer, but this could work also with value type return by specifying some default value not returnable (error codes or something like that).

Of course I don't expect some possible action via the SomeTest method on NULL pointer (but you never know), so this could be also seen as an extra check for NULL pointer for the SomeTest(contents) call.


答:
More seriously than the repetition of the call to DefaultAction is the style itself because the code is written non-orthogonal
(see this answer for good reasons for writing orthogonally).

To show why non-orthogonal code is bad consider the original example,
when a new requirement that we should not open the file if it is stored
on a network disk is introduced. Well, then we could just update the code to
the following:

if(FileExists(file))
{
    if(! OnNetworkDisk(file))
    {
        contents = OpenFile(file); // <-- prevents inclusion in if
        if(SomeTest(contents))
        {
            DoSomething(contents);
        }
        else
        {
            DefaultAction();
        }
    }
    else
    {
        DefaultAction();
    }
}
else
{
    DefaultAction();
}
```

<p>But then there also comes a requirement that we should not open large files over 2Gb either.
Well, we just update again:</p>

<pre class="lang-cs prettyprint-override"><code>if(FileExists(file))
{
    if(LessThan2Gb(file))
    {
        if(! OnNetworkDisk(file))
        {
            contents = OpenFile(file); // <-- prevents inclusion in if
            if(SomeTest(contents))
            {
                DoSomething(contents);
            }
            else
            {
                DefaultAction();
            }
        }
        else
        {
            DefaultAction();
        }
    else
    {
        DefaultAction();
    }
}
else
{
    DefaultAction();
}
</code>```

It should be very clear that such code style will be a huge maintenance pain.

Among the answers here which is written properly orthogonally are Abyx' second example and Jan Hudec's answer, so I will not repeat that, just point out that adding the two requirements in those answers would just be

if(! LessThan2Gb(file))
    return null;

if(OnNetworkDisk(file))
    return null;
```

(or goto notexists; instead of return null;), not affecting any other code than those lines added. E.g. orthogonal.

When testing, the general rule should be to test exceptions, not the normal case.

Title: Elegant ways to handle if(if else) else

Body:
More seriously than the repetition of the call to DefaultAction is the style itself because the code is written non-orthogonal
(see this answer for good reasons for writing orthogonally).

To show why non-orthogonal code is bad consider the original example,
when a new requirement that we should not open the file if it is stored
on a network disk is introduced. Well, then we could just update the code to
the following:

if(FileExists(file))
{
    if(! OnNetworkDisk(file))
    {
        contents = OpenFile(file); // <-- prevents inclusion in if
        if(SomeTest(contents))
        {
            DoSomething(contents);
        }
        else
        {
            DefaultAction();
        }
    }
    else
    {
        DefaultAction();
    }
}
else
{
    DefaultAction();
}

But then there also comes a requirement that we should not open large files over 2Gb either.
Well, we just update again:

if(FileExists(file))
{
    if(LessThan2Gb(file))
    {
        if(! OnNetworkDisk(file))
        {
            contents = OpenFile(file); // <-- prevents inclusion in if
            if(SomeTest(contents))
            {
                DoSomething(contents);
            }
            else
            {
                DefaultAction();
            }
        }
        else
        {
            DefaultAction();
        }
    else
    {
        DefaultAction();
    }
}
else
{
    DefaultAction();
}

It should be very clear that such code style will be a huge maintenance pain.

Among the answers here which is written properly orthogonally are Abyx' second example and Jan Hudec's answer, so I will not repeat that, just point out that adding the two requirements in those answers would just be

if(! LessThan2Gb(file))
    return null;

if(OnNetworkDisk(file))
    return null;

(or goto notexists; instead of return null;), not affecting any other code than those lines added. E.g. orthogonal.

When testing, the general rule should be to test exceptions, not the normal case.


答:
Enthusiasm, knowledge and background info on the employer.

Don't bring physical artifacts. Seriously, its 20111 your applying for a job in the tech field. There's this fantastic new thing called the internet. Have a decent portfolio of work available online (a GitHub profile is awesome), have a CV available online and have a website or profile with a link to both of these. Be able to give them this address. Bonus points if you get a domain, even if it just redirects to a profile, it's less than the cost of lunch to register one for a year. If you're really need something physical have a thumb drive with this content on it you can leave with them, or a card with your name and this address.

1 Yes, I know the original question was from '09, but still relevant.


问:
Why don't more companies hire remotely?
I keep hearing about the desperate recruiting efforts of companies in tech hubs such as SF and NYC. However, every time I'm contacted by a startup I'm told the position is on-site and working remotely isn't possible.

Let me clarify that these are tech startups. They should be very comfortable with the idea of using technology to get things done and connect teams together.

With the housing market the way it is, many of us can't relocate even if we wanted to pay the higher cost of living. Why are so many companies still stuck in the industrial mindset of butts in seats?

答:
I've worked remotely in a couple of companies over several years. Let me tell you something: it's not convenient. Both as a remote member of a team and as an employer of remote contractors. I wouldn't do it again if I had a choice (and I have - work on-site with the team).

Its OK to work remotely a day or two a week, and many do so. But to have a full-time remote engineer is a pain. It may work well with contractors that get a chunk of work to be done, and deliver on time. But to hire a new employee, train him, have him integrated into a team, and supervise his daily work - all that on remote - it just doesn't work well with most people (managers, engineers, or both).

Now add to that the complexity of equipment - many tech start-ups require labs, hardware development, testing suits, and all these are very expensive, and not always available for remote connection and control. I have in one occasion witnessed my company shipping a $100K piece of equipment to a remote location for the contractors to work with (a whole team of contractors, not one). I had another one of these in my cube for my whole team to share. Had my team been all remote - we would have to ship another bunch of these, just for them to be able to work. Does it make sense to do so? Of course not.

Many companies offer relocation packages, and the tech salaries are way higher than the average, everywhere, so you don't have the excuse of "oh, it's so expensive in San Francisco".

Title: Why don't more companies hire remotely?


答:
There are many reasons that companies/managers may prefer local candidates:

Easier to integrate new programmer into a team/build comraderie

Easier communications face-to-face

Not all employees can work effectively at a remote site

Easier to ask questions/get up to speed when working locally

Harder to have impromptu whiteboarding sessions when working remotely

Now, this may not be true for all companies, but it's particularly tough to start out working remotely, particularly if you don't already know people at the company.

Check out this other Programmers.SE post for good answers to a similar question.

Title: Why don't more companies hire remotely?

Body:
I keep hearing about the desperate recruiting efforts of companies in tech hubs such as SF and NYC. However, every time I'm contacted by a startup I'm told the position is on-site and working remotely isn't possible.

Let me clarify that these are tech startups. They should be very comfortable with the idea of using technology to get things done and connect teams together.

With the housing market the way it is, many of us can't relocate even if we wanted to pay the higher cost of living. Why are so many companies still stuck in the industrial mindset of butts in seats?


问:
Freelancers do you have a surcharge for going to client site to work?
I'm currently new to freelancing as a programmer and need to work out what some of the "norms" are without making myself look like an amateur.

I've already won some work from a local company doing C# development and quoting an hourly rate for work that i am doing from my office.

However on one upcoming project I've been asked to come on-site (client office) to work a full week.

Is it reasonable to charge more than my regular hourly rate for working on site?  And how should i justify the extra charges?

答:
We charge 50% of our hourly rate for travel in excess of our normal commute.  We do not have an on site surcharge.

That being said, you can charge what you like as long as you specify the terms in your contract. And the client agrees.


答:
Please consider these (pre-written by my coauthor and myself, not quoted here):

Rules for Distributed Teams

But We Have These Distributed Folks

It's hard being distributed, and especially if you have an agile team. I'm a distributed team member (part of the time) and have worked as a distributed member for years. It is hard. It is especially hard on the managers who don't see you working or hear you talking about your work.

It's hard on teammates (as described in the articles above).

If you're doing solo work, and you can do it in isolation from the other employees of the team, and you turn in frequent increments of work to the boss, it can work.

If you work very tightly with other teammates through remote collaboration tools (webex, etc) then it can work. In may cases, it does not work even though it has every reason to work fine.

If I were the manager, distributed team members probably would not be my default initial stance.

See the 5-point list by JW01 here (nice work, JW01).

Title: Why don't more companies hire remotely?


问:
Where does jQuery fit-in with frameworks like JavaScriptMVC, BackboneJS, SproutCore and Knockout?
I have been happily using JQuery for the last 2 years and have been quite sucessful creating some really cool functionality with it...so I am very comfortable with it.  I also beleive the future of the web will continue on the current client-side path.

However...

The next challenge seems to be coming in the form of various controller frameworks: KnockoutJS, BackboneJS, SproutCore, JavaScriptMVC (the list goes on).

Additonally, there are some great AMD Loader tools for use like RequireJS or LabJS etc. However, jQuery now has define and then capabilities baked-in.

It's getting harder-and-harder to keep track of it all...

And now, my task seems to be to evaluate/decide-on a strategic-direction for using some form of either an MVC or MVVM framework client-side...but I have so many questions.

Where does JQuery fit-in with the various controller-frameworks mentioned above?

Is JQuery used alongside each or do some of them have their own 'JQuery-styled version' baked-in?

Are tools like RequireJS still needed if you implement one of the various controller-frameworks mentioned above?

Does the define and then capabilities baked-into JQuery now supercede the AMD Loader mentioned above?

Which one seems most modular? (see notes below)

NOTES:

One thing I don't want in any future-framework is the requirement of having to take-in vast amounts of functionality that I don't use.  Meaning, I would rather use a framework that is truly modular. For example, to use jQuery UI you have to take-in a lot other core libraries that you might not actually use.

I will be experimenting with each one, but some REAL feedback would be great.  I've seen some 'similar' questions, but none have really answered the above skew.

Thanks in advance!

答:
I'll answer on JavaScriptMVC as I'm a contributor:

Where does JQuery fit-in with the various controller-frameworks
  mentioned above?

JavaScriptMVC depends on jQuery and uses it extensively.

Is JQuery used alongside each or do some of them have their own
  'JQuery-styled version' baked-in?

JavaScriptMVC has no competing functionality with jQuery.  This is not as true with Backbone that has its own event system.  But, anything backbone or spine add
are very minimal.

Are tools like RequireJS still needed if you implement one of the
  various controller-frameworks mentioned above?

JavaScriptMVC comes with a dependency management system -> steal.  You can use JavaScriptMVC with RequireJS, but steal is actually much more powerful and about equal in size downloaded by a user.

Which one seems most modular? (see notes below)

This isn't opinionated.  JavaScriptMVC is extremely modular.  You use only what you need.  Compared to Backbone or spine, you can use it's M, V, or C parts standalone.  When assembled together, it's only 1k bigger than Backbone (when using jQuery and Underscore).  You can see the various sizes of base components here:  https://github.com/jupiterjs/javascriptmvc/issues/26

But JavaScriptMVC is much more powerful (in terms of features) vs Backbone or Spine.  For example, it's templated event handlers prevents practically all memory leaks.  Here's a tooltip that hides itself when the window is clicked:

```<code>$.Controller('Tooltip',{
  "{window} click" : function(){
    this.element.remove();
  }
})
</code>```

This is absolutely critical with the MVC approach when your controls are listening to changes in the model like:

```<code>$.Controller('Todos',{
  "{Todo} created" : function(Todo, ev, createdTodo){

  }
})
</code>```

Controller will auto-unbind all of these external event handlers.

A few other strengths of just the MVC parts:

$.Class is a very powerful class system

$.View and $.Model supports deferreds

$.Controller can 'rebind' event handlers

$.Model supports associations, getter / setters, defaults, validations

Now, JavaScriptMVC is much more than just it's MVC parts (which are part of the jQueryMX sub-project).  It has:

jQueryMX - jQuery's missing functionality like special events, dom helpers, etc.

Steal - a dependency management system.  But it can do things like take an ajax app and make it google crawlable.

FuncUnit - An awesomely powerful testing framework.

Now, on what to use, a lot depends.  A lot depends if you are making an "app" or a "page".  An application, that needs testing, dependency management, where you care about memory leaks, I'd look at JMVC or SproutCore.

If you are gluing a few basic widgets together, I'd look at spine or backbone.

Body:
I'll answer on JavaScriptMVC as I'm a contributor:

Where does JQuery fit-in with the various controller-frameworks
  mentioned above?

JavaScriptMVC depends on jQuery and uses it extensively.

Is JQuery used alongside each or do some of them have their own
  'JQuery-styled version' baked-in?

JavaScriptMVC has no competing functionality with jQuery.  This is not as true with Backbone that has its own event system.  But, anything backbone or spine add
are very minimal.

Are tools like RequireJS still needed if you implement one of the
  various controller-frameworks mentioned above?

JavaScriptMVC comes with a dependency management system -> steal.  You can use JavaScriptMVC with RequireJS, but steal is actually much more powerful and about equal in size downloaded by a user.

Which one seems most modular? (see notes below)

This isn't opinionated.  JavaScriptMVC is extremely modular.  You use only what you need.  Compared to Backbone or spine, you can use it's M, V, or C parts standalone.  When assembled together, it's only 1k bigger than Backbone (when using jQuery and Underscore).  You can see the various sizes of base components here:  https://github.com/jupiterjs/javascriptmvc/issues/26

But JavaScriptMVC is much more powerful (in terms of features) vs Backbone or Spine.  For example, it's templated event handlers prevents practically all memory leaks.  Here's a tooltip that hides itself when the window is clicked:

$.Controller('Tooltip',{
  "{window} click" : function(){
    this.element.remove();
  }
})

This is absolutely critical with the MVC approach when your controls are listening to changes in the model like:

$.Controller('Todos',{
  "{Todo} created" : function(Todo, ev, createdTodo){

  }
})

Controller will auto-unbind all of these external event handlers.

A few other strengths of just the MVC parts:

$.Class is a very powerful class system

$.View and $.Model supports deferreds

$.Controller can 'rebind' event handlers

$.Model supports associations, getter / setters, defaults, validations

Now, JavaScriptMVC is much more than just it's MVC parts (which are part of the jQueryMX sub-project).  It has:

jQueryMX - jQuery's missing functionality like special events, dom helpers, etc.

Steal - a dependency management system.  But it can do things like take an ajax app and make it google crawlable.

FuncUnit - An awesomely powerful testing framework.

Now, on what to use, a lot depends.  A lot depends if you are making an "app" or a "page".  An application, that needs testing, dependency management, where you care about memory leaks, I'd look at JMVC or SproutCore.

If you are gluing a few basic widgets together, I'd look at spine or backbone.


答:
The simple answer is: humans like face to face interaction, we've been doing it for quite some time.

If you're in the same physical environment its extremely easy to spin around and run an idea past a colleague, roll some code together (and discuss it in the process) and be extremely spontaneous and agile in the way you work. This is an extremely precious thing in a startup.

An experience very close to this, but not the same, can be created in the digital world. Videoconfercing, distributed VCS's and a good selection of the many, many web based collaboration tools can be combined to create an environment that supports and encourages remote collaboration. The problem with this is

It needs to be set up specifically for your environment (that's people and workflow), and

people need to be taught how to, and actually use it.

A lot of places that implement a distributed team tend to not quite perfect one of these points. This results in the tech being labelled as at fault, rather than the implementation.

Personally I've had some fantastic experiences working as a member of a distributed team. One technique that works extremely well is to get everyone to set up a camera in their workspace. Not directly on top of their monitor but on a secondary display if they have it, or off to one side - looking at peoples blank expressions when they're working is creapy. Whenever you are working call into a videoconference (using your platform of choice) so that you can see everyone else in 'the office' / 'studio' / 'dev dungeon'. If you need to talk to someone - do it. This provides nice flexible communication and also helps prevent people from working in their underwear covered in three day old cheezels crumbs (hopefully).

Title: Why don't more companies hire remotely?


答:
Clearly, the most elegant and concise solution is to use a preprocessor macro.

#define DOUBLE_ELSE(CODE) else { CODE } } else { CODE }
```

<p>Which allows you to write beautiful code like this:</p>

<pre class="lang-c prettyprint-override"><code>if(FileExists(file))
{
    contents = OpenFile(file);
    if(SomeTest(contents))
    {
        DoSomething(contents);
    }
    DOUBLE_ELSE(DefaultAction();)
</code>```

It might be difficult to rely on automatic formatting if you use this technique often, and some IDEs might yell at you a little bit about what it erroneously supposes is malformed. And as the saying goes, everything is a tradeoff, but I suppose it's not a bad price to pay to avoid the evils of repeated code.

Title: Elegant ways to handle if(if else) else

Body:
Clearly, the most elegant and concise solution is to use a preprocessor macro.

#define DOUBLE_ELSE(CODE) else { CODE } } else { CODE }

Which allows you to write beautiful code like this:

if(FileExists(file))
{
    contents = OpenFile(file);
    if(SomeTest(contents))
    {
        DoSomething(contents);
    }
    DOUBLE_ELSE(DefaultAction();)

It might be difficult to rely on automatic formatting if you use this technique often, and some IDEs might yell at you a little bit about what it erroneously supposes is malformed. And as the saying goes, everything is a tradeoff, but I suppose it's not a bad price to pay to avoid the evils of repeated code.


答: I think that if ledger was a table in db, I suggest put these thress task to one class(e.g DAO).If the ledger has more logic and was not a table in db, I suggest we should create more class to do these tasks(may be two or thress class) and provide a facade class to do simply for customer.</p>

Title: Single responsibility principle - am I overusing it?

Body:
For reference - http://en.wikipedia.org/wiki/Single_responsibility_principle

I have a test scenario where in one module of application is responsible for creating ledger entries. There are three basic tasks which could be carried out -

View existing ledger entries in table format.

Create new ledger entry using create button.

Click on a ledger entry in the table (mentioned in first pointer) and view its details in next page. You could nullify a ledger entry in this page.

(There are couple more operation/validations in each page but fore sake of brevity I will limit it to these)

So I decided to create three different classes -

LedgerLandingPage

CreateNewLedgerEntryPage

ViewLedgerEntryPage

These classes offer the services which could be carried out in those pages and Selenium tests use these classes to bring application to a state where I could make certain assertion.

When I was having it reviewed with on of my colleague then he was over whelmed and asked me to make one single class for all. Though I yet feel my design is much clean I am doubtful if I am overusing Single Responsibility principle


答:
The case shown in the sample code can usually be reduced to a single if statement. On many systems, the file-open function will return an invalid value if the file doesn't already exist. Sometimes this is the default behavior; other times, it must be specified via an argument. This means the FileExists test can be dropped, which can also help with race conditions resulting from file deletion between the existence test and file opening.

file = OpenFile(path);
if(isValidFileHandle(file) && SomeTest(file)) {
    DoSomething(file);
} else {
    DefaultAction();
}
```

<p>This doesn't directly address the abstraction-level-mixing issue as it sidesteps the issue of multiple, unchainable tests entirely, though doing away with the file existence test is not incompatible with separating abstraction levels. Assuming that invalid file handles are equivalent to "false" and file handles close when they go out of scope:</p>

<pre class="lang-cs prettyprint-override"><code>OpenFileIfSomething(path:String) : FileHandle {
    file = OpenFile(path);
    if (file && SomeTest(file)) {
        return file;
    }
    return null;
}

...

if ((file = OpenFileIfSomething(path))) {
    DoSomething(file);
} else {
    DefaultAction();
}
</code>```

Title: Elegant ways to handle if(if else) else

Body:
The case shown in the sample code can usually be reduced to a single if statement. On many systems, the file-open function will return an invalid value if the file doesn't already exist. Sometimes this is the default behavior; other times, it must be specified via an argument. This means the FileExists test can be dropped, which can also help with race conditions resulting from file deletion between the existence test and file opening.

file = OpenFile(path);
if(isValidFileHandle(file) && SomeTest(file)) {
    DoSomething(file);
} else {
    DefaultAction();
}

This doesn't directly address the abstraction-level-mixing issue as it sidesteps the issue of multiple, unchainable tests entirely, though doing away with the file existence test is not incompatible with separating abstraction levels. Assuming that invalid file handles are equivalent to "false" and file handles close when they go out of scope:

OpenFileIfSomething(path:String) : FileHandle {
    file = OpenFile(path);
    if (file && SomeTest(file)) {
        return file;
    }
    return null;
}

...

if ((file = OpenFileIfSomething(path))) {
    DoSomething(file);
} else {
    DefaultAction();
}


答:
Any sort of cargo-cult mentality (including cargo cults themselves) comes from a lack of fundamental understanding of the technology involved.

Cargo-cult programming shouldn't be thought of as a problematic habit, but rather a symptom of the underlying confusion that the programmer is facing.

More importantly, the assumption that the student's lack of understanding of is simply the outgrowth of his lack of confidence is fundamentally misguided and does not address the underlying problem.

Instead, the student's copy-paste programming style should be a red flag telling you that this student is overwhelmed by the complexity of what he's expected to do.

He's instinctively using past work as a scaffold upon which to build his current project, attempting to compose a solution using previously solved problems as building blocks. We all do this to a certain extent, but most of us do this by using the knowledge gained from past work as our building blocks. This student is instead using the work itself, which means he doesn't truly understand the blocks he's working with. He's decomposed the work as far as his understanding permits, and treating large blocks of code as atomic units because he does not understand how they work. He only knows what they do.


问:
Why are PHP function signatures so inconsistent?
I was going through some PHP functions and I could not help notice the following:

```<code><?php
function foo(&$var) { }

foo($a); // $a is "created" and assigned to null

$b = array();
foo($b['b']);
var_dump(array_key_exists('b', $b)); // bool(true)

$c = new StdClass;
foo($c->d);
var_dump(property_exists($c, 'd')); // bool(true)
?>
</code>```

Notice the array_key_exists() and property_exists() function.
In the first one, the property name(key for an array) is the first parameter while in the second one it is the second parameter. By intuition, one would expect them to have similar signature. This can lead to confusion and the development time may be wasted by making corrections of this type.

Shouldn't PHP, or any language for that matter, consider making the signatures of related functions consistent?

答:
The major source of inconsistency is that many (most?) of the php in built functions are really wrappers around some C library. The initial thinking was "I am wrapping C function xxxx therefore I should keep the parameter order the same". When it came to writing a "pure php" function this thinking was extended to "xxxx takes file and options the new function takes a file name and options so it makes sense to have yyyy take the same parameters in the same order.

The big flaw here is that the underlying C libraries were very inconsistent to begin with.


答:
With regards to what this is called, it can easily develop into the arrowhead anti pattern as your code grows to handle more requirements (as shown by the answer provided at https://softwareengineering.stackexchange.com/a/122625/33922) and then falls into the trap of having huge sections of codes with nested conditional statements that resemble a arrow.

See Links such as;

http://codinghorror.com/blog/2006/01/flattening-arrow-code.html

http://lostechies.com/chrismissal/2009/05/27/anti-patterns-and-worst-practices-the-arrowhead-anti-pattern/

There's plenty more on this and other anti patterns to be found on Google.

Some great tips Jeff provides on his blog regarding this are;

1) Replace conditions with guard clauses.

2) Decompose conditional blocks into seperate functions.

3) Convert negative checks into positive checks

4) Always opportunistically return as soon as possible from the function.

See some of the comments on Jeff's blog regarding Steve McConnells suggestions on early returns also;

"Use a return when it enhances readability: In certain routines, once
  you know the answer, you want to return it to the calling routine
  immediately. If the routine is defined in such a way that it doesn't
  require any further cleanup once it detects an error, not returning
  immediately means that you have to write more code."

...

"Minimize the number of returns in each routine: It's harder to understand a routine
  when, reading it at the bottom, you're unaware of the possibility that
  it returned somewhere abouve. For that reason, use returns
  judiciously--only when they improve readability. "

I always subscribed to the 1 entry/exit per function theory due to what I was taught 15 years or so ago. I feel this just makes code so much easier to read and as you mention more maintainable

Title: Elegant ways to handle if(if else) else


问:
Django as Python extension?
I come from php community and just started learning Python. I have to create server-side scripts that manipulate databases, files, and send emails.

Some of it I found hard to do in python, comparing to php, like sending emails and querying databases.

Where in php you have functions like mysql_query(), or email(), in python you have to write whole bunch of code. Recently I found Django, and my question is: is it a good framework for network-oriented scripts, instead of using it as a web-framework?

答:
No, there are many Python libraries you can use instead of using a giant web framework.

Have a look at: http://wiki.python.org/moin/DatabaseInterfaces to help you decide on a database interface; And a quick google query revealed: http://docs.python.org/library/smtplib.html as a possible solution to sending email.

Point being, a framework like Django is aimed at solving a specific problem, that being - easily creating a feature-rich website using Python. Not sending emails. :)

Title: Django as Python extension?

OwnerDisplayName: potato


问:
Are design patterns generally a force for good or bad?
I've heard it argued that design patterns are the best thing since sliced bread.  I've also heard it argued that design patterns tend to exacerbate "Second System Syndrome," that they are massively overused, and that they make their users think they're better designers than they really are.

I tend to fall closer to the former camp, but recently I've been seeing designs where nearly every single interaction is replaced with an observer relationship, and everything's a singleton.

So, considering the benefits and problems, are design patterns generally good or bad, and why?

答:
I think of design datterns not of something that you're constantly trying to apply to your code. For me it is mainly about a common language for developers. It's easier to say "we follow a builder pattern" than explaining the whole thing over and over.

I'm currently re-reading Patterns Of Enterprise Application Architecture right now, because I stumble upon a lot of code that follows one of the patterns from that book. I don't think it was intentionally chosen to follow one of the patterns, but it definitely helps if you can say "it's a transaction script" and everyone has a clear understanding what that means.

But I like the idea that you can choose from a prepared catalog of patterns, when you design a new functionality or a brand new application. Why reinvent everything if there are proven solutions for certain problems?


答:
Disclaimer

This answer does not say which language is better, its sole purpose is to show Python code for things you said you needed from Django and tries to prove that in Python, as contrary to some other languages, you do not need frameworks to perform needed actions.

Python's "batteries included" vs. PHP

In PHP you often need a framework or separate script / library to perform some more advanced tasks.

In Python a lot of tools come bundled, thus the term "batteries included", referring to multiple standard modules you can use without need to download them etc.

Thus your approach from PHP may not work - Python itself is very powerful and does not need frameworks for most features.

Querying the database in Python vs. PHP

Actually in Python it is a lot easier to do such things as querying the database. For example querying the database looks like that in Python:

```<code>import MySQLdb as db

conn = db.connect(host='localhost', user='user', passwd='password', db='database')
cursor = conn.cursor()

cursor.execute('SELECT * FROM `some_table`')
result = cursor.fetchall()
</code>```

where the first line (import statement) can involve other databases (such as sqlite3), as Python approach is to have the same interface for different RDBMSs. This means a lot of flexibility.

In PHP you may write the same thing similar to this:

```<code><?php

$db = mysql_connect('localhost','user','password') or die("Database error");
mysql_select_db('database', $db);

$query = 'SELECT * FROM `some_table`';
$result = mysql_query($query);

while ($row = mysql_fetch_row($result)) {
    // do what you need with $row
}
</code>```

which uses 4 MySQL-specific PHP functions. This code will not work for different RDBMs without replacing these functions. Of course, the better approach would be to use eg. PDO, but you said you are using mysql_query() function - my example just follows that.

Sending emails in Python

Here is an example from documentation page using SMTP:

```<code>import smtplib
from email.mime.text import MIMEText

msg = MIMEText('Hello, world!')
msg['Subject'] = 'This is an email title'
msg['From'] = 'me@example.org'
msg['To'] = 'you@example.com'

s = smtplib.SMTP('localhost')
s.sendmail(me, [you], msg.as_string())
s.quit()
</code>```

In PHP sending email may be very easy (and shorter, as in case of mail() PHP function), but considering some often used solutions for sending emails through SMTP in PHP, Python's approach may be considered a lot simplier.

Conclusion

Python is fun! :) If you need to query the database, it is a pleasure to do it in Python. If you want to send emails, Python has built-in module for it too. You do not need to use big, complex frameworks to accomplish these tasks.

Title: Django as Python extension?

Body:
I come from php community and just started learning Python. I have to create server-side scripts that manipulate databases, files, and send emails.

Some of it I found hard to do in python, comparing to php, like sending emails and querying databases.

Where in php you have functions like mysql_query(), or email(), in python you have to write whole bunch of code. Recently I found Django, and my question is: is it a good framework for network-oriented scripts, instead of using it as a web-framework?

Body:
Disclaimer

This answer does not say which language is better, its sole purpose is to show Python code for things you said you needed from Django and tries to prove that in Python, as contrary to some other languages, you do not need frameworks to perform needed actions.

Python's "batteries included" vs. PHP

In PHP you often need a framework or separate script / library to perform some more advanced tasks.

In Python a lot of tools come bundled, thus the term "batteries included", referring to multiple standard modules you can use without need to download them etc.

Thus your approach from PHP may not work - Python itself is very powerful and does not need frameworks for most features.

Querying the database in Python vs. PHP

Actually in Python it is a lot easier to do such things as querying the database. For example querying the database looks like that in Python:

import MySQLdb as db

conn = db.connect(host='localhost', user='user', passwd='password', db='database')
cursor = conn.cursor()

cursor.execute('SELECT * FROM `some_table`')
result = cursor.fetchall()

where the first line (import statement) can involve other databases (such as sqlite3), as Python approach is to have the same interface for different RDBMSs. This means a lot of flexibility.

In PHP you may write the same thing similar to this:

<?php

$db = mysql_connect('localhost','user','password') or die("Database error");
mysql_select_db('database', $db);

$query = 'SELECT * FROM `some_table`';
$result = mysql_query($query);

while ($row = mysql_fetch_row($result)) {
    // do what you need with $row
}

which uses 4 MySQL-specific PHP functions. This code will not work for different RDBMs without replacing these functions. Of course, the better approach would be to use eg. PDO, but you said you are using mysql_query() function - my example just follows that.

Sending emails in Python

Here is an example from documentation page using SMTP:

import smtplib
from email.mime.text import MIMEText

msg = MIMEText('Hello, world!')
msg['Subject'] = 'This is an email title'
msg['From'] = 'me@example.org'
msg['To'] = 'you@example.com'

s = smtplib.SMTP('localhost')
s.sendmail(me, [you], msg.as_string())
s.quit()

In PHP sending email may be very easy (and shorter, as in case of mail() PHP function), but considering some often used solutions for sending emails through SMTP in PHP, Python's approach may be considered a lot simplier.

Conclusion

Python is fun! :) If you need to query the database, it is a pleasure to do it in Python. If you want to send emails, Python has built-in module for it too. You do not need to use big, complex frameworks to accomplish these tasks.

OwnerDisplayName: Tadeck


问:
Can I use jQuery Mobile if I am developing a native app?
I am new to jQuery and mobile apps development. I know the features of jQuery Mobile. I want to know where and why to use it. Can I use jQuery Mobile if I am developing a native app?</p>

答:
For all these reasons here: http://tech.amikelive.com/node-22/7-reasons-to-use-jquery-as-the-javascript-framework-in-your-web-20-apps/ (ok, maybe not the last one if you don't care about John)

Also, see https://stackoverflow.com/questions/176324/why-does-everyone-like-jquery-more-than-prototype-script-aculo-us-or-mootools-or and the accepted answer.

I use JQuery because I like how it has evolved, how there seems to be a plugin for everything I want, and most of all in the Javascript world, because the documentation is great. Also, I like the fact that you write very few lines of code to great effect. You really don't need to write rich UIs to have a reason to use JQuery.

But honestly, prototype or scriptaculous are also great. In the end, it's just a matter of personal taste I think.


答:
jQuery Mobile is:

A unified, HTML5-based user interface system for all popular mobile device platforms, built on the rock-solid jQuery and jQuery UI foundation.

Its use is to provide a consistent experience across mobile devices UI for web applications. Web applications are applications that are accessible via a web browser through the Internet. Some web applications are intended for local use but you would still need a browser to access them.

So if your intentions are to build a native mobile application (your question wasn't very clear), jQuery Mobile is not of much use to you. But if you are developing a web application that targets mobile devices, jQuery Mobile is a valid option. If it's better than other similar options is not a question that's considered on topic here, you should decide for yourself. Personally, I like it and use it but I don't have much experience on the mobile domain, so don't take my word for it.

Body: I am new to jQuery and mobile apps development. I know the features of jQuery Mobile. I want to know where and why to use it. Can I use jQuery Mobile if I am developing a native app?</p>


答:
To really give an exact answer to your question: Yes.

Although JQueryMobile is meant for web applications (as pointed out by Yannis Rizos), you can use Phonegap to create native applications with JQuerymobile.

What Phonegap does, is create a native app with a webkit browser embedded. So it still is kind of a web application, but also kind of a native app, so it can be downloaded from the Market/Appstore, etc.

Also see Phonegap and JQuerymobile.

Title: Can I use jQuery Mobile if I am developing a native app?


问:
What should I put in comments while commiting to the Source Control?
I am a lone developer and maintain a SVN server for source control. So far, I haven't followed anything specific while committing my changes.

I was just reviewing my previous commits, and couldn't make any sense of my comments.

What do you put in comments while committing your checkins?

答:
Generally, what you worked on in that commit is a good start :)

(out of curiousity... what have you been writing if you couldn't make any sense of it?)


答: The changes that you have made to the code and what ever else that might be of relevance including put not limited to bug fixes, new features, breaks in functionality, changes in libraries, etc. Of course since the code is committed in small increments it will not have all the above. E.g. if you are fixing a bug you might make multiple changes. This will be multiple commits to fix the bug but what changes you made to fix the particular bug.</p>

Title: What should I put in comments while commiting to the Source Control?

Body:
I am a lone developer and maintain a SVN server for source control. So far, I haven't followed anything specific while committing my changes.

I was just reviewing my previous commits, and couldn't make any sense of my comments.

What do you put in comments while committing your checkins?


答:
You might be interested in reading this: https://stackoverflow.com/questions/321720/best-practices-for-version-control-comments.

If you are not using a bug tracker, and as such, cannot include a bug report id/number, you have to be very descriptive in your comments. Otherwise, if you just write "fixed problem with X" for example, two weeks after the commit you won't remember what was the problem. In that case, you will need to compare the before and after commit versions to understand what it was.

When I started developing applications professionally, we did not use a bug tracker, and I can remember that sometimes comments were very descriptive (too much even), sometimes there was no comment at all, it was a mess. With a bug tracker id, comments are way more useful and with a few more words you may even indicate why you made that particular change. Also, IDE's such as Eclipse for example have plugins that detect the bug tracker id's in comments (and in source code also) and can provide a clickable link to the bug tracker's web page.


答: I think that this all boils down to how you manage your projects.  For me, I tend to commit whenever I finish a feature that I want to push to a release build.  Since in my case, every feature results in a commit, I use my feature's story and issue number as my comment. The same goes for fixing bugs.  I start with a spike, derive a story, use the story to describe the changes that I need to make, and once again commit to source control with a story in the comments.</p>


答:
What did you expect to find in the comments of your previous commits?

Just put that information in your next commits.

Sometimes a ticket ID is enough, a ticket representing a bug report or a feature request.


答:
Issue ID.

Most issue trackers have a format that they can parse issue IDs out of commit messages and group commits with issues.

If you don't use an issue tracker, you should, it doesn't matter you are a solo developer, I've elaborated on the matter on another answer:

Use an issue tracker. It doesn't matter you are a lone wolf, keep track of everything you do for your project, whether it's a feature or a bug. Make a feature / components list. Mark truly essential components as version 1.0 and all else as version 2.0. And then delete everything that's marked as 2.0.

Ok, since the question got a mod notification for longer answers, I feel obliged to expand:

Yes, I just put the issue ID in commit comments, nothing else. That's when on solo projects, on team projects it's a whole other story. I'm not advocating putting just the issue ID, there should be something more there, but:

On solo projects it's extremely tempting to not document anything,

Putting the issue ID means by default that you've gone through the process of setting up an issue tracker,

That's good enough for me.

Effectively using an issue tracker when developing solo it's a far bigger achievement than commit comments. It'd be nice if I had the motivation to add something helpful in the comments, but I don't.


问:
Should we stick to a framework?
I currently work with Zend Framework, but I also know about CodeIgniter and Kohana. I've just wonder that should I stick to a framework or depend on my purposes? Because I think I cannot master everything.</p>

答:
As long as your current framework does what you need it to do, stick with it. Switching frameworks takes some time and once you master the new framework, you will have a hard time to maintain older projects because your have already forgotten how that other framework worked.

Of course, if your current framework becomes desupported or the new framework is way better (as in: 10 times more productive), you might have to do the switch anyway.

Title: Should we stick to a framework?


答:
You can, of course, charge for anything that you and the client agree to.  Whether you should or not, however, really depends.

You state that the company you're doing the work for is "local".  Many times, companies seek out local contractors over remote freelancers precisely because it makes it easier to physically meet at least occasionally over the course of a longer project.  Many local contractors use this when pitching their services to the company.  If one of your pitches has been that you're a local developer, it would be counterproductive to turn around and negate that benefit by making it difficult for the customer to meet with you face to face.

Continuing on the "local" front, exactly how far away are your offices from the client's offices, both in time and distance.  If "local" means "same city", for example, charging extra for the minimal inconvenience of potentially driving across town would likely come across as petty if you're closer than most of the client's actual staff.  On the other hand, if "local" means "close enough to drive rather than to fly" so that coming in for a week means a multi-hour drive, renting a hotel, etc., then it's much more reasonable to charge for that inconvenience either in the form of actual expenses or billing for travel time or upping the hourly rate.

You say that you've done work for them in the past so, presumably, there is at least a decent possibility of doing more work for them in the future.  With that in mind, it may well make sense to use this as an opportunity to build some goodwill at relatively little actual cost to you.  If coming to their office for a week doesn't cost you much out of pocket, just a couple extra hours of commuting time, you may be much better off in the long run telling the client that you'd normally charge X for working on-site but since they're a good customer, you'll credit the invoice for that (so that the invoice shows a charge for X and a credit for X).  That sort of informal "customer loyalty program" is generally a great investment in ensuring that you stay in everyone's good graces without costing you much out of pocket.  It certainly helps when there are future issues with bills to be able to point out that you've proactively given them discounts in the past.  Plus, physically meeting people, putting names to faces, maybe grabbing a bite to eat at lunch or after work can make the working environment much better so it may be in your interest to spend the occasional week on-site with key clients.

Of course, the bigger the request actually is, the more likely it makes sense to charge for it.  If you're running up a thousand dollars in hotel bills, travel expenses, and meals away from home in order to work from the client site for a week, it's perfectly reasonable to charge for that.  If you're doing a fixed price bid and working from the client site is going to slow you down because you're spending time getting your equipment to work in their environment or configuring their machine with your preferred development environment, it makes sense to build in those estimates for the work.  If you're charging an hourly rate, on the other hand, it makes much less sense to charge for the fact that they're asking you to be less productive for a bit.

Title: Freelancers do you have a surcharge for going to client site to work?

Body:
I'm currently new to freelancing as a programmer and need to work out what some of the "norms" are without making myself look like an amateur.

I've already won some work from a local company doing C# development and quoting an hourly rate for work that i am doing from my office.

However on one upcoming project I've been asked to come on-site (client office) to work a full week.

Is it reasonable to charge more than my regular hourly rate for working on site?  And how should i justify the extra charges?


问:
What would you do if your client required you not to use object-oriented programming?
I am writing a program to simulate the activity of ants in a grid (PDF). The ant can move around, pick up things and drop things.

The problem is while the action of the ants and the positions of each ant can be tracked by class attributes easily (and we can easily create many instances of such ants) my client said that since he has a background in functional programming he would like the simulation to be made using functional programming.

To be clear, the original words from the client is "no class" only, but not "functional programming". So I assume he doesn't mean functional programming and I can do it imperatively. Additionally, I have no prior experience in functional programming.

However, I think it's beneficial to focus on this question being particularly about a functional programming requirement than just simply "do it imperatively."

How would you handle this situation? Would you try to persuade your client that using object-oriented programming is much cleaner, try to follow what he required and give him poor-quality code, or do something else?

答:
You've wrote nothing about programming language, which is propably the most important thing there. The difference between OOP and functional programming is not only the way the code is organized but the language itself. When high concurrency is the case, functional language Erlang is in usage, and it has very high advantage over e.g. Java (it is used e.g. by Facebook chat). OOP solution could simply fail because of performance issues.

The client here is university, so language isn't only performance/configuration issue, the code could be also used for didactic work with students or own research. So 'persuading' client to choose other paradigm is in my opinion not applicable here. This is either you can deal with the task or you can not (and so, you should not take that project).