问:
Comparison of IDEs for C++ and C development on Linux: KDevelop, Eclipse, NetBeans, CodeBlocks and Anjuta
I'd like to note your experience of full scale IDEs on Linux.

I personally work mostly with vim, however other programmers would like
to see a real IDE. So I'd like to hear your personal opinion about different
IDEs and comparison between them, in following context:

C++ and maybe some C development (not Java, Python and other stuff)

Server side programming (no need for GUI development)

Working on Linux not "cross-platform" development.

Opinion needed regard:

How stable is it? If IDE crashes I don't need it.

Comfortable to use.

Powerful for debugging.

Integration with various build systems

Scalability over huge projects (projects of hundreds thousands of lines of code)

I used to work with KDevelop and it was very nice IDE and seems that KDevelop 4 is a huge progress. It seems also that many rather use Netbeans and Eclipse.

答:
Here is my personal experience with IDEs. I installed all IDEs I could find, and played with them all (that is what I would advise you to do) :

kdevelop

I personally use it. The version I have installed crashes, but I downloaded the latest version from their site, and it works good. It is simple to configure and great to use.
They support custom build system through plug-ins. You might find some weird features (like parsing only directly included headers), but generally it works good for big projects.

eclipse

Super complex to configure, but it allows literally everything. If you have enough time to find a correct configuration that pleases everyone, then go for it. But trying to change anything is very annoying because it has so many options.

anjuta and codeblocks

I tried it shortly, and it wasn't as good as the previous two. Codeblocks is good for short projects, but not for medium and big.

netbeans

Another good IDE, but since my home is on network share, and the project I work is fairly big, it was very slow. It parses all the time.

qtcreator

Simple to configure, but it is missing lots of options. For example, the strangest thing with it is that it can not parse and auto complete qt classes. Supports custom build system.

To conclude :

if you are patient enough (or if you find a good configuration), go with eclipse. It is really the best free IDE.

If you want something simple to configure, go with kdevelop.

Another option is to install both, and let your developers pick what suits them better.


答:
Take a look at Qt Creator.

It's pretty stable. I don't remember any crashes with it.

It may take some time to get used to absence of tabs but overall interface is good.

It uses gdb. Debugging is not as great as in Visual Studio but still pretty good. It also integrates with profiler (Valgrind) now.

It integrates with qmake and CMake. But you can run custom commands so it should be possible to use almost everything.

Can't say anything about huge projects but it's made and used by the same guys who write Qt so requirements are high.

It doesn't seem to make any assumptions about project structure.

I tried KDevelop 4 some time ago. It's certainly moving in the right direction but slightly buggy. You may want to try it anyway.

I used CodeBlocks for very short time but I remember I didn't like it because Interface was ugly.

ContentLicense: CC BY-SA 3.0

Title: Comparison of IDEs for C++ and C development on Linux: KDevelop, Eclipse, NetBeans, CodeBlocks and Anjuta

Body:
I'd like to note your experience of full scale IDEs on Linux.

I personally work mostly with vim, however other programmers would like
to see a real IDE. So I'd like to hear your personal opinion about different
IDEs and comparison between them, in following context:

C++ and maybe some C development (not Java, Python and other stuff)

Server side programming (no need for GUI development)

Working on Linux not "cross-platform" development.

Opinion needed regard:

How stable is it? If IDE crashes I don't need it.

Comfortable to use.

Powerful for debugging.

Integration with various build systems

Scalability over huge projects (projects of hundreds thousands of lines of code)

I used to work with KDevelop and it was very nice IDE and seems that KDevelop 4 is a huge progress. It seems also that many rather use Netbeans and Eclipse.


问:
Protecting the uninitiated (developer) from generics
Is it acceptable to have a dummy generic parameter in the parameters list in order to save method consumers from the need to specify type arguments? For example -

public T Generate<T>(int paramForInstance) where T : MyClass {
    return MyClass.SomeFactoryMethod<T>(paramForInstance);
}

//calling code needs to specify type
MyDerivedClass instance = Generate<MyDerivedClass>(5);

public T Generate<T>(int paramForInstance, T dummy) where T : MyClass {
    return MyClass.SomeFactoryMethod<T>(paramForInstance);
}

//calling code needs to provide a "sample" to enable type inference
MyDerivedClass instance = null;
instance = Generate(5,instance);
```

<p>The assumption here is that if <strike>junior</strike> other devs on the team don't need to think about generics, they're less likely to kick.</p>

<h2>A Little Background (feel free to skip this)</h2>

<p>A couple weeks ago, a management-developer type in my team freaked out when he saw code (my code) that looked like this:</p>

<pre class="lang-cs prettyprint-override"><code>//conversion methods, using generics
private static TResult? IfNotDangerous<TResult>
  (SomeType firstThing, string name, Func<object, TResult?> conversion)
  where TResult : struct
{
    return IfNotDangerous(firstThing, name,
          (any, dummy) => conversion(any), (TResult?)null);
}

private static TResult IfNotDangerous<TResult>
  (SomeType firstThing, string name, Func<object, TResult, TResult> conversion,
  TResult defaultValue)
{
    if (firstThing == null) return defaultValue;
    if (!firstThing.Contains(name)) return defaultValue;
    if (firstThing[name] == DangerousValue) return defaultValue;
    return conversion(firstThing[name], defaultValue);
}
</code>```

The complaint he had was, "Why are you using a struct?! That's so resources-heavy! And what does 'where' mean? Nobody on the senior development end knows what that does - I've asked them all!"

After overcoming my self-pity, I found a way around that didn't use generics for this particular method. Appeasement was achieved. But I'd like to avoid trouble in the future, if possible.

EDIT

I appreciate all the encouragement, but the question was not "should I look elsewhere for work?" - it was "is this a usable workaround?"

答:
Sad to see programmers that do not move along with the times.

The fact is that generics have been part of C# and .NET since version 2 and LINQ since version 3. These are no longer cutting edge new techniques.

