问:
Should I provide a language reference in addition to a formal specification for the programming language I am designing?
I am designing a programming language, and I would like to provide a complete documentation for it.

So far, I have planned to write the following documents:

An initial design outline, mostly as a reminder of the design and proposed changes to it, as well as an aid to construct all the other documents when the design phase has been completed.

A formal specification of the language's syntax and semantics, both in English and in a suitable formal mathematical notation.

A tutorial.

I have found that some languages have references, and I have found on Wikipedia that language references and language specifications are not quite the same, references being usually less detailed due to being aimed at users of the language rather than implementors of it.

However, I would like to know...

What parts of a language specification are usually omitted in a language reference?

Is it really useful to provide a language reference when ultimately a good programmer should consult the language specification as their definitive source of information?

In case the answer to the preceding question is "Yes"... Is it really worth the risk of introducing contradictions between the language specification and the language reference?

答:
Personally, I would suggest not doing a tutorial, and instead make a reference with plenty of examples. The C# spec has this sort of thing at the beginning. It provides enough meat to get the idea without having to translate from the dry specification parts. It also provides your mechanism to describe how the language differs from C++ , which should help your target audience. For your specific sub-questions:

A lot of the mathematical notation, a lot of the exceptional case handling (such as the detailed order of initializers for example), a lot of the common behaviors (such as mathematical order of operations), the BNF, and probably more I'm overlooking.

I would say yes for two reasons. Firstly, there are a lot of not good programmers in the world. Your language won't get much traction if only people who can stomach reading programming language design docs can use it. Secondly, good 'definitive sources' are not necessarily good learning sources.

It should be clear that the specification is the definitive definition of the language. Errors can be corrected, and if you have problems writing simple documentation for the language, that seems like a symptom of a larger problem.


问:
introducing pointers to a large software project
I have a fairly large software project written in c++.

In there, there is a class foo which represents a structure (by which i don't mean the programmers struct) in which foo-objects can be part of a foo-object.

Here's class foo in simplest form:

```<code>class Foo
{
    private:
        std::vector<unsigned int> indices;
    public:
        void addFooIndex(unsigned int);
        unsigned int getFooIndex(unsigned int);
};
</code>```

Every foo-object is currently stored in an object of class bar.

```<code>class Bar
{
    private:
        std::vector<Foo> foos;
    public:
        void addFoo(Foo);
        std::vector<Foo> getFoos();
}
</code>```

So if a foo-object should represent a structure with a "inner" foo-object, I currently do

```<code>Foo foo;
Foo innerFoo;
foo.addFooIndex(bar.getFoos().size() - 1);
bar.addFoo(innerFoo);
</code>```

And to get it, I obviously use:

```<code>Foo foo;
for ( unsigned int i = 0; i < foo.getFooIndices().size(); ++i )
{
    Foo inner_foo;
    assert( foo.getFooIndices().at(i) < bar.getFoos().size() );
    inner_foo = bar.getFoos().at(foo.getFooIndices().at(i));
}
</code>```

So this is not a problem. It just works. But it's not the most elegant solution.

I now want to make the inner foos to be "more connected" with the foo-object. It would be obviously to change class foo to:

```<code>class Foo
{
    private:
        std::vector<Foo*> foo_pointers;
    public:
        void addFooPointer(Foo*);
        std::vector<Foo*> getFooPointers();
};
</code>```

So now, for my question: How to gently change this basic class without messing up the whole code? Is there a "clean way"?

答:
I'll take a stab at this.

It all boils down to what kind of memory management you want/need. You can either store pointers in Foo, or Foo objects. Since you said you do not need bar, which currently 'owns' the Foo's memory-wise, I suggest you put them directly in Foo:

```<code>class foo
{
public:
  add_child(foo child); //Foo by value. Utilize 'move' semantics if copy is not possible.
  const std::vector<foo>& get_children(); //Get a reference to the children. Could use iterators or whatever.

private:
  std::vector<foo> foos;
}
</code>```

Usage:

```<code>foo parent;
foo child;
foo grand_child;
child.add_child(std::move(grand_child)); //move semantics.
parent.add_child(child);  //no move semantics.

parent.traverse(root);

void traverse(foo root)
{
    root.discombobulate_the_parafunctors(); //act on root

    auto children = root.get_children();
    std::for_each(children.begin(), children.end(), traverse);
}
</code>```

This is what I would try to move towards, but you said you want to do it 'gently' - I guess you mean incrementally, without breaking things? Since ownership is transferred from bar to foo in the example above, it will not be possible to use both at the same time. The pointer approach, however, can be layered on top of the existing bar implementation.

If I really wanted to 'gently' switch, I'd make a class called something like foo_tree_view, which is like your first approach, with pointers, and doesn't assume ownership. I'd build it from a given bar instance, and then use it in client code.

```<code>std::vector<foo_tree_view> bar_view;

class foo_tree_view
{
public:
  foo_tree_view(foo this_foo, bar source);
  std::vector<foo*> get_children();
private:
   ...
}
</code>```

At this point, you start gently changing all places to use this new foo_tree_view class. When all code uses it, you change to implementation of foo_tree_view to use the above implementation, without 'bar', and rename it to foo.

Hope you'll make some sense out of this answer!

ContentLicense: CC BY-SA 3.0

Body:
I'll take a stab at this.

It all boils down to what kind of memory management you want/need. You can either store pointers in Foo, or Foo objects. Since you said you do not need bar, which currently 'owns' the Foo's memory-wise, I suggest you put them directly in Foo:

class foo
{
public:
  add_child(foo child); //Foo by value. Utilize 'move' semantics if copy is not possible.
  const std::vector<foo>& get_children(); //Get a reference to the children. Could use iterators or whatever.

private:
  std::vector<foo> foos;
}

Usage:

foo parent;
foo child;
foo grand_child;
child.add_child(std::move(grand_child)); //move semantics.
parent.add_child(child);  //no move semantics.

parent.traverse(root);

void traverse(foo root)
{
    root.discombobulate_the_parafunctors(); //act on root

    auto children = root.get_children();
    std::for_each(children.begin(), children.end(), traverse);
}

This is what I would try to move towards, but you said you want to do it 'gently' - I guess you mean incrementally, without breaking things? Since ownership is transferred from bar to foo in the example above, it will not be possible to use both at the same time. The pointer approach, however, can be layered on top of the existing bar implementation.

If I really wanted to 'gently' switch, I'd make a class called something like foo_tree_view, which is like your first approach, with pointers, and doesn't assume ownership. I'd build it from a given bar instance, and then use it in client code.

std::vector<foo_tree_view> bar_view;

class foo_tree_view
{
public:
  foo_tree_view(foo this_foo, bar source);
  std::vector<foo*> get_children();
private:
   ...
}

At this point, you start gently changing all places to use this new foo_tree_view class. When all code uses it, you change to implementation of foo_tree_view to use the above implementation, without 'bar', and rename it to foo.

Hope you'll make some sense out of this answer!


问:
Do you perfect your code as you go or FINISH the product first, improve structure later
I recently read a blog post (which I lost the link) that really make me think. The writer said that the one of the biggest problem in software projects is actaully completing it, and most people will end up abandoning the work.

I have been self-learning programming for over 15 years now, at this stage I actually feel pretty competent. However, I have never finish any big project that I set out to do.

What I usually do is this:

I "sketch" my idea in code, compile and run to see if it works, and imagine how other stuff can come toogether.

As the "sketch" becomes messy, I start to refactor it, consolidate functions, make classes, re-organisation data structures etc.

Repeat 1 and 2.... forever!

I tried to write on paper UML diagrams etc. but it always end up with things I overlook and then requires some drastic changes and then I becomes 1, 2, 1, 2, 1, 2 again.

How does commercial projects handle deadlines? Should I just keep on sketching until the final product is completed before thinking of making the readability/reusability/architecture/engine more sound?

答:
Speaking from my experience, I've found that it is a balance.  Starting a new project and molding the architecture as you go is more difficult than maintaining an existing project.  With new projects, you have a blank slate of sorts and it's up to you to define how it is structured.  Existing projects already have this defined and give you some constraints to work under, limiting your choices and, because of this, potentially giving you a quicker time to implement.

I would say it is unfair to compare your personal projects to your professional projects.  Personal projects are your projects and you should use them as an opportunity to objectively try new methodologies and technology.  That is, unless you're writing the project purely for the functionality, in which case - why would you place more weight on the design versus the functionality?

With respect to UML diagrams, I've not had any experience in using them for project design.  I tend to think that they are a bit heavy handed when the company considers the most important thing is to ship code.  Because of this, I tend to start coding at a high level after giving it some thought to the approach of what I want the final product to look like.  I consider maintainability and readability to be the most important factors at this point.  Another problem with the documentation is that it has to be read to be useful.  You could sketch a UML diagram to help you think through design, but even if you package up all of your documentation later, will anyone actually read it?  Unread documentation is not useful.

Regarding the "code, refactor, code, refactor" cycle, you only need to do this when you need to improve the code.  Avoid refactoring for the sake of refactoring.  Take the approach that you are making necessary improvements to the architecture.  I usually do minor refactoring (extract to method, naming conventions, etc) and leave major refactoring (architecture, class structure) to the times when I'm enhancing the system or fixing a particularly nasty bug that seems to be the byproduct of the design (or lack of it).  I have seen many places that would benefit from refactoring, but if the function is working, I don't mess with it unless I think it's necessary.  In the short term, I will still make the minor refactoring adjustments just so I know things are improving.

At work, I try to keep in mind to "leave things better than you found them."  This doesn't mean I'm continually refactoring code with every change, but that if I am making a change that is significant enough to warrant an evaluation of making it better, I consider the options (also weighing in the amount of time it would take to implement along with risk, maintainability, etc) and choose the best bang-for-the-buck option.

Part of the advantage of working on a team producing applications is that you get exposed to alternative methods of design.  You also are made aware of obvious short-cuts in design or implementation to get it out the door.  The consistent example I come across is the lack of use of polymorphism versus the use of variables to control behavior.  The former takes a little more effort to implement and is usually more maintainable and less prone to weird behavior.  The developer may have thought that (s)he was just reusing the code that is already there, but the long term maintenance weight that carries is not always insignificant.

Regarding commercial project deadlines, there are many variables.  Not all projects are on a death march, although it seems to be fairly common to value the shipping of code over its quality.  End users do not care about any fancy designs you may have implemented, much less your choice of dependency injection container.  They are more concerned with well performing, accurate, and reliable software that gets the job done.


答:
I think it's a bit of a false dichotomy really.  Many productivity guides or programmer advice boards paint this idea that you either: 1) perfect the code and never release product or 2) rush out buggy half-finished code.  In reality, most of your work is maintaining old code (yours or someone else's) not implementing brand new things completely from scratch.

