答:
You need to learn new things yourself - go where your curiosity takes you.

Get a formal education as well - 90% of what you get taught in a formal education won't be used in the workplace. But the 10% that is used will be some strange and obscure thing that you thought at the time would never be of any use at all.

Without the formal education, you suffer from the problem best described as "you don't know what you don't know". The formal education gives you a wide wide wide coverage of lots of things in the full knowledge that nobody will ever go out and use it all. Because what you will use is something you won't know until you need it, it's all about being prepared so you know where to go looking.

The self-learning / curiosity driven thing is what makes you a far more knowledgeable and well-rounded person. Not to mention more valuable to an employer.

Side note: I've spent my entire career, since starting programming aged about 15 (sheesh, over 25 years... nearer 30 years) finding that apart from my university education, most training courses (you know... learn BLAH in 3 full time days) are pretty useless. These are generally superficial, and as far as the much touted "keeping your skills up" mantra goes, not very helpful for one who needs to get into deep technical detail. Buying books, using the internet, delving into the maths / physics / architecture / whatever are what have made me useful and valuable. At one stage I was one of about 10 people in the world with specific expertise on a particular subject - all that knowledge was gained by self-teaching and on-the-job learning.

The only time to stop learning is when you are 6 feet under in a pine box.


问:
Build functionality around the design, or the other way around?
When you build an application, is it better to design the UI first (in Photoshop or whatever), then implement the functionality following the UI you just designed, or do the programming and build the design as you go?

Advantages I see using UI as reference:

the app will end up very UI-friendly :)

like pdr mentioned, if working for a client, he gets exactly what he imagined

Disadvantages:

the programming will get more complicated, so development time increases

any others? :D

答:
You should generally design around functionality.

The reasoning behind this is that your customer will have an idea for a system in mind, and yet they won't really have all of the details worked out. These are things you will need to tease out over time, and they are things that could - and most likely will - change. When you start with the GUI, you are asking the customer to put all of their ideas onscreen, and yet you've missed the opportunity to get an unbiased view of the processes and functionality that the customer needs.  Sure, they might have many of their needs defined with how they might like a screen to look, but without understanding critical workflow and data management issues, you only get a small part of the picture up front. GUI's can be finicky things to get right, and you can find yourself spending a lot of time on them, which may risk running out of time to do the serious back-end stuff, and by relying on the GUI to dictate the overall design, you risk creating a dependency between the UI and the back-end.

Starting the other way around seems less intuitive to many people (including the customer), but it can save you a great deal of heart-ache later on. While on the one hand you want ot put of major decisions until the last possible moment, having as much information as possible up front will allow you a little flexibility in how you go about implementing a system. You'll need to know early on whether you will be handling large volumes of data, and whether you will be communicating that data beyond the confines of the user's local PC. Will you need a distributed system, N-Tier, Web-Based, etc? Knowing this stuff up front gives you time to research your options while you are encoding your business rules in libraries that could exist in nearly any configuration.

Something else to ponder, is that you may wish to deliver a whole system at the end, or schedule major milestone releases, or release incrementally in the Agile style. When you begin with the GUI, you lock your customer into a particular mode of thinking, that is, in how the software will be perceived. If you start with the back-end and release incrementally, you can build a rudimentary interface and tell your customer that it is simply to provide a means to conduct a controlled test of functionally, so that the customer can decide how best to present that functionality to their users, maintain their branding, and so on. Starting with the GUI will kind of limit everybody's thinking in terms of presentation possibilities to be biased towards whatever everybody sees first.

ContentLicense: CC BY-SA 3.0


问:
How to call modern Pascal?
Should the developers who creates programs with Delphi, FPC, Lazarus agree with the name of the language? This struck me since every possible variation not only adds confusion for new programmers, also when I write or name each of them, I feel that it's not fully correct.

Pascal. We know how Wirth dislikes OOP, so this plain naming is not correct. There were years where there were no objects in Pascal so it's also not correct to name it Pascal.

Delphi ("please, give me a link to the code fragment in Delphi"). Seeing how strong fpc/Lazarus is while keeping the high level of compatibility, now it's also isn't completely correct.

Object Pascal. Seems like a good choice, but the only places where it used noticeably is Delphi help and Wikipedia. And seems like there's even no badge "Object Pascal" at stackexchange/stackoverflow.

This also makes me sad because the developer of other languages don't hesitate at this moment. They can mention multiply compilers or dialects, but rarely hesitate in how to name the language.

答: I think "Object Pascal" is the best possible name. Even though some programmers don't know it, it's as self-descriptive as it can get.</p>

Title: How to call modern Pascal?


问:
I don't know C. And why should I learn it?
My first programming language was PHP (gasp).  After that I started working with JavaScript.  I've recently done work in C#.

I've never once looked at low or mid level languages like C.

The general consensus in the programming-community-at-large is that "a programmer who hasn't learned something like C, frankly, just can't handle programming concepts like pointers, data types, passing values by reference, etc."

I do not agree. I argue that:

Because high level languages are easily accessible, more "non-programmers" dive in and make a mess

In order to really get anything done in a high level language, one needs to understand the same similar concepts that most proponents of "learn-low-level-first" evangelize about.

Some people need to know C; those people have jobs that require them to write low to mid-level code. I'm sure C is awesome, and I'm sure there are a few bad programmers who know C.

Why the bias?  As a good, honest, hungry programmer, if I had to learn C (for some unforeseen reason), I would learn C.  Considering the multitude of languages out there, shouldn't good programmers focus on learning what advances us? Shouldn't we learn what interests us?  Should we not utilize our finite time moving forward?  Why do some programmers disagree with this?

I believe that striving for excellence in what you do is the fundamental deterministic trait between good programmers and bad ones.

Does anyone have any real world examples of how something written in a high level language—say Java, Pascal, PHP, or JavaScript—truly benefited from a prior knowledge of C? Examples would be most appreciated.

答:
The bias is one of status quo.  In the old days (1980s and earlier), C / C++ was pretty much a requirement for performance applications.  That's changed but senior developers generally come from that old-skool background and view things in that context.

For actual development other languages are used - C# is a popular one, as is Java, while PHP and Python are popular for internal projects and it's always useful to have someone on hand with at least basic knowledge in that area in case you choose an open source PHP project for, let's say, your bug tracking system.  However, job specs still seem to come from that standard template that was written 25 years ago.

ContentLicense: CC BY-SA 2.5


答:
I work with the Delphi IDE, I program in Pascal, dialect is object pascal.

I like project Euler, but when you look at the statistics page you see all the different " versions" of pascal listed as different languages while c/c++ is put into one big pile.

That and Delphi really is not a language, it's an IDE.

No programmer states: "Visual Studio" as his programming language, you shouldn't use Delphi that way either.

So, I would say: Pascal.

Title: How to call modern Pascal?

Body:
Should the developers who creates programs with Delphi, FPC, Lazarus agree with the name of the language? This struck me since every possible variation not only adds confusion for new programmers, also when I write or name each of them, I feel that it's not fully correct.

Pascal. We know how Wirth dislikes OOP, so this plain naming is not correct. There were years where there were no objects in Pascal so it's also not correct to name it Pascal.

Delphi ("please, give me a link to the code fragment in Delphi"). Seeing how strong fpc/Lazarus is while keeping the high level of compatibility, now it's also isn't completely correct.

Object Pascal. Seems like a good choice, but the only places where it used noticeably is Delphi help and Wikipedia. And seems like there's even no badge "Object Pascal" at stackexchange/stackoverflow.

This also makes me sad because the developer of other languages don't hesitate at this moment. They can mention multiply compilers or dialects, but rarely hesitate in how to name the language.


问:
How important is self-teaching in the programming field?
I'm 16. I started programming about a year ago when I was about to start high-school. I'm going for a career in programming, and I'm doing my best to learn as much as I can. When I first started, I learned the basics of C++ from a book and I started to learn things by myself from there on. Nowadays I'm much more experienced than I was a year ago. I knew I had to study by myself because high-school won't (likely) teach me anything valuable about programming, and I want to be prepared.

The question here is: how important is it to study programming by oneself?

答:
As always in mathematics and computer science - there are 2 points of view:
1. Necessary
and
2. Sufficient contitions

It's necessary to (self-)learn throughout your live. No other option to be and remain good programmer.

Above point is not sufficient condition - you must have strong background in mathematics - high school and then graduate good University in the field of computer science. This is (maybe) the sufficient condition. Your brain must be taught to think algorithmically. This CANNOT be achieved by self-learning.


答:
Try to seperate design from functionality, where possible and have a communication layer between the two.

This way you can have a dumb ui and a smart backend and development of both is rather independent, giving you best of both worlds.

Title: Build functionality around the design, or the other way around?

Body:
When you build an application, is it better to design the UI first (in Photoshop or whatever), then implement the functionality following the UI you just designed, or do the programming and build the design as you go?

Advantages I see using UI as reference:

the app will end up very UI-friendly :)

like pdr mentioned, if working for a client, he gets exactly what he imagined

Disadvantages:

the programming will get more complicated, so development time increases

any others? :D


问:
Should one check for null if he does not expect null?
Last week, we had a heated argument about handling nulls in our application's service layer. The question is in the .NET context, but it will be the same in Java and many other technologies.