Instead of "Protecting" them you should be teaching them. Start a weekly tutorial (over lunch if you don't have buy-in) for all developers who are interested in staying current.

The fact is that if they bring in a new senior, chances are they would also be using generics and LINQ. Keeping these "hidden" or not  using them is a disservice to the other developers and the company.

If you are told to not use generics and LINQ at all, I would sadly conclude it is time to look for a job where developers don't cripple themselves.

Update:

Since you don't seem to think the above answers the question "is this a usable workaround?" I will answer now:

No it isn't. It is an abuse of generics and has too much "magic" - it is even less understandable than the straight generic code and if any of your colleagues will have to delve into it, they will not be able to figure it out.

The fact that it works and does what you want it to (hide the use of generic) is besides the point. It is opaque and even the usage is not idiomatic (giving a "prototype" to the function for it to work).


问:
Starting off with web dev with php
I'm currently working with Java / C++. I'm interested in web development and am planning to shift my stream. I heard that PHP is a good platform to start off and also it does not require that much of knowledge in technologies like JSP / Servlets or frameworks like springs / struts / hibernate.

I have basic ideas about HTML and Javascript as well. I have gone through previous posts in SO and found out the relevant resources as well:

http://net.tutsplus.com/tutorials/php/the-best-way-to-learn-php/

http://www.webhostingtalk.com/archive/index.php/t-1028265.html

http://www.killerphp.com/

http://phpforms.net/tutorial/tutorial.html

http://www.php5-tutorial.com/ etc.

Now, my question is: I heard of PHP frameworks like CodeIgniter, Zend Frameworkd and Yii.

Doesn't learning PHP & MySql implicitly makes us aware of these frameworks?

Am I making a good choice in stating with PHP?

Is it a good idea to shift streams?

答:
Doesn't learning PHP & MySql implicitly makes us aware of these frameworks?

Nope. As @GrandmasterB mentions it's possible to work with PHP without any kind of framework or any other third party library. Nowadays PHP includes a native MVC framework. It's still in its early days, and mostly undocumented, but it works (for basic stuff).

But, there is no reason at all to avoid working with a framework. A framework is supposed to take care of common stuff and let you concentrate on the important stuff. Some do it better than others, but in general it wouldn't hurt to learn one of the popular ones. A couple of related questions:

Need for a framework

When do I need to use a framework?

But try to avoid Zend Framework at first, as it's not an entry level framework.

Am I making a good choice in stating with PHP?

Yes. Compared to the alternatives:

PHP is extremely easy to get the hang of,

Is widely deployed, I have still to find one hosting solution that didn't provide PHP by default,

Is web oriented, whereas most alternatives are general purpose.

It's portable across operating systems and across web servers1,

Its core is extendable via C and C++ (which you already know),

The manual is fantastic,

It's open source2,

It has a large and vibrant community,

It's the platform of choice for a lot of definitive web applications3

Not to say that many other platforms don't fit most of the above, but AFAIK PHP is the only one that fits all of them.

But there are quite a few traps:

One of the reasons it's extremely easy to get the hang of, is that it allows a wide range of paradigms, doesn't enforce anything and it's completely up to you to follow best practices. There's no reason at all you shouldn't be able to write brilliant PHP code, comparable to brilliant Java or C++ code, but there is almost none of the common safeguards against, well, not so brilliant code.

And because it's so easy and popular, it provides a sense of false confidence. The internet is full of crappy PHP code, that works fine but it's a horror to look at. And quite a few crappy "tutorials". It's up to you to apply good judgement and successively swim through the seas of PHP @#!$. When learning, that's quite a challenge.

Is it a good idea to shift streams?

That's unanswerable, it's definitely a risk. If it's one worth taking you'll have to decide for yourself.

Unfortunately PHP, MySQL, HTML and Javascript not a web developer make. There is a very long list of technologies and concepts involved, the accepted answer to the "What should every programmer know about web development?" question. It's a very scary list and of course it's impossible to know everything that's on it at first. But it's not the full list. You are not making a language shift, but a domain shift. The web employs an extremely wide range of technologies, and something new pops up every day.

And if that list doesn't scare you enough, I've assembled a few PHP specific ones, as answers to these questions:

What is a good way to familiarize myself with php, coming from an asp.net background?

Progressing past CRUD applications in PHP?

Test PHP Skills in a interview

It's going to be a very long road. To me it's worth it, but again you'll have to decide for yourself.

1 With minor tweaks across operating systems and not so minor but not that significant tweaks across web servers.

2 Which matters to me.

3 Examples: Wordpress, the most popular blogging platform, phpMyAdmin, the most widely deployed MySQL administration tool, and, ahem, Facebook.

Title: Starting off with web dev with php


答:
From the moment they do not allow you to use the full features of the language (a language which, I presume, was chosen by them, not you,) anything goes. Is it acceptable? Sure it is. I would never do such a thing, but it seems like you have to. And it will work.

But if I were in your shoes I would go all the way with it: I would set the compatibility level of the compiler (in project options) so that language constructs that they consider unacceptable cannot even compile, which would mean that the entire shop would be coding in C# 1.0. And I would start looking for another job.

Title: Protecting the uninitiated (developer) from generics

Body:
Is it acceptable to have a dummy generic parameter in the parameters list in order to save method consumers from the need to specify type arguments? For example -

public T Generate<T>(int paramForInstance) where T : MyClass {
    return MyClass.SomeFactoryMethod<T>(paramForInstance);
}

//calling code needs to specify type
MyDerivedClass instance = Generate<MyDerivedClass>(5);

public T Generate<T>(int paramForInstance, T dummy) where T : MyClass {
    return MyClass.SomeFactoryMethod<T>(paramForInstance);
}

//calling code needs to provide a "sample" to enable type inference
MyDerivedClass instance = null;
instance = Generate(5,instance);
```

<p>The assumption here is that if <strike>junior</strike> other devs on the team don't need to think about generics, they're less likely to kick.</p>

<h2>A Little Background (feel free to skip this)</h2>

<p>A couple weeks ago, a management-developer type in my team freaked out when he saw code (my code) that looked like this:</p>

<pre class="lang-cs prettyprint-override"><code>//conversion methods, using generics
private static TResult? IfNotDangerous<TResult>
  (SomeType firstThing, string name, Func<object, TResult?> conversion)
  where TResult : struct
{
    return IfNotDangerous(firstThing, name,
          (any, dummy) => conversion(any), (TResult?)null);
}

private static TResult IfNotDangerous<TResult>
  (SomeType firstThing, string name, Func<object, TResult, TResult> conversion,
  TResult defaultValue)
{
    if (firstThing == null) return defaultValue;
    if (!firstThing.Contains(name)) return defaultValue;
    if (firstThing[name] == DangerousValue) return defaultValue;
    return conversion(firstThing[name], defaultValue);
}
</code>```

The complaint he had was, "Why are you using a struct?! That's so resources-heavy! And what does 'where' mean? Nobody on the senior development end knows what that does - I've asked them all!"

After overcoming my self-pity, I found a way around that didn't use generics for this particular method. Appeasement was achieved. But I'd like to avoid trouble in the future, if possible.

EDIT

I appreciate all the encouragement, but the question was not "should I look elsewhere for work?" - it was "is this a usable workaround?"


问:
What's the best way to organize JavaFX 2.0 code?
In every example I have seen yet almost all of the GUI code is written in the start(Stage stage) method of the main class. Is this the best approach, or is it OK to subclass the Stage class and make your own thing? If the latter is OK, wouldn't the performance suffer because of lot of Stages?

答:
You have to use stage given to start method as your main Stage because it's created for you by JavaFX startup logic (and it can be desktop stage, jnlp one, or a plugin in the browser so you better not create it yourself).
If you need another windows in your application (dialogs, warning, popup windows, etc) you can create new Stages. You can use them as new Stage() objects or subclass, at doesn't really matter or affect performance (IMHO).


问:
How important are design patterns in programming?
I'm a university student and I've just started learning about design patterns and im struggling to understand the purpose of them. I have tried researching them but all the resources I have found seem to talk about them in an academic, not professional, way.

What is their purpose and are they important to learn?

答:
Design patterns are great for communicating your intent very quickly- everyone knows what a Factory is.

What's a really, really, really bad thing to do is start trying to fit your code to patterns, or separate responsibilities according to patterns, or something like that. It's one thing to say "This object is a Factory" and another to say "This object should be exclusively a Factory".


答:
From the wikipedia article on Design Patterns:

The usefulness of speaking of patterns is to have a common terminology
  for discussing the situations designers already see over and over.

For a very long time we have had a serious problem in software engineering: you hire a newcomer to a project, and no matter how well they know the programming language, it takes them months to get up to date with how things are done in your project before they can be productive. In hardware engineering, they solved this problem a very long time ago: they have a common terminology called 'schematic diagrams'. You hire a hardware engineer, give them the schematics of your hardware project in the morning, let them study them, and by evening before it is time to call it a day they can pick up the soldering gun and become productive. We have been trying to come up with ways to become better at that; standardization of programming languages was one way; standard libraries (class libraries nowadays) have been another way; but one of the most important ways has perhaps been design patterns.  So, are they important?  You bet!

Title: How important are design patterns in programming?

Body:
I'm a university student and I've just started learning about design patterns and im struggling to understand the purpose of them. I have tried researching them but all the resources I have found seem to talk about them in an academic, not professional, way.

What is their purpose and are they important to learn?


答:
The way I see your question is as follows:

Should I write code which doesn't follow the standard conventions and will teach people who don't know generics bad habits, or should I use them the way they're intended to be used?

Viewed from that perspective, I think it answers itself.

In answer to "What does where mean?" you could send an e-mail linking to http://msdn.microsoft.com/en-us/library/6b0scde8(v=vs.80).aspx explaining that although MS have clearly borked the "Other versions" link, the documentation of where clauses from VS2005 is still valid.


答:
The gerneric parameter in your code is not "dummy", since it is used as return type. This is a common pattern also used by Microsoft in the BCL. Example found in

System.Data.DataRowExtensions

```<code>public static T Field<T>(this System.Data.DataRow row, string columnName)
</code>```

Body:
The gerneric parameter in your code is not "dummy", since it is used as return type. This is a common pattern also used by Microsoft in the BCL. Example found in

System.Data.DataRowExtensions

public static T Field<T>(this System.Data.DataRow row, string columnName)


答:
Patterns are about re-use of ideas and concepts and about establishing a common/consistent platform for communication of same.

We're all agreed (!) that in theory code-reuse is a good thing - but it turns out to be harder than we'd like to do so practically (in some respects this is changing, but it will always be a challenge). But in reality a lot of what we want to reuse is a way of doing things, to use a sort of template for constructing a solution to a particular problem - these are Patterns. So you get to a case where you say that a good approach to solving problem X is to use Pattern Y and we know that the elements of pattern Y are a,b and c and off we go. Because the patterns are widely understood you don't have to explain in depth which is the communications benefit.

What's entertaining about patterns is that languages and frameworks are evolving to provide better support for common patterns with the net effect that we're getting more and better code reuse (more and better lego bricks!) because the way we build applications (by implementing patterns) facilitates reuse.


问:
How to go about "taking over" an open-source project?
There's an open-source project that I'm interested in and use regularly. It's licensed under the Apache License 2.0 and it has basically no activity any more. It's hosted on Google Code and I'm interested in continuing it's development. I'm new to the open-source process and I'm trying to figure out the appropriate way to go about this. Can I just check it out and push it to github so I can continue it's development in the open there? Should I contact the project "owner" first? Also, do I leave all the author information at the top of the classes, etc even though I'm going to be making changes..(I'm assuming the answer is yes)?

Also, how do I practically adhere to the license requirement of "all modifications are clearly marked as being the work of the modifier"? Do I place a comment by every change I make?

Any guidance on what's the normal course/standard here would be greatly appreciated?

答:
There are many ways to go about doing this:

Email the original "owner/author". Tell him about your intentions and how you can help development. Wait about 1 week. If there is no answer...

Fork the repository. Out of respect, and to make sure you did nothing wrong (which you probably didn't) make clear reference to the original author.

Get coding! You are now the the proud developer of Project ABC.

OwnerDisplayName: LuxuryMode


问:
Does object-orientation really affect algorithm performance?
Object orientation has helped me a lot in implementing many algorithms. However, object-oriented languages sometimes guide you in "straightforward" approach and I doubt if this approach is always a good thing.

OO is really helpful in coding algorithms fast and easily. But could this OOP be a disadvantage for software based on performance i.e. how fast does the programm executes?

For example, storing graph nodes in a data structure seems "straightforward" in the first place, but if Node objects contain many attributes and methods, could this lead to a slow algorithm?

In other words, could many references between many different objects, or using many methods from many classes, result in a "heavy" implementation?

答: A good object oriented design helped me to speed up an application considerably. A had to generate complex graphics in an algorithmic way. I did it through Microsoft Visio automation. I worked, but was incredibly slow. Fortunately, I had inserted an extra level of abstraction between the logic (the algorithm) and the Visio stuff. My Visio component did expose its functionality through an interface. This allowed me to easily replace the slow component with another creating SVG-files, that was at least 50 times faster! Without a clean object-oriented approach, the codes for the algorithm and the Vision control would have been entangled in a way, which would have turned the change into a nightmare.</p>


答:
There are really two different, substantial reasons for the existence of patterns.

The first has already been explained pretty well: the use of patterns lubricates communication between developers.  If you and I both understand that when I say 'Observer' I am talking about a very specific structure of code, then I can very quickly describe how a bit of code which uses that pattern works.  The alternative is to fully describe the solution, which is time consuming and error prone.  ("Well, I created this pure virtual class which describes and interface for consumer objects, and then I created a class which maintains a list of active consumers, which ...")

The second benefit of patterns is that they are off-the-shelf solution-forms for common problem-forms.  If you know your patterns, and, for example, you encounter a problem where you need to find a good way to get information from (possibly multiple) producer objects to multiple consumer objects, without introducing unnecessary coupling between classes, you will recognize "this is a job for an Observer!" and you will immediately know how to solve your problem.

These benefits also really reinforce each other.  They allow you to quickly solve certain common classes of problem, and then when you're done, you can very quickly communicate how you solved the problem.

Contrast this with a world where patterns "don't exist".  You run into one of these classes of problems, which are generally not trivial design problems, and you spend a fair bit of time coming up with a good solution (which, incidentally, will very likely look a lot like the appropriate pattern).  Then, your co-worker comes up and wantx to know how you solved it, and you spend an hour discussing the how and the why.

This is all associated with a caveat which should seem pretty obvious: don't try to force problems into patterns that don't fit.  If the pattern doesn't fit the problem, then the solution will end up being convoluted and you will lose the effort reduction benefit of patterns.  Additionally, since your work will no longer fit with your co-workers' understanding of the meaning of the pattern, you will lose the cost of communication benefit.  In fact, you will likely increase the cost of communication beyond the no-patterns cost, because the misuse of the pattern will give your co-workers a false understanding of the solution, which is worse than no understanding at all.


问:
Is Java free software?
Free software as defined by FSF.
Are its standard libraries free/open source?
Is its implementation free/open source? Which parts of it are not free/open source?
Any other relevant information.</p>

答:
Java itself has been opened sourced, so in that respect it is free.

Some library implementations are open source, some are not. The ones from Sun have been opened sourced with the rest of the language.

As for the software you write - that's up to you.

Title: Is Java free software?


问:
Do you have to include a license notice with every source file?
I've been looking for various licenses that I can use for an open-source project of mine, but all of the projects that I've seen, with all kinds of licenses, appear to have a giant, obnoxious (in my opinion) notice in each source file that states that the file is listed under a certain license.  I don't think that I've found a single source project that isn't public domain that doesn't have a notice like that.

This just seems like a waste of time and file space. I plan on putting @license and @author tags in my projects, but I don't see why I need to list such a giant notice in each individual file if I don't want to make my code public domain.

Is there any reason why I would want to include such a notice in my projects, or would simply including a notice in the README and a @license tag be good enough?  Does this affect the "clearly stated" rule of most licenses, or is it just overkill so that people won't argue?

答:
There is no secret superpower meeting in an underground bunker that says what you must put it in each source file.

It does make it clear to the user that this file is under whatever license  and in fact most GPL software contains a short preamble saying to read license.txt.  Remember projects get split up and files get reused so only  putting the message in a single file might not be a good idea.

If in the unlikely event it ever went to court you might have more claim if you had clearly marked each file as your work and what license it was under - then nobody could claim they thought that this prticular file wasn't covered


问:
Avoiding "Smart Guy" Syndrome on Team Projects
A lot of bad practices were being committed at the beginning of a project, and I recognized them and fought against all of them. Since I didn't pick and choose my battles, my boss now assumes anything out of my mouth is an over complicated response, and spends a lot of time defending himself personally, instead of looking out for the best interest of the project.

How do I push the team in the right direction, without waiting four months for everyone to come to the consensus I was trying to get in place all along, or scarring my reputation on the team as a difficult know-it-all?

答: You need to provide explicit, irrefutable, compilable, proof that you are correct, or reduce the problem to something trivially true, e.g., something that must be safe like RAII is by definition safer than something that can be safe, e.g. malloc/free.


答:
Change takes time. Udi Dahan has an excellent article that touches on what you are asking, and I think he does a better job with the answer than I would.

Be enthusiastic, not bitter. Be prepared to carefully, cheerfully explain your position far more often than you'd like. Count your wins, and be prepared for others resisting your ideas. Always keep in mind, that other people's view points, while not your own, may in fact still be right.  In time, you can achieve your goals if you are prepared to work with people.

I wonder if you had a little bit of a twinge when you wrote "since I don't pick and choose my battles" ... it seems like a bit of a red flag to me. Getting a few early, easy wins can set you up not as "that jerk that thinks he's smarter than everyone else" but "that guy that had that great idea last month".

Title: Avoiding "Smart Guy" Syndrome on Team Projects

Body:
A lot of bad practices were being committed at the beginning of a project, and I recognized them and fought against all of them. Since I didn't pick and choose my battles, my boss now assumes anything out of my mouth is an over complicated response, and spends a lot of time defending himself personally, instead of looking out for the best interest of the project.

How do I push the team in the right direction, without waiting four months for everyone to come to the consensus I was trying to get in place all along, or scarring my reputation on the team as a difficult know-it-all?


答:
I've seen many projects which only mention the license in the README or in a LICENSE or COPYING file.

Your software is automatically covered under copyright, as agreed in international law. (Unless you are working for the US government or some other organization for which copyright does not apply.)

If someone uses your software then they must make sure to follow the license agreement, or follow the fair use restrictions on what they can do.

Suppose that person wants to use one of the files in your code distribution, which of course requires a copy and hence copyright law applies. By default they do NOT have the right to use your software under copyright law. It's only when they know and follow the license restrictions that they are allowed to use it.

So if they use a file without a software license then they are breaking copyright law. Since all the licenses say something like "The above copyright notice and this permission notice shall be included in all copies or substantial portions of the Software", they are obliged to put that license somewhere.

That can be in the file itself, or when I've used code as library I put the relevant portions into its own directory and added a "README" or "LICENSE" into that subdirectory.

In short, you don't need to put the license in each file. I think it's overkill. There's no extra legal protection in doing so. It does help a downstream user somewhat, but not by much.

I think the tradition of lots of comment-based metadata (license, creation date of each function, changelog, etc.) are very old traditions which exist because they are easy to do and which more a talisman than useful.

For example, the default Eclipse template adds what I think of as useless metadata before each function, which I think is much better captured by version control. But that practice is common in many shops.

Title: Do you have to include a license notice with every source file?

Body:
I've been looking for various licenses that I can use for an open-source project of mine, but all of the projects that I've seen, with all kinds of licenses, appear to have a giant, obnoxious (in my opinion) notice in each source file that states that the file is listed under a certain license.  I don't think that I've found a single source project that isn't public domain that doesn't have a notice like that.

This just seems like a waste of time and file space. I plan on putting @license and @author tags in my projects, but I don't see why I need to list such a giant notice in each individual file if I don't want to make my code public domain.

Is there any reason why I would want to include such a notice in my projects, or would simply including a notice in the README and a @license tag be good enough?  Does this affect the "clearly stated" rule of most licenses, or is it just overkill so that people won't argue?


答:
In my understanding, the GPLv3 strongly suggests (or even perhaps requires, at least that how I understand the text How to Apply These Terms to Your New Programs, after its section 17) a copyright notice in every source file. It says

To do so, attach the following notices to the program. It is safest to
attach them to the start of each source file to most effectively state
the exclusion of warranty; and each file should have at least the
“copyright” line and a pointer to where the full notice is found.

```<code><one line to give the program's name and a brief idea of what it does.>
Copyright (C) <year>  <name of author>

This program is free software: you can redistribute it and/or modify
it under the terms of the GNU General Public License as published by
the Free Software Foundation, either version 3 of the License, or
(at your option) any later version.

This program is distributed in the hope that it will be useful,
but WITHOUT ANY WARRANTY; without even the implied warranty of
MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.  See the
GNU General Public License for more details.

You should have received a copy of the GNU General Public License
along with this program.  If not, see <http://www.gnu.org/licenses/>.
</code>```

And GNU projects which are FSF owned, like GCC, have such a notice in every file.

I also know of a program (J.Pitrat's CAIA system) which has been refused on a free software community web site because it had no such notice in every file.

I am not a lawyer, but I believe that such notice is practically mandatory in every source file of a GPLv3 program.

The question becomes more interesting for software projects which are generating some (or most) of their source files, e.g. RefPerSys.

(if you use other license, notably a non-FSF one, read carefully about how to apply it; YMMV; however AFAIK writing a notice in every file won't harm.)

Body:
In my understanding, the GPLv3 strongly suggests (or even perhaps requires, at least that how I understand the text How to Apply These Terms to Your New Programs, after its section 17) a copyright notice in every source file. It says

To do so, attach the following notices to the program. It is safest to
attach them to the start of each source file to most effectively state
the exclusion of warranty; and each file should have at least the
“copyright” line and a pointer to where the full notice is found.

<one line to give the program's name and a brief idea of what it does.>
Copyright (C) <year>  <name of author>

This program is free software: you can redistribute it and/or modify
it under the terms of the GNU General Public License as published by
the Free Software Foundation, either version 3 of the License, or
(at your option) any later version.

This program is distributed in the hope that it will be useful,
but WITHOUT ANY WARRANTY; without even the implied warranty of
MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.  See the
GNU General Public License for more details.

You should have received a copy of the GNU General Public License
along with this program.  If not, see <http://www.gnu.org/licenses/>.

And GNU projects which are FSF owned, like GCC, have such a notice in every file.

I also know of a program (J.Pitrat's CAIA system) which has been refused on a free software community web site because it had no such notice in every file.

I am not a lawyer, but I believe that such notice is practically mandatory in every source file of a GPLv3 program.

The question becomes more interesting for software projects which are generating some (or most) of their source files, e.g. RefPerSys.

(if you use other license, notably a non-FSF one, read carefully about how to apply it; YMMV; however AFAIK writing a notice in every file won't harm.)

ContentLicense: CC BY-SA 4.0


答:
Yes, the object-oriented mindset can definitely be neutral or negative when it comes to high-performance programming, both at the algorithmic and implementation level. If OOP replaces algorithmic analysis, it can lead you into premature implementation and, at the lowest level, the OOP abstractions have to be put aside.

The issue stems from OOP's emphasis on thinking about individual instances. I think it's fair to say that the OOP way of thinking about an algorithm is by thinking about a specific set of values and implementing it that way. If that is your highest-level path, you are unlikely to realize a transformation or restructuring that would lead to Big O gains.

At the algorithmic level, it is often thinking about the bigger picture and the constraints or relationships between values that lead to Big O gains. An example might be that there's nothing in the OOP mindset that would lead you to transform "sum a continuous range of integers" from a loop to (max + min) * n/2

At the implementation level, although computers are "fast enough" for most application-level algorithms, in low-level performance-critical code one worries a great deal about locality. Again, the OOP emphasis on thinking about an individual instance and the values of one pass through the loop can be a negative. In high-performing code, instead of writing a straightforward loop, you might want to partially unroll the loop, group several loading instructions up at the top, then transform them in a group, then write them in a group. All the while you'd be paying attention to intermediate calculations and, hugely, to cache and memory access; issues where the OOP abstractions are no longer valid. And, if followed, can be misleading: at this level, you have to know about and think about the machine-level representations.

When you look at something like Intel's Performance Primitives you have literally thousands of implementations of the Fast Fourier Transform, each one tweaked to work better for a specific data-size and machine architecture. (Fascinatingly, it turns out that the bulk of these implementations are machine-generated: Markus Püschel Automatic Performance Programming)

Of course, as most of the answers have said, for most development, for most algorithms, OOP is irrelevant to performance. As long as you aren't "prematurely pessimizing" and adding in a lot of non-local calls, the this pointer is neither here nor there.

Title: Does object-orientation really affect algorithm performance?

Body:
Object orientation has helped me a lot in implementing many algorithms. However, object-oriented languages sometimes guide you in "straightforward" approach and I doubt if this approach is always a good thing.

OO is really helpful in coding algorithms fast and easily. But could this OOP be a disadvantage for software based on performance i.e. how fast does the programm executes?

For example, storing graph nodes in a data structure seems "straightforward" in the first place, but if Node objects contain many attributes and methods, could this lead to a slow algorithm?

In other words, could many references between many different objects, or using many methods from many classes, result in a "heavy" implementation?


问:
Sharing buffer between multiple threads part 2
This is a follow up to my previous not answered question, so I try to make it more clear: last  question.

I have a n-size buffer that is filled up from an external source, it has 2 main methods get() and add(), get() blocks (via wait()) if buffer is empty and add() blocks if buffer is full.

This buffer object reference  is available  to multiple consumers (threads).

Each consumer reads data  from buffer independently from other consumers .

All Consumers must read ALL data from the buffer.

As someone suggested, I have created A hashmap where key is an id of the consumer  and value is the index within the buffer that was read by this consumer.

The problem is that every consumer continues to request data from buffer. I need somehow to block it until next dataitem get available for it in buffer.

Where and how should I block it?

(I can't use wait() in consumers object, because the producer can't call notify()
since producer and consumer are different objects)

答: Is performance crucial? Seems like you could use a queue for this instead of implementing it yourself. Perhaps ActiveMQ could help?</p>


问:
Translating between Python-Django and Javascript
I have a conceptual question about 'translating' between objects I have stored in Django (in Postgres) that I want to use on the front-end. So I have a user object in Python that holds basic things: an id, a username, a password. Let's say I want to output all of that information using Javascript on the client side. Can I just give JS a python object and it will make it into a JS object? I know JS is known for being 'fast and loose' with typing but that just seems absurd!

I'm not looking for syntax, but just an overview of how this would work. Can I put Python objects in AJAX requests, then translate them client side, or is this going to be a basic break-down-things-on-server-side, ship them off, and recombine them on the client side type of thing?

答:
It's called serialize python objects as a string or binary data and deserialize these objects in javascript.

is this going to be a basic break-down-things-on-server-side, ship them off, and recombine them on the client side type of thing?

Yes it is.

Can I put Python objects in AJAX requests, then translate them client side

Yes you can. The actual breaking down, shipping and recombining is so easy that you could do it in a thin ajax abstraction which takes python objects on the server and gives you javascript objects on the client.


问:
What is the accepted style for using the `this` keyword in Java?
I come from languages like Python or Javascript (and others that are less object-oriented) and I am trying to improve my working knowledge of Java, which I know only in a superficial way.

Is it considered a bad practice to always prepend this to the current instance attributes? It feels more natural to me to write

```<code>...
private String foo;

public void printFoo() {
    System.out.println(this.foo);
}
...
</code>```

than

```<code>...
private String foo;

public void printFoo() {
    System.out.println(foo);
}
...
</code>```

as it helps me to distinguish instance attributes from local variables.

Of course in a language like Javascript it makes more sense to always use this, since one can have more function nesting, hence local variables coming from larger scopes. In Java, as far as I understand, no nesting like this is possible (except for inner classes), so probably it is not a big issue.

In any case, I would prefer to use this. Would it feel weird and not idiomatic?

答:
Normally adding this is unnecessary. I don't think it is bad practice per se, but excessive use of this would probably be considered unusual in most Java code bases that I've seen.

However I find it valuable in a couple of specific situations:

Overriding local parameters - sometimes it is necessary to specify that you want to use an instance variable rather than a parameter / local variable of the same name. This is quite common in constructors, where you want the parameter name to match the internal name of the instance variable it is used to initialise e.g.

```<code>class MyObject {
  int value;

  public MyObject(int value) {
    this.value=value;
  }
}
</code>```

When handling other instances of the same class - I believe it makes the code clearer and more understandable to be explicit which instance of the class you are referring to, e.g.

```<code>class MyObject {
  int value;
  ....

  public MyObject add(MyObject other) {
    return new MyObject( this.value + other.value )
  }
}
</code>```

Body:
Normally adding this is unnecessary. I don't think it is bad practice per se, but excessive use of this would probably be considered unusual in most Java code bases that I've seen.

However I find it valuable in a couple of specific situations:

Overriding local parameters - sometimes it is necessary to specify that you want to use an instance variable rather than a parameter / local variable of the same name. This is quite common in constructors, where you want the parameter name to match the internal name of the instance variable it is used to initialise e.g.

class MyObject {
  int value;

  public MyObject(int value) {
    this.value=value;
  }
}

When handling other instances of the same class - I believe it makes the code clearer and more understandable to be explicit which instance of the class you are referring to, e.g.

class MyObject {
  int value;
  ....

  public MyObject add(MyObject other) {
    return new MyObject( this.value + other.value )
  }
}


答:
You can serialize the data in your Python objects easily and use this data in your Javascript code- as some other answers say, JSON for instance is a fairly multi-language way to represent data which has support for many languages- among them Javascript (JSON is really limited Javascript object literal syntax) and Python.

However, these approaches mostly deal with data. If your Python objects have "behaviour"- namely, they have methods with code, they will be "lost in translation".

Say if you have a Python class with a person's data (name, birth date) but with a method which calculates the person's age (now - birth date), if you encode an object of this class as JSON and use it in Javascript, you won't have the "age" method, you will have to reimplement it.

That is, most inter-language communication methods ship "data" not "objects and classes".

There are approaches that try to communicate "objects and classes"; see Java's RMI for instance, which lets you obtain references to remote objects and invoke methods remotely. However, these things get messy quick- for instance, different languages are well, different, and stuff cannot translate 100% accurately. Also, the semantics of remote method invocation are not trivial, and can rapidly become confusing.

Title: Translating between Python-Django and Javascript

Body:
I have a conceptual question about 'translating' between objects I have stored in Django (in Postgres) that I want to use on the front-end. So I have a user object in Python that holds basic things: an id, a username, a password. Let's say I want to output all of that information using Javascript on the client side. Can I just give JS a python object and it will make it into a JS object? I know JS is known for being 'fast and loose' with typing but that just seems absurd!

I'm not looking for syntax, but just an overview of how this would work. Can I put Python objects in AJAX requests, then translate them client side, or is this going to be a basic break-down-things-on-server-side, ship them off, and recombine them on the client side type of thing?


答: You can think of a pattern as a proven way to solve a problem that you and other developers understand. Eg, the problem is to create a sorted list of data, then you can choose to use a linked list, or put data into a vector and sort. You probably understand the both these options because you may already know the linked list pattern or the load and sort vector pattern. You may know the pros and cons of each and do not need to see the implementation to understand what is going on. </p>


问:
What is a value object in domain-driven design?
I have an entity and I've realised that there is a group of properties that work together. So, I moved them to a value object (together with their behavior) and now I have a reference from my entity to this value object.

I've read "Domain Driven Design Quickly" (PDF) and I came across the following statement when explaining Value objects:

If Customer is an entity object, then one instance of this  object, representing a specific bank client, cannot be reused for  account operations corresponding to other clients. The outcome  is that such an instance has to be created for every client. This  can result in system performance degradation when dealing with thousands of instances.

But I'm still not clear exactly what this means. Is my new object a value object or should it be an entity? I am having trouble reasoning whether it should in fact be an entity. In other words, what questions should I ask in my domain to assure me that it should be a value object?

答:
The key property of a Value Object it that it has no identity.  It is defined only by it's attributes, and any other instance with identical attribute values can be substituted.

Los Techies had a good explanation on their blog a while back, and it has been asked on StackOverflow.


问:
Did I understand the website "autologin" feature right?
I'm developing an authentication library (*) for a website and I realized that maybe I'm not completely understanding what an "autologin" feature is, and how to develop it.

While gathering infos and studying other code I came across a couple of libraries which implement the option to login the user without having to sign in (these libraries are Tank Auth and Ion Auth, built for the PHP framework CodeIgniter); basically they work on creating a cookie which, in case the user is not logged (session datas are not set) but this cookie is found, it allows them to login nonetheless.

Ok, so far it's clear. What I don't understand, though, is why both library delete the autologin cookie when the user logs out. I mean: I log in, I check the "remember me" option (**), I do what I need to do in my admin panel, then I log out; if the autologin cookie is deleted, next time I'll have to log in again by filling the form, ignoring the option I flagged. What's its purpose then? I thought this "autologin" would be an extendend login which allowed me to avoid having to fill in the sign in form again.

So I went on and developed my autologin feature, but of course I bumped into the problem of not being able to logout at all, as I'm not deleting it. So I log out, redirect to the home page, then go to the admin panel and the system logs me in...well, it works as expected, but I'm not sure if this is how it's meant to be...How should this be done correctly?

Can someone explain to me how this actually should work? I'm getting a bit confused

P.S. Don't know if this is the right place to ask it, or if SO is a better fit; I'm sorry if I posted on the wrong SE site.

(*) Please don't tell me "don't reinvent the wheel" or any variant of it; I'm doing this to learn and I'm planning to make it an open source project for the public amusement, so I volutarily do want to reinvent the wheel, at the cost of making it oval.

(**) I think I guessed the difference between the "remember me" option and the "autologin" feature; so far, I didn't consider the first one ( 1-because many browsers ask you to do that nonetheless; 2-because I don't know how to do it right, i.e. how to have the login fields automatically filled without this posing the security threat of having the password stored in clear text inside a cookie), but please tell me if I misunderstood this also..

答:
Log out should Log the user out until he\she (manually) logs in again. ie: an Temporary dis-ablement of the auto logon.

In other words, delete the cookie.

Remember me should only remember the username not the password.


答:
I think that you've answered your own question somewhat.  The only suggestion I have is to learn to pick your battles, and learn to be patient.  Inject a few ideas every now and then, then let those ideas percolate until you get "buy in" from others in your team.

The main problem isn't about who is right or wrong.  It all comes down to both individual and group psychology. People tend to wrongly feel a sense of inferiority when their values and ideals are challenged, and people can be very resistant to change. They can become argumentative and will seek others to validate their position and be comforted as a group so that they do not have to challenge their own values, and so that they do not have to face changes that might make them feel that they had certain concepts wrong. On the flip-side, software developers in particular can be very sensitive people, and yet can often be insensitive (particularly when younger) in terms of how they might approach challenging the values of others. The result is that you will often find teams where one individual is very unhappy and feels that everyone else seems to refuse to understand, and treats that individual like the proverbial tall poppy.  Often this results in a group culture that is poisonous to all, where blame and defensiveness become the norm.

You also need to consider your own position in all of this. It isn't likely that the blame for a poisonous culture lies entirely with your colleagues, even if it may have started there.  It is more likely that their reactions to you and your reactions to them all feeds back on itself over time, and left unchecked becomes a very difficult to manage problem.  A good manager spots these sorts of problems early and fixes them, but the reality is that most managers in IT come from IT backgrounds first, and are promoted without the additional training needed to actually manage people effectively, so that by the time they realize there is a problem, it has grown very large, and has become a part of the team culture.

So what can you do about this?

One option is to simply leave, but to do so in a way that allows you to leave with your reputation intact, and with a good referral from your employer.  You don't want to have your "Jerry McGuire" moment and burn all your bridges, and at your interviews you'll need to be careful about how you phrase your reasons for leaving, and to avoid coming across as arrogant or bitter at how you felt you were treated.

If you wish to stay, then you'll need to do the hardest thing of all.  Swallow your pride, and over time show others that from their perspective you have "changed".  You need to stop and listen to the others, and to avoid the temptation to take rejected ideas personally. Time, patience, and learning not to invest yourself too emotionally in the work that you are doing. Even more importantly, you need to learn how to phrase things so that you are showing others that you are sensitive to their point of view, while still getting your own across.

Your question echoes some of the experiences that I have had over the last 10 or so years, and while I'm not a psychologist, I am a keen observer of how people interact with each other, and I have myself needed to work at changing myself before I could effect cultural change in my team. In some cases I have changed jobs, and in others, I have stayed and done everything I could to really make a difference to my workplace.  I've walked away with the greatest satisfaction from those places where I overcame being the tall poppy, and left an improved work culture and with great references. See this as opportunity to really rise to a challenge. It can be hard, but very rewarding in the end.


答:
Let's clarify a few things first:

PHP sessions, in their default form are cookie based, I have an overview of how they work in another answer. But since they are cookie based, to me that says that if you are going to base your authentication and authorization workflow around cookies, go with normal cookies for everything - and just use sessions for what they are good for: session data persistence.

The circular login pattern you noticed is exactly why you should delete cookies on logout. Also, as @Morons writes, when a user  clicks log out, expects to actually log out. It doesn't cancel out the auto-login feature, but one should be able to log out at any time.

Now, my auto login-approach goes something like this:

Which of course is pretty basic, but what is really important is the whole "cookie is valid" check. When a user successfully logins with the "remember me" option checked, I generate an auto-login token: A sensibly unique random string, most probably a salted hash.

That's the only thing I store in the cookie, nothing else nothing more. There is no actual need to store anything that could possibly identify an individual user in a cookie, you should avoid storing stuff like usernames and emails (even hashed). In my database, I have a simple token table that basically stores:

A user id,

The token,

An expiration date

And my check involves just checking against this table. The expiration date may seem like an overkill, as you can expire the cookie whenever you want but: You should treat everything that comes along with the cookie as user input, unsafe and easily faked. That includes it's expiration. And of course at log out I don't bother killing the cookie, I just set a NOW() as the expiration date. Easy as pie, and I keep most elements of the check server-side, where it feels a little bit more safe.

In a recent project, I went a step further and added the check at every page request instead of storing something in a session to indicate an authorized session. Some may argue that the call to the database will lead to performance issues, but my 'token' table has grown to about 10 million tokens1 and still I haven't noticed any actual issue. Keep in mind that sessions involve file system access, that's almost never faster than a simple select.

Of course, any cookie that stores anything related to authentication and authorization should be encrypted. And I'd recommend you always enforce secure cookies, with setcookie() is as easy as setting the secure parameter to true:

Indicates that the cookie should only be transmitted over a secure HTTPS connection from the client. When set to TRUE, the cookie will only be set if a secure connection exists. On the server-side, it's on the programmer to send this kind of cookie only on secure connection (e.g. with respect to $_SERVER["HTTPS"]).

1 I don't delete expired tokens for a variety of reasons.

Title: Did I understand the website "autologin" feature right?

Body:
I'm developing an authentication library (*) for a website and I realized that maybe I'm not completely understanding what an "autologin" feature is, and how to develop it.

While gathering infos and studying other code I came across a couple of libraries which implement the option to login the user without having to sign in (these libraries are Tank Auth and Ion Auth, built for the PHP framework CodeIgniter); basically they work on creating a cookie which, in case the user is not logged (session datas are not set) but this cookie is found, it allows them to login nonetheless.

Ok, so far it's clear. What I don't understand, though, is why both library delete the autologin cookie when the user logs out. I mean: I log in, I check the "remember me" option (**), I do what I need to do in my admin panel, then I log out; if the autologin cookie is deleted, next time I'll have to log in again by filling the form, ignoring the option I flagged. What's its purpose then? I thought this "autologin" would be an extendend login which allowed me to avoid having to fill in the sign in form again.

So I went on and developed my autologin feature, but of course I bumped into the problem of not being able to logout at all, as I'm not deleting it. So I log out, redirect to the home page, then go to the admin panel and the system logs me in...well, it works as expected, but I'm not sure if this is how it's meant to be...How should this be done correctly?

Can someone explain to me how this actually should work? I'm getting a bit confused

P.S. Don't know if this is the right place to ask it, or if SO is a better fit; I'm sorry if I posted on the wrong SE site.

(*) Please don't tell me "don't reinvent the wheel" or any variant of it; I'm doing this to learn and I'm planning to make it an open source project for the public amusement, so I volutarily do want to reinvent the wheel, at the cost of making it oval.

(**) I think I guessed the difference between the "remember me" option and the "autologin" feature; so far, I didn't consider the first one ( 1-because many browsers ask you to do that nonetheless; 2-because I don't know how to do it right, i.e. how to have the login fields automatically filled without this posing the security threat of having the password stored in clear text inside a cookie), but please tell me if I misunderstood this also..


答:
I do not mean to overstep @Yannis Rizos's extensive answer, but I just want to answer a very specific item you asked about: The "Log Out" option exists precisely so that the user can indicate that they do not wish to be remembered anymore. Check any major website, and you will see that they all work this way: once I have checked the 'remember me' checkbox in the log-in screen, and for as long as I don't explicitly log out, I am remembered. Once I explicitly log out, I am not remembered anymore.

A couple of more points:

In all major web sites I know of, "remember me" of course means "remember both my user name and my password"; in other words, "please don't bother me with log-in screens".

Also, the state of the art nowadays for web sites that are generally used by people daily, such as gmail, apparently seems to be that about once a month you should forget your users anyway, meaning that they see a log-in screen and have to re-type their credentials once a month. Apparently they (i.e. the guys at gmail) have done some research on this subject and they found out that this helps users keep remembering their password, with a minimum of annoyance. (Just once a month.)


问:
How far has process-i-fi-cation of SW engineering come in the past 10 years?
I read a UML book a long time ago (15 or so years ago) by the inventors which said something like "software engineering should be like building a house".  Meaning architects produce blue prints, and specialized workers utilize various views of them to produce their part of the end result.

When I read it, it seemed reasonable, but from my perspective - I don't think much progress has been made to that end.  It might be that the goal was wrong, or unrealistic - I'm not sure...

答:
I think that as a concept "software engineering should be like building a house" is largely misunderstood. As a literal metaphor I kind of agree somewhat with S.Lott's answer that the metaphor appears to be broken.  As a concept however, I think that the idea that software should be "engineered" just as physical constructs are "engineered" is sound, but that it requires a little perspective. Is creating software like building a house?  No,  and it never will be, but as the creative processes have improved and developed over time, I think that sound engineering has grown to be so integrated with what we do, that we barely recognize it for what it truly is.

Forget about how the 3 Amigos championed UML, and how building houses relies on a waterfall methodology and all that stuff.  Instead of looking at the differences, look at the conceptual similarities.  An architect specifies an approximation of what a house will be.  He specifies a framework, but states only enough to ensure that regardless of how the blueprints are implemented, that the design will be structurally sound. This is also true of a good software architect.

While I agree that software development processes need to be highly iterative, I'm at odds with the people who believe you can create a sound software design by simply wishing it into existence after you've started coding.  Even the most gung-ho Agile Warriors out there will at least have the experience to have a rough overall design in mind before they put anything down in either test or code.  The advantage for the software engineer however, is that flaws in design can become quickly apparent, and that with tests in place, refactoring is easier, and a poorly factored architecture can become "better" organically, as time passes.

So to the heart of the OP's question, has any progress been made towards developing software using sound engineering practices?  My answer is a resounding yes, but that it depends largely on your point of view. From my own experiences/perspective, I have seen the rise and "fall" of UML as an indication that the concept of software engineering has outgrown the need for heavily regimented design processes in terms of documentation, but that UML retains a place in the process as a means to help developers draft conceptual designs diagrammatically. This helps developers explain what they are doing to others, particularly to the lay-persons. Procedural guidelines and methodologies have sprung up in many different forms, and it is these that are the true indication of how software is engineered today.  Take any agile process, and there is a focus on testing, and in most cases a test-first approach.  From a design perspective, the tests are an integral part of the design process, as the tests validate the design.  Specifications in the form of short "story"/"feature" statements are also a part of the engineering processes, and with the advent of the continuous integration and automated build processes that are so common today, the role of the average software developer has leaned more towards the design end of the spectrum, and left the more mundane and often repetitive tasks to be dealt with by a dedicated "robot" system.

As for the software architects out there?  What is it that they really do? Again I feel that this is a role that is poorly understood because people think that architects are supposed to design everything up front.  This may be true for hardware design, but where software is concerned, architects should be communicators and facilitators, and should be the people who determine how business constraints will influence the overall design of a product.  If this means specifying a skeletal design up front, then this is a good thing, but the architect then needs to ensure that the rest of the product can and does grow within that framework, and that appropriate software engineering processes will be used to actually implement the product within specified guidelines.


答:
I think you are a starter for programming, I do not suggest you learn design pattern early.
Learning and Understanding design pattern need to base on the experience of software development. You should be more practice to code and found which code style is bad and then to learn design pattern to improve design.</p>


问:
How can I move from Java and ColdFusion to Ruby on Rails?
Currently I work with ColdFusion 9+ and some Java in a Windows environment. Prior to ColdFusion, my background was in Java and JSP.

I'm considering a move towards Ruby on Rails, as I think it would be a real challenge, keep things fresh, and provide more job opportunities.

In order to get into it, I started to build my personal website in Rails 3.0. But what else can I do to make this transition from what I know now to Ruby and Rails? Are there specific or idiomatic aspects of Ruby or Rails I should keep in mind when switching over from a ColdFusion and Java mindset?

答:
I have made the transition myself and I am loving it so far.

Coming from Java/ColdFusion background, one of the hardest things to understand for me was how Object Oriented is different in Ruby. Well Grounded Rubyist is highly recommended book, if you are interested in understanding Ruby and the philosophy behind it.

I was working on ColdFusion on my day job and learn Ruby on Rails after work. I initially did my learning on a Ubuntu VM (much better than doing Ruby on Windows). But switching to Mac is way another level of awesomeness.

If there is a Ruby user group meetings in your area, do attend them, network with Ruby developers and watch them code. I learned heaps from attending user group meetings and hack nights here in Sydney.


答:
With some bosses, you have to somehow trick them into believing that it was their idea all along to fix some practice, not yours.

Choose which battles you want to win, and which ones you just want credit for.


答:
The problem is that it's very easy to dis-aggregate a single source code file from its larger project, such as someone just checking out, emailing, downloading one file, without the rest that contains the full copyright.  And then that file can get passed along ad-infinitum into time, to Nth parties who may have no idea of the files origins.

The copyright notice at the top reminds anyone who runs across that lone file that it is in fact copyrighted, not public domain, and thus some license may or may not be involved in its distribution or use.  Versus letting the finder make their own random assumptions.


问:
Is there a subset of programs that avoid the halting problem
I was just reading another explanation of the halting problem, and it got me thinking all the problems I've seen that are given as examples involve infinite sequences. But I never use infinite sequences in my programs - they take too long. All the real world applications have lower and upper bounds. Even reals aren't truly reals - they are approximations stored as 32/64 bits etc.

So the question is, is there a subset of programs that can be determined if they halt? Is it good enough for most programs. Can I build a set of language constructs that I can determine the 'haltability' of a program. I'm sure this has been studied somewhere before so any pointers would be appreciated. The language wouldn't be turing complete, but is there such a thing as nearly turing complete which is good enough?

Naturally enough such a construct would have to exclude recursion and unbounded while loops, but I can write a program without those easily enough.

Reading from standard input as an example would have to be bounded, but that's easy enough - I'll limit my input to 10,000,000 characters etc, depending on the problem domain.

tia

[Update]

After reading the comments and answers perhaps I should restate my question.

For a given program in which all inputs are bounded can you determine if the program halts. If so what are the constraints of the language and what are the limits of the input set. The maximal set of these constructs would determine a language which can be deduced to halt or not. Is there some study that's been done on this?

[Update 2]

here's the answer, it's yes, way back in 1967
from http://www.isp.uni-luebeck.de/kps07/files/papers/kirner.pdf

That the halting problem can be at least theoretically solved for ﬁnite-state
systems has been already argued by Minsky in 1967 [4]:
“...any ﬁnite-state machine, if left completely to itself, will fall eventually into a
perfectly periodic repetitive pattern. The duration of this repeating pattern cannot
exceed the number of internal states of the machine...”

(and so if you stick to finite turing machines then you can build an oracle)

答:
First off, consider what would happen if we had a halting detector. We know from the diagonal argument that there exists at least one program that would cause a halting detector to either never halt or give a wrong answer. But that's a bizarre and unlikely program.

There is another argument though that a halting detector is impossible, and that is the more intuitive argument that a halting detector would be magical. Suppose you want to know if Fermat's Last Theorem is true or false. You just write a program that halts if it is true and runs forever if it is false, and then run the halting detector on it. You don't run the program, you just run the halting detector on the program. A halting detector would enable us to immediately solve a huge number of open problems in number theory just by writing programs.

So, can you write a programming language that is guaranteed to produce programs whose halting can be always determined?  Sure. It just cannot have loops, conditions and use arbitrarily much storage. If you're willing to live with no loops, or no "if" statements, or a strictly restricted amount of storage, then sure, you can write a language whose halting is always determinable.


问:
How to model a many to many from a DDD perspective in UML?
I have a two entity objects Site and Customer where there is a many to many relationship. I have read you try not to model this in DDD as it is in the data model and go for a unidirectional flow.

If I wanted to show this in UML, would I show it as it is in the data model:

Site * ----->*Customer but the direction arrow gives the flow?

or as following

Site ----->*Customer But then this would imply that Customer can only go in one site.

答:
The sense I get from this article is that within the realm of DDD, Site--->*Customer does not indicate that a Customer cannot be related to more than one site.  Rather, it simply indicates that a Site can have multiple Customers (as in a list of them) whereas, the Customer treats each Site as a unique interaction and does not maintain a list of Sites.

This makes some sense.  The Site is a Site, whether or not anyone visits it.  The Customer, on the other hand, only becomes a Customer upon visiting a Site.


答:
is there a subset of programs that can be determined if they halt?

Yes.

Is it good enough for most programs?

Define "most".

Can I build a set of language constructs that I can determine the 'haltability' of a program?

Yes.

is there such a thing as nearly turing complete which is good enough?

Define "nearly".

Many folks write Python without using while statement  or recursion.

Many folks write Java using only the for statement with simple iterators or counters that can be trivially proven to terminate; and they write without recursion.

It's pretty easy to avoid while and recursion.

For a given program in which all inputs are bounded can you determine if the program halts?

No.

If so what are the constraints of the language and what are the limits of the input set.

Um. The Halting problem means the program can't ever determine things about programs as complex as itself.  You can add any one of a large number of constraints to get past the halting problem.

The standard approach to the halting problem is to allow proofs using a slightly "richer" set of mathematical formalisms than are available in the programming language.

It's easier to extend the proof system than it is to restrict the language.  Any restriction leads to arguments for the one algorithm that's difficult to express because of the restriction.

The maximal set of these constructs would determine a language which can be deduced to halt or not. Is there some study that's been done on this?

Yes.  It's called "Group Theory".  A set of values closed under a set of operations.  Pretty well understood stuff.

Title: Is there a subset of programs that avoid the halting problem

Body:
I was just reading another explanation of the halting problem, and it got me thinking all the problems I've seen that are given as examples involve infinite sequences. But I never use infinite sequences in my programs - they take too long. All the real world applications have lower and upper bounds. Even reals aren't truly reals - they are approximations stored as 32/64 bits etc.

So the question is, is there a subset of programs that can be determined if they halt? Is it good enough for most programs. Can I build a set of language constructs that I can determine the 'haltability' of a program. I'm sure this has been studied somewhere before so any pointers would be appreciated. The language wouldn't be turing complete, but is there such a thing as nearly turing complete which is good enough?

Naturally enough such a construct would have to exclude recursion and unbounded while loops, but I can write a program without those easily enough.

Reading from standard input as an example would have to be bounded, but that's easy enough - I'll limit my input to 10,000,000 characters etc, depending on the problem domain.

tia

[Update]

After reading the comments and answers perhaps I should restate my question.

For a given program in which all inputs are bounded can you determine if the program halts. If so what are the constraints of the language and what are the limits of the input set. The maximal set of these constructs would determine a language which can be deduced to halt or not. Is there some study that's been done on this?

[Update 2]

here's the answer, it's yes, way back in 1967
from http://www.isp.uni-luebeck.de/kps07/files/papers/kirner.pdf

That the halting problem can be at least theoretically solved for ﬁnite-state
systems has been already argued by Minsky in 1967 [4]:
“...any ﬁnite-state machine, if left completely to itself, will fall eventually into a
perfectly periodic repetitive pattern. The duration of this repeating pattern cannot
exceed the number of internal states of the machine...”

(and so if you stick to finite turing machines then you can build an oracle)


问:
Are there any languages that have both high- and low-level facilities?
Are there any languages that have both high- and low-level facilities? If not, is it feasible to create one? Why or why not?

In theory, it would be very helpful to have a programming language that has both shell and regular programming language facilities, like Forth for example can easily be made to, and also to have high-level facilities; Forth does not seem (and it would probably take a good bit of work to make it) like a natural fit for high-level things.

Of course, languages like C or C++ can be made to simulate features of high-level languages, but at the cost of ugly or difficult syntax, and the addition of considerably more complexity, or at the cost of a lot of work, which would be unnecessary since it would often be easier just to use a more standard high-level programming language.

Clarification: Low-level meaning things like manual memory management, limited data structures, only one return value, and the like. Examples: Assembly language, C, C++ to some extent, and Forth.

High-level language examples would be: Python, Perl, JavaScript, Java and C# to a big extent, Lisp.

答:
C++ fits the bill to some extent if you use the right template metaprogramming tricks.  D takes this to the next level.  D has every low-level facility that C has except the macro preprocessor (which is made obsolete by a combination of a real module system and string mixins) and bitfields (which are implemented in the standard library instead).

On the high-level side, D is garbage collected, but the garbage collector is written in D and manual memory management can be done using C's malloc and free.  The template metaprogramming system was designed with the help of Andrei Alexandrescu, the author of Modern C++ Design and is actually designed for readable metaprogramming beyond simple generics.  It is advanced enough to allow high-level standard library modules like std.range, std.algorithm and std.parallelism.

Pushing the boundaries even further, I mentored a Google Summer of Code project last summer to create a matrix library in D.  It's not production ready yet, but it allows matrix expressions to be written in a high-level form like the following, with the language inferring all the types and no unnecessary temporary matrices/vectors allocated:

```<code>auto m = matrix(
    [[1.0, 2, 3],
     [4.0, 5, 6],
     [7.0, 8, 9]]
);

auto v1 = vector([8.0, 6, 7]);
auto v2 = vector([3.0, 1, 4]);
auto v3 = vector([2.0, 7, 1]);

// .t is the transpose operator.
auto result = eval( inv(m * v1 * v2.t) * v3 );
writeln(result.pretty);
</code>```

I doubt even Matlab code would be much shorter or cleaner than that, and matrices are Matlab's home turf.

Body:
C++ fits the bill to some extent if you use the right template metaprogramming tricks.  D takes this to the next level.  D has every low-level facility that C has except the macro preprocessor (which is made obsolete by a combination of a real module system and string mixins) and bitfields (which are implemented in the standard library instead).

On the high-level side, D is garbage collected, but the garbage collector is written in D and manual memory management can be done using C's malloc and free.  The template metaprogramming system was designed with the help of Andrei Alexandrescu, the author of Modern C++ Design and is actually designed for readable metaprogramming beyond simple generics.  It is advanced enough to allow high-level standard library modules like std.range, std.algorithm and std.parallelism.

Pushing the boundaries even further, I mentored a Google Summer of Code project last summer to create a matrix library in D.  It's not production ready yet, but it allows matrix expressions to be written in a high-level form like the following, with the language inferring all the types and no unnecessary temporary matrices/vectors allocated:

auto m = matrix(
    [[1.0, 2, 3],
     [4.0, 5, 6],
     [7.0, 8, 9]]
);

auto v1 = vector([8.0, 6, 7]);
auto v2 = vector([3.0, 1, 4]);
auto v3 = vector([2.0, 7, 1]);

// .t is the transpose operator.
auto result = eval( inv(m * v1 * v2.t) * v3 );
writeln(result.pretty);

I doubt even Matlab code would be much shorter or cleaner than that, and matrices are Matlab's home turf.


答:
C++ is the canonical example of a language that combines low-level and high-level features1. It doesn't simulate anything, it provides native support for almost every high-level construct you'll usually find in a common high-level language and almost every low-level construct you'll find in C.

But of course the terms are highly relative, there was a point in time (not that long ago2) where C was considered a very high level language. And there are quite a few other languages that offer considerable low-level functionalities while still commonly regarded as high-level, and vice versa, the lines are kind of fuzzy.

As for the syntax, that's something that naturally affected by the language's level of abstraction. Low-level generally means:

In computer science, a low-level programming language is a programming language that provides little or no abstraction from a computer's instruction set architecture. Generally this refers to either machine code or assembly language. The word "low" refers to the small or nonexistent amount of abstraction between the language and machine language; because of this, low-level languages are sometimes described as being "close to the hardware."

So naturally a low-level language adopts a syntax that's closer to machine code, which is inherently non human friendly. Quite a few languages, like C++, have adopted a wide variety of syntactic sugar, as a mechanism to make things easier to read or to express. But syntactic sugar is something that almost every high level language has opted for, C++'s sugar alone doesn't make it a low-level language.

As for the complexity of a low & high-level language, it's also natural: It's a tool with multiple goals, every single goal adds to its complexity. That's unavoidable regardless of the goal. High-level languages are not "better" than low-level one, they are just more concentrated on one goal. Languages that are designed with ease of use as a primary goal tend to be high-level, but that's only important if the necessary trade-offs to achieve the goal don't affect your applications.

Low or high level doesn't really matter, languages are primarily tools. You should choose the one that best fits whatever you're building in combination with what skills you have. Most popular languages are multi-purpose and Turing complete, in theory they are valid choices for building almost anything. There are no absolutes, of course, you may win in some areas if you opt for a high-level language and in others if you opt for a lower-level one, even within the same application.

Most large scale applications mix and match, following the "right tool for the job" mentality, and that's a more efficient approach, imho, than trying to have your cake and eat it too.

1 But please note that there isn't a definitive answer on what's considered a strictly high-level feature and what a low-level one.

2 In human years, in software years it was long ago...

Body:
Are there any languages that have both high- and low-level facilities? If not, is it feasible to create one? Why or why not?

In theory, it would be very helpful to have a programming language that has both shell and regular programming language facilities, like Forth for example can easily be made to, and also to have high-level facilities; Forth does not seem (and it would probably take a good bit of work to make it) like a natural fit for high-level things.

Of course, languages like C or C++ can be made to simulate features of high-level languages, but at the cost of ugly or difficult syntax, and the addition of considerably more complexity, or at the cost of a lot of work, which would be unnecessary since it would often be easier just to use a more standard high-level programming language.

Clarification: Low-level meaning things like manual memory management, limited data structures, only one return value, and the like. Examples: Assembly language, C, C++ to some extent, and Forth.

High-level language examples would be: Python, Perl, JavaScript, Java and C# to a big extent, Lisp.


问:
When should I use a CSS class over inline styling?
I have some hidden divs that I show via JavaScript when a button is clicked. Right now, I'm hiding them with by using inline styling (i.e. style="display:none;").

This works, but are there general rules or guidelines to follow to determine if I should use inline styles or styling via stylesheets and class selectors?

答:
Best Practice is to avoid using in-line styles where possible so Yes I would suggest you use the class="hidden"

Check out this link for more information on best practices with inline styles vs external:
http://webdesign.about.com/od/css/a/aa073106.htm

OwnerDisplayName: chrismealy

OwnerDisplayName: Aaron


答:
Sure, why not? For example:

```<code><html>
   <head>
   <style type="text/css">
   body
   {
   background-color:#d0e4fe;
    }
   .hidden
   {
    display:none;
   }
  p
  {
   font-family:"Times New Roman";
   font-size:20px;
   }
  </style>
 </head>

 <body>

  <div class="hidden">This CSS example is hidden!</div>
  <p>This paragraph is visble.</p>

</body>
</code>```

Title: When should I use a CSS class over inline styling?

Body:
I have some hidden divs that I show via JavaScript when a button is clicked. Right now, I'm hiding them with by using inline styling (i.e. style="display:none;").

This works, but are there general rules or guidelines to follow to determine if I should use inline styles or styling via stylesheets and class selectors?

Body:
Sure, why not? For example:

<html>
   <head>
   <style type="text/css">
   body
   {
   background-color:#d0e4fe;
    }
   .hidden
   {
    display:none;
   }
  p
  {
   font-family:"Times New Roman";
   font-size:20px;
   }
  </style>
 </head>

 <body>

  <div class="hidden">This CSS example is hidden!</div>
  <p>This paragraph is visble.</p>

</body>

OwnerDisplayName: Arvind


问:
Is "call and return" a pattern or an antipattern?
Imagine to have this code:

```<code>class Foo:
  def __init__(self, active):
    self.active = active
  def doAction(self):
    if not self.active:
      return
      # do something

f=Foo(false)
f.doAction() # does nothing
</code>```

This is a nice code; I actually have (not in Python) a global active variable called "dosomething" and a routine called "something," where the first thing happening inside the "something" routine is if not dosomething return.

An alternative implementation would call to a routine that always performs an action, and the flag is checked at invocation time, as in the following code:

```<code>class Foo:
  def doAction(self):
    # do something

doaction = False

f=Foo()
if doaction:
  f.doAction()
</code>```

What is your opinion on this? I personally find that the first solution violates the least surprise principle: The caller is invoking an action which is never performed in response to a status which has been set somewhere else, but from the code it looks like the action is performed.

Would you consider it a total pattern, a total antipattern, or just an option with no strong opinion for or against it?

答: I believe that this is a useful pattern, provided that you have an assertion (or debug log message) before it returns. When the application is deployed, the assertion should be off and thus the method should return harmlessly without crashing. On the other hand you should see it during development and can refactor your code so that the call is not made in the first place.</p>


答:
Software development is like building a house where the new homeowners come through on the final inspection and ask that the plumbing be shifted to the other side of the structure and the order of the floors be shuffled.

To be clear: the right methodology is dependent on the problem domain (you don't use the same process for avionics and art gallery websites). That said, the vast majority of software projects out there have really benefited from the increasing adoption of agile methodologies. There is something in the nature of software that makes it impossible for people to understand what they want or what is best until they see the system work. Yes, architectural vision is essential, but modern software architectures are much more open ended and flexible than was the case in the days when UML was conceived.

One thing that shouldn't be overlooked is that the underlying technology we work with has evolved enormously and in a very good way during the past 15 years. The projects of the early to mid 1990s mostly didn't have the benefit of garbage collected memory, automatic array bounds checking, and other niceties that we take for granted. C, C++, or even assembler was often actually needed in mainstream applications in order to get performance out of hardware that we would now consider primitive and extremely limited. So the tendency to pursue waterfall or "build a house" project management strategy was a natural response to tools and development environments that were much less flexible that we enjoy today.

Title: How far has process-i-fi-cation of SW engineering come in the past 10 years?

Body:
I read a UML book a long time ago (15 or so years ago) by the inventors which said something like "software engineering should be like building a house".  Meaning architects produce blue prints, and specialized workers utilize various views of them to produce their part of the end result.

When I read it, it seemed reasonable, but from my perspective - I don't think much progress has been made to that end.  It might be that the goal was wrong, or unrealistic - I'm not sure...


答:
Thanks god they were wrong or today our work would be labelled as a simple factory worker one.

I've witnessed so many IT service companies trying to industrialize the software development process, to downsize and reduce costs, and eventually be able to offshore all the developments. Most of them have face failures with that approach.

We are more like artisans. And so can be very proud of our realisations.


答:
For every program that works on a limited amount of memory (including storage of all kind), the halting problem can be solved; i.e. an undecidable program is bound to take more and more memory on the run.

But even so, this insight doesn't mean that it can be used for real-world problems, since a halting program, working on just a few kilobytes of memory, can easily take longer than the remaining lifetime of the universe to halt.


问:
Commented short fancy code vs. uncommented longer easy-to-understand code - which is preferred?
Sometimes an algorithm can be written in two ways:

The short, fancy way; or

The longer, easy-to-understand way.

For example, here is a longer, easier way of copying a string source to dest in C:

```<code>*dest = *source;
while (*source != '\0') {
    source++;
    dest++;
    *dest = *source;
} (true);
</code>```

And here is a short, fancy way.

```<code>// Copy string source to dest
while (*dest++ = *source++);
</code>```

I've always heard and read that fancy code should be avoided, and I tend to agree. But what if we take comments into account? Assume that, as in the examples above, we have an uncommented, longer and supposedly easier-to-understand code, and a well-commented, short, fancy code? Is the non-fancy code still preferred?

EDIT: Many have commented on variable names, so I've modified the example code as to not make that a factor when preferring on over the other. I tried to remove the double assignment in the first example, but that only made the code less readable.

Perhaps this wasn't the best of examples because many find the 'fancy' code more readable and understandable than the longer code. The idea was to have one longer code which was much easier to understand than a very short but complicated code.

EDIT2: Here's a new examle I got from SO:

Commented fancy version:

```<code>//direct formula for xoring all numbers from 1 to N
int Sum = (N & (N % 2 ? 0 : ~0) | ( ((N & 2)>>1) ^ (N & 1) ) );
</code>```

Non-commented long version:

```<code>int Sum = 0;
for (int i = 1; i < N; ++i)
{
   Sum ^= i; //or Sum = Sum ^ i;
}
</code>```

答: Readability and maintainability are key, and your second example (i.e. the longer one) is much more of both.  But why limit yourself to two options?  Even the longer code is too complex (IMHO) to not notate further.  I'd put it in a method of its own with appropriate Javadoc (or whatever) and a suitable method name.</p>

ContentLicense: CC BY-SA 2.5


答:
While I commonly see call and return used throughout my colleague's code (and mine), I wouldn't recommended it in this case (we use it to implement the fail fast property). If possible, try to apply the State pattern.

In this case, active and inactive would be valid states upon which the implementation of doAction(...) changes. This should clear up the code and make it more maintainable. Additionally, you get the benefit of state transitions, e.g., informObservers(boolean active).

Title: Is "call and return" a pattern or an antipattern?

Body:
Imagine to have this code:

```<code>class Foo:
  def __init__(self, active):
    self.active = active
  def doAction(self):
    if not self.active:
      return
      # do something

f=Foo(false)
f.doAction() # does nothing
</code>```

This is a nice code; I actually have (not in Python) a global active variable called "dosomething" and a routine called "something," where the first thing happening inside the "something" routine is if not dosomething return.

An alternative implementation would call to a routine that always performs an action, and the flag is checked at invocation time, as in the following code:

```<code>class Foo:
  def doAction(self):
    # do something

doaction = False

f=Foo()
if doaction:
  f.doAction()
</code>```

What is your opinion on this? I personally find that the first solution violates the least surprise principle: The caller is invoking an action which is never performed in response to a status which has been set somewhere else, but from the code it looks like the action is performed.

Would you consider it a total pattern, a total antipattern, or just an option with no strong opinion for or against it?


问:
How to organize programming exercise
Due to my bad performance on past job interviews, I decided to perform daily programming exercises out of my work.

Currently, I am concentrating on algorithms, design patterns, and unit testing in C++ language platform. But I'd like to have balance over more important areas. So if I may, I'd like to know how other programmers organize their programming exercises.

答:
Are you sure it's just the technical part that goes wrong for you in interviews? If yes, good going - solve problems, learn from approaches taken previously, ask on SO/P@SE wherever relevant. I suggest you check out TopCoder - there are some fantastic tutorials and great problems to solve. Also, if you are particularly keen at learning some subject, say, neural nets for example, try implementing one for solving your own problem - that way, you'll actually be working out ALL your "programming muscles" at once. Though I don't always go for TDD, in your case, it should actually help.

All programmers are learning something or the other constantly, so you're not alone! :)

Project Euler is a great place to hone your problem solving and mathematical skills.

Title: How to organize programming exercise