In that light, taking the extra time to clean things up is almost always better, I find.  In the long run, the time you save by refactoring towards better design beats the time you spend fixing up bad code. This effect compounds as well, as usually if you aren't working towards a better implementation, you are adding to a worse one and making it harder to change and maintain it later.

For new software, this notion interestingly leads to the opposite conclusion.  Since you will be maintaining the code for a while and it's very hard to get the ideal design up front, it is usually best to get it out the door with the best design you can work out at the time.  Once it is in the wild, the design will evolve through maintenance into what it needs to be.

Title: Do you perfect your code as you go or FINISH the product first, improve structure later

Body:
I recently read a blog post (which I lost the link) that really make me think. The writer said that the one of the biggest problem in software projects is actaully completing it, and most people will end up abandoning the work.

I have been self-learning programming for over 15 years now, at this stage I actually feel pretty competent. However, I have never finish any big project that I set out to do.

What I usually do is this:

I "sketch" my idea in code, compile and run to see if it works, and imagine how other stuff can come toogether.

As the "sketch" becomes messy, I start to refactor it, consolidate functions, make classes, re-organisation data structures etc.

Repeat 1 and 2.... forever!

I tried to write on paper UML diagrams etc. but it always end up with things I overlook and then requires some drastic changes and then I becomes 1, 2, 1, 2, 1, 2 again.

How does commercial projects handle deadlines? Should I just keep on sketching until the final product is completed before thinking of making the readability/reusability/architecture/engine more sound?


问:
Master page design (reloads on new page)
Ive been building a website with 2 pages and 1 master page. The master master page works as a "Menu". The two pages inherits from the master page and have some content on them.

On Page1 I have a link to Page2. Once I click on the link Page2 (and master page) loads.

Pretty straight forward I guess. But my question is now:

The master page ofcourse reloads everytime I go to a new page and thereby the entire site "flicks" for short moment to switch to the next page. Is there some "best practice" for keeping the master page(the menu) on the page while only loading the content?

I still want to split the two pages up in Page1.aspx and Page2.aspx and not having all my content in 1 page with panels showing the content of page1 and another panel showing the content of page2 etc.

Should I use some sort of control that has the pages inside them or is this just a stupid question and I shouldnt be bothered by the entire page flicking as this is just normal "web behaviour"?

Hope you can help :)

答:
You seem to be looking for a site the loads new data and updates the HTML directly - this is not how ASP.NET webforms work by default. When you go to a new page, it needs to load from scratch.

To achieve what you want, you would need to use AJAX to query the web server for the data/template and update the page.

Webforms can work this way - using the UpdatePanel and related classes and javascript.


答:
Agree with the other posters that it's a balance, you need to be pragmatic, and need to understand the commercial incentive for shipping early.

That said, I would still tend towards doing things well & doign them right the first time rather than coming back later.

If you layer poor and rushed code onto poor and rushed design decisions, you end up with a tangled mess thats hard to maintain and extend surprisingly quickly.

When you're under business pressure, you tend to live with and press ahead with these compromises for longer than you intended, but sure enough they will begin to have more and more of a hidden cost in terms of productivity and quality of the end product.

Before you know it, you're completely backed into a corner due to all of the shortcuts you've made.  But the alternative of rewriting all of this junk can end up looking a big task in itself with the 'fixes' you put in breaking something else in the application.

As a developer, you obviously dont want to come across as a perfectionist who will never ship because he's refactoring his code for the 100th time.  However, you do have a bit of a  professional responsibility to push back on being told to take short cuts or ship junk by at least explaining the downside of technical debt.


问:
Is overloading an example of the Open/closed principle?
Wikipedia says

"software entities (classes, modules, functions, etc.) should be open for extension, but closed for modification"

The word functions caught my eyes, and I now wonder if we can assume that creating an overload for a method can be regarded as an example of the Open/closed principle or not?

Let me explain an example. Consider that you have a method in your service layer, which is used in almost 1000 places. The method gets userId and determines whether user is admin or not:

```<code>bool IsAdmin(userId)
</code>```

Now consider that somewhere it's necessary to determine if the user is admin or not, based on username, not userId. If we change the signature of the above-mentioned method, then we've broken code in 1000 places (functions should be closed to modification). Thus we can create an overload to get the username, find the userId based on username, and the original method:

```<code>public bool IsAdmin(string username)
{
    int userId = UserManager.GetUser(username).Id;
    return IsAdmin(userId);
}
</code>```

This way, we've extended our function through creating an overload for it (functions should be open to extension).

Is it an Open/closed principle example?

答:
Open-Closed Principle is a goal, an ideal case, not always a reality.  Particularly when looking to refactor old code, the first step is often heavy modification in order to make the OCP a possibility.  The root of the principle is that working code already works, and changing possibly introduces bugs.  Therefore the best scenario is not to change existing code, only to add new code.

But let's say you had a function called BigContrivedMethod(int1, int2, string1).  BigContrivedMethod does three things: thing1, thing2, and thing3.  At this point, reusing BCM is probably tough, because it does too much.  Refactoring it (if possible) into ContrivedFunction1(int), ContrivedFunction2(int), and ContrivedFunction3(string) gives you three smaller, more focused methods that you can combine more easily.

And that is the key to OCP in regards to methods/functions: composition.  You "extend" functions by calling them from other functions.

Remember that OCP is part of 5 other principles, the SOLID guidelines.  That first one is key, Single Responsibility.  If everything in your code base only did the one specific thing it had to do, you'd never need to modify code.  You'd only need to add new code or combine old code together in new ways.  Since real code rarely meets that guideline, you often have to modify it to get SRP before you can get OCP.


问:
Replacing dao layer
I am developing a series of webservices (based on spring and spring mvc).

For the first time in my dev career I do plan on replacing the dao layer in the future(I have always seen it mentioned but never had to do it).

Currently I'm using spring annotations, so I could simply change the qualifier name of the injected dao in each place it is used; is there a better (global) mechanism I could use ?

Currently my code looks like this (declaring the dao) :

```<code>@Repository("regionDao")
public class RegionDao implements IRegionDao
</code>```

and Injecting it :

```<code>@Resource(name = "regionDao")
IRegionDao regionDao;
</code>```

But going into each service class and changing the qualifier name seems rather long winded, is their a better way. Basically in the future I want to flip a switch and each reference to a regionDao will then point to newRegionDao and so on for other dao's.

A solution using annotations is preferred- for no other reason than I subjectively prefer them. But I realize this may be a case for xml based config ?

答:
You can add a layer of indirection by using property placeholders for class names:

< bean id="regionDao" class="${com.wibble.newRegionDao}" >

And then configuring DAOs class names in the property files.

I agree with other posters that this is possibly overkill to do this for a task you'll do as rarely as changing your persistence back end.

[This technique is possibly more useful in integration testing scenarios by the way - where you for instance want to run tests against one data store or messaging provider and run in production against another.]

http://static.springsource.org/spring/docs/1.1.5/api/org/springframework/beans/factory/config/PropertyPlaceholderConfigurer.html

Title: Replacing dao layer


问:
Why not Spring framework?
Are there any disadvantages in tying my application to Spring framework?

I'm not talking about bugs or issues like that, if any. I'm talking about strategic, architectural things that will influence my application lifecycle.

Should I prefer Spring over Java EE core features supported by EE container? What are the advantages?

答:
Spring does try hard to be non-invasive in terms of keeping it loosely coupled from your application code.