The question was: should you always check for nulls and make your code work no matter what, or let an exception bubble up when a null is received unexpectedly?

On one side, checking for null where you are not expecting it (i.e. have no user interface to handle it) is, in my opinion, the same as writing a try block with empty catch. You are just hiding an error. The error might be that something has changed in the code and null is now an expected value, or there is some other error and the wrong ID is passed to the method.

On the other hand, checking for nulls may be a good habit in general. Moreover, if there is a check the application may go on working, with just a small part of the functionality not having any effect. Then the customer might report a small bug like "cannot delete comment" instead of much more severe bug like "cannot open page X".

What practice do you follow and what are your arguments for or against either approach?

Update:

I want to add some detail about our particular case. We were retrieving some objects from the database and did some processing on them (let's say, build a collection). The developer who wrote the code did not anticipate that the object could be null so he did not include any checks, and when the page was loaded there was an error and the whole page did not load.

Obviously, in this case there should have been a check. Then we got into an argument over whether every object that is processed should be checked, even if it is not expected to be missing, and whether the eventual processing should be aborted silently.

The hypothetical benefit would be that the page will continue working. Think of a search results on Stack Exchange in different groups (users, comments, questions). The method could check for null and abort the processing of users (which due to a bug is null) but return the "comments" and "questions" sections. The page would continue working except that the "users" section will be missing (which is a bug). Should we fail early and break the whole page or continue to work and wait for someone to notice that the "users" section is missing?

答:
Since Fail early, fail fast as stated by @DeadMG (@empi) is not pssible because the web-application must work well under bugs
you should enforce the rule

no exception catching without logging

so you as developpers are aware of potential problems by inspecting the logs.

if you are using a logging framework like log4net or log4j you can setup an additional  special logging output (aka appender) that mail you errors and fatalerrors. so you stay  informed.

[update]

if the enduser of the page should not be aware of the error you can setup an appender
 that mail you errors and fatalerrors you stay informed.

if it is ok that the enduser of the page sees cryptic errormessages you can setup an appender that puts the errorlog for the pageprocessing at the end of the page.

No matter how you use the logging if you swallow the exception the programm continue with data that makes sense and the swallowing is no more silent.


问:
How were some language communities (eg, Ruby and Python) able to prevent fragmentation while others (eg, Lisp or ML) were not?
The term "Lisp" (or "Lisp-like") is an umbrella for lots of different languages, such as Common Lisp, Scheme, and Arc. There is similar fragmentation in other language communities, like in ML.

However, Ruby and Python have both managed to avoid this fate, where innovation occurred more on the implementation (like PyPy or YARV) instead of making changes to the language itself.

Did the Ruby and Python communities do something special to prevent language fragmentation?

答:
Lisp-like languages are too basic and theoretical to be changed dramatically. Grammatical changes (I do not mean to just change the names of commands) would just not fit the functional-programming theory behind them.

But the fact that there are languages like lisp shows that "changes" were already made to lisp anyway. In other words, there are languages made by people who were inspired by lisp or it's theory behind it and made a in-a-way similar new language.

There are also a lot of languages inspired by Python. E.g. Julia, CoffeeScript, etc. which would form their own family of whitespace-sensitive object-oriented languages.

I think, fundamental basics of a language like Python will never really change. Python is object-oriented and therefore has similarities to C++ and Java but it's dynamic and therefore also similar to a lot of script languages.

Well who actually cares about languages? What counts is the purpose: French is  similar to Latin but girls who understand French are way hotter ;)


问:
If you were the manager of a team of 25 developers, how would you motivate them?
Imagine yourself hired by a new startup backed with few millions coming from venture capitalists.

Your mission: organize the development of the next killer app.

25 developers is too much to take care of each individually, so what decision(s) you would make to motivate them?

I will appreciate any answers from stock options to free cookies ;)

Of course the trick here (unless you are really a manager of a such startup), is put yourself in the shoes of one of those programmers.

EDIT: it's an imaginary context. The purpose of this story is to stimulate your wishes. I want to capture what motivates developers.

答:
You want to find out about the personalities of the people.
According to recent leadership theories, it is important that you are authentic and share common behavior and goals with your team members. Leadership can also be seen as coaching your team members to achieve their goals (here would be some theory)</p>


问:
Algorithm for creating cluster groups on two criteria
I would like to group a population based on two criteria. I will use an analogy to simplify my question.

Let's say I want n number of groups. I want to populate those groups based on person's age and weight, so that all groups contain about the same total age and are evenly distributed by weight (so that there are about same number of heavy and light people in each group).

What kind of algorithm could I use to automate this process? Is there a simple Excel formula or some other method?

UPDATE

Here is the motivation for this statistical analysis. I would like to set up partitioning in a database which will have the best performance. I need to store a lot of data which is grouped by county. I do not know ahead of time, what would be the best number of partitions. Partitions should be uniform, so that they contain about the same number of rows. A partition should hold data rows for one or more counties. Each county will be ranked on the frequency and possibly quantity of updates. Partitions should be built so that frequently updated county data is uniformly distributed.

It does not seem as if there is a simple way to do this. So what kind of algorithm would work for this? I probably would not use VBA for coding, instead most likely I would use perl to write the program for doing the analysis. Are there any ready-made statistical tools that do these type of analysis?

Let me clarify what I mean when I say n number of groups. I will basically pick a number of groups (partitions), plug it into the formula or analysis tool, or custom program. Then I will repeat the process for a different number of groups (partitions) until I find by trial and error, the number of partitions that yields best performance.

Maybe there is a name for this type of analysis? Something that I could try to research via a search engine?

答:
@Anony-Mousse, usually (or rather in its simplest form) "cluster analysis" is used to build clusters of similar objects.

I would suggest @dabest1 to consider looking into biclustering - this wikipedia article seems to be a bit weak at the time of the post.

I have discussed Biclustering in another post in CV.

To further help you in your research, here are a few links that will help get you started in Biclustering from the aforementioned post:

Article in Nature that describes a possible scenario for biclustering

Another post that discusses biclustering

A study comparing biclustering

And finally, some notes on biclustering from princeton.

HTH!


问:
When to use typedef?
I'm a bit confused about if and when I should use typedef in C++. I feel it's a balancing act between readability and clarity.

Here's a code sample without any typedefs:

```<code>int sum(std::vector<int>::const_iterator first,
        std::vector<int>::const_iterator last)
{
    static std::map<std::tuple<std::vector<int>::const_iterator,
                               std::vector<int>::const_iterator>,
                    int> lookup_table;

    std::map<std::tuple<std::vector<int>::const_iterator,
                        std::vector<int>::const_iterator>, int>::iterator lookup_it =
        lookup_table.find(lookup_key);

    if (lookup_it != lookup_table.end())
        return lookup_it->second;

    ...
}
</code>```

Pretty ugly IMO. So I'll add some typedefs within the function to make it look nicer:

```<code>int sum(std::vector<int>::const_iterator first,
        std::vector<int>::const_iterator last)
{
    typedef std::tuple<std::vector<int>::const_iterator,
                       std::vector<int>::const_iterator> Lookup_key;
    typedef std::map<Lookup_key, int> Lookup_table;

    static Lookup_table lookup_table;

    Lookup_table::iterator lookup_it = lookup_table.find(lookup_key);

    if (lookup_it != lookup_table.end())
        return lookup_it->second;

    ...
}
</code>```

The code is still a bit clumsy, but I get rid of most nightmare material. But there's still the int vector iterators, this variant gets rid of those:

```<code>typedef std::vector<int>::const_iterator Input_iterator;

int sum(Input_iterator first, Input_iterator last)
{
    typedef std::tuple<Input_iterator, Input_iterator> Lookup_key;
    typedef std::map<Lookup_key, int> Lookup_table;

    static Lookup_table lookup_table;

    Lookup_table::iterator lookup_it = lookup_table.find(lookup_key);

    if (lookup_it != lookup_table.end())
        return lookup_it->second;

    ...
}
</code>```

This looks clean, but is it still readable?

When should I use a typedef? As soon as I have a nightmare type? As soon as it occurs more than once? Where should I put them? Should I use them in function signatures or keep them to the implementation?

答:
Your last example is very much readable, but it depends on where you define the typedef. Local scope typedefs (like in your second example) are IMVHO almost always a win.

I still like your third example best, but you might want to think about the nameing, and give the iterators names which tell the intend of the container.

Another option would be to make a template out of your function, so that it works with different containers, too. Along the lines of

```<code>template <typename Input_iterator> ... sum(Input_iterator first, Input_iterator last)
</code>```

which is also very much in the spirit of the STL.

Title: When to use typedef?

Body:
Your last example is very much readable, but it depends on where you define the typedef. Local scope typedefs (like in your second example) are IMVHO almost always a win.

I still like your third example best, but you might want to think about the nameing, and give the iterators names which tell the intend of the container.

Another option would be to make a template out of your function, so that it works with different containers, too. Along the lines of

template <typename Input_iterator> ... sum(Input_iterator first, Input_iterator last)

which is also very much in the spirit of the STL.


答:
I started programming 2 years ago. My school could not teach the languages well, and I have to go online and do lots of research on myself. I am a slower learner and so it took me 2 year to write my first program, while all my school mates are still struggling or have given out on programming. </p>

