It's difficult to tell what is being asked here. This question is ambiguous, vague, incomplete, overly broad, or rhetorical and cannot be reasonably answered in its current form. For help clarifying this question so that it can be reopened, visit the help center.
Closed 10 years ago.
Once I've read in the "Clean Code" book that comments shouldn't be written because they mess up the code.
On the second hand however, "kohana" code (as one of many) contains extensive documentations and comments before almost every line of code.
I'm creating the project which will be used by user-programmers in the future...how should I write comments then?
To make this more clear - should I:
Write documentation before each class ?
Write documentation before each method ?
Write #param, #return... for each method ?
Write comments for almost every line of code to make it more clear ?
You should:
Write documentation before each class
Write documentation before each method
Write #param, #return... for each public method
Comments on every line of code aren't too necessary, but I recommend them on lines of code which would otherwise be unclear or obscure.
I write comments/documentation in two major cases:
When something the program does isn't immediately obvious. Even if it looks obvious now, it won't be in 6 months, or to another guy trying to maintain your work.
When the variable/argument/property types aren't clear. That's when I add a docblock.
Most (all) decent IDEs have mechanisms for collapsing and even hiding comments. Don't give them up because a book told you so, or because you think it's "messy".
Messy is a subjective term. I'd argue writing one comment line can save 10 hours of headache to future you.
To be honest, I would consider future readers. Will they benefit from the comments? In my own case, I have only regretted the comments that I failed to write and rarely the unnecessary comments that I did. Many times I've thought "there's no way I'll forget this"... and did.
As an alternative, you can also maintain a separate copy of the code with full commenting, and a release version where you remove most/all comments.
Whatever book you read that said comments shouldn't be written, you should immediately throw away and forget about forever. I don't care if you are the only person who will ever be working with the code, you should still document it.
To me, if you are working on code that will be used by other developers, I would try to stick with the PHPDoc (JavaDoc) style of documentation, which means you document every class, method, property, etc. as thoroughly as possible. One benefit this gives is that a lot of IDE's will actually use this information for code completion, making your application even easier to work with.
Now within code blocks themselves, I don't think you need to comment every line (especially lines where it is readily apparent what you are doing), but it is useful to comment different sections of the code, different logic branches, etc.
Also one non-comment thing I would also suggest, is using variable names that are meaningful to their purpose (with the exception of simple counters). Oftentimes people get cute and want to use 3-4 letter variable names, because of some misplaced opinion that it will same them loads of time in typing, or make their code shorter. If you need a long name like product_catalog_iterator to describe a class, to me that is better than prodcatit or similar.
I'm a believer in not writing comments. Instead writing code that is self commenting. What I mean by that is your functions and variables describe what they do. For example you could write it two ways:
function foo1($a, $b, $c){
return md5($a . $b . $c);
}
or you could write
function encryption($pepper, $content, $salt){
return md5($pepper . $content . $salt);
}
In this example the first one you have no idea what it's doing, but the 2nd, one you know exactly what it's doing. The only time I feel comments are needed is after you write really hacky code that took you a long time to figure out how to do it and isn't very clear what it is doing. This however should be far and in between.
The reason documentation isn't a good idea, is because what generally happens is you write great comments for when the function is first created and then after bug fixes and maintenance. The comments were never updated and now that comments are saying something the function doesn't do and offers confusion instead of help.
Related
It's difficult to tell what is being asked here. This question is ambiguous, vague, incomplete, overly broad, or rhetorical and cannot be reasonably answered in its current form. For help clarifying this question so that it can be reopened, visit the help center.
Closed 10 years ago.
I am writing a website in PHP where the aim is to allow the users to enter some monthly data, this is stored in MySQL, and at any point a user can view statistics to do with there data. I have all the basics done, however my code is completely unreadable, it is a mass of if statements, with no obvious structure, even with comments it's fairly opaque. How should I structure my code elegantly, and in what way should I utilise the OOP features of PHP.
Well.. I can only tell you what I generally do, not if it's the 'best' way or if there are more transparent workflows... just that it works for me very well ;)
First thing, and most important:
get rid of ALL non-php code in your php, for html display use templates either make a template system yourself or get one off the shelf (smarty for example).
Try to identify structures you use very often (like sql conenction and access) and put those into classfiles (you can easily change your sql system that way if you need to, by just editing ONE file, not countless others too)
Now find duplicate codeflow (mostly identical if-else-structures and so on)
and create functions for them to replace the original code with said function.
maybe even create more classes for functions that belong to a certain task.
So you end up with one class for the db, one for user information and editing, one for adding, editing and removing informations, and one for html output (and maybe even more)
Now set up your file system accordingly (put class files into a subfolder, templates in another, the same for images, javascripts etc.pp)
Next: Find all "settings"
All predefined values that may need to be changed, and put those into a settingsfile (init.php for example) maybe even as a class construct.
And as the last part, clean up all the mess inside single phps you cannot reduce further.
First: all the setup, include the files(classes) you need setup define the constants you will need for this script etc.
Second: all the script functions either in alphabetical or logical order.
and last the codeflow.
And that's it (a lot of work...) But you'll end up with a structure that I find easy to maintain. If you need to edit a setting, than it is in the init.php for sure, you want to change some db-structures or have changed your database, then you'll just need to update your sql.php and the like.
If someone else has to maintain the code too, you'll most likely will have to comment each file properly as well, personally I use comments for myself as well, since I have some scripts that needed to be changed after five or more years, that way I still know what goes where ;)
Good luck!
I recommend reading up on code cohesion and loose coupling, those are important concepts which you need to familiarize yourself with if you're to build great, maintainable applications.
You should also catch-up on design patterns and common usage cases, if not all of them - atleast the big ones, which are IMO: singletons, factories, DI and IoC (you see those across the board).
Once you've got the theoratical thinking going, you should start writing your code in an indsutry-standard type of way, which for PHP is MVC - you can use one framework, whichever really doesn't matter much, once you've learnt one framework - reading alot of other projects code will be very easy because it usually follows the same pattern with some written better than others.
Good Luck!
You are in need of a framework to structure your code. Luckily for you, this problem has been solved by many. CodeIgniter, Cake, Zend, Kohana, Symfony, Yii, Slim, Laravel, Fuel, the list goes on.
I highly recommend you look into CodeIgniter as your first PHP framework. The documentation and community are both second-to-none.
You may use some kind of PHP framework like Yii, Zend, Symfony or Kohana. MVC separation will be your good friend.
It's difficult to tell what is being asked here. This question is ambiguous, vague, incomplete, overly broad, or rhetorical and cannot be reasonably answered in its current form. For help clarifying this question so that it can be reopened, visit the help center.
Closed 10 years ago.
Does anyone know of any good tutorials to build a database driven website?
I am trying to build a site, that will do the following:
I upload data into different tables (categories) into a MYSQL Database
The user on the front end selects a category
The database then prints out all of the data in that category
Seems simple right? But where do I start!
In my opinion, take up php basics from the ground up, learn your variables and what they do, if/else statements, loops n functions etc etc..and leanr how/why they operate.
once you have a handle on the basics, then do something like was suggested above like lynda.com(ive used em theyre great) and other tuts online/books etc.
To do what you want to do, not only will you need this (the basic concepts i put up above), but youll need to learn SQL/MySql as well which is another simple but easy to messup language especially at first depending on what/how/how much you want to extract from the DB, mixing it with php and printing on the page, seting up databases/tables etc etc...
ALSO, in order to organize and display your content, youll need to understand how to extract said data hence, learning the basic basics.
as far as W3Schools - for basics theyre fine.just my .02
If you do your homework, And can tackle what you need in an orderly fashion, in a few days you should be up n running.
Good luck.
You could always get started with the PHP Tutorials on W3Schools - http://www.w3schools.com/php/default.asp
Before I get slated for suggesting them, they are a good start, especially if youre quite new to PHP or PHP with MySQL.
As for the printing it out, I guess you mean display it on a web page, the tutorials would cover this as well.
Once familiar with what you are doing, I highly recommend the tutorials put together on Lynda.com - http://www.lynda.com/
They are really well put together, and come with a video walk-through, so you get covered whatever your learning style.
You could start off by looking at the example code here:
http://www.willfitch.com/mysqli-tutorial.html
Then look at the php documentation:
http://php.net/manual/en/book.mysqli.php
Be careful not to get confused with the mysql_ and mysqli_ functions. mysqli_ is the one you want!
If you are using PHP to build your website,then maintain database on PHPMYADMIN of your server.Connect from your php code to mysql using mysql_connect function..follow this link...php_on_server
I used a couple of the For Dummies series to learn PHP/MySQL/phpMyAdmin. I'm sure the purists will disapprove :)
However, one of my acquaintances works for Google, and he got in my ear that AJAX sites are a much better way to approach things than PHP-driven sites.
So I pretty much rewrote everything I'd done to minimise the need for page reloads. So I now use PHP on the server side, but the client side is never built with PHP. It starts as pure HTML, and then makes calls using Javascript.
I share this not because I have great expertise, but because it might save you some heartache later if you head down the AJAX road from the start :)
It's difficult to tell what is being asked here. This question is ambiguous, vague, incomplete, overly broad, or rhetorical and cannot be reasonably answered in its current form. For help clarifying this question so that it can be reopened, visit the help center.
Closed 11 years ago.
I'm new to cakephp and still learning my way through php in general. To learn I'm trying to build an app which allows the following:
- A user can sign up (using the basic Auth component)
- A signed up user can create a 'campaign', ie fill in a form which will end-up as a page on my website containing details of things the user is trying to achieve. As well as that there will be a 'story' field in the form for the user to explain the reason they are trying to achieve whatever it is they are doing.
Users will have different reasons for creating their campaign, ie new years resolution/wife nagged you into doing it/need to make more money etc etc...
To help users along what I'd like is to have some default stories written and via a radio button users can select their default template to edit. In other words, if they select the 'new years resolution' template a pre-written story will appear in the text box for the story field which they can edit to their preference before submitting.
As I said, Im new to cakephp but have bought all the books and read the manual a couple of times, but since I'm also a bit green with php too I'm struggling a bit. But whats the best way to go about doing the above?
If someone could give me a bit of a break down so I can go off and google the correct things then it would sure make this learning curve a whole lot less daunting.
thanks in advance
pete
ireland
[Sorry to be so blunt but] It's pretty tough to answer this since you don't really have a specific problem but a general problem: you don't know the tools you want to work with.
Again, I don't mean you no harm.
For PHP in general, I would probably suggest to keep http://docs.php.net open in your browser at any time. PHP has one of the best (or maybe the best) language reference and manual. It probably also doesn't hurt to buy a book - IMHO, one from O'Reilly is usually a good fit.
As for CakePHP, I'd recommend starting here: http://cakephp.org/#learn
What you need to do is learn the framework and then go from there. Learn and adapt. There's no other way. What you described is of course not specifically part of any of the tutorials or screencast, but they teach you the skills necessary to achieve your own goals.
It seems like I am "wearing the same exact shoes" as yourself. I have a huge project to work with and no CakePHP knowledge. I tried to start with a plugin like many have suggested, but quickly got lost. Now a couple of months into learning CakePHP, this is what I would suggest you do:
Read the manual entirely (I downloaded this COPY and ordered it only as a manual)
Place sticky markers on the pages and sections you feel you need to reference back
Use a notebook to create your database structure as detailed as possible and use CAKEAPP to make them all come together. Use as much time as you need since the Database is the most important section of your app. CakeAPP allows you to set your app relantionships as well. Pretty neat!
Download the SQL code from CAKEAPP and dump it into your MySQL Database
Use Cake Bake to generate all your Models and Controllers (Change them later if necessary)
Create your main site layout (default.ctp)
Manually create all your other Views.
At this stage, DO NOT look at plugins. Plugins will make you lazy and prevent you from learning CakePHP. After you got your main application structure going, you can then look at plugins to beef it up. Looking at plugins this early in your game will only slow you down. Also, look at tutorials online and Q&A like STACKOVERFLOW's. Most importantly, read the Manual
BTW, I am still working on my Database to make sure, from the get go everything is as close to what I need as possible.
It's difficult to tell what is being asked here. This question is ambiguous, vague, incomplete, overly broad, or rhetorical and cannot be reasonably answered in its current form. For help clarifying this question so that it can be reopened, visit the help center.
Closed 12 years ago.
as web developer using PHP/JS/CSS for years , i suffer from repeat myself over and over and over and over , even if i use a PHP framework , i feel the same thing every time, i start to build new feature , so every time i started new thing i feel the 'Déjà vu' ( i write it before ) , and i rewrite many things from scratch despite i write something same before , if i use previous written code , i may take more time to reuse it , i love programming and web development , but by this way i will lose this :( ...
Where the problem ? in language , my way to built software or what ?
if i use previous written code , i may take more time to reuse it
This, I believe, is your real problem: you're writing way too much quick-and-dirty code and are suffering from the resulting techincal debt. The problem is, what is quick in the short term can lead to being very slow in the long term.
If I may offer a non-technical comparison, consider a Ferrari and a cargo ship. When delivering just one letter, it seems obvious that the Ferrari would be much faster not to mention much more convenient compared to using a cargo ship. Just loading the ship before leaving the docks can take hours. By which time the Ferrari would have already completed the delivery. But when you have to deliver a hundred tons of mail, the cargo ship would complete the delivery while the Ferrari would still be busy speeding back and forth delivering each letter.
It's the same in your case. When developing just a single web site, it will always seem obvious that you should write the least amount of the simplest possible code to get the job done quickly. And if your whole career is devoted to just one web site I would even say that that's the right way to do it. It is, after all, the essential spirit of Agile methods. But if your job is to develop websites (plural) then this approach will start to become slower with each new site. Just like how the Ferrari is not ideal for delivering a hundred tons of anything.
One real world example is 37signals. When their business model requires that they should be able to quickly develop and deploy sites as necessary, instead of just diving in and develop their first site in a quick-and-dirty way, they took a step back and developed Ruby on Rails instead.
I'm not saying that you should go ahead and start your own framework, re-inventing the wheel is exactly what you want to avoid at this point. What I'm suggesting is to separate the functionality you're developing from the web related code. In other words, when writing new code write it as a library. Yes, it's a bit more involved writing code in two or more files compared to inlining the functionality directly in the PHP page. But in the end your next web site would be easier/quicker to implement.
I always, as a matter of habbit, create a lib directory in a project's base directory whenever I start a new project. I then force myself to write all code even remotely reusable as separate modules in this directory. These days I find that, more often than not, I'd simply copy (or more commonly make a symlink) of files I need to the lib directory instead of writing the needed code.
The problem is that when PHP started, every tutorial, every demo and all code was made in a very structured way, because PHP descended from the C/C++ family. Many developers took this problem and have carried it, and it was visible that we couldn't keep this.
Now, we have PHP 5.3.3 available, we have namespaces, objects, classes, interfaces and all of this. Many of the things that helpt making bad code like magic quotes and register globals are now deprecated. PHP is evolving into the OO world, it took long enough, but is happening. So if you want to start again to "relearn" PHP I would suggest getting your hands on some frameworks like:
symfony, joomla, propel, doctrine
learn about mvc and design patterns applied to PHP and you will see how you'll start making good OO code, and the deja-vus might stop before you knwo it.!
Hope I can help
David
This is exactly why a framework is the best way to go. It takes out the mundane parts of code (the stuff you always have to write over and over like DB connections).
I would suggest picking a good framework (I use CakePHP, but there are others like Symphony, Codeignitor, Zend, etc.), and as you build various components, you can reuse them in other projects. It will reduce the time it takes to write all future projects.
As it currently stands, this question is not a good fit for our Q&A format. We expect answers to be supported by facts, references, or expertise, but this question will likely solicit debate, arguments, polling, or extended discussion. If you feel that this question can be improved and possibly reopened, visit the help center for guidance.
Closed 11 years ago.
We're looking for someone to help us enhance & maintain our high-quality, php-based prototype of a transactional web app. Ideally, who can communicate well, and do both front- and back-end web development (as well as smart/gets things done, etc.). Among other more general things, I've been using this question:
Given this:
$foo = array(1, 3, 7);
write a function (on this whiteboard) to sum the values of the array.
It seems trivially easy to me, but has caused a couple of deer-in-the-headlights situations, which always makes me feel like a villain.
I've read a number of posts here and there (including both Joel's and Jeff's) saying that how candidates think, design skills, passion, etc. are more important than any specific technical skill, and I agree with that. Also, I can see that programming at a whiteboard is a little unrealistic. OTOH, this seems so basic to me that I'm inclined to see it as a fine first-pass filter between front-end devs (who know their way around html, css, and how to copy-and-paste a js function or two), and people who can really code. Thoughts?
A touch more info: I'm open to all sorts of answers: array_sum, a for loop, a foreach loop. Heck, if they want to write an ArraySum class, that would be overkill, but just fine. Using javascript, or another language would be fine, if they're more comfortable with that. Even attempts with minor errors would be ok, but I've had a couple of complete freezes, so I just wanted to sanity check myself.
I would consider that much too easy of a question, personally. If someone asked me that question in an interview I'd probably be busy trying to figure out what the "trick" was, because it's so simple.
I think it's fine for weeding out the absolute worst programmers, but make sure that you don't have one particular "right" answer in mind and refuse to accept anything else. For example, don't only accept "use the array_sum() function" as the correct answer, where it's really just a test to see if they know the function exists.
I mention this because my fiancee once had a programming interview where she was asked how she would reverse a string. She gave several different algorithms that would accomplish it, with the interviewer telling her that she was wrong after each one. She finally gave up, and he (disapprovingly) told her that she should have just used the String.Reverse() function.
Don't do that. Please.
in my opinion, the question is perfectly valid, and tells a bit (not a lot, but an important bit) about the candidate, depending on how much time you invest in it. just tell her that it's not a trick question beforehand, that it's really, really as simple as it appears, so she doesn't spend to much time thinking about the pitfalls and to minimize the deer-situation. throw in you do that just as a measure to filter out the people who apply for a programming without actually knowing anything about it but hoping they get hired anyway by pure luck (if they know how to code but are just nervous, that should take a bit of pressure away). let them code, but don't focus if there is a $ missing or if the <?php tags are present or not.
if she provides array_sum or sum_array as an answer almost doesn't matter, especially if the language in question is php (but if two candidates are equal otherwise ... i can't even remember the last time i had to use this function). and the use of an auto-completion and syntax-coloring (with predefined keywords) IDE vs. a dumb text editor matters a lot in this hindsight. in this case ask for an alternate, handcrafted solution.
if i was in the position of asking that question i wouldn't ask for the right solution, i'd ask for ways that come to her mind how this problem could be solved, what pitfalls could arise in special cases. try to find out what she knows about programming, not what she knows about php. try to find out about intelligence, problem solving and creativity. altought experience matters a lot even when it comes to bang out code fast, it's not a constant.
the solutions i'd provide, the pros/cons and what it tells about me ...
built-in array_sum (very fast and definitley not buggy, but inflexible): i have a bit of experience with traditional php projects
for/loop constructs (good enough, reinventing the wheel. but can be used if there are different objects than numbers. pros: everybody will understand it): i can solve simple problems if there are no predefined copy&pasteable solutions
array_reduce (with an offering to implementat array_reduce, if the interviewer wants to see it): unusual for a php programmer, so it seems i have knowledge and experience outside of the php sandbox
an ArraySum-Object (with an ArraySum::add($value) method that keeps all values stored but caches the sum): i'm used to at least some of the oop-principles
function () { return 11; } (with the disclaimer that this is a joke solution, but valid): i have (albeit crude) programmer-specific humour - a sign i'm personally interested in programming outside of work ... some interviewers who are programmers (but not hackers) might interpret this as a willingness to use dirty hacks as placeholders (aehm) if time constraints are too tight
a recursive solution would be nice. i can probably solve a bit more complex, algorithily problems too and most likley know my way around simple trees and data structures
recursive divide and conquer: bonus! i know even more about algorithms.
try to get as much as possible out of this question (if time permits). in the end you'll know a little bit about programming capability and a lot about experience (altought not necessarily PHP specific).
i'd choose this question over letting the candidate write out quicksort - a very specific question about knowledge almost never needed in the web dev world - any time.
disclaimer
the question is useless when ...
the interviewer is not a programmer. forget it if a hr-guy is doing it
there's a very tight time constraint when interviewing. then the result is almost random anyway.
additionally, who are you looking for? if you need a cheap grunt coder, even a simple question like this should work. if you need quality and experience, don't waste too much time on it (but do it anyway).
No, it isn't too hard. If someone doesn't understand the concept of a loop or how to iterate through an array, they're not qualified as programmers. I'd also want them to know that there's a built-in function for that (array_sum()), or at least where to look for it.
You might want to take a look at The Five Essential Phone-Screening Questions, although you'll probably have to rework them a bit to suit your needs.
My own view is that there is a limit to the kind of toy questions you could ask for programming on a whiteboard. At best, these are simply toys that are often circulated on online forums and your candidates will memorize.
Most PHP developers created visible websites - you could see their work.
To me, a much better question would be to give him a complicated piece of your own production code and have him explain what it does or how it can be improved, etc. Most of the time will be spent doing maintenance anyway, better get an idea on his code reading skill, not just code writing.
Short Answer: No
Edit: Just to clarify I don't think this is a hard question at all. Regardless of the language. As others have posted, even if they can't get the syntax correct, the should at least be able to write it out in a reasonable pseudocode.
Long Answer:
I often ask interview questions I expect the candidate to miss. One could classify them as too (hard|vague|open-ended), but I am not really looking for an answer. I am looking to see the following:
Do they try to answer the question? Some people just give up immediately
How do they approach the problem? Even if they go down the wrong path are they generally making good assumptions and asking good questions?
How well do they maintain composure under stress? The question is designed to be hard, and therefore will be stressful. Do they panic, remain calm, withdraw, talk it out, etc...?
Are they able to find the solution if I give them hints and pointers? Or how well do they listen, and do they assimilate new information quickly?
Occasionally I am surprised with a candidate who is whip-smart, and just codes up a quick and elegant solution. Those are definite keepers. But I also find good candidates by people who miss the final solution, but are clearly thoughtful, logical, and given enough time would eventually solve the problem.
no, it isn't too hard, but it may cause people to panic if they do not exactly remember the syntax (though if you specifically ask for a php dev, then they should at least remember some syntax). Ask for pseudocode instead, if they still cannot do the question then there is a problem :)
If your applicant can't write a simple for loop and some addition on a whiteboard, you absolutely don't want them touching your code. Even as a front-end developer, they'll be using for loops all the time to output lists, table rows, image galleries and the like.
This is the type of basic thing you ask on the phone before bothering to bring a candidate in house.
There are a couple of standard things I ask every programmer about: Do a select on two tables to give a sum of a column in the second table, delete records from one table based on values in a second, difference between an object and a string as a method parameter, and a couple of html/css related questions.
Within 5 questions I can weed out 90% of the candidates before I even see them. The rest of it is going to boil down ideology.
My favorite would be:
while ($foo && $sum += array_shift($foo)) continue;
This question may be better improved by providing the documentation for the array() function, because if they don't know what it is, they could very easily look it up themselves in a job.
It's not too hard. If they cannot answer that question, they obviously cannot code their way out of a wet paper bag. I would definitely not hire such a person for any kind of development work.
Question is, how could you improve your recruiting process to avoid interviewing these candidates in the first place? Sounds to me like you're not screening your applicants enough before inviting them in for a chat.
If you can't write code to sum an array (in whatever language you prefer) I don't know what you can write. What on earth do you think someone could contribute to your project if they can't write code to do that question?
Actually, this questions seems kind of... easy.
I suppose writing it on a whiteboard makes it more difficult, though.
This question should be easy for people that have programming experience, but I'm guessing you may be getting a lot of designers that picked up PHP by copying/pasting code snippets in place.
Maybe you need to update your job listings to make them more programming centric and avoid web design terms.
No, it's not hard. What you've discovered is that there are a lot of "programmers" out there who can't program - they can memorize, they can copy and paste, but they don't actually understand what they are creating (in most cases they seem totally unaware of their lack of understanding).
This lack of understanding becomes painfully obvious when they are asked to write something simple from scratch - writing just the glue code, without all the complex stuff that they'd normally just grab as code snippets and then shift around until the compiler stops complaining.
In general you want to avoid these people like the plague, as they will consistently produce buggy code and will not understand why you or your customers think it doesn't work.
Jeff wrote about this a few years ago: Why Can't Programmers.. Program?
To be honest, I would like to think that if a person applies to a programming position, he or she will probably have the relevant skills on their resumes. Why not ask simple problem solving questions instead if the position doesn't require some sort special skills in the language in question? I was once asked how many pizza stores there are in my country. They were interested in checking how I approached the problem and weren't really interested in how awesome I might be in the relevant programming language. I think that was a good way to go about it. Am I awfully wrong in thinking that?
Edit: Or is it very common that people fake their resumes?
(I think the array_sum($array) method, as part of PHP, will do the job.)
The question really is trivial. Although there is enough space for error in a stressful situation but summing up an array should be easy enough for anyone with basic programming skills in any language.
It would take a dunce to muck up an interview with a question like this. The question is not too hard, it's actually very lenient.
It depends on what you're trying to ask. Are you screening their ability to recall syntax? Or are you looking for best-practice methods in dealing with array functions? If it's the first case, your question is fine.
On the other hand, if you're trying to see how well a person actually understands code, and knows implications based on how something is structured, the question is good, but instead of requiring them to write a line by line function, invite a discussion on how they would do it, and what would be some considerations with their answer. Why not do it via method B?
IME, asking for rote memory responses (syntax recall, port numbers, etc etc) tells you some aspects of an individuals ability, and sometimes need to be asked. But more important is digging into their problem solving abilities.
I don't see why anyone would have any problems with that. (Assuming that they are developers) And yes, programming at the whiteboard is unrealistic but that is a trivial question which any developer should be able to solve.
I had a deer-in-the-headlights moment wondering what the trick was!
Anyone applying for a programming job will know how to add integers together (one way or another, even if it's in a loop), so I'd skip it and find something more challenging....but not so confusing! :)
I've done interview recently for PHP position. I've been asked to write simple function on paper (of course not as simple as your example).
Anyway, when I've done that function (some 6 lines of Python code), interviewers where
pleased. They told me, that there are lot of ppl unable to write any code without IDE, and this small test serves to filter them out.
As for your example — it's just to simple. Especially if you accept array_sum() as an answer.
I wouldn't believe that there are such "programmers" out there, if you'd asked me a few years ago. But what has been seen cannot be unseen. I've witnessed firsthand people who make a living out of programming websites and know nothing about programming. They just copy and paste other people's code around, until they get it running. And you wouldn't possibly believe how their income level fares compared to their "skills" (yeah, income level does not directly relate to skills but it still freaks me out).
Yes, you are sane and those people do exist. And what you are doing is one of the useful filters for filtering "pragmatist script copy-pasters" (or others) from real coders. Of course, unless you want copy-pasters (they can accomplish some simple tasks! -or more complex ones but with unbelievable code-) in which case such an interview question is really hard for them.