It's also moving more in that direction over tiem.  In earlier versions you'd need to extend base classes, then it moved to annotations, and nowadays it's more and more use of POJOs configured in XML.

This is a huge strategic benefit over other application frameworks.

Title: Why not Spring framework?


问:
New senior developer tasks
I've got a senior developer with eight years of .NET experience starting tomorrow to work on a 11,000-lines-of-code application. In the team there's myself and another programmer. We've both got about three years experience each.

It's my first project as a manager (I'm also a developer on the project) and this is the first time I've ever had to introduce someone to an already established code base. Obviously I'll be going over each module, the deployment process, etc., and handing them the location of the source control repository, documentation (which isn't the best), etc.

How long should I give them before they're ready to start writing new features and fixing bugs?

答:
Start them up immediately on small tasks - things that don't require the bigger picture.

As they get more confident and familiar with the codebase, graduate them to bigger and bigger tasks. How fast that happens mostly depends on them.

Title: New senior developer tasks


答:
How long?

How long is a rope?

When he is comfortable: when he fixes his first bug -> he is ready.

Title: New senior developer tasks

Body:
I've got a senior developer with eight years of .NET experience starting tomorrow to work on a 11,000-lines-of-code application. In the team there's myself and another programmer. We've both got about three years experience each.

It's my first project as a manager (I'm also a developer on the project) and this is the first time I've ever had to introduce someone to an already established code base. Obviously I'll be going over each module, the deployment process, etc., and handing them the location of the source control repository, documentation (which isn't the best), etc.

How long should I give them before they're ready to start writing new features and fixing bugs?


答:
I always like to get tasks assigned to me right of the bat, with the understanding that it will take much longer to dig through the code, and a lot of questions will be asked during the first few days/weeks.

I find that I'm not able to completely get my head wrapped around a project until I have to actually go in and fix or change something.

Also... No matter how well you think you have explained how a project works there is always the 'oh yeah I forgot to tell you', 'we ran into this problem, so we did this' moments that are not teased out until you actually begin work.

Title: New senior developer tasks


答: For an app that small, and a developer that experienced, I'd think a day is enough for basic bugs. Involved bugs or small features closer to a week (once they're clearer on the problem domain and architecture).</p>

Title: New senior developer tasks


问:
When programmers talk about "data structures", what are they referring to?
When programmers talk about "data structures", are they only talking about abstract data types like lists, trees, hashes, graphs, etc.?

Or does that term include any structure that holds data, such as composite types (class objects, structs, enums, etc.) and primitive types (boolean, int, char, etc.)?

I've only ever heard programmers use the term to reference complex data structures or abstract data types, however the Wikipedia article that provides a list of data structures includes both composite types and primitive types in the definition, which is not what I expected (even though it does make sense).

When looking around online I see other places that refer to the term "data structure" in the programming sense as only referring to abstract data types, such as this lecture from Stony Brook University's Department of Computer Science which states

A data structure is an actual implementation of a particular abstract data type.

or this wikibook on data structures, which uses the term in sentences like this:

Because data structures are higher-level abstractions, they present to
  us operations on groups of data, such as adding an item to a list, or
  looking up the highest-priority item in a queue

So why do I only ever hear programmers referring to complex data structures or abstract data types when they use the term "data structure"? Do programmers have a different definition for the term than the dictionary definition?

答:
The generic definition of "data structure" is anything that can hold your data in a structured way, so yes this would include composite types and primitive types in addition to abstract data types. For example, a string is a data structure as it can hold a sequence of characters in a structured way.

However, the term also has another meaning to programmers.

Since the term "data structures" is so broad, developers usually use a more specific term to identify what they are talking about, such as class or data object or primitive type, and the specific term used for most complex or abstract data types is "data structure"

This is why you hear "data structure" most frequently being used for abstract data types like Arrays, Lists, Trees and Hashtables, and not for things like primitive data types


答:
The term refers to both, though things like ints and booleans are typically considered primitive data types (or primitive data structures). The term itself simply referes to anything that stores data in a specific way. Certainly int meets this definition just as well as something like a Hash table, only it's simpler.

Typically, when people use data structure, they refer to more complex data structures, and not the simpler ones but both meet the definition.

Title: When programmers talk about "data structures", what are they referring to?

Body:
When programmers talk about "data structures", are they only talking about abstract data types like lists, trees, hashes, graphs, etc.?

Or does that term include any structure that holds data, such as composite types (class objects, structs, enums, etc.) and primitive types (boolean, int, char, etc.)?

I've only ever heard programmers use the term to reference complex data structures or abstract data types, however the Wikipedia article that provides a list of data structures includes both composite types and primitive types in the definition, which is not what I expected (even though it does make sense).

When looking around online I see other places that refer to the term "data structure" in the programming sense as only referring to abstract data types, such as this lecture from Stony Brook University's Department of Computer Science which states

A data structure is an actual implementation of a particular abstract data type.

or this wikibook on data structures, which uses the term in sentences like this:

Because data structures are higher-level abstractions, they present to
  us operations on groups of data, such as adding an item to a list, or
  looking up the highest-priority item in a queue

So why do I only ever hear programmers referring to complex data structures or abstract data types when they use the term "data structure"? Do programmers have a different definition for the term than the dictionary definition?


答:
Oded's excellent answer is correct, the UpdatePanel will allow you to make use of AJAX so that contents within the UpdatePanel can be rerendered without refreshing the entire page within the browser, but then this won't cause page navigation to be magically AJAX'ified.

Invoking a browser action where you request another page be ASPX page be accessed will result in the server navigating to another page.

I think you fundamentally misunderstand how a MasterPage works.  It is not a single web page with injectable AJAX enabled child pages preventing the need for browser navigation.  It is merely a template that Page1.aspx and Page2.aspx both use, but ultimately the server will still recognize that these two pages are seperate navigable items.

I think you should maybe look at how to develop a UserControl.  These can be defined in markup and code behind as if they were a seperate page, and they can be placed inside of an UpdatePanel to refresh the components in question without have to do a full page postback.

Title: Master page design (reloads on new page)

Body:
Ive been building a website with 2 pages and 1 master page. The master master page works as a "Menu". The two pages inherits from the master page and have some content on them.

On Page1 I have a link to Page2. Once I click on the link Page2 (and master page) loads.

Pretty straight forward I guess. But my question is now:

The master page ofcourse reloads everytime I go to a new page and thereby the entire site "flicks" for short moment to switch to the next page. Is there some "best practice" for keeping the master page(the menu) on the page while only loading the content?

I still want to split the two pages up in Page1.aspx and Page2.aspx and not having all my content in 1 page with panels showing the content of page1 and another panel showing the content of page2 etc.

Should I use some sort of control that has the pages inside them or is this just a stupid question and I shouldnt be bothered by the entire page flicking as this is just normal "web behaviour"?

Hope you can help :)


答:
one interesting thing that Martin Thompson mentions in this article is that spring can have a non-trivial impact on GC times:

Keep call stacks reasonably small.  Still more work to do here.  If you are crazy enough to use Spring, then check out your call stacks to see what I mean!  The garbage collector has to walk them finding reachable objects. -Martin Thompson

This kind of thing won't be a big issue for most sorts of apps, but it's a very real concern for the kinds of apps Martin is referring to.

Title: Why not Spring framework?

Body:
Are there any disadvantages in tying my application to Spring framework?

I'm not talking about bugs or issues like that, if any. I'm talking about strategic, architectural things that will influence my application lifecycle.

Should I prefer Spring over Java EE core features supported by EE container? What are the advantages?


问:
Wrong use of CSS3 Animations or not?
Well, I started using some CSS3 animations a couple of days ago. After hardcoding I've started trying different tools like Adobe Edge Preview version.

I made a short animation to get the functionality of the tool
http://things.eyemade.ch/css3edge/

After that someone at Twitter took a look at it and said that it is wrong using divs to paint things like these. But I'm not sure about that. Things changed over the last years and if we keep in mind this stuff is going to be used in many web/mobile games, is it really wrong to use divs this way nowadays?

答: It depends on how the animation is going to be used. If it's just a simple animation with no interaction, this is fine and there is nothing wrong with it.</p>

Title: Wrong use of CSS3 Animations or not?


答:
I would assign a couple of low priority bugs the first day, that way no one is screaming if they aren't done right away giving the new developer some time to get familiar with the code base.

The most critical thing to do is to have a code review of all of his work the first couple of weeks. You don't want to find out that the guy is going in the wrong direction or not following company coding standards months into things. It is better to make sure he knows what is expected from the start, and code reviews ensures this. Of course I think code reviews are good for all employees (We review 100% of our code before deployment), but they are critical for new employees and should be done in person where you can answer questions and refer them to documentation they may not have seen yet if need be.

What you don't want is a new guy coming in and using a different style from the rest of you. People often try to keep using the code style of their previous job even when it conflicts with the code style used at the new place which can create confusion and annoyance on the part of the other developers.

One thing I have noticed even with experienced developers is that some of them are not as good as they seemed to be in the interview, code review will help you find this out fast, so you can fix it. It will also encourage them to actually get something done, I have seen new employees who are not code reviewed drag out a project without showing what they were doing to anybody and then leave a week before the deadline they knew they were not going to hit because they were in over their heads and had not actually completed any part of the project. Better to check early and often with new people until you are really sure that they are working out.