<p>This shows that it is better for a programmer to be self taught rather than depend on the school. School will always hide information, as they think we are not ready for it. </p>

Title: How important is self-teaching in the programming field?

Body:
I'm 16. I started programming about a year ago when I was about to start high-school. I'm going for a career in programming, and I'm doing my best to learn as much as I can. When I first started, I learned the basics of C++ from a book and I started to learn things by myself from there on. Nowadays I'm much more experienced than I was a year ago. I knew I had to study by myself because high-school won't (likely) teach me anything valuable about programming, and I want to be prepared.

The question here is: how important is it to study programming by oneself?

Body:
I started programming 2 years ago. My school could not teach the languages well, and I have to go online and do lots of research on myself. I am a slower learner and so it took me 2 year to write my first program, while all my school mates are still struggling or have given out on programming.

This shows that it is better for a programmer to be self taught rather than depend on the school. School will always hide information, as they think we are not ready for it.


答:
Here's my checklist, in no particular order:

Awesome computers to develop on. At least double the power of the target user,  with plenty of RAM and large/multiple monitors... ~$3 to 5k budget.

Nice headphones for whoever needs them, when they prefer to work to music.

Excellent development tools to work with. This depends somewhat on your target environment, but Visual Studio / Eclipse / whatever is the best for the job. This includes things like continuous integration/build servers.

Fast internet access - perhaps with a caching proxy server to pre-cache things like SO, TheRegister, Reddit, etc

Very few meetings - only what is absolutely necessary and a hard limit on their length (we use a timer); think 'stand-up meeting' like Scrum.

Healthy atmosphere in which to work. Daylight, fresh air options, stable aircon, plants, pictures, good lighting.

10 to 20% downtime to learn something new or flex your skills a little.

A water cooler for each group of desks that is regularly maintained.

Market-competitive salaries with performance-related bonuses, where performance and the remuneration are clearly defined. Performance bonuses would likely be company profit share.

Encourage a collaborative work ethic; have tech debriefs to share learning, rotate people around teams to build their experience.

Free drinks (non-alcoholic).

A fruit basket for healthy snacks that don't ruin lunch.

Establish a level of professional respect from the other parts of the business for the software development department and vice versa. This is a long-term, fuzzy target, but there are ways and means of establishing it.

Clear communication to and from management of expectations and delivery on those expectations.

Clear priorities for work items, reviewed regularly.

Use of best practices in terms of SDLC methodologies - Agile/Scrum, etc.

Clear and documented procedures on what has to be done, why and how for important stuff like release management. Whatever can be automated would be, so this is just the manual bits - there's always some.

Supportive environment for when things don't go so well. No kicking people when they cause bugs, but helping them learn from their mistakes.

24x7 access to the building and remote access for when team members get inspiration outside of normal hours.

Whiteboards for prototyping/thinking out loud.

Celebrations of success - whether a team lunch or a trip to the Grand Prix at the weekend, it's important to recognise great effort and great results.

I would not have:

Nerf guns/frisbees/pool table/toys. The work environment is where we work. There's lots of fun to be had while doing the job without playing soldiers around colleagues that are trying to focus.

Free food - people should take a break to go out and get something to eat.

Internet censorship - I'd leave it up to the individuals to exercise their judgement.

Title: If you were the manager of a team of 25 developers, how would you motivate them?

Body:
Imagine yourself hired by a new startup backed with few millions coming from venture capitalists.

Your mission: organize the development of the next killer app.

25 developers is too much to take care of each individually, so what decision(s) you would make to motivate them?

I will appreciate any answers from stock options to free cookies ;)

Of course the trick here (unless you are really a manager of a such startup), is put yourself in the shoes of one of those programmers.

EDIT: it's an imaginary context. The purpose of this story is to stimulate your wishes. I want to capture what motivates developers.


问:
How to handle interview questions on programming style
As a C++-programmer in interviews I repeatedly found myself in situations were the interviewer wanted to probe my knowledge of good programming style. These typically were centered around basic knowledge of OOP.

I know OOP is useful to encapsulate concepts and I use it daily. However, since a language like C++ allows many different styles and some C++ approaches like TMP or STL algorithms are not OOP at all (but rather more like functional programming) I find myself stuck on how to best "sell" my knowledge of other approaches as well without coming across as arrogant or as somebody without appreciation of the basics. I fear this emphasis on OOP of the askers comes from them being socialized in the 90s where OOP was believed to be the cure-all, but that is an arrogant standpoint to take.

How would I make the best of questions like this?

答:
I would say you have to do your best answering this kind of questions, like you should do your best answering any kind of questions.

Later on when you are given the opportunity to ask the interviewer questions, you should raise the subject, asking questions like:

Do you only do OOP?

I use a different programming approach, how is it acceptable in your team?

And so on... and this way you can not only start a conversation about selling your expertise with those other approaches, you can also see how rigid and how much emphasis is really given to OOP in that team/company.


答: Self teaching is very important since you internalize the concepts your own way and that really helps.Choosing a language to self-teach with is very important.Languages that have clear documentation are very important and what you don't want to be is very ambitious in wanting to learn too many popular languages too fast.Since you say you started with c++,i would recommend java for you,it always works so well for self taught programmers.</p>


答:
I would emphasize that you follow SOLID principle, which is OOP and more.  Not only does it guarantee that your code is object oriented, but that it's fashioned in such a way that substituting objects following the SOLID principle is a relatively straightforward task.  Not only would it send the message that you know OOP, but it demonstrates that you understand the subtle points about what distinguishes good OOP code from hacky complicated OOP code written by someone who used to program in C and thinks all other languages should be programmed in the same fashion, since lets be honest, that's what makes you a good programmer, not just being able to use OOP.  </p>

<p>Be prepared to thoroughly explain for each of the five principles why each is important and what might happen to code which ignores that principle.  </p>

Title: How to handle interview questions on programming style

Body:
As a C++-programmer in interviews I repeatedly found myself in situations were the interviewer wanted to probe my knowledge of good programming style. These typically were centered around basic knowledge of OOP.

I know OOP is useful to encapsulate concepts and I use it daily. However, since a language like C++ allows many different styles and some C++ approaches like TMP or STL algorithms are not OOP at all (but rather more like functional programming) I find myself stuck on how to best "sell" my knowledge of other approaches as well without coming across as arrogant or as somebody without appreciation of the basics. I fear this emphasis on OOP of the askers comes from them being socialized in the 90s where OOP was believed to be the cure-all, but that is an arrogant standpoint to take.

How would I make the best of questions like this?

Body:
I would emphasize that you follow SOLID principle, which is OOP and more.  Not only does it guarantee that your code is object oriented, but that it's fashioned in such a way that substituting objects following the SOLID principle is a relatively straightforward task.  Not only would it send the message that you know OOP, but it demonstrates that you understand the subtle points about what distinguishes good OOP code from hacky complicated OOP code written by someone who used to program in C and thinks all other languages should be programmed in the same fashion, since lets be honest, that's what makes you a good programmer, not just being able to use OOP.

Be prepared to thoroughly explain for each of the five principles why each is important and what might happen to code which ignores that principle.


问:
How to apologize when you have broken the nightly build
My first commit in my project resulted in the nightly build being broken and people are all over me as we are nearing the release. I want to send an apology email that should sound sincere
and at the same time hinting that this was my first commit and this would not be repeated any more.

Being a non-native English speaker, I have difficulties coming up with correct words. Can someone please help?

答: While I think some kind of apology can be in place, please don't say: "I will make sure this doesn't happen again." Because it will. And if it does it will bite you.</p>


问:
How can Scrum be adapted to an academic environment?
I'm currently working with a professor at my university to develop new curricula for the Software Engineering and Capstone Design courses offered in my college.

Up until recently, both courses used the waterfall model exclusively, and thus students spent a majority of their time writing lengthy reports. After much pressure from me, my professor decided to include Scrum in the Software Engineering curriculum this past semester.

The first half of the semester was still waterfall-esque, with students writing 40-page design reports and software specification documents. Mid-semester, all teams were required to release a demo of their applications. At that point, the course switched to Scrum, with two 3-week sprints. We are now trying to figure out how to eliminate waterfall altogether and create an exclusively Scrum-based curriculum.

Unfortunately, we encountered a few incompatibilities between Scrum and the students:

Daily Scrum meetings are nearly impossible for students. Even during the class itself, it's inconvenient for students to hold Scrum meetings since the professor is usually lecturing.

Estimating points/hours is difficult, since students are inexperienced and therefore can't accurately predict how long something will take.

Scrum works best with full-time, co-located developers, but students are neither. At most, students dedicate 15-20 hours per week to the course, and organizing work meetings can be extremely difficult. Teams can have up to 10 students (and there's always one or two slackers).

Professors crave documentation! I haven't heard of any Scrum reports—just the backlogs and burndown charts (which I'm not sure will be enough to appease the academics).

Students often assume that agile means "Jump right in and start coding without looking back". This leads to some of the most horrible code imaginable. Therefore, I'm looking for a way to enforce proper design without requiring a 50-page document or a pile of UML diagrams.

Given these problems, how do you think my professor and I can adapt Scrum to function in an academic environment (and should we even bother with Scrum in the first place)? Also, is there still value to teaching the waterfall model?

Thanks in advance for any feedback!