Also, it is normal for the new guy to be appalled at the state of your legacy project. It's not designed the way he thinks it should have been. Expect this, hear him out and don't automatically dismiss everything he says. In particular, this person appears to have more experience than you or the other developers, he may see things you hadn't considered. However, as a manager, you have to balance the proposed changes against the current workload and deadlines. You all may want to invest some time in learning how to refactor existing code and invest some hours in your time estimates to do that especially if the new guy has some valid concerns. You probably can't support a total re-write (many people who come in new think we should start over and do it better), but you can create a refactoring plan to fix the worst of the problems if there are any that he brings up.

If you have some time where he is not expected to be fully contributing (and fully accounting for his time by client), it might also be a time when he can start on some of those refactoring things that you have wanted to do but haven't had time to do. Sometimes, it is a good thing to use the new person training period to address some things that aren't in the project plan. They can learn the code base and if what they want to do doesn't work, you haven't affected the existing schedules because you hadn't factored them into the existing schedule yet. And if it does work, you might have a big win making future maintenance easier or security better or whatever the problem is.

Title: New senior developer tasks


答:
Another approach is to drop the concept of a "master page" with navigation and 2 content pages.

Maybe just think of it as 2 pages, which both contain content and navigation where the navigation might be similar on both pages.

An html page is a document and both navigation and content are part of that document. Without the navigation, you can't find other pages and without content there's nothing too find.


答:
What I'd do:

Add a member variable Bar * bar and int index to Foo.

Have Bar::addFoo set foo->bar = this and foo->index = foo.size()

Implement Foo:getFoo on Foo to use the getFooIndex and bar to return a foo pointer

Implement Foo:addFoo similiarily

Then you should be able to use both APIs simultaneously. You can deprecate the index based apis and slowly remove them.

Title: introducing pointers to a large software project

Body:
I have a fairly large software project written in c++.

In there, there is a class foo which represents a structure (by which i don't mean the programmers struct) in which foo-objects can be part of a foo-object.

Here's class foo in simplest form:

```<code>class Foo
{
    private:
        std::vector<unsigned int> indices;
    public:
        void addFooIndex(unsigned int);
        unsigned int getFooIndex(unsigned int);
};
</code>```

Every foo-object is currently stored in an object of class bar.

```<code>class Bar
{
    private:
        std::vector<Foo> foos;
    public:
        void addFoo(Foo);
        std::vector<Foo> getFoos();
}
</code>```

So if a foo-object should represent a structure with a "inner" foo-object, I currently do

```<code>Foo foo;
Foo innerFoo;
foo.addFooIndex(bar.getFoos().size() - 1);
bar.addFoo(innerFoo);
</code>```

And to get it, I obviously use:

```<code>Foo foo;
for ( unsigned int i = 0; i < foo.getFooIndices().size(); ++i )
{
    Foo inner_foo;
    assert( foo.getFooIndices().at(i) < bar.getFoos().size() );
    inner_foo = bar.getFoos().at(foo.getFooIndices().at(i));
}
</code>```

So this is not a problem. It just works. But it's not the most elegant solution.

I now want to make the inner foos to be "more connected" with the foo-object. It would be obviously to change class foo to:

```<code>class Foo
{
    private:
        std::vector<Foo*> foo_pointers;
    public:
        void addFooPointer(Foo*);
        std::vector<Foo*> getFooPointers();
};
</code>```

So now, for my question: How to gently change this basic class without messing up the whole code? Is there a "clean way"?


问:
How do you deal with the anxiety of not knowing enough?
I just finished college a couple of months ago and I'm taking time out to improve my knowledge. I love programming but I feel like I don't know enough to be confident if I went for an interview. Last night I was browsing through questions and came across a question that asks interviewees how to work out a linked list. I learned these at college but if I was asked on the spot how to do it I wouldn't know. So that's another thing added to the list of what to learn.

This is when the anxiety hit me because I have so much to learn in so little time (at least it feels that way). Upon introspection, I think this anxiety is related to my perfectionism even though being perfect isn't rational e.g. Shakespeare and Einstein failed 80% of the time.

So the questions are, have you felt this anxiety of not knowing enough? If so, how did you deal with it? I suppose there's a point in time when you begin to feel comfortable in your abilities?

答:
Some people:

Thought they know and they do

Thought they know but they don't

Don't know they know but they do

Don't know they know and they don't

To me, 1 > 3 > 4 > 2

The fact that you know that you don't know everything is already knowing something. Learning takes longer than a lifetime, pace yourself and convince yourself that you can never learn everything; so is the genius in the next cubicle.

Knowing is one thing, applying it is another. Apply what you have learnt and be open-minded for new ideas and let the passion leads your way. Sounds philosophical? Maybe, but life is too short to be so tensed up. :P

ContentLicense: CC BY-SA 2.5


问:
Spec Writing Management
I simply cannot imagine writing software without a spec. No matter how sketchy or high level it is, spec is important to explain to the clueless programmers on what are the functionalities of the program.

But the problem with spec is that it is somewhat a second class citizen in the whole software development cycle; when the development picks up the steam, it is neglected. But when dispute arises, the developers and testers and sales will scramble to find the spec to justify their grounds.

Either one or more scenarios will happen:

The spec cannot be recovered, no one knows where is the spec

Different versions of the spec emerge from different sources; it takes great difficulties to find out which version is the latest version, or whether there is a latest version available.

The spec is incomplete, some parts of the documents it refers to are missing.

So spec management is important, and it's equally important that everyone has only One Single Source of Spec.

How do you manage your specs? I tried to get everyone to use Google Docs but everyone objected. Everyone is just too attached and enamored with Microsoft Word, which is-- in their opinion-- very easy to use, very easy to insert image, very easy to type equation and whatnot.

How to convince them that MS Word is just terrible for sharing?

答:
```<code> > How to convince them that MS Word is just terrible for sharing?
</code>```

you cannot easily compare what-s the difference of two instances in a version-control-system.

I dont-t like word specs for that reason. But since it-s a political decision to use word-specs we have as first page "history informations" with these colums:

version-number(relates to product-verision), author, date, description

Title: Spec Writing Management

Body:
 > How to convince them that MS Word is just terrible for sharing?

you cannot easily compare what-s the difference of two instances in a version-control-system.

I dont-t like word specs for that reason. But since it-s a political decision to use word-specs we have as first page "history informations" with these colums:

version-number(relates to product-verision), author, date, description


问:
How should I go about re-releasing a GPL-licensed project?
A few months ago we found a library licensed under GPL that fit the bill for what we were looking to do at that time. We included it in our codebase and all was fine. Now, a few frantic months of coding later, we've refactored the hell out of the library: it's more feature complete, more stable, fully unit tested, PSR-0 compatible, etc.

Now we would like to use the library in another one of our projects and that got me thinking, why not re-release the library?

The problem is that I don't have any idea on how to attribute the work the original developers have put in (which is actually that much refactored that it's kinda unrecognizable) when releasing the library as GPL again. Over time all the file documentation headers with the original credits have been replaced and all that remains is the LICENSE file which is an exact copy of the GPL v3 license.

I have absolutely no problem giving credit where it's due, but I would like to do it according to what is right in the FOSS world. Anyone can tell me how to proceed?

答:
Is the original library site still active?  Many FOSS and GPL'd projects end from lack of activity.

If the site is still active, contact the owners and offer up the changes you have made.

If the site isn't active, there are a number of hosting places.  Do as you have stated in your question - give full credit; explain what you changed; offer it up to others.

At the risk of redundancy, but also for future research, here are some relevant links to your question.  The GPL overview is rich with additional links.

Overview of software licenses: http://en.wikipedia.org/wiki/Software_license

GPL overview: http://en.wikipedia.org/wiki/GNU_General_Public_License

GPL FAQ: http://www.gnu.org/licenses/gpl-faq.html

Based upon the additional information that the original project is a GPLv3 licensed project, and you've significantly changed your derivative of the project, I would consider the following.

You have effectively forked the project, and I think your example demonstrates that forking can sometimes be a good thing.

The first step, and a polite one at that, is to contact the original project team and offer to contribute your updates.  You have stated they will likely reject the changes, which is okay - they don't see the need or just can't afford the overhead to switch.  Technically, you don't have to do this since the GPL gives you full rights to create a derivative work.

The next step is to determine what license you wish to use in releasing your version of the project.  Take a look at:

http://www.gnu.org/licenses/gpl-faq.html#AllCompatibility

 and that should help guide you.  I'll assume you stick with GPLv3, but you don't have to.

Once you find a home for your project, you should state that you are releasing the project as a GPLv3 project and that your project is based upon project XYZ that was released under GPLv3 as well.  Attribution for work isn't quite as important here as history of project licensing.  OTOH, by calling out the license history you are explicitly attributing the origins of this project.  Two birds, one stone.  :-)


答:
You may want to check the license as distributed with the software. Section 7 has "additional terms" that MAY be applied which is where attribution comes in. Check if this is required. The main requirement is to PRESERVE attribution notices. If they aren't there, you obviously can't preserve them.

If you have done a lot of work and the project is still active, you can offer the new/modified code, but if they don't want it, you can always fork it and distribute it seperately.

As always IANAL, YMMV

-- edit

As I understand it the standard GPL v3 doesn't require attribution.

Title: How should I go about re-releasing a GPL-licensed project?

Body:
A few months ago we found a library licensed under GPL that fit the bill for what we were looking to do at that time. We included it in our codebase and all was fine. Now, a few frantic months of coding later, we've refactored the hell out of the library: it's more feature complete, more stable, fully unit tested, PSR-0 compatible, etc.

Now we would like to use the library in another one of our projects and that got me thinking, why not re-release the library?

The problem is that I don't have any idea on how to attribute the work the original developers have put in (which is actually that much refactored that it's kinda unrecognizable) when releasing the library as GPL again. Over time all the file documentation headers with the original credits have been replaced and all that remains is the LICENSE file which is an exact copy of the GPL v3 license.

I have absolutely no problem giving credit where it's due, but I would like to do it according to what is right in the FOSS world. Anyone can tell me how to proceed?


问:
OOP :What are some of the situations in which class based design is better than interface based one?
I was reading  JDOM's website.

Why is the JDOM API defined in terms of concrete classes rather than interfaces?

Jason Hunter summarizes the arguments against an interface-based API for JDOM:

With interfaces everything becomes a factory, elements have to be 'imported' into new documents instead of just added, features like long-term serialization cannot be guaranteed, and the list goes on.

We started with interfaces actually. During our pre-release review to some peers we received the feedback we should try concrete classes. We did, and the design was much better for it.

I am a beginner designer. All the advice I have heard about till now is advising against using designing with concrete classes.

May be using concrete classes are appropriate in certain places. Are there any common class problems for which using concrete classes in design is okay?

答:
From the JDOM site:

Jason (Hunter) founded the JDOM project in early 2000 along with Brett McLaughlin

That is, around the time Java 1.3 was being introduced.  There was nothing in the way of maturity when it came to Java development--the most experienced developers only had 4 years using Java at best.  There were no broadly used IoC containers, no Hibernate. Apache Struts was just getting its start.