答:
When I did my master's in software engineering, there was a course called Software Process that dealt with XP, Scrum and other agile approaches. Essentially, the entire class formed a hypothetical software company and was instructed to develop a piece of fairly elaborate software during the time the course ran. The lectures were about things such as XP practices, doing stand-up meetings, etc.

Most students have heard about these techniques and are usually keen on applying them. Ofcourse there's no way to force the team to actually work iteratively, etc. But that was actually the point of the course: to itself become a motivation for holding lots of short meetings, working iteratively, doing continuous builds, etc. because you quickly discover it's simply the easiest and most reliable way to produce anything of value with a group of people and a small amount of time.

One thing to remember: make sure you play the customer well and change some key requirements halfway through. Or "forget" to mention them initially.


答:
My general approach is to never test for an error condition that you do not know how to handle. Then the question that needs to be answered in each specific instance becomes: can you do something reasonable in the presence of the unexpected null value?

If you can continue safely by substituting another value (an empty collection, say, or a default value or instance), then by all means do so. @Shahbaz's example from World of Warcraft of substituting one image for another falls into that category; the image itself is likely just decoration, and has no functional impact. (In a debug build, I'd use a screaming color to draw attention to the fact that substitution has occured, but that depends greatly upon the nature of the application.) Log details about the error, though, so you know it's occuring; otherwise, you'll be hiding an error that you probably want to know about. Hiding it from the user is one thing (again, assuming processing can continue safely); hiding it from the developer is quite another.

If you cannot continue safely in the presence of a null value, then fail with a sensible error; in general, I prefer to fail as soon as possible when it's obvious that the operation cannot succeed, which implies checking preconditions. There are times when you don't want to fail immediately, but defer failure for as long as possible; this consideration comes up for example in cryptography-related applications, where side-channel attacks might otherwise divulge information you do not want known. At the end, let the error bubble up to some general error handler, which in turn logs relevant details and displays a nice (however nice they can be) error message to the user.

It's also worth noting that the proper response may very well differ between testing/QA/debug builds, and production/release builds. In debug builds, I would go for failing early and hard with very detailed error messages, to make it completely obvious that there is a problem and allow a post-mortem to determine what needs to be done to fix it. Production builds, when faced with safely recoverable errors, should probably favor recovery.

Title: Should one check for null if he does not expect null?

Body:
Last week, we had a heated argument about handling nulls in our application's service layer. The question is in the .NET context, but it will be the same in Java and many other technologies.

The question was: should you always check for nulls and make your code work no matter what, or let an exception bubble up when a null is received unexpectedly?

On one side, checking for null where you are not expecting it (i.e. have no user interface to handle it) is, in my opinion, the same as writing a try block with empty catch. You are just hiding an error. The error might be that something has changed in the code and null is now an expected value, or there is some other error and the wrong ID is passed to the method.

On the other hand, checking for nulls may be a good habit in general. Moreover, if there is a check the application may go on working, with just a small part of the functionality not having any effect. Then the customer might report a small bug like "cannot delete comment" instead of much more severe bug like "cannot open page X".

What practice do you follow and what are your arguments for or against either approach?

Update:

I want to add some detail about our particular case. We were retrieving some objects from the database and did some processing on them (let's say, build a collection). The developer who wrote the code did not anticipate that the object could be null so he did not include any checks, and when the page was loaded there was an error and the whole page did not load.

Obviously, in this case there should have been a check. Then we got into an argument over whether every object that is processed should be checked, even if it is not expected to be missing, and whether the eventual processing should be aborted silently.

The hypothetical benefit would be that the page will continue working. Think of a search results on Stack Exchange in different groups (users, comments, questions). The method could check for null and abort the processing of users (which due to a bug is null) but return the "comments" and "questions" sections. The page would continue working except that the "users" section will be missing (which is a bug). Should we fail early and break the whole page or continue to work and wait for someone to notice that the "users" section is missing?


答:
It sounds a bit similar to a subject I took once.

Some thoughts:

Would you really have a whole-team scrum meeting? Would subteams work?

If "without looking back" means no refactoring, then assess evidence of refactoring?

Assess reflection and documentation - get the students to maintain a blog of their activities. (This is actually a pretty useful skill for the workplace - far more so than most formal documentation)

If estimates are bad, hopefully they're learning - can they keep track of variations between estimates and reality, reflect on differences, and demonstrate that they've learnt something?

Are there less formal ways of documenting a design that would be appropriate?

Would Skype or Gchat or something suffice for some scrum meetings?

Title: How can Scrum be adapted to an academic environment?

Body:
I'm currently working with a professor at my university to develop new curricula for the Software Engineering and Capstone Design courses offered in my college.

Up until recently, both courses used the waterfall model exclusively, and thus students spent a majority of their time writing lengthy reports. After much pressure from me, my professor decided to include Scrum in the Software Engineering curriculum this past semester.

The first half of the semester was still waterfall-esque, with students writing 40-page design reports and software specification documents. Mid-semester, all teams were required to release a demo of their applications. At that point, the course switched to Scrum, with two 3-week sprints. We are now trying to figure out how to eliminate waterfall altogether and create an exclusively Scrum-based curriculum.

Unfortunately, we encountered a few incompatibilities between Scrum and the students:

Daily Scrum meetings are nearly impossible for students. Even during the class itself, it's inconvenient for students to hold Scrum meetings since the professor is usually lecturing.

Estimating points/hours is difficult, since students are inexperienced and therefore can't accurately predict how long something will take.

Scrum works best with full-time, co-located developers, but students are neither. At most, students dedicate 15-20 hours per week to the course, and organizing work meetings can be extremely difficult. Teams can have up to 10 students (and there's always one or two slackers).

Professors crave documentation! I haven't heard of any Scrum reports—just the backlogs and burndown charts (which I'm not sure will be enough to appease the academics).

Students often assume that agile means "Jump right in and start coding without looking back". This leads to some of the most horrible code imaginable. Therefore, I'm looking for a way to enforce proper design without requiring a 50-page document or a pile of UML diagrams.

Given these problems, how do you think my professor and I can adapt Scrum to function in an academic environment (and should we even bother with Scrum in the first place)? Also, is there still value to teaching the waterfall model?

Thanks in advance for any feedback!


答:
At that point, the course switched to Scrum, with two 3-week sprints. We are now trying to figure out how to eliminate waterfall altogether and create an exclusively Scrum-based curriculum.

Is the purpose to facilitate development, or to learn Scrum, or - my guess - both? I would consider shorter sprints to speed up the learning process.

•Daily Scrum meetings are nearly impossible for students. Even during the class itself, it's inconvenient for students to hold Scrum meetings since the professor is usually lecturing.

Perhaps you can replace daily stand-ups with a less stringent form, when it works best for the students. Also, not everyone needs to participate in every meeting.

•Estimating points/hours is difficult, since students are inexperienced and therefore can't accurately predict how long something will take.

Estimating calendar time is even more difficult, of the same reasons :-) With story points you don't estimate how long something will take: you estimate its relative size. Duration is derived.

•Scrum works best with full-time, co-located developers, but students are neither. At most, students dedicate 15-20 hours per week to the course, and organizing work meetings can be extremely difficult. Teams can have up to 10 students (and there's always one or two slackers).

Maybe try with smaller teams? 10 is on the upper scale for a Scrum team. I think you can succeed with non full-time distributed teams as well, but of course it's harder! Let that be a lesson in itself.

•Professors crave documentation! I haven't heard of any Scrum reports—just the backlogs and burndown charts (which I'm not sure will be enough to appease the academics).

Scrum does not dictate what kind of documentation is required. As a matter of fact, not even burndown charts are mandatory. This does not mean documentation is forbidden: the team should produce the documentation necessary, including the reports professors deem necessary.

•Students often assume that agile means "Jump right in and start coding without looking back". This leads to some of the most horrible code imaginable. Therefore, I'm looking for a way to enforce proper design without requiring a 50-page document or a pile of UML diagrams.

Not only students :-) Most Scrum teams use XP practices such as TDD (Test Driven Development) and refactoring: I propose you incorporate that in the curricula.

Also, is there still value to teaching the waterfall model?

Yes, of two reasons at least: First, it's not certain your students will use Scrum in their work life, and second, I imagine it is easier to understand the essence of agile development if you have something to compare it with.


答:
My advice is to separate and isolate what you are trying to teach. If it's a course in software design or some other software engineering subject (algorithms or whatnot), focus on that. If involving SCRUM becomes a hindrance (as you hint at) then don't bother with it.

How we did this when I was in college was to have a dedicated course for agile methodologies. The course included a development project that was to be run according to either SCRUM or XP. The actual software that was to be delivered was trivial, as the focus of the course was not programming or design but process. The reasoning here is the same as why you should not mix "hard core" software development subjects with methodology subjects as one tend to eclipse the other and students are mostly not ready or skilled enough to handle both at that stage.

Course deliverables were things like sprint planning reports, weekly progress reports, retrospectives, burndown reports plus each week we had at minimum two sessions that included a group stand-up/scrum meeting where the TAs would circulate and listen in.

This course also included TDD (Test Driven Development) and that worked really well.

Also, is there still value to teaching the waterfall model?