Which is all to say that Jason and Brett were just wrong.  A lot of people didn't "get it" yet. If they had C++ backgrounds, well, you didn't need interfaces in C++ (well, they were there in C++, but you didn't really need them, right?), why the heck use them in Java?  Well, there's a lot of good reasons, which others can direct you to.

They were definitely wrong about

anything that can be done with interfaces can be done with subclassing

Java does not allow multiple inheritance of classes, but it does allow the implementation of multiple interfaces.  That can make a real difference.


问:
Need to process 2 million 100k messages per second and route them to a particular event, delegate or multicast delegate
I need to process 2 million messages per second (perhaps in a scale out configuration) and route each message to a N delegates or multicast delegates.

Question

How should I structure my application in C# so that I can achieve the
best performance when receiving the message, and routing it to the
correct delegate?

Additional Details

Each inbound message has the following properties in the format of a JSON array:

Customer

Category

TopicID

DateTime

Data[]

Each message will be processed by a delagate function that is interested one or more of those properties.

Simple examples of delegate processing needed:

A customer counter function may count the quantity of messages per customer,

A category counter may count the quantity of messages that counter

A customer-counter will count messages unique to that customer.

答:
200Gb of data per second?

To do this you're not going to get too much help with C#, all the High Performance Computing applications are written in C/C++, so for a start, you should be looking to go this direction simply to leverage their expertise, libraries and frameworks.

That said, a lot of telecoms work is done using functional languages, and they deliver input streams of a magnitude similar to what you're expecting, so try Haskel too.

In any case, your first task is to split that input stream to several servers, then pass them to more servers for processing. In these cases, you don't need delegates, you need a full message passing architecture that is stateless and memory efficient. Try OpenMPI for some hints.


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

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

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

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

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

component data element separator (: in this sample)

data element separator (+ in this sample)

decimal notification (. in this sample)

release character (? in this sample)

reserved, must be a space

segment terminator (' in this sample)

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

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

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

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

Questions:

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

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

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

Notes:

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

答: I don't know what you want to exactly do with this data afterwards and if it is not a sledgehammer for a nut, but i had good experiences with eli. You describe the lexical phrases and then concrete/abstract syntax and generate what you want to generate. </p>

Title: Best way to parse a file


问:
What are the arguments against or for putting application logic in the database layer?
Most software developers want to keep application logic in the application layer, and it probably feels natural for us to keep it here. Database developers seem to want to put application logic in the database layer, as triggers and stored procedures.

Personally I would prefer to keep as much as possible in the application layer to make it easier to debug and keep the responsibilities of the layers separate.

What are your thoughts on this, and what should or should not be ok to implement in the database layer?

Edit This question is also covered on dba.se, from the DBAs perspective. As programmers.se & dba.se have different audiences and biases, future readers might want to review both sets of answers before deciding what works best for them.

答:
Having read both questions, I think we may have all missed one critical point. The correct answer may depend on the type of software you are developing. The DBA group tends in large part to work on business critical Enterprise software systems and their answers tend to reflect what is necessary in that world. There is a huge difference in what is needed for those types of applications than what is needed for the next "Facebook" application. It's no big deal if you lose a couple of wall posts, it is if you lose a couple of orders or other financial transactions.

The people who work in the COTS (commercial off-the Shelf) world tend to need to be database agnostic for sales reasons and they want everything in complied code to make it more difficult to reverse engineer and replace their product with one that is homegrown. The Enterprise applications developed and maintained in-house will almost never need to change database backends except to upgrade.

Enterprise applications are also the ones which tend to have inputs from many places with the database being the only commonality. The system I work in has hundreds of different applications accessing it as well as hundreds of imports of client data, exports of data to clients and to data warehouses and uses mulitple reporting systems. The code that works well when adding one record is fails when I have to import 20,000,000. We got forced to use the application layer once because that was where the logic was and had to stop the process 18 hours later unfinished. The logic that should apply to all data records in a table needs to be in the database when you can't have one data layer that everyone uses.

Conversely when only one application will consume the data and the data is not the lifeblood of your company or is emphemeral, the rules are different and putting all of the logic in the application makes more sense.


问:
What's the best practice to do SOA exception handling?
Here's some interesting debate going on between me and my colleague when coming to handle SOA exceptions:

On one side, I support what Juval Lowy said in Programming WCF Services 3rd Edition:

As stated at the beginning of this chapter, it is a common illusion
  that clients care about errors or have anything meaningful to do when
  they occur. Any attempt to bake such capabilities into the client
  creates an inordinate degree of coupling between the client and the
  object, raising serious design questions. How could the client
  possibly know more about the error than the service, unless it is
  tightly coupled to it? What if the error originated several layers
  below the service—should the client be coupled to those lowlevel
  layers? Should the client try the call again? How often and how
  frequently? Should the client inform the user of the error? Is there a
  user?  By having all service exceptions be indistinguishable from one
  another, WCF decouples the client from the service. The less the
  client knows about what happened on the service side, the more
  decoupled the interaction will be.

On the other side, here's what my colleague suggest:

I believe it’s simply incorrect, as it does not align with best
  practices in building a service oriented architecture and it ignores
  the general idea that there are problems that users are able to
  recover from, such as not keying a value correctly.  If we considered
  only systems exceptions, perhaps this idea holds, but systems
  exceptions are only part of the exception domain.  User recoverable
  exceptions are the other part of the domain and are likely to happen
  on a regular basis.  I believe the correct way to build a service
  oriented architecture is to map user recoverable situations to checked
  exceptions, then to marshall each checked exception back to the client
  as a unique exception that client application programmers are able to
  handle appropriately.  Marshall all runtime exceptions back to the
  client as a system exception, along with the stack trace so that it is
  easy to troubleshoot the root cause.

I'd like to know what you think about this.

答:
A service that does not provide any status on its health or the execution of a transaction is like a black box - the service consumer and the administrators who monitor the environment cannot tell if things are working.

There are several techniques for instrumenting services for monitoring. You can implement a heart beat whereby the service sends an "I am alive" message that can be picked up by a monitor. This is a simple task but does not really tell you if the service is working - only that it is running and has the ability to send a message. This however, is more that an OS level monitor will tell you. You can set up the monitor to automatically register the service for monitoring when it sees the heart beat the first time.

You can also develop a monitoring interface I call a "ping" interface. You send the ping interface a message and the interface can do some internal verifications of functionality and respond. This tells you more than the service is simply up and running. You can also build in the support of a "synthetic transaction" where you send specific transactions to a set of services and they execute the transaction but with no impact to the business - like updating a test account. But, to tell if a service is running properly in the context of all business transactions you have to develop a framework for application-level monitoring.

Application-level monitoring requires status data about each business transaction. The ability to monitor an application in a business or transactional context requires a monitoring interface within the service to send messages detailing the transaction's status specific to the service invocation. This requires each service to send a status message at critical steps in the business transaction. You can then build a real-time viewer to correlate status messages (based on the semantics of the message - e.g. transaction ID) with the services within the composite application. This provides an end-to-end view of the business transaction for SLA management, fault tracing and problem determination.

Here is a set of utilities that help implement this framework. I did help build these utilities.


问:
Does the structured programming definition only consider imperative programming?
Does the structured programming definition only consider imperative programming?  By this I mean does the definition of structured programming automatically exclude functional programming (in the most common usage, by which I mean not necessarily pure-functional programming, but something like Clojure).

Structured programming, at least from the definitions that I've found seem to really be saying: "good programming shouldn't use goto, and should be modular".  Which doesn't necessarily exclude functional programming, while most definitions seem to begin with "... is a subset of imperative programming".

I'm looking for a bit of clarification I think.

BTW, I have read "What's The Difference Between Imperative, Procedural and Structured Programming?" which is a pretty good historical description.

答:
Suppose that you use and create only pure functions. These by definition have no shared state and are easy to compose, and there's no way to use a goto. This satisfies both 'modularity' and 'structured control flow' properties.

What could it be? A map-reduce calculation. A Prolog inference. An SQL query (can be reused as a subquery or a view). Are you comfortable to put all these under the umbrella of the notion from 1960s?

To me, 'structured programming' is mostly a historical concept, connected to, for instance, 'Goto Considered Harmful' and other works of Dijkstra. It is deeply rooted in imperative world. You do structured programming when you write good C code. You do something different when you write highly modular, well-structured code in Haskell or probably even Scala.


答:
At risk of sounding dramatic, I'm genuinely horrified by the idea of application logic in the database. A lot of answers here have focused on the software development advantages, so the sake of brevity, I'm going to focus on the advantages yielded by the division of responsibility.

Databases provide an efficient means of storing and accessing information, while minimizing redundant data and producing logical relationships in the data.  While database logic might be capable of implementing production-level business logic, my personal opinion is that the database should be as application-agnostic as possible to ensure that the data can be effectively leveraged by multiple applications while playing to the respective strengths of the database engine versus the strengths of the application's language of implementation.

One user on the DBA stack exchange stated this...

I want all the logic that has to apply to all users and all applications in the database. That's the only sane place to put it.

The last Fortune 500 I worked at had applications written in at least 25 languages hitting their OLTP database. Some of those programs moved to production in the 1970s.

... Followed by his belief that this is indicative of a violation of the DRY principle.

Rather than being a repetition of business logic, I think this is more likely a perfect example of the flexibility provided by a distinct division of responsibilities between the business layer and data layer.

Their OLTB database has been providing data reliably and efficiently to 25+ applications for decades!  That's amazing! (Way to go!)

I can only assume that the data is agnostic enough to provide content for a number of distinct applications.  Something that would be largely impossible if those developers attempted to hack something together using database logic.

As other answers have indicated, there are many other reasons not to implement a program in the database.  I'm sure it would work, but the most probable result would be decades of regret, rather than decades of stability.

Title: What are the arguments against or for putting application logic in the database layer?

Body:
Most software developers want to keep application logic in the application layer, and it probably feels natural for us to keep it here. Database developers seem to want to put application logic in the database layer, as triggers and stored procedures.

Personally I would prefer to keep as much as possible in the application layer to make it easier to debug and keep the responsibilities of the layers separate.

What are your thoughts on this, and what should or should not be ok to implement in the database layer?

Edit This question is also covered on dba.se, from the DBAs perspective. As programmers.se & dba.se have different audiences and biases, future readers might want to review both sets of answers before deciding what works best for them.


答:
Structured programming is essentially programming by composing procedures.

Can you do something similar with functions in a functional language? Yes.

When people talk about structured programming, do they usually mean to include functional programming? No.

If you say "structured programming style," will people understand you to be including functional programming? No.

Body:
Does the structured programming definition only consider imperative programming?  By this I mean does the definition of structured programming automatically exclude functional programming (in the most common usage, by which I mean not necessarily pure-functional programming, but something like Clojure).

Structured programming, at least from the definitions that I've found seem to really be saying: "good programming shouldn't use goto, and should be modular".  Which doesn't necessarily exclude functional programming, while most definitions seem to begin with "... is a subset of imperative programming".

I'm looking for a bit of clarification I think.

BTW, I have read "What's The Difference Between Imperative, Procedural and Structured Programming?" which is a pretty good historical description.


答:
You are following the open-closed principle if you are altering your program's behavior by writing new code rather than altering old code.

Since it's pretty well impossible to write code that is open to every possible change (and you don't want to because you enter analysis paralysis) you write code that responds to all the different behaviors you are currently working on by extension rather than modification.

When you run into something you need to change, instead of simply altering something to allow the new behavior, you figure out what the point of change is, restructure your program without altering its behavior so that you can then change that behavior by writing NEW code.

So, how this applies to your case:

If you are adding new functions to your class then your class is not open/closed but the clients of the function you're overloading are.

If you are simply adding new functions that work ON your class, then both it and the clients of your function are open/closed.

Title: Is overloading an example of the Open/closed principle?

Body:
Wikipedia says

"software entities (classes, modules, functions, etc.) should be open for extension, but closed for modification"

The word functions caught my eyes, and I now wonder if we can assume that creating an overload for a method can be regarded as an example of the Open/closed principle or not?

Let me explain an example. Consider that you have a method in your service layer, which is used in almost 1000 places. The method gets userId and determines whether user is admin or not:

```<code>bool IsAdmin(userId)
</code>```

Now consider that somewhere it's necessary to determine if the user is admin or not, based on username, not userId. If we change the signature of the above-mentioned method, then we've broken code in 1000 places (functions should be closed to modification). Thus we can create an overload to get the username, find the userId based on username, and the original method:

```<code>public bool IsAdmin(string username)
{
    int userId = UserManager.GetUser(username).Id;
    return IsAdmin(userId);
}
</code>```

This way, we've extended our function through creating an overload for it (functions should be open to extension).

Is it an Open/closed principle example?


问:
How much detail about a user story can a developer expect?
The biggest drawback of agile development I have experienced is that people not involved in development focus on the mantra that a user story (3-10 ideal person days) should not contain more than 1-3 sentences like:

As a customer, I can use free-text search so that I can find the products I'm looking for.

Giving this sentence, project managers expect me as a developer to commit to an estimate and develop the story. They assume that agile development means that sentences like this are all they have to provide to developers.

I won't blame them because the well-known literature about agile development creates the impression that this would actually work. I've read something like 2 pages in natural language per story in "Planning XP", but that's it. Because "working software" is favored over "comprehensive documentation", this topic seems to be generally avoided.

The reality is, of course, that if the developer is given the chance to do so, an interview with the customer brings up a long list of requirements that the customer has about the story:

We need boolean operators like AND and OR.

We need fuzzy search an all terms.

We need to search by single words as well as by phrase.

We don't want to find products that meet criteria X, Y, and Z.

We want to sort the result. Oh, and by the way, the user can select the sort criteria in a combo box with options a, b, and c.

So you see that I'm not talking about technical details or software design or even implementation details. It's pure requirements. The longer we talk the more the customer realizes that there's actually quite a lot to say about what they want.

But often enough I find myself in the situation that such information is not provided or in very shoddy fashion. Neither is it possible that I do the interview, nor does the person that would be in the position to do the interview provide me with a result of it.

Sometimes, managers even come up with technical details like "we want Lucene search" but they don't want to think about if they want find only product names or also product descriptions. Sometimes I think they are just lazy ;)

For me, this is the top issue in projects I work in (e-business web application, 500-2000 person days per project). I've addressed this problem often enough, and managers are aware that most developers have a problem with the situation. But they believe that developers are just too much "perfectionists". They seem annoyed that developers "always want to have everything specified".

Due to the lack of generally acknowledged numbers it's hard to argue. Everybody knows how long an iteration should be. But nobody can tell how much requirements are needed to estimate and develop a story.

Do you have some reference?

答:
Customer

I want to search products

Product manager
I have analysed customer's story and came up with the following requirements. Each requirement has been recorded as a seperate user story.

Search for products

Sort result

Filter search results

Developer
I have received user stories from a product manager. I have analysed each user story and came up with a list of task for each user story.

Search for products

Task 1: Database changes

Task 2: Server side changes

Task 3: Front end changes

Customer, product manager and developer are all stake holders in this process. They all need to contribute to the analysis process before the work can commence. Please note, that this is very simplified example.

Our user stories are analysed and refined in the following order (with some variations of course):

Help Desk --> Product Owner --> Product Manager --> Department Leads (senior developers, qa leads, etc) --> Developers

Once all the relevant stakeholder have contributed to the analysis process, we can estimate how long it will take us to deliver the story. Estimation process that we follow is based on velocity and expertise of individual developers.

I'm not saying that this is a correct way of doing things, but it works really well within our organisation.


答:
8 years of experience.  I would just throw him in.  He should be able to swim.  As others have noted start with small easy tasks.  It will allow him to fumble through the code check-in/check-out process, and any other development processes you have.

I have changed jobs many times and I have been a contributor in all of them within the first week. The toughest took me a week to get the code to compile (100k+ lines of code at least).  A full build took 8 hours for that project.

I worked something like 80 hours the first week (project was seriously behind).

Title: New senior developer tasks


问:
What is the difference between an Array and a Stack?
According to Wikipedia, a stack:

is a last in, first out (LIFO) abstract data type and linear data structure.

While an array:

is a data structure consisting of a collection of elements (values or variables), each identified by at least one array index or key.

As far as I understand, they are fairly similar. So, what are the main differences? If they are not the same, what can an array do that a stack can't and vice-versa?

答:
I think the biggest confusion going on here is implementation versus basic data structures.

In most (more basic languages) an array represents a fixed length set of elements which you can access any at a given time. The fact that you have a bunch of elements like this tells you nothing about how it is supposed to be used (and frankly a computer won't know/care how you use it, as long as you don't violate usage).

A stack is an abstraction used to represent data that should be handled in a certain way. This is an abstract concept because it just says that it has to have some subroutine/method/function that can add to the top or remove from the top, while data below the top doesn't get touched. Purely your choice to use an array this way.

You can make a stack out of many different kinds of data structures: arrays (with some max size), dynamic arrays (can grow when out of space) or linked lists. Personally I feel that a linked list represents the restrictions of a stack the best as you have to put in a bit of effort to see things beyond the first element and it's very easy to add to the front and remove from the front.

So you can use an array to MAKE a stack, but they are not equivalent


问:
Working machines of developers - in what ways are they usually standardized or restricted?
My boss wants to introduce new guidelines for the computers in our company. This means that the software environments will be completely standardized with a predefined set of tools. The goal is that all machines are completely reproducable and exchangable.

I'm wondering what the guidelines for developer's computers are in large companies, such as Google or Microsoft, especially companies which are certified according to some standard (e.g. ISO 9001). Do they allow developers to install software from the internet if they need it for some small task? (e.g. a code compare tool, CygWin, Windows Service Packs) or do they really want all needed tools in a fixed, predefined environment where all proposed changes must be discussed with a system administrator first?

答:
Even standardization for developers is crazy talk.  I have never worked anywhere where everyone users the exact same set of tools.  Is he going to buy 100 seats of Photoshop because the 2 guys on the graphics team need it?

What is going to happen is you will need some tool specific to your task on the project.  They won't buy it because then they will have to buy 100 seats.

I get having some commonality of setup and a certain degree of standardization is important.  (like all linux, Mac, Windows, same brand, model,etc)  Make sure they are willing to commit the resources though to equipping the development team to be their best.

Fought this battle once where we had to use the same machines as the customer service flunkies.  Lasted a few weeks and we had to upgrade the memory, still wasn't enough because they bought the lowest common machine they could and it didn't support the larger amounts of memory, came with slow hard drives, and no dual display support.

An IT professional has different needs than the secretary.  We tried to get them to create a few classes of machine (like workstation and desktop) but no dice.

Sad to say, company is no more.  Not just on that issue, but it is indicative of bad management or allowing one group (IT purchasing and Support) to make decisions for another (IT development)


问:
Managing a website with version control?
The small website I built a long time ago is starting to pick up a little and I'm starting to run into problems with making changes. Originally, all the pages were .html and I would edit and test them offline to make sure everything worked. Then I realized how helpful php includes were, so I changed everything to .php and used includes. Without apache, I could no longer test offline, so with Filezilla, I would choose the "view/edit" option on files that were already on the server, edit them, and then have them uploaded again. This is what I've been doing so far and it's worked pretty well for the most part. I just save the temp file that filezilla creates, and let it upload it back to the server.

Yesterday, I realized that one of the javascript files I had worked on the day before had been replaced by an empty file. This was something to do with sublime text keeping the non-existent temp file open/filezilla uploading an empty file - I'm not really sure what happened, but it shouldn't have been able to happen. And now, I need to change the design of the site, and doing that one page at a time would be noticeable, so I need to do it offline first.

I would like to use version control and install apache so that I can completely test my site offline, but there are a couple problems I have with this. The first is that I have a Forum on the site. I could install mysql and export the tables, then import them offline, but then, while people are making posts on the website, the offline copy becomes out of date and I can no longer upload that back to the server. I also have some Python scripts on the site using WSGI. My webhost's settings are very specific, so if I wrote python scripts offline and ensured they were working, I wouldn't know if they were going to work online.

Should I edit everything offline and upload it all back to the server when it works? What happens if a php or python script executes one way on my local machine than on the server?

答:
Version control will only help to the extent that you will be able to go back to previous (hopefully working) versions.

It will not help with botched deployments and changes.

You need to have a test environment - a web server that you can put the changes on and test them and only when happy, push to a live (publicly visible) web server.


答:
You're missing the point of agile a little bit.  What you are calling a user story, I see as at least six: one bare-bones search, and one for each of your bullet points.  By all means, make enough plans to avoid painting yourself into a corner that's going to be expensive to get out of, but the whole idea is that you provide the minimum needed to deliver some value, and do it quickly enough to get rapid feedback.

When you divide a story up like that, it not only makes it easier to estimate, it allows the product owner to prioritize in a more fine-grained manner.  Certainly they like the ability to sort the search results, but maybe it's not as important as another item on the backlog that's completely unrelated to search.

Also, on the idea of programmers needing everything specified, try to look at it from the customer's point of view.  A lot of times, it's like you're going in to buy a car, and the salesman is asking what color you want for the windshield wiper knob.  A lot of details we might find important are completely irrelevant from a customer point of view.  I've worked where requirements are highly over-specified, and trust me, it is not very fun.  The kind of latitude you're complaining about, a lot of programmers would love to have.

Title: How much detail about a user story can a developer expect?

Body:
The biggest drawback of agile development I have experienced is that people not involved in development focus on the mantra that a user story (3-10 ideal person days) should not contain more than 1-3 sentences like:

As a customer, I can use free-text search so that I can find the products I'm looking for.

Giving this sentence, project managers expect me as a developer to commit to an estimate and develop the story. They assume that agile development means that sentences like this are all they have to provide to developers.

I won't blame them because the well-known literature about agile development creates the impression that this would actually work. I've read something like 2 pages in natural language per story in "Planning XP", but that's it. Because "working software" is favored over "comprehensive documentation", this topic seems to be generally avoided.

The reality is, of course, that if the developer is given the chance to do so, an interview with the customer brings up a long list of requirements that the customer has about the story:

We need boolean operators like AND and OR.

We need fuzzy search an all terms.

We need to search by single words as well as by phrase.

We don't want to find products that meet criteria X, Y, and Z.

We want to sort the result. Oh, and by the way, the user can select the sort criteria in a combo box with options a, b, and c.

So you see that I'm not talking about technical details or software design or even implementation details. It's pure requirements. The longer we talk the more the customer realizes that there's actually quite a lot to say about what they want.

But often enough I find myself in the situation that such information is not provided or in very shoddy fashion. Neither is it possible that I do the interview, nor does the person that would be in the position to do the interview provide me with a result of it.

Sometimes, managers even come up with technical details like "we want Lucene search" but they don't want to think about if they want find only product names or also product descriptions. Sometimes I think they are just lazy ;)

For me, this is the top issue in projects I work in (e-business web application, 500-2000 person days per project). I've addressed this problem often enough, and managers are aware that most developers have a problem with the situation. But they believe that developers are just too much "perfectionists". They seem annoyed that developers "always want to have everything specified".

Due to the lack of generally acknowledged numbers it's hard to argue. Everybody knows how long an iteration should be. But nobody can tell how much requirements are needed to estimate and develop a story.

Do you have some reference?


答:
In my experiences, many of the changes or projects I'm working on deal with this very thing.  Custom X wants something and they have an idea of what they want, but they only give you a small email worth of requirements.  That's mostly because the client doesn't 'exactly' know what they want.  That's why most of our client service department's job is fleshing out those customer demands and filtering the needed information while also predicting what the client REALLY is going to want, or what they really need.

Say a client (for me) wants a section of our web application to return them a list of all phone numbers.  They never specify if they mean physical ones, logical ones, ones that are assigned to a person or a location, ect.  They simply want all the phone numbers.  As a developer, I can sit there and think of a dozen or more questions that I would need to ask the client, much like you have.  But, as you say, that's not possible.  That's why having a good client services department that knows the product and the client is invaluable.

When that kind of call comes in to our client reps, they are able to elaborate on it with the client, knowing what they need to ask them to get the right questions answered.  They also have the forethought to know what the client has asked for in the past and they know enough about the systems that we develop that they can say yes or no to something without even asking the client.

Sure, you'll have a lot of cases where the client will still need something else that both you and client services missed, but that's always going to happen.  Your goal, and the goal of client services, should be minimizing the lag time between you developing something and you getting it back from the client with changes that need to be made.  And this just comes down to communication and training with your client services.

Maybe it's not as feasible for you as it is where I am, but having a good line of communication and trust with your client reps will almost always help you by degrees, and it will reduce your frustration and increase the client's satisfaction.  Also, you can more easily give a time frame for your projects rather then shrugging your shoulders and saying "I don't know the full scope of the project, so I don't know how long it'll take".  We're having the same problem here, and better communication and training is what's helping us create reasonable deadlines and hit them consistently.


问:
Best way to set sys.path for "hot library" development in Python?
I have my Python source structured as follows:

```<code>+-branchname/
  +-dst/
  +-src/
  | +-library/
  | | +-cleese/
  | | | +-test/
  | | | | +-__init__.py
  | | | | +-test_cleese.py
  | | | +-__init__.py
  | | | +-cleese.py
  | | +-palin/
  | |   +-test/
  | |   | +-__init__.py
  | |   | +-test_palin.py
  | |   +-__init__.py
  | |   +-palin.py
  | +-productline/
  |    +-circus/
  |    | +-test/
  |    | | +-__init__.py
  |    | | +-test_circus.py
  |    | +-__init__.py
  |    | +-circus.py
  |    +-grail/
  |      +-test/
  |      | +-__init__.py
  |      | +-test_grail.py
  |      +-__init__.py
  |      +-grail.py
  +-branch_root_marker
</code>```

Entry points are in circus/ and grail/, as well as (possibly) each of the test/ directories, depending on how testing is implemented.

I have multiple copies of this source tree present on local storage at any one point in time (corresponding to various maintenance and feature branches), so I cannot set PYTHONPATH in my shell without some pain. (I would need to remember to change it each time I switched to work on a different branch, and I am very forgetful)

Instead, I have some logic that walks up the file tree, starting at the "current" file location, moving from leaf towards root, looking for branch_root_marker. Once the root directory of the current working copy is found, it adds library/ and productline/ to sys.path. I call this function from each entry-point in the system.

```<code>"""Add working copy (branch) to sys.path"""

import os
import sys

def _setpath():
    """Add working copy (branch) to sys.path"""

    markerfile = "branch_root_marker"
    path = ""
    if ("__file__" in locals() or globals()) and __file__ != "__main__":
        path = __file__
    elif sys.argv and sys.argv[0] and not sys.argv[0] == "-c":
        path = sys.argv[0]
    path = os.path.realpath(os.path.expandvars(path))
    while os.path.exists(path):
        if os.path.exists(os.path.join(path, markerfile)):
            break
        else:
            path = os.path.dirname(path)
        errormsg = " ".join(("Could not find", markerfile))
        assert os.path.exists(path) and path != os.path.dirname(path), errormsg

    path = os.path.join(path, "src")
    (_, subdir_list, _) = os.walk(path).next()
    for subdir in subdir_list:
        if subdir.startswith("."):
            continue
        subdir_path = os.path.join(path, subdir)
        if subdir_path in sys.path:
            continue
        sys.path.append(subdir_path)
_setpath()
</code>```

Currently, I need to keep a separate but identical copy of this function in each entry point. Even though it is quite a short function, I am quite distressed by how fragrantly the DRY principle is being violated by this approach, and would love to find a way to keep the sys.path modification logic in one place. Any ideas?

Note:- One thing that springs to mind is to install the sys.path modifying logic into a common location that is always on PYTHONPATH. Whilst this is not a terrible idea, it means introducing an installation step that needs to be carried out each time I move to a fresh environment; another thing to remember (or, more likely, forget), so I would like to avoid this if at all possible.

答:
Does your revision control allows you to run a script on sync/clone/update? If so you can configure appropriate files in each directory of your source tree so that the root directory is referenced explicitly.

For example if you were using mercurial then this might help, from http://mercurial.selenic.com/wiki/TipsAndTricks:

Avoid merging autogenerated (binary) files (PDF)

Creating pdfs on the fly

This assumes that you always want to have the PDFs you can use, but that you don't need to track them - only their contents (and those are defined in the tex files).

For this you add an update hook which crates the pdf whenever you update to a revision.

Edit your .hg/hgrc to include the hooks section with an update hook:

[hooks]
update.create_pdfs = latex your_tex_file.tex
To make this still a bit easier, you can use a versioned script which creates all pdf. that way you can just call the script and don't need to worry about editing the .hg/hgrc when you add text files or change the call.

I use a python script for platform compatibility:

parse_latex.py:

Toggle line numbers
   1 #!/usr/bin/env python
   2 from subprocess import call
   3 for i in ("file1.tex", "file2.tex"):
   4   call(["latex", i])
.hg/hgrc:

[hooks]
update.create = ./parse_latex.py


答:
In a pure stack, the only allowable operations are Push, Pop, and Peek but in practical terms, that's not exactly true.  Or rather, the Peek operation often allows you to look at any position on the stack, but the catch is that it's relative to the one end of the stack.

So, as others have said, an array is random access and everything's referenced to the beginning of the array.

In a stack, you can only add/remove at the working end of the stack, but you still have random access read but it's referenced to the working end.  That's the fundamental difference.

For instance, when you pass parameters on a stack to a function, the callee doesn't have to pop the parameters off to look at them.  It just pushes local variables on the stack and references all the local variables and parameters based on an offset from the stack pointer.  If you were using just an array, then how would the callee know where to look for its parameters?  When the callee is done, it pops off its local variables, pushes a return value, returns control to the caller, and the caller pops the return value (if any), and then pops the parameters off the stack.  The beauty is that it works no matter how far nested you are into your function calls (assuming you don't run out of stack space).