It most certainly is. Many companies use versions of this model for their projects (PPS, RUP, PROPS, etc). Many find (correctly, in my opinion) that "pure" SCRUM is better suited for ongoing maintenance than projects. SCRUM (and Agile in general) requires a certain flexibility in scope and the possibility of negotiating requirements and delivery along the way. Not all projects work like that, they are binary: deliver X at Y point in time, all else is a failure.


答:
I would be hesitant to discard Waterfall across the board so quickly.

Although it is a flawed model for actually building software systems, it's not a bad teaching model to instruct on good practices for each stage of the lifecycle. Regardless of the process model that you apply to the project, you still perform requirements engineering, system architecture and design, implementation, testing, release, and maintenance (including refactoring and enhancement). The difference is how these phases are organized and conducted, but all of the activities still happen.

I'd argue that your transition from Waterfall to Scrum in the middle of the project is not the best idea. A key to Scrum's success is a long-running project. The first three to five sprints are the team settling in on a velocity, learning the process, and going through team development. Although you are doing through the motions, it's not really Scrum at that point. In addition, trying to create an exclusively Scrum-based curriculum is probably a bad idea as Scrum as not a silver bullet - it's better to teach best practices rather than a single methodology. In the workforce, not all projects are going to use Scrum. In fact, in some environments, Scrum would be detrimental to the success of the project.

You've already found problems with Scrum in an academic setting, and some of them are hard to adequately address.

The non-issue in your list of incompatibilities is that estimating is difficult. Yes, it is. But the only way to get better at estimating is to estimate and compare actuals against estimates. Students should be estimating size, time, and effort using various means (story points, source lines of code, hours, pages, person-hours) early so that they are more prepared to do so after graduating and entering the workforce.

The need for documentation is something that can be addressed from both the perspective of the professor and the perspective of the students. The Lean approaches tell us that documentation that doesn't add value to either the team or the customer is wasteful (in terms of time and cost). However, some documentation is needed to achieve some objectives of both the students and the professor (the customer/client) for various purposes. Overall, it sounds like an opportunity to teach process tailoring and quantitative project management (which does have a role even in agile methods).

With respect to Scrum meetings and scheduling, there are two ideas that come to my mind. The first is that this indicates that Scrum might not be the best process to use in an academic setting. There is no singular "best process model" for software projects, with factors such as schedule, staffing, visibility, and experience of the development team (among others).

Overall, I'd suggest emphasizing good practices, process tailoring, and process improvement over single methodologies. This will let you be the most effective to everyone taking the courses, and expose them to a variety of process methodologies and understand what the best practices are for a given set of conditions.

Since you're working to build a university curriculum, I'll give a high level overview of how the software engineering curriculum at the university I attended fit together.

The was an introductory software engineering went through the project in a waterfall model, with the lectures during each phase corresponding to different ways to conduct the activities of that phase. The teams progressed through the phases at the same rate. Having those clearly defined boundaries made fit well into the teaching model for a group of people with no to minimal experience working on teams to build software. Throughout the course, references were made to other methodologies - various agile methods (Scrum, XP), Rational Unified Process, Spiral Model - with regards to how their advantages and disadvantages.

In terms of the activities, there were specific courses to discuss requirements engineering, architecture and design (two courses - one focusing on detailed design using object-oriented methods and one focusing on system architecture), a number of courses focusing on designing and implementing various classes of systems (real-time and embedded systems, enterprise systems, concurrent systems, distributed systems, and so on), and software testing.

There are also three courses dedicated to software process. Software Engineering Process and Project Management that focuses on best practices for managing a software project with respect to multiple methodologies. A second process course teaches measurements, metrics, and process improvement (emphasizing CMMI, Six Sigma, and Lean). Finally, there's a process course that teaches agile software development (Scrum, Extreme Programming, Crystal, DSDM discussed) using a project carried out using the Scrum methodology.

The capstone project was a two-quarter project that was performed for a sponsoring company and run entirely by the student project team, with guidance from both the sponsors and a faculty advisor. Every aspect of how to conduct the project is up to the students, within any constraints set forth by the sponsors. The only university-mandated deadlines were an interim presentation half way (10 weeks) into the project, a final presentation at the end, and a quad poster presentation shortly before the end. Everything else was up to the sponsor and team to agree to.


问:
Best way to parse a file
I'm trying to find a better solution for making a parser to some of the famous file formats out there such as: EDIFACT and TRADACOMS.

If you aren't familiar with these standards then check out this example from Wikipedia:

See below for an example of an EDIFACT message used to answer to a
  product availability request:-

```<code>UNA:+.? '
UNB+IATB:1+6XPPC+LHPPC+940101:0950+1'
UNH+1+PAORES:93:1:IA'
MSG+1:45'
IFT+3+XYZCOMPANY AVAILABILITY'
ERC+A7V:1:AMD'
IFT+3+NO MORE FLIGHTS'
ODI'
TVL+240493:1000::1220+FRA+JFK+DL+400+C'
PDI++C:3+Y::3+F::1'
APD+714C:0:::6++++++6X'
TVL+240493:1740::2030+JFK+MIA+DL+081+C'
PDI++C:4'
APD+EM2:0:130::6+++++++DA'
UNT+13+1'
UNZ+1+1'
</code>```

The UNA segment is optional. If present, it specifies the special characters that are to be used to interpret the remainder of the message. There are six characters following UNA in this order:

component data element separator (: in this sample)

data element separator (+ in this sample)

decimal notification (. in this sample)

release character (? in this sample)

reserved, must be a space