That's one particular use/implementation, but it illustrates the difference:  array is always referenced from the beginning but stacks are always referenced from some working end position.

One possible implementation of a stack is an array plus an index to remember where the working end is.

Title: What is the difference between an Array and a Stack?

Body:
According to Wikipedia, a stack:

is a last in, first out (LIFO) abstract data type and linear data structure.

While an array:

is a data structure consisting of a collection of elements (values or variables), each identified by at least one array index or key.

As far as I understand, they are fairly similar. So, what are the main differences? If they are not the same, what can an array do that a stack can't and vice-versa?


答:
In my experience, most companies have three tiers of standardization:

Standard developer images - Standard hardware, and the software that the developer needs to communicate with the rest of the company. Email, Office (or equivalent), standard browser, IM, service packs, sometimes Visual Studio if TFS is required universally, etc.

Standard apps - Apps that some people need, but not others. You maybe don't need 4 different paint apps running around the company, or you don't want to pay for licenses for people that are just going to ignore the app. These are good to get and have in a central location to cut down on bandwidth/wait time too.

One-off apps - Stuff that developers want/need. Most companies I've seen allow developers leeway to install what they want/need. Alternative browsers, profiler of choice, visual studio plug-ins, etc. Things that are free, un-supported by IT, and don't cause compatibility issues with others.

Title: Working machines of developers - in what ways are they usually standardized or restricted?

Body:
My boss wants to introduce new guidelines for the computers in our company. This means that the software environments will be completely standardized with a predefined set of tools. The goal is that all machines are completely reproducable and exchangable.

I'm wondering what the guidelines for developer's computers are in large companies, such as Google or Microsoft, especially companies which are certified according to some standard (e.g. ISO 9001). Do they allow developers to install software from the internet if they need it for some small task? (e.g. a code compare tool, CygWin, Windows Service Packs) or do they really want all needed tools in a fixed, predefined environment where all proposed changes must be discussed with a system administrator first?


答:
You need a test server.

If your own PC runs Linux or some Unix flavor already, installing Apache should be easy. If it doesn't, build your own server - simply pick a decent Linux distro (I recommend debian, it's super-reliable and easy enough to install, but there's plenty others to choose from), and install it either on a spare PC you may have lying around, or inside a virtual machine on your own PC.

The added benefit of a dedicated test server is that you can test not only your code, but also your deployment procedure, especially if the test server is very similar to the actual environment (same directory structure, same software versions, etc.).

You'll also pick up the basics of *nix system adminstration, which is good because you'll understand better what you are doing as a programmer.

Title: Managing a website with version control?

Body:
The small website I built a long time ago is starting to pick up a little and I'm starting to run into problems with making changes. Originally, all the pages were .html and I would edit and test them offline to make sure everything worked. Then I realized how helpful php includes were, so I changed everything to .php and used includes. Without apache, I could no longer test offline, so with Filezilla, I would choose the "view/edit" option on files that were already on the server, edit them, and then have them uploaded again. This is what I've been doing so far and it's worked pretty well for the most part. I just save the temp file that filezilla creates, and let it upload it back to the server.

Yesterday, I realized that one of the javascript files I had worked on the day before had been replaced by an empty file. This was something to do with sublime text keeping the non-existent temp file open/filezilla uploading an empty file - I'm not really sure what happened, but it shouldn't have been able to happen. And now, I need to change the design of the site, and doing that one page at a time would be noticeable, so I need to do it offline first.

I would like to use version control and install apache so that I can completely test my site offline, but there are a couple problems I have with this. The first is that I have a Forum on the site. I could install mysql and export the tables, then import them offline, but then, while people are making posts on the website, the offline copy becomes out of date and I can no longer upload that back to the server. I also have some Python scripts on the site using WSGI. My webhost's settings are very specific, so if I wrote python scripts offline and ensured they were working, I wouldn't know if they were going to work online.

Should I edit everything offline and upload it all back to the server when it works? What happens if a php or python script executes one way on my local machine than on the server?