segment terminator (' in this sample)

As you can see it's just some data formatted in a special way waiting to be parsed (much like XML files).

Now my system is built on PHP and I was able to create parser using regular expressions for each segment, but the problem is not everybody implements the standard perfectly.

Some suppliers tend to ignore optional segments and fields entirely. Others may choose to send more data than others. That's why I was forced to create validators for segments and fields to test if the file was correct or not.

You can imagine the nightmare of regular expressions I'm having right now. In addition each supplier needs many modifications to the regular expressions that I tend to build a parser for each supplier.

Questions:

1- Is this the best practice for parsing files (using regular expressions)?

2- Is there a better solution for parsing files (maybe there are ready made solution out there)? Will it be able to show what segment is missing or if the file is corrupted?

3- If I have to build my parser anyway what design pattern or methodology should I use?

Notes:

I read somewhere about yacc and ANTLR, but I don't know if they match my needs or not!

答:
What you need is a true parser. Regular expressions handle lexing, not parsing. That is, they identify tokens within your input stream. Parsing is the context of the tokens, I.E. who goes where and in what order.

The classic parsing tool is yacc/bison. The classic lexer is lex/flex. Since php allows for integrating C code, you can use flex and bison to build your parser, have php call it on the input file/stream, and then get your results.

It will be blazing fast, and far easier to work with once you understand the tools. I suggest reading Lex and Yacc 2nd Ed. from O'Reilly. For an example, I've set up a flex and bison project on github, with a makefile. It is cross compilable for windows if necessary.

It is complex, but as you found out, what you need done is complex. There is a great deal of "stuff" that must be done for a properly working parser, and flex and bison deal with the mechanical bits. Otherwise, you find yourself in the unenviable position of writing code at the same abstraction layer as assembly.

Title: Best way to parse a file


问:
Are Java applets worth learning?
I'm on the way of learning Java myself. I find most of texts giving emphasis to Java applets. I got confused about the importance. Is it something widely used?  Do I need to spend more time on it?</p>

答:
If your aim is to learn GUI development in Java, I would say to stay away from applets and just focus on learning Swing the old-fashioned way.  I don't know all the ins and outs of Applets and it hasn't affected my job negatively.  On the other hand, many games are distributed as applets, as well as the output of Processing.  So it's a good skill to have if you want to distribute your work in an easy to view way on the web, but I wouldn't strive to create anything huge within an applet.

(Do note that it's not impossible to port existing code written for the desktop to run as an applet, which is why I suggest you learn desktop development first.  You'll learn the concepts but without having to jump through the extra hoops of the special applet GUI code, and the browser interactions.

Title: Are Java applets worth learning?


答:
The point of an academic Software Engineering course is to teach to fundamental stages of the software lifecycle - analysis, design, implementation, testing together with using actual software quality standards instead of regular homework quality code.

There is value in demonstrating the practice using a non-waterfall process, however, due to the reasons you meantioned SCRUM is not a suitable process - students take many courses per semester, many also have real jobs while studying, therefore you can not have 100% dedicated team members or conduct daily meetings.

Consider using a less-agile iterative process such as UP (RUP) instead.

To show the value compared to the waterfall process, change requirements between iterations. This will show the difference between UP and the waterfall and hint towards the value of using agile processes.

Demonstrating the waterfall after this will be redundant as UP covers all of the waterfall's stages.

Since the semesters are relatively short, 2 small iterations would be realistic.

Provide a broad framework for the students to use, as the emphasis of this course shouldn't be the depth of the implementation, there are other courses for that, instead it should emphasize coding standards and unit testing.

During the course lectures teach the theory of a few processes e.g. waterfall, UP, XP, SCRUM and Kanban (along with other topics e.g. writing requirements, UML, testing and etc.).

For students that completed the above course, consider a separate SCRUM workshop as an elective course which takes a full-time two week period during the summer semester.


答:
instead of fiddling with regexes make your own state machine </p>

<p>this will be more readable (and be able to have better comments) in non-trivial situations and will be easier to debug that the black box that is regex </p>

Title: Best way to parse a file

Body:
I'm trying to find a better solution for making a parser to some of the famous file formats out there such as: EDIFACT and TRADACOMS.

If you aren't familiar with these standards then check out this example from Wikipedia:

See below for an example of an EDIFACT message used to answer to a
  product availability request:-

```<code>UNA:+.? '
UNB+IATB:1+6XPPC+LHPPC+940101:0950+1'
UNH+1+PAORES:93:1:IA'
MSG+1:45'
IFT+3+XYZCOMPANY AVAILABILITY'
ERC+A7V:1:AMD'
IFT+3+NO MORE FLIGHTS'
ODI'
TVL+240493:1000::1220+FRA+JFK+DL+400+C'
PDI++C:3+Y::3+F::1'
APD+714C:0:::6++++++6X'
TVL+240493:1740::2030+JFK+MIA+DL+081+C'
PDI++C:4'
APD+EM2:0:130::6+++++++DA'
UNT+13+1'
UNZ+1+1'
</code>```

The UNA segment is optional. If present, it specifies the special characters that are to be used to interpret the remainder of the message. There are six characters following UNA in this order:

component data element separator (: in this sample)

data element separator (+ in this sample)

decimal notification (. in this sample)

release character (? in this sample)

reserved, must be a space

segment terminator (' in this sample)

As you can see it's just some data formatted in a special way waiting to be parsed (much like XML files).

Now my system is built on PHP and I was able to create parser using regular expressions for each segment, but the problem is not everybody implements the standard perfectly.

Some suppliers tend to ignore optional segments and fields entirely. Others may choose to send more data than others. That's why I was forced to create validators for segments and fields to test if the file was correct or not.

You can imagine the nightmare of regular expressions I'm having right now. In addition each supplier needs many modifications to the regular expressions that I tend to build a parser for each supplier.

Questions:

1- Is this the best practice for parsing files (using regular expressions)?

2- Is there a better solution for parsing files (maybe there are ready made solution out there)? Will it be able to show what segment is missing or if the file is corrupted?

3- If I have to build my parser anyway what design pattern or methodology should I use?

Notes:

I read somewhere about yacc and ANTLR, but I don't know if they match my needs or not!

Body:
instead of fiddling with regexes make your own state machine

this will be more readable (and be able to have better comments) in non-trivial situations and will be easier to debug that the black box that is regex


答:
While a null pointer exception will eventually be thrown it will often be thrown far from the point where you got the null pointer.  Do yourself a favor and shorten the time it takes to fix the bug by at least logging the fact that you git a null pointer as soon as possible.

Even if you don't know what to do now, logging the event will save you time later.  And maybe the guy who gets the ticket will be able to use the time saved to figure out the proper response then.


答:
ouch.. 'true' parser? state machines??

sorry but i've been converted from academic to hacker since I began my employment.. so I would say there are easier ways.. although maybe not as 'refined' academically :)

I will try to offer an alternative approach which some may or may not agree with but it CAN be very practical in a work environment.

I would;

```<code>loop every line
   X = pop the first 3 letters of line
   Y = rest of line
   case X = 'UNA':
       class init (Y)
</code>```

from there i would use classes for the data types. splitting component and element separators and iterate over the returned arrays.

For me, this is code re-use, OO, low cohesion and highly modular.. and easy to debug and program. simpler is better.

to parse a file you don't need state machines or anything entirely complicated.. state machines are well suited to parse code, you'll be suprised at how powerfull the above pseduo code can be when used in an OO context.

ps. i've worked with very similar files before :)

More pseudo code posted here:

class

```<code>UNA:

init(Y):
 remove ' from end
 components = Y.split(':')
 for c in components
     .. etc..

 getComponents():
   logic..
   return

 getSomethingElse():
   logic..
   return

class UNZ:
   ...

Parser(lines):

Msg = new obj;

for line in lines
   X = pop the first 3 letters of line
   Y = rest of line
   case X = 'UNA':
      Msg.add(UNA(Y))

msg.isOK = true
return Msg
</code>```

you could then use it like this..

```<code>msg = Main(File.getLines());
// could put in error checking
// if msg.isOK:
msg.UNA.getSomethingElse();
</code>```

and say you have more than one segment.. use a queue to add them and get the first, second etc.. as you need. You are really just representing the msg into an obj and giving the object methods to call the data. you could take advantage of this by also creating custom methods.. for inheritance.. well that's a different question and i think you could easily apply it if you understand it

Title: Best way to parse a file

Body:
ouch.. 'true' parser? state machines??

sorry but i've been converted from academic to hacker since I began my employment.. so I would say there are easier ways.. although maybe not as 'refined' academically :)

I will try to offer an alternative approach which some may or may not agree with but it CAN be very practical in a work environment.

I would;

loop every line
   X = pop the first 3 letters of line
   Y = rest of line
   case X = 'UNA':
       class init (Y)

from there i would use classes for the data types. splitting component and element separators and iterate over the returned arrays.

For me, this is code re-use, OO, low cohesion and highly modular.. and easy to debug and program. simpler is better.

to parse a file you don't need state machines or anything entirely complicated.. state machines are well suited to parse code, you'll be suprised at how powerfull the above pseduo code can be when used in an OO context.

ps. i've worked with very similar files before :)

More pseudo code posted here:

class

UNA:

init(Y):
 remove ' from end
 components = Y.split(':')
 for c in components
     .. etc..

 getComponents():
   logic..
   return

 getSomethingElse():
   logic..
   return

class UNZ:
   ...

Parser(lines):

Msg = new obj;

for line in lines
   X = pop the first 3 letters of line
   Y = rest of line
   case X = 'UNA':
      Msg.add(UNA(Y))

msg.isOK = true
return Msg

you could then use it like this..

msg = Main(File.getLines());
// could put in error checking
// if msg.isOK:
msg.UNA.getSomethingElse();

and say you have more than one segment.. use a queue to add them and get the first, second etc.. as you need. You are really just representing the msg into an obj and giving the object methods to call the data. you could take advantage of this by also creating custom methods.. for inheritance.. well that's a different question and i think you could easily apply it if you understand it


答:
Think of a typedef as the variable declaration equivalent of a function:  it's there so you...

...don't have to repeat yourself when re-using the same type (which your first two examples do).

...can conceal the gory details of the type so they're not always out on display.

...make sure that changes to the type are reflected everyplace they're used.

Personally, I glaze over if I have to read long type names like std::vector<int>::const_iterator repeatedly.

Your third example doesn't repeat itself unnecessarily and is easiest to read.

Title: When to use typedef?

Body:
I'm a bit confused about if and when I should use typedef in C++. I feel it's a balancing act between readability and clarity.

Here's a code sample without any typedefs:

```<code>int sum(std::vector<int>::const_iterator first,
        std::vector<int>::const_iterator last)
{
    static std::map<std::tuple<std::vector<int>::const_iterator,
                               std::vector<int>::const_iterator>,
                    int> lookup_table;

    std::map<std::tuple<std::vector<int>::const_iterator,
                        std::vector<int>::const_iterator>, int>::iterator lookup_it =
        lookup_table.find(lookup_key);

    if (lookup_it != lookup_table.end())
        return lookup_it->second;

    ...
}
</code>```

Pretty ugly IMO. So I'll add some typedefs within the function to make it look nicer:

```<code>int sum(std::vector<int>::const_iterator first,
        std::vector<int>::const_iterator last)
{
    typedef std::tuple<std::vector<int>::const_iterator,
                       std::vector<int>::const_iterator> Lookup_key;
    typedef std::map<Lookup_key, int> Lookup_table;

    static Lookup_table lookup_table;

    Lookup_table::iterator lookup_it = lookup_table.find(lookup_key);

    if (lookup_it != lookup_table.end())
        return lookup_it->second;

    ...
}
</code>```

The code is still a bit clumsy, but I get rid of most nightmare material. But there's still the int vector iterators, this variant gets rid of those:

```<code>typedef std::vector<int>::const_iterator Input_iterator;

int sum(Input_iterator first, Input_iterator last)
{
    typedef std::tuple<Input_iterator, Input_iterator> Lookup_key;
    typedef std::map<Lookup_key, int> Lookup_table;

    static Lookup_table lookup_table;

    Lookup_table::iterator lookup_it = lookup_table.find(lookup_key);

    if (lookup_it != lookup_table.end())
        return lookup_it->second;

    ...
}
</code>```

This looks clean, but is it still readable?

When should I use a typedef? As soon as I have a nightmare type? As soon as it occurs more than once? Where should I put them? Should I use them in function signatures or keep them to the implementation?


问:
Options for programming by contract in Java
I am working on a project (which includes JavaEE web apps and JavaSE apps) that has grown from a single developer to a team of three, and issues of readability and robustness are starting to emerge.

One glaring omission from the Java language has been fine tuned contracts, and how easily these are exposed to other developers. (By contracts I mean mostly validating method parameters and object pre/post conditions).

There are a few solutions that I am looking at, and I would like to get some feedback from others who have some practical experience.

It would seem that Java currently has two supported ways to define a contracts:

The assert statement

Throwing exceptions (such as IllegalArgumentException)

Asserts seem to only have value as a debugging tool. Since asserts are not enabled by default, the expectation is that developers will only rely on them during some formalized testing period, after which they are ignored.

Throwing exceptions seems like a robust option in that they allow almost any kind of checks to be made. However, the range of exceptions defined by the Java library seem to be poorly suited to defining contracts (for examply subclasses of IllegalArgumentException don't specifically with range issues, null checks etc, and subclasses of IllegalStateException appear to be concerned with network connection and file states), which forces each group to define their own range of exception classes.

But the biggest problem is that neither asserts nor exceptions explicitly map contract requirements to parameters or concepts like pre and post conditions. It is expected that the developer will manually maintain the JavaDoc comments with the code to make it clear under what conditions an assert will fail or an exception will be thrown.

It is clear to me that the standard Java libraries don't adequately support design by contract, which brings me to my questions:

Are my assumptions above correct, or have I missed some property of asserts and exceptions that actually makes them quite useful for this kind of problem?

答:
Your assumptions are correct.  Java requires a third-party library to implement design by contract.

Here are some third-party libraries listed in the Wikipedia article on design by contract.

Contract4J, jContractor, Jcontract, C4J, Google CodePro Analytix, STclass, Jass preprocessor, OVal with AspectJ, Java Modeling Language (JML), SpringContracts for the Spring framework, Modern Jass, Custos using AspectJ,JavaDbC using AspectJ, JavaTESK using extension of Java, chex4j using javassist, or Contracts for Java, and the highly customizable java-on-contracts.


答:
The TEAM failed.

Your company needs more code review on a dev doing a first time build.

I just don't see how a team allows this to go on without them doing a review and offering some assurances along the way that you are doing things correctly.

Being close to release time is not an excuse, but a better reason to double-check new code.

If your release cannot be easily undone, there are even bigger problems with this group.

Title: How to apologize when you have broken the nightly build

Body:
My first commit in my project resulted in the nightly build being broken and people are all over me as we are nearing the release. I want to send an apology email that should sound sincere
and at the same time hinting that this was my first commit and this would not be repeated any more.

Being a non-native English speaker, I have difficulties coming up with correct words. Can someone please help?


问:
Estimate cost of project depends on [SLOC|COCOMO]?
Is it logical to estimate cost of project depends on source lines of code?

Like those calculated reports from tools such as

sloccount

ohloh estimating

*

How to convince [somebody|employer|client] to pay depends on those reports ?
The weird things come to scene when I see something like $83,862 based on my project.

Sometimes the developer [him|her]self would write more lines of code because of this estimating.

So if the count of the source lines isn't worthy, Why should be [sometimes|somehow] interesting part of development, Specially for employer, It does amaze them but why doesn't have any effect on pricing ?

Hey Employer I've developed this project that worth $1 million dollars, This source code counter program will prove it.

Maybe I don't know the real worth of my work, Should I public it for people and collect some comments about it or show it to some [experts|consultants] to find-out or just estimate myself upon my knowledge, And all of these solutions aren't right or at least logical.

And what happens to those codes I didn't wrote by myself, I mean sometimes we just copy a piece of code and [pasted|modified] into project.

And if estimating in this way is wrong, What is the purpose of these tools to generate such a report about source lines of code, Average hourly work and other facts.

Ohloh :

Estimated Cost

We calculate the estimated cost of the project using the Basic COCOMO
  model. For those familiar with the details, we are using coeffcients
  a=2.4 and b=105.

Estimate still seems way off?

Software cost estimation is tricky business even when all the
  variables are known (which we certainly don't have). One thing to
  remember is that COCOMO was created to model large institutional
  projects, which often don't compare well with distributed open-source
  projects. Beyond just development time, COCOMO is meant to include the
  design, specification drafting, reviewing and management overhead that
  goes along with producing quality software.

This model seems to be most accurate with mature, large projects.
  Young projects with little activity are typically overvalued.

I know quote from ohloh isn't just about SLOC

答:
No, it's not a good idea to try and equate lines of code with an amount of work. LOC can be used as an extremely rough estimate for the size of a program, but that's a negative trait. You don't want a program that's more complex then it needs to be. Even the simplest tetris clone could have millions of lines of code if made horribly.

As an alternative, I suggest you find a consultant that has the skill-set for this project. Send him a description of the job and ask for an estimate. (Which, since you have no intention of actually hiring him, isn't the nicest thing to do. So buy him lunch or something afterwards.)

Consultants charge an arm and a leg because they can, theoretically, walk in with the exact skill set and knowledge base you need and can get the job done quickly. Show this price quote and he should be at least a little happier.

The free market is a fantastic means of finding the real value of a thing.


答:
Usually I find that good tests plus a sensible level of runtime validation deliver most of the benefits of design-by-contract. I'm not sure it is necessarily worth bring in a whole new toolset for design-by-contract in normal Java programs.

Techniques you can use without leaving standard Java:

Use JUnit tests to explicitly post conditions on a wide variety of inputs

For any public API (i.e. one that is intended to be consumed by external users / other groups in your organisation) do runtime validation of parameters explicitly. Throw exceptions with a meaningful error message in the event of any invalid input (an IllegalArgumentException is fine, but do make sure the message makes sense!)

For any functions that validate their arguments, you should write JUnit tests with invalid input and verify that an exception is thrown (this is effectively a pre-condition test)

Write a validate() method for all complex custom objects that tests the internal state / consistency of the object and any composed sub-objects. You can call this method either during testing or at runtime to ensure that the whole structure is valid. Effectively this is an invariant check on a data structure.

Use asserts within functions to test for invariants during execution. These can be expensive, so it make sense to use asserts so that the checks will not be applied in production code, but these checks are very valuable during testing and debugging. Remember that your assets should also get used during your JUnit automated test suite runs, so you should pick up most logic errors during development.

Title: Options for programming by contract in Java

Body:
I am working on a project (which includes JavaEE web apps and JavaSE apps) that has grown from a single developer to a team of three, and issues of readability and robustness are starting to emerge.

One glaring omission from the Java language has been fine tuned contracts, and how easily these are exposed to other developers. (By contracts I mean mostly validating method parameters and object pre/post conditions).

There are a few solutions that I am looking at, and I would like to get some feedback from others who have some practical experience.

It would seem that Java currently has two supported ways to define a contracts:

The assert statement

Throwing exceptions (such as IllegalArgumentException)

Asserts seem to only have value as a debugging tool. Since asserts are not enabled by default, the expectation is that developers will only rely on them during some formalized testing period, after which they are ignored.

Throwing exceptions seems like a robust option in that they allow almost any kind of checks to be made. However, the range of exceptions defined by the Java library seem to be poorly suited to defining contracts (for examply subclasses of IllegalArgumentException don't specifically with range issues, null checks etc, and subclasses of IllegalStateException appear to be concerned with network connection and file states), which forces each group to define their own range of exception classes.

But the biggest problem is that neither asserts nor exceptions explicitly map contract requirements to parameters or concepts like pre and post conditions. It is expected that the developer will manually maintain the JavaDoc comments with the code to make it clear under what conditions an assert will fail or an exception will be thrown.

It is clear to me that the standard Java libraries don't adequately support design by contract, which brings me to my questions:

Are my assumptions above correct, or have I missed some property of asserts and exceptions that actually makes them quite useful for this kind of problem?


答: I probably learned 95+% of what I know related to programming from trying stuff on my own and learning how it works. School can help with teaching good programming style and optimizing code for speed, etc, but you will never become a "good" programmer just by reading a textbook. A great way to build programming skills is to find everyday problems that you could use a computer to solve, and try to write some code to get it done. Getting stuck is part of learning. I started out wanting to be a web dev, so I would make dummy websites fairly often (not hosting them or anything of course) to test out new things I wanted to try. It worked out pretty well for me!</p>


问:
Has whitespace in identifiers ever been idiomatic?
C# style suggests using CamelCase in identifiers to delimit words. Lisp tradition suggests using-dashes-instead.

Has there ever existed a programming language where using spaces in identifiers was not only allowed, but a commonly used idiom when employing multi-word identifiers?

It's possible to have identifiers with spaces in some Scheme implementations, but it's not a widely seen practice. Here's an example:

```<code>Petite Chez Scheme Version 8.4
Copyright (c) 1985-2011 Cadence Research Systems

> (define |hey there| 100)
> (define |x y z| 200)
> (list |hey there| |x y z|)
(100 200)
</code>```

答: The o42a programming language I am currently developing supports a multi-word names. The language has no keywords at all and the names are usually separated   with some symbol. In the rare case the two names follow each other, the underscore is used to separate them.</p>


答:
Don't worry too much about the asker's motivations, and just answer honestly.  Remember, an interview is a two-way street.  You don't want to get stuck in an ideologically inflexible company any more than they want to get stuck with you.

That being said, I think you're being a little paranoid about interviewers' intentions.  An astounding number of supposedly professional programmers do not understand the fundamentals of OOP.  99% of the time, interviewers aren't trying to see if you drank the OOP kool-aid, but only want to see if you have a basic understanding of it.  Even if you feel another paradigm is better suited for a certain solution, interviewers want to know that was an informed conclusion, and not borne of ignorance of OOP.

Rationalization is a very common defense mechanism when someone doesn't understand something.  If people don't understand a concept, they argue the concept is stupid or inapplicable rather than admit their own ignorance.   Even if you truly think OOP is a poor choice for an answer, you must nevertheless distinguish yourself from the rationalizers.  The way to do that is to both explain the OOP solution and why you think it's a poor choice in that situation.


答:
SLOC can be an effective means of pricing projects when historical company metrics are kept.  Also, it is not simply a matter of the project is x-number of lines of code and price according to that single metric. You have to break the system into modules and functionality. Then for each module you have to take into account, how much is new, how much is reused, how much is redesigned, how much is auto-generated, the difficulty level, the expected developer's familiarity with the module, the developer experience/productivity level, the destination platform and company historical results for similar functionality.  In the end, this gives an ESLOC (Effort SLOC) number that can then be used to price the software. It is a tried and true method of quoting software used by many companies quite successfully. The key is that historical records must be kept since a company's culture and  the type of applications that are developed affect the schedule to a great degree.

While pricing software using SLOC works for many companies, it should also be noted that it is completely ineffective at evaluating software developer productivity.  Better software developers will write far, far fewer lines of code than mediocre or bad programmers but get many times the functionality than the mediocre developers in those fewer lines of code.  In fact, the good developers tend to get negative productivity (when using SLOC as the metric) when they go in and refactor away hundreds or thousands of the mediocre developers lines of code because it should have been written so much more cleanly and easier to understand.

Title: Estimate cost of project depends on [SLOC|COCOMO]?

Body:
Is it logical to estimate cost of project depends on source lines of code?

Like those calculated reports from tools such as

sloccount

ohloh estimating

*

How to convince [somebody|employer|client] to pay depends on those reports ?
The weird things come to scene when I see something like $83,862 based on my project.

Sometimes the developer [him|her]self would write more lines of code because of this estimating.

So if the count of the source lines isn't worthy, Why should be [sometimes|somehow] interesting part of development, Specially for employer, It does amaze them but why doesn't have any effect on pricing ?

Hey Employer I've developed this project that worth $1 million dollars, This source code counter program will prove it.

Maybe I don't know the real worth of my work, Should I public it for people and collect some comments about it or show it to some [experts|consultants] to find-out or just estimate myself upon my knowledge, And all of these solutions aren't right or at least logical.

And what happens to those codes I didn't wrote by myself, I mean sometimes we just copy a piece of code and [pasted|modified] into project.

And if estimating in this way is wrong, What is the purpose of these tools to generate such a report about source lines of code, Average hourly work and other facts.

Ohloh :

Estimated Cost

We calculate the estimated cost of the project using the Basic COCOMO
  model. For those familiar with the details, we are using coeffcients
  a=2.4 and b=105.

Estimate still seems way off?

Software cost estimation is tricky business even when all the
  variables are known (which we certainly don't have). One thing to
  remember is that COCOMO was created to model large institutional
  projects, which often don't compare well with distributed open-source
  projects. Beyond just development time, COCOMO is meant to include the
  design, specification drafting, reviewing and management overhead that
  goes along with producing quality software.

This model seems to be most accurate with mature, large projects.
  Young projects with little activity are typically overvalued.

I know quote from ohloh isn't just about SLOC


答:
There's a great YouTube video about the "Surprising Truth About What Motivates Us". I blogged this a while back:

http://www.chrisholmesonline.com/2010/06/02/the-surprising-truth-about-what-motivates-us/

I like the part where he says, essentially, to pay your employees enough so that money is taken off the table as a consideration for why they want to work there. When money is no longer a motivating factor, you get a much better set of results.

I know what motivates me:

Being able to use the tools I prefer. So give your developers the tools they want and need. With a team of 25 people, obviously, you have to come to compromise and consensus, but the bottom line is they need the best tools. This encompasses hardware and software.

Normal work hours. 35-40 hours per work. Nothing more. If they want to come in on their own to do more because they're inspired, fine. But overworking people in jobs where they are required to flex their critical thinking muscles is the fast track to disaster.

Telecommute options. I like to work from the comfort of my own home; not have to deal with the headache of traffic and losing an hour a day to travel. I can be there for my family, for emergencies, as a taxi, etc. If you have employees who can handle it and get their workloads done, give them the telecommute option. Also, it is way easier to take a 20-30 minute power-nap at home (proven to increase productivity, but society still frowns on the nap).

A quality workspace. Whiteboards, collaborative tools, conference rooms, etc. A team of 25 employees can only really create something awesome if they're working together, and to work together they have to share ideas freely and collaborate. If they're working remotely, have Skype, etc. But give them the tools to be collaborative.

Clearly defined goals. Not deadlines - those are different. Goals. Implement this however you want - Scrum, XP, I don't care - but your team needs clear goals and milestones.

Don't get locked into one particular dogma; be open to change and new ideas, new technologies, etc. Listen to each other. Don't force architecture on your team; let it evolve through collaboration, feedback, input.

Developers want to make awesome software. If you can give them the opportunity to do that, compensate them well enough that money doesn't factor into their thought processes, and provide them with a healthy work/life balance, they'll produce.


答:
typedef declarations serve essentially the same purpose as encapsulation.  For that reason, they almost always fit best in a header file, following the same naming conventions as your classes, because:

If you need the typedef, chances are the callers will too, especially as in your example where it is used in the arguments.

If you need to change the type for whatever reason, including replacing it with your own class, you will only have to do it in one place.

It makes you less prone to mistakes due to repeatedly writing complex types.

It hides unnecessary implementation details.

As an aside, your memoization code would be a lot cleaner if you abstracted it further, like:

```<code>if (lookup_table.exists(first, last))
    return lookup_table.get(first, last);
</code>```

Title: When to use typedef?

Body:
typedef declarations serve essentially the same purpose as encapsulation.  For that reason, they almost always fit best in a header file, following the same naming conventions as your classes, because:

If you need the typedef, chances are the callers will too, especially as in your example where it is used in the arguments.

If you need to change the type for whatever reason, including replacing it with your own class, you will only have to do it in one place.

It makes you less prone to mistakes due to repeatedly writing complex types.

It hides unnecessary implementation details.

As an aside, your memoization code would be a lot cleaner if you abstracted it further, like:

if (lookup_table.exists(first, last))
    return lookup_table.get(first, last);


问:
How would you create a mobile (android) offline wiki site?
My apologies in advance if this is not a good forum for this question; pointers to others happily accepted.

On the off chance it matters, I'm not going to commercialize this idea or anything; if anything in here is interesting to you, use it as you see fit.

My basic problem is this: My favorite place to do non-code writing (essays, fiction, etc) is on my Android phone when I'm traveling.  Said traveling often causes the phone to lose all signal/web connection.  I would like a system that auto-syncs with the phone in some fashion, can be written in a fairly wiki-ish style (i.e. links are supported but I don't have to actually type out also be edited easily at a regular computer when needed.  I'd prefer the editing on the phone be as close to plain text as possible, because fine manipulation like that required to set something to bold or whatever is a pain; I'd rather just be able to type things out.

Nice-to-have is the ability for other people to collaborate on documents.  Very-nice-to-have is authentication so that some documents can be private, without having to get into the auth quagmire myself.

There really doesn't seem to be any such thing out there.

The two options I've thought of for implementing this:

Now that there exists a proper 2-way sync dropbox app ( https://play.google.com/store/apps/details?id=com.ttxapps.dropsync ), I could just use a plain-text editor on the phone and have a simple web app that presents the text via a wiki markup library of some kind out of the relevant dropbox folder.  Advantages: Dead simple.  Disadvantages: No easy auth or collaboration.

I could use Google Docs, and have a not-so-simple Web app that pulls documents from there, treats them as wiki text, maybe does some cashing, and presents them as a coherent-ish web site(s).  Advantages: If I can get the auth to pass through properly, auth and collaboration are free.  Disadvantages: Much more complex, and this is just a one-off personal project.

I'm curious as to whether I've missed anything, any other easier ways to solve this problem.  I'm actually a little surprised that no-one seems to have thought of backing a wiki on Google Docs; there's the Google app wiki stuff, but that pretty much requires a browser AFAICT, whereas there are several Google Doc apps on pretty much everything with offline sync options.

答:
This sounds like something that could be done in HTML5 with a little server-sided code.

The fundamentals of the webapp could be stored on the phone via the cache manifest.

Assuming you're just typing, and there's not too much to store, you could use localStorage to store document data on the phone in the background. In addition, the phone can attempt to save changes to the server periodically, or when you leave the page.

A periodic asynchronous javascript request could try polling the server to see if there have been any changes in the last few minutes, and ask the user if they want to update these changes. If you're expecting quicker updates, consider using WebSockets instead of xmlhttprequests.

Authentication would be a little more difficult if you plan on incorporating offline work, but it's very possible. In addition, this scheme would require a webhost that allows writing files on a server (most will do that, but it usually costs extra). There may be a way to push text documents to Google Docs, though I've never heard of such a thing.

Hope that has inspired you!


问:
What is the canonical reference on probabilistic data structures?
I've heard of probabilistic data structures like Skip Lists and Bloom Filters being immensely useful and I'd like to learn more about them in general. Is there a canonical reference on the subject on the level of Cormen et al.?</p>

答:
The closest site I can think of that might be canonical is
the NIST standards web site:

http://xlinux.nist.gov/dads/HTML/skiplist.html

This site can be short on descriptions but has links to external
sites ..