答:
Message passing is a different way of handling the need in OO code for one object to get another object (or potentially itself) to do something.

In most modern languages that descend from the C++ approach we do that with method calls. In this case the called object (via its class definition) puts a big list of what method calls it accepts and then the coder of the calling object simply write the the call:

```<code>public void doSomething ( String input )
...
other_object.dosomething ( local )
</code>```

For statically typed languages then compiler can then check the type of the thing being called and confirm that the method has been declared. For dynamically typed languages then that is carried out at runtime.

But in essence what happens is that a bundle of variables is sent to a specific block of code.

Message passing

In message passing languages (such as Objective C) instead of methods there are recievers, but broadly the approach of defining them and calling them is much the same - the difference is the way its handled.

In a message passed language the compiler may check that the receiver that you've called exists, but at worst it will pop up a warning to say it's not sure that its there. This is because at run time what will happen is that a block of code on the receiving object will be called passing both the bundle of variables and the signature of the receiver you want to call. That block of code then looks for the receiver and calls it. However if the receiver doesn't exist then the code will simply return a default value.

As a result one of the oddities found when moving from C++/Java -> Objective C is understanding that you can "call a method" on an object that wasn't declared on the compile-time type, and didn't even exist on the run-time type ... and that the call would not result in an exception being thrown but in fact a result being passed back.

The advantages of this approach are that it flattens the subclass hierachy and avoids most of the needs for interfaces/multiple inheritance/duck types. It also allows objects to define default behaviour when asked to do something that they don't have a receiver for (commonly "if I don't do it, forward the request to this other object"). It can also simplify the linking to callbacks (e.g. for UI elements and timed events) particularly over statically typed languages such as Java (so you can have the button call the receiver "runTest" rather than call the "actionPerformed" method on the inner class "RunTestButtonListener" which does the call for you).

However it would seem to be at the cost of the need for additional checking by the developer that the call they think they are making is on the right object with the right type and passing the right parameters in the right order, because the compiler might not warn you and it will run perfectly well at runtime (just returning a default response). There is also arguably a performance hit from the extra look-up and paramter passing.

These days, dynamically typed languages can give a lot of the benefits of message passed OO with less of the issues.

Title: What is message passing in OO?

Body:
I've been studying OO programming, primarily in C++, C# and Java. I thought I had a good grasp on it with my understanding of encapsulation, inheritance and polymorphism.

One frequently referenced concept when discussing OO is "message passing". Apparently, this is something that is not used whilst OO programming in today's mainstream languages, but is supported by Smalltalk.

My questions are:

What is message passing?

Is there any support for this "message passing" in C++, C# or Java?

Body:
Message passing is a different way of handling the need in OO code for one object to get another object (or potentially itself) to do something.

In most modern languages that descend from the C++ approach we do that with method calls. In this case the called object (via its class definition) puts a big list of what method calls it accepts and then the coder of the calling object simply write the the call:

public void doSomething ( String input )
...
other_object.dosomething ( local )

For statically typed languages then compiler can then check the type of the thing being called and confirm that the method has been declared. For dynamically typed languages then that is carried out at runtime.

But in essence what happens is that a bundle of variables is sent to a specific block of code.

Message passing

In message passing languages (such as Objective C) instead of methods there are recievers, but broadly the approach of defining them and calling them is much the same - the difference is the way its handled.

In a message passed language the compiler may check that the receiver that you've called exists, but at worst it will pop up a warning to say it's not sure that its there. This is because at run time what will happen is that a block of code on the receiving object will be called passing both the bundle of variables and the signature of the receiver you want to call. That block of code then looks for the receiver and calls it. However if the receiver doesn't exist then the code will simply return a default value.

As a result one of the oddities found when moving from C++/Java -> Objective C is understanding that you can "call a method" on an object that wasn't declared on the compile-time type, and didn't even exist on the run-time type ... and that the call would not result in an exception being thrown but in fact a result being passed back.

The advantages of this approach are that it flattens the subclass hierachy and avoids most of the needs for interfaces/multiple inheritance/duck types. It also allows objects to define default behaviour when asked to do something that they don't have a receiver for (commonly "if I don't do it, forward the request to this other object"). It can also simplify the linking to callbacks (e.g. for UI elements and timed events) particularly over statically typed languages such as Java (so you can have the button call the receiver "runTest" rather than call the "actionPerformed" method on the inner class "RunTestButtonListener" which does the call for you).

However it would seem to be at the cost of the need for additional checking by the developer that the call they think they are making is on the right object with the right type and passing the right parameters in the right order, because the compiler might not warn you and it will run perfectly well at runtime (just returning a default response). There is also arguably a performance hit from the extra look-up and paramter passing.

These days, dynamically typed languages can give a lot of the benefits of message passed OO with less of the issues.


问:
Is it a waste of time to free resources before I exit a process?
Let's consider a fictional program that builds a linked list in the heap, and at the end of the program there is a loop that frees all the nodes, and then exits. For this case let's say the linked list is just 500K of memory, and no special space managing is required.

Is that a waste of time, because the OS will do that anyway?

Will there be a different behavior later?

Is that different according to the OS version?

I'm mainly interested in UNIX based systems, but any information will be appreciated. I had today my first lesson in OS course and I'm wondering about that now.

Edit: Since a lot of people here are concerned about side effects, and general 'good programming practice' and so. You are right! I agree 100% with your statements. But my question is only hypothetical, I want to know how the OS manages this. So please leave out things like 'finding other bugs when freeing all memory'.

答:
If you implement your own data type "linked list" not writing a cleanup routine/deconstructor will give you more headaches in the long run than you might think.

Without cleanup code reusing what you wrote will be much harder since your type cannot be used without taking special care (e.g. never create them in a function or loop, but preferably exclusively in main).

Do yourself and everybody else a favor and just write you list_cleanup or ~List.

ContentLicense: CC BY-SA 3.0


问:
How can I work efficiently on a desktop sharing workflow?
I am a freelance Magento developer, based in Spain. One of my clients is a Germany based web development company and they're asking me something I think it's impossible. OK, maybe not impossible but definitely not a preferred way of doing things.

One of their clients has a Magento Entreprise installation, which is the paid (and I think proprietary) version of Magento. Their client has forbidden them to download the files from his server. My client is asking me now to study one particular module of the application in order to interact with it from a custom module I'll have to develop.

As they have a read-only ssh access to their client's server, they came up with this solution: Set up a desktop/screen sharing session between one of their developer's station and mine, alongsides with a skype conversation. Their idea is that I'll say to the developer:

show me file foo.php

The developer will then open this foo.php file in his IDE. I'll have then to ask him to show me the bar method, the parent class, etc...

Remember that it's a read-only session, so forget about putting a Zend_Debug::log() anywhere, and don't even think about a xDebug breakpoint (they don't use any kind of debugger, sic). Their client has also forbidden them to use any version control system...

My first reaction when they explained to me this was (and I actually did say it outloud to them):

Well, find another client.

but they took it as a joke from me. I understand that in a business point of view rejecting a client is not a good practice, but I think that the condition of this assignment make it impossible to complete.

At least according to my workflow. I mean, the way I work or learn a new framework/program is:

download all files and copy of db on my pc

create a git repository and a branch

run the application locally

use breakpoints

use Zend_Debug::log()

write the code and tests

commit to git repo

upload to (test/staging first if there is one, production if not) server

I have agreed to try the desktop sharing session, although I think it will be a waste of time. On one hand I don't mind, they pay me for that time, but I know me and I don't like the sensation of loosing my time. On the other hand, I have other clients for whom I can work according to my workflow.

I am about to say to them that I cannot (don't want to) do it. Well, I'll first try this desktop sharing session: maybe I'm wrong and it can actually work. But I like to consider myself as a professional, and I know that I don't know everything. So I try to keep an open mind and I am always willing to learn new stuff.

So my questions are:

Can this desktop-sharing workflow work? What should be done in order to take the most of it?

Taking into account all the obstacles (geographic locations, no local, no git), is there another way for me to work on that project?

答:
Get on a train and sit next to the guy.  No, really.  And while you are there you might be able to talk to the right people and find some way you can do the work properly from your nice warm country.

If that's not feasible and your local company is forcing you to go ahead with the screenshare, you need to leave.  I realise that might be tricky in Spain at the moment, but there are other countries including Spanish-speaking ones, that are doing pretty well in the computing field.  Except the trains aren't as good there.

OwnerDisplayName: OSdave


问:
Advantages of using business logic in model
In an MVC framework i have often heard that use business logic in a model. But i think using the business logic in controller would run faster as view is directly connected to controller. I want to know what are the advantages of using a business logic in model?</p>

答:
Model Concept....

The model manages the behavior and data of the application domain, responds to requests for information about its state (usually from the view), and responds to instructions to change state (usually from the controller). In event-driven systems, the model notifies observers (usually views) when the information changes so that they can react.

View Concept....

The view renders the model into a form suitable for interaction, typically a user interface element. Multiple views can exist for a single model for different purposes. A view port typically has a one to one correspondence with a display surface and knows how to render to it.

Controller Concept...

The controller receives user input and initiates a response by making calls on model objects. A controller accepts input from the user and instructs the model and a view port to perform actions based on that input.

MVC

also see the screenshot

Please read carefully and reply me if you have any Query regarding this @shayan


问:
How you prepared for your .NET interview?
I gave many interviews in the last few years and each time I found the interviewers are not satisfied with what I know. My first company only developed desktop Windows applications using .NET. They had nothing to do with features like: Remoting etc. We also had limited use of Generics, Reflection and Multi-threading.

When I appeared for the interviews, I was asked questions on above features even when I told them that I don't have real-life experience.

Now the .NET interviews are even more complex. Seeing my experience, the interviewers target the latest framework. I have no real-life exposure to the new features and technologies like WPF, WCF etc.

Please suggest me how to effectively prepare for the .NET interview. I have 3 years experience in .NET but I only developed Windows based applications. At present I work on .NET Framework 3.5. I never worked on ASP.NET, as in my present company I work on PHP for web-applications.

答:
Even at a junior level, if someone has been using .net 3.5 then I would certainly expect them to be comfortable using generics. At a more intermediate level I would expect at least some knowledge of reflection and multi-threading.

So my first piece of advice is, if you want to progress your skills in programming then you must devote at least a little bit of your own time to learning and keeping up with current developments in the field. I'm not talking about cutting edge stuff here - if you're a good programmer and have been using .net 2+ for a significant amount of time if you're not comfortable with generics by now then it tells me you're not keeping your skills up to date at all. This applies if, as in your case, you don't have the opportunity to learn in the workplace but also if you're lucky enough to be somewhere where skills development is valued. You can get this knowledge by reading books, blogs and by supplementing that knowledge by applying it to some personal/open source projects.

My second piece of advice is, if you have a lot of experience with windows apps and you want to join a company that is doing web development then you should understand that you're looking at what is potentially a very different job despite it having .net in common. So, either apply for jobs where your current experience is going to be valuable, or gain the skills in those areas (see above) before applying, or accept that you're going to be applying for potentially more junior jobs than if you were applying for windows app development roles and treat it as a stepping stone to a more senior position.

ContentLicense: CC BY-SA 2.5


答: If your client has so much money to spend, they would better pay you a flight to Germany, at that client's place, where you can work with that client on his machines. Programming by the word of mouth is a nonsense and it would work until your client would really realize how much money they are loosing.</p>

Title: How can I work efficiently on a desktop sharing workflow?

Body:
I am a freelance Magento developer, based in Spain. One of my clients is a Germany based web development company and they're asking me something I think it's impossible. OK, maybe not impossible but definitely not a preferred way of doing things.

One of their clients has a Magento Entreprise installation, which is the paid (and I think proprietary) version of Magento. Their client has forbidden them to download the files from his server. My client is asking me now to study one particular module of the application in order to interact with it from a custom module I'll have to develop.

As they have a read-only ssh access to their client's server, they came up with this solution: Set up a desktop/screen sharing session between one of their developer's station and mine, alongsides with a skype conversation. Their idea is that I'll say to the developer:

show me file foo.php

The developer will then open this foo.php file in his IDE. I'll have then to ask him to show me the bar method, the parent class, etc...

Remember that it's a read-only session, so forget about putting a Zend_Debug::log() anywhere, and don't even think about a xDebug breakpoint (they don't use any kind of debugger, sic). Their client has also forbidden them to use any version control system...

My first reaction when they explained to me this was (and I actually did say it outloud to them):

Well, find another client.

but they took it as a joke from me. I understand that in a business point of view rejecting a client is not a good practice, but I think that the condition of this assignment make it impossible to complete.

At least according to my workflow. I mean, the way I work or learn a new framework/program is:

download all files and copy of db on my pc

create a git repository and a branch

run the application locally

use breakpoints

use Zend_Debug::log()

write the code and tests

commit to git repo

upload to (test/staging first if there is one, production if not) server

I have agreed to try the desktop sharing session, although I think it will be a waste of time. On one hand I don't mind, they pay me for that time, but I know me and I don't like the sensation of loosing my time. On the other hand, I have other clients for whom I can work according to my workflow.

I am about to say to them that I cannot (don't want to) do it. Well, I'll first try this desktop sharing session: maybe I'm wrong and it can actually work. But I like to consider myself as a professional, and I know that I don't know everything. So I try to keep an open mind and I am always willing to learn new stuff.

So my questions are:

Can this desktop-sharing workflow work? What should be done in order to take the most of it?

Taking into account all the obstacles (geographic locations, no local, no git), is there another way for me to work on that project?


问:
Steps to Learn a Programming Language / Framework
I am new to programming. I am eager to learn new programming languages / frameworks.

Can any one suggest the best way to master programming languages / frameworks?

答: I tend to try to find something that is a good fit for the language/framework and is something I already know how to do. That allows me to start with getting a feel for the language/framework, without the "how do I do this" and impedance mismatch between "this is what's needed but that is what's provided".</p>


答:
There's no "best way". Best I can offer only a few recommendations to make the learning easier.

Start project with relatively fast gratification. Simple games tend to work quite well - I learned my first languages (Basic, Pascal, C) this way and ended up with published game later.

Alternatively I like also Project Euler. It's set of problems where you can progress in small steps towards more complex algorithms. Problems are more algorithmic and mathematical in their nature which may be off-putting for some.

Last but not least, select easier language: my choice would be Python.

Title: Steps to Learn a Programming Language / Framework

Body:
I am new to programming. I am eager to learn new programming languages / frameworks.

Can any one suggest the best way to master programming languages / frameworks?


问:
Software solution from the 2000's, should I attempt to patch or remake the whole thing?
I was sent out to discuss a system that a certain company is currently using and what should be done with it.

The company manufactures various carton displays. This system was developed to keep track of clients, orders and prices. Lots have happened since the system was created and the system is now, as the manager described it, "locked up" and "problematic", which I translate as "not dynamic" and "unstable".

Some info about the system

It was developed around the year 2000

Fairly small system, 2-5 users, 6 forms, ~8 tables with average quantities of data

Built on early Visual Basic, forms created with the drag and drop design. Interface is basically just a window with a menu and some forms

Uses MSSQL database (SQL2005 server) to store data and ODBC driver to query, data was migrated from excel before this system, and before excel it was handled, calculated and written by hand and paper

Users work in Microsoft XP environment (and up)

Their main problem is that they can't adjust and calculate prices, can't add new carton types etc, correctly anymore because they can't (or rather, they don't know how to) touch the data on the server.

I suggested 3 possible solutions

Attempt to patch the current system

Create a fresh new interface (preferably similar environment, VB.net or VB based)

Bring it back to an Excel solution, considering it is such a small system

There might be more options, but these are the ones I could think of.

My questions are

What should I recommend and why?

What is or could be the pros and cons of these alternatives?

Are there other (possibly better) alternatives?

答:
Rewriting the interface is an excellent option, given that the system is relatively small. Advantages are -

Improved stability (assuming you do it well!)

Improved maintainability

Modern interface

The main disadvantage is that it will still probably cost a fair bit more than hacking the existing code.


答:
Another option could be a compromise between rewriting the whole thing and hacking the existing app.

Give them the new functionality in a new application built from scratch.

This could potentially be easier to do, and not cost as much as a full rewrite.

Once this has been done and they are happy they can add/update data, it opens the doot ro a phase two could be replacing the existing funcationality in the new app.

This might be a more palatable approach.

Title: Software solution from the 2000's, should I attempt to patch or remake the whole thing?

Body:
I was sent out to discuss a system that a certain company is currently using and what should be done with it.

The company manufactures various carton displays. This system was developed to keep track of clients, orders and prices. Lots have happened since the system was created and the system is now, as the manager described it, "locked up" and "problematic", which I translate as "not dynamic" and "unstable".

Some info about the system

It was developed around the year 2000

Fairly small system, 2-5 users, 6 forms, ~8 tables with average quantities of data

Built on early Visual Basic, forms created with the drag and drop design. Interface is basically just a window with a menu and some forms

Uses MSSQL database (SQL2005 server) to store data and ODBC driver to query, data was migrated from excel before this system, and before excel it was handled, calculated and written by hand and paper

Users work in Microsoft XP environment (and up)

Their main problem is that they can't adjust and calculate prices, can't add new carton types etc, correctly anymore because they can't (or rather, they don't know how to) touch the data on the server.

I suggested 3 possible solutions

Attempt to patch the current system

Create a fresh new interface (preferably similar environment, VB.net or VB based)

Bring it back to an Excel solution, considering it is such a small system

There might be more options, but these are the ones I could think of.

My questions are

What should I recommend and why?

What is or could be the pros and cons of these alternatives?

Are there other (possibly better) alternatives?


问:
Is listing developer's full names in splash screen or about box still a widely spread and desirable practice?
Just like in the closing credits of movies, some software vendors list the full names of the team that worked on the piece of software you are using.

They are usually displayed in the splash screen (Photoshop)

... or in the about box (Traktor).

In the demoscene, it is a mandatory practice, like in the movie industry.

How do you see that in your own software? Is there any reason why not doing it? Is there any reason encouraging companies to do it?

答:
It seems that the main reason why programmer's names are listed in startup screens or about box is related to moral rights.

While copyright is transferable (usually automatically when working as an employee), moral rights can't be transmitted, regardless your status.

Therefore, employers must list names if programmers require it.

Please note that this law is not completely integrated in every country, and it seems more complicated that we think for an employee to ask that to the employer. Therefore it's generally an initiative of the latter.


答:
Something with only 6 forms and such should  be easy to rebuild on a more modern framework. I've worked with migrating VB6 projects that had around 200 forms along with dozens of classes and database tables. It doesn't sound like you're looking at anything that messy but looks can be deceiving.

I'd have to analyze the code, the database and business requirements to say if rewriting or refactoring the existing code base would be best. Given what you've said, I'd lean toward a rewrite. But, there could be hidden difficulties that you don't see right now.


答:
I have slightly different advice the most of the responses so far.

Attempt to patch the current system

I would at least learn the current system well enough to explain to the client how to use it.  I would take this time to explain the flaws in their current system, avoid negative words, just tell them what it cannot do even if all the known bugs were fixed.

Create a fresh new interface (preferably similar environment, VB.net
  or VB based)

After you have learned everything you can with their current setup.  Provide them with options, if you can address their concerns with their current system, there really isn't anything wrong with their current system.  The only concern of course is that Visual Basic 6 support might not exist in 5 years.

Another concern is the way it communicates with the database.  Microsoft is slowly getting rid of some of the older ways to communicate with its database products ( Access, MSSQL ) so the way you interact with those products will determine if the solution can be used on Windows 9, and Windows 10 in the future.

This answer entirely depends on the fact they have the source to the application itself.  If they do not have the source then it will be hard to address their concerns, fix the current major bugs, or even make it a tool they can actually use.

I don't feel there is anything "wrong" with a Visual Basic 6 application, besides the fact, its support for future versions is unknown.  Even today with Windows 7 and 64-bit operating systems its getting harder and harder to support.  This is a major reason a rewrite into a modern language with proper 64-bit support might be a good idea.

If they don't have the source at that point a rewrite is really their only solution.


问:
How can I refactor a code base while others rapidly commit to it?
I'm on a private project that eventually will become open source. We have a few team members, talented enough with the technologies to build apps, but not dedicated developers who can write clean/beautiful and most importantly long-term maintainable code.

I've set out to refactor the code base, but it's a bit unwieldy as someone in the team out in another country I'm not in regular contact with could be updating this totally separate thing.

I know one solution is to communicate rapidly or adopt better PM practices, but we're just not that big yet. I just want to clean up the code and merge nicely into what he has updated. Would using a branch be a suitable plan? A best-effort-merge? Something else?

答:
Yes, a branch is a good solution for this.

I would suggest you start working on this on a branch and make sure it applies cleanly on top of your current HEAD in the meantime (i.e. make test rebases and merges at regular intervals to make sure you can apply your changes easily and your tests still pass -- also look into git rerere for help from git with this). Then once you are done rebase and merge your changes into your HEAD.

The sooner you start working on this the better since changing architecture becomes more and more work the colder the code gets. Also, there might be many instances of handcoded code scattered throughout the code base where e.g. your new and shiner helper function might have made things much simpler.


答:
The very best way to fire this client is to say, "Given the constraints imposed on my access to the system and the impact that this will have on my productivity, it is going to take dramatically more time than usual to get this work done. As a result, my price for this project is going up by X%." Make X a number between 300 and 1000.

They'll be shocked and horrified at this new expense. They'll either work out a sane level of access for you, or they'll go find another sucker. Or if they take you up on the change, then do the job and cash the check and be paid for your time.


问:
Variable naming conventions?
I've just started using ReSharper (for C#) and I kind of like its code smells finder, it shows me some things about my writing that I meant to fix a long time ago (mainly variable naming conventions).

It caused me to reconsider some of my naming conventions for methods and instance variables. ReSharper suggests that instance variable be lower camel case and begin with an underscore. For a while I meant to make all my local variables lower camel case but is the underscore necessary? Do you find it comfortable? I don't like this convention but I also haven't tried it yet, what is you opinion of it?

The second thing it prompted me to re-evaluate is my naming conventions for GUI event handlers. I usually use the VS standard of ControlName_Action and my controls usually use hungarian notation (as a suffix, to help clarify in code what is visible to the user and what isn't when dealing with similarly named variable) so I end up with OK_btn_Click(), what is your opinion of that? Should I succumb to the ReSharper convention or there are other equally valid options?

答:
In C# starting protected or public name with underscore is against Common Language Specification. It's correct only in case of private members.

From MSDN:

To fully interact with other objects regardless of the language they
  were implemented in, objects must expose to callers only those
  features that are common to all the languages they must interoperate
  with. For this reason, the Common Language Specification (CLS), which
  is a set of basic language features needed by many applications, has
  been defined.

See: http://msdn.microsoft.com/en-us/library/12a7a7h3.aspx

Here you can read warning about underscore:

Element names starting with an underscore (_) are not part of the
  Common Language Specification (CLS), so CLS-compliant code cannot use
  a component that defines such names. However, an underscore in any
  other position in an element name is CLS-compliant.

See: http://msdn.microsoft.com/en-us/library/81ed9a62.aspx

Protected members are problem because you can inherit from class written in another language.

But maybe it's not problem in your case if you don't need CLS-compilant code.

Title: Variable naming conventions?


答:
Marketing Approach - If you have too much work or you are getting too much of the type of work you don't like, you're not charging enough.

Customer Is Always Right Approach - They seem to be aware of the situation they have created and are willing to pay for the inefficient use of your time. It's not like you are bleeding them of extra hours. They cut themselves.

Programmer's Approach - stick to your principles and avoid the mental anquish and focus on doing the kind of work you like.

Reality Approach - Get over it and get paid!

True Story - A former employer decided to update the website I built on their own and crashed the whole thing. I got a phone call just as I was finishing dinner. After 2 hours of "talking" them through the fix, we go it going. I charged them $500. They questioned paying such a high hourly-rate and I asked them if they would prefer if I took longer. They took the risk of the cheap approach and had no problem calling me at odd hours to bail them out. I did them a favor and asked for one in return. They decided to pay me. Never heard from again. Oh, well.


问:
when to introduce an application services tier in an n-tier application
I am developing a web based application whose primary objective is to fetch data from the database, display it on the UI, take in user inputs and write them back to the database. The application is not going to be doing any industrial strength algorithm crunching, but will be receiving a very high number of hits at peak times (described below) which will be changing thru the day.

The layers are your typical Presentation, Business, Data. The data layer is taken care of by the database server. The business layer will contain the DAL component to access the database server over tcp. The choices I have to separate these layers into tiers are:

The presentation and business layers can be either kept on the same tier.

The presentation layer on a separate tier by itself and the business layer on a separate tier by itself.

In the case of choice 2, the business layer will be accessed by the presentation layer using a WCF service either over http or tcp.

I don't see any heavy processing being done on the Business layer, so I am leaning towards option 1 above. I also feel for the same reason, adding a new tier will only introduce the network latency. However, in terms of scalability in case I need to scale up or scale out, which is a better way to go? This application will need to be able to support up to 6 million users an hour. There will be a reasonable amount of data in each user session, storing user's preferences and other details. I will be using page level caching as well.

答:
I would agree with your initial assessment. It probably doesn't make much sense to add an additional network hop into the processing of your system. The reason people separate tiers physically is for reuse across applications. That is you have multiple applications calling the same services to perform a part of their work. As you mentioned, there's not a lot of built in logic the business layer provides; and so far there is only one application using it.

It's good that you have separated the tiers logically but a physical separation at this time might be overkill.

Update to address scalability concerns

I would still argue that keeping the BLL on the same physical tier as the presentation layer is the best approach for now. You can scale out by adding more presentation/bll nodes (already addressed if you're using a fat client deployment, simple enough to do with a web application). Also if you find that the database is becoming the bottleneck, most databases support clustering/sharding and other neat tricks to scale out. Only after I've gone down both of these paths (and of course adding in distributed caching), would I look at adding another physical tier.

Before you can go there however, I'd start looking at making a more "hearty" Business Layer than a simple facade to the Data Access Layer. The first step is to consider using a powerful O/RM that does the data mapping for you. Then consider making your business objects more intelligent. There are reams of paper written on Domain Driven Design (the book is a great place to start). Going through the steps of domain modeling, defining bounded contexts, and finding aggregate roots will help you produce an architecture that has natural seams. This will help split your application into self-contained services that can scale independently as needed.


答: I am assuming that you are using the term "tier" to mean a physical server.  If you do not need to distribute your business and presentation layer I would definitely avoid it. Sending objects over the wire is expensive and prone to issues that if can be avoided should.  But you should design your architecture in a way that makes it easy to add more tiers as the system evolves and design considerations warrant distribution. I usually develop an application service layer as a class library/assembly that would have the same interface that your WCF service would have.  This is what the presentation layer interfaces with or any other external systems.  If the business and presentation layers do not need to be distributed then the presentation layer references the class library directly.  If they do need to be distributed then your WCF service is just a thin wrapper around service layer class library that provides the ability to access the service remotely.</p>

Title: when to introduce an application services tier in an n-tier application

Body:
I am developing a web based application whose primary objective is to fetch data from the database, display it on the UI, take in user inputs and write them back to the database. The application is not going to be doing any industrial strength algorithm crunching, but will be receiving a very high number of hits at peak times (described below) which will be changing thru the day.

The layers are your typical Presentation, Business, Data. The data layer is taken care of by the database server. The business layer will contain the DAL component to access the database server over tcp. The choices I have to separate these layers into tiers are:

The presentation and business layers can be either kept on the same tier.

The presentation layer on a separate tier by itself and the business layer on a separate tier by itself.

In the case of choice 2, the business layer will be accessed by the presentation layer using a WCF service either over http or tcp.

I don't see any heavy processing being done on the Business layer, so I am leaning towards option 1 above. I also feel for the same reason, adding a new tier will only introduce the network latency. However, in terms of scalability in case I need to scale up or scale out, which is a better way to go? This application will need to be able to support up to 6 million users an hour. There will be a reasonable amount of data in each user session, storing user's preferences and other details. I will be using page level caching as well.


答: You are never "not big enough to communicate".  If you fingers can do the typing, your lips can do the talking too.  At the end of the day technology improvement is 85% communication and 15% technical.  Just because you'd rather sit there coding than having difficult conversations with someone... doesn't mean it's a good idea.  Communication is actually the hard piece of what you are trying to, but don't just avoid it. </p>

Title: How can I refactor a code base while others rapidly commit to it?

Body:
I'm on a private project that eventually will become open source. We have a few team members, talented enough with the technologies to build apps, but not dedicated developers who can write clean/beautiful and most importantly long-term maintainable code.

I've set out to refactor the code base, but it's a bit unwieldy as someone in the team out in another country I'm not in regular contact with could be updating this totally separate thing.

I know one solution is to communicate rapidly or adopt better PM practices, but we're just not that big yet. I just want to clean up the code and merge nicely into what he has updated. Would using a branch be a suitable plan? A best-effort-merge? Something else?


答:
Will there be a different behavior later?

There is a critical question related to this one that you need to ask:

Will anyone ever use this code ever again for any reason?

If the answer could ever be yes, whether the code is used alone or as a part of a larger system, you have created a monumental memory leaking landmine for the next person to step on.

It is very hard to remember during your coursework that you are learning how to make software that other people are going to use including future-you (rather than just solving the homework problem of the day).  This means that you need to abide by certain basic programming behaviors including: give back the resources when you are done with them.

Title: Is it a waste of time to free resources before I exit a process?

Body:
Let's consider a fictional program that builds a linked list in the heap, and at the end of the program there is a loop that frees all the nodes, and then exits. For this case let's say the linked list is just 500K of memory, and no special space managing is required.

Is that a waste of time, because the OS will do that anyway?

Will there be a different behavior later?

Is that different according to the OS version?

I'm mainly interested in UNIX based systems, but any information will be appreciated. I had today my first lesson in OS course and I'm wondering about that now.

Edit: Since a lot of people here are concerned about side effects, and general 'good programming practice' and so. You are right! I agree 100% with your statements. But my question is only hypothetical, I want to know how the OS manages this. So please leave out things like 'finding other bugs when freeing all memory'.


问:
Storing images in file system and returning URLs  or virtually resizing and returning byte arrays?
I need to create a REST web service to manage user submitted images and displaying them all in a website. There are multiple websites that are going to use this service to manage and display images. The requirements are to have 5 pre-defined image sizes available.

The 2 options I see are the following:

The web service will create the 5 images, store them in the file system and and store the URL's in the database when the user submits the image. When the image is requested, the web service will return an array of URLs.

I see this option to be a little hard on the hard drive. The estimates are 10,000 users per site, and lets say, 100 sites. The heavy processing will be done when the user submits the image and each image is going to be pulled from the File System.

The web service will store just the image that the user submits in the file system and it's URL in the database. When the user request images, the web service will get the info from the DB, load the image on memory, create its 5 instances and return an object with 5 image arrays (I will probably cache the arrays).

This option is harder on the processor and memory. The heavy processing will be done when the images get requested.

A plus I see for option 2 is that it will give me the option to rewrite the URL of the image and make them site dependent (prettier) than having a image repository for all websites. But this is not a big deal.

What do you think of these options? Do you have any other suggestions?

答:
Definitely use a file store, whether that's a classic CDN, a cloudy one, or a roll-your-own. I also wouldn't bother storing all 5 image sizes. Create the scaled images on the fly, at first access (i.e. if the DB query for a particular image and size returns NULL for the URL, scale the larger image down, and return the newly created URL, then store it for future references).

Don't bother too much about hard drives. There's already a very effective file cache in every relevant OS, and you're going to be hard-pressed to beat that. Furthermore, you'd planning to service a million users. You can quote storage at a reasonable $1.00 per user and have plenty of money to play with.

Don't worry about the URL pretty-ness. Our filestore is known as download.<OurCompanyName>.com, even though it's actually hosted by a well-known CDN company.


问:
New Job Over Budget
I recently started a new job as a contract developer, and my non-developer boss of about two weeks ago gave me the task to re-create an app from another language and developer that he will reuse with multiple clients (replacing the front-end), that I estimated would take longer than his estimate of 12 hours.

Two weeks later, I'm 230% over-budget. I admit this was my 2nd web app, I had been a wordpress developer in the past, so I am somewhat new to code igniter, but not shabby php by any means. My boss hired me knowing this and I was clear that it would take longer than his 12 hours. He's seen me in the office on task for 2 weeks, he should be somewhat prepared for this bill.

Do I expect the full amount of hours, or do I filter against how much of learned?
Can I bill for research as a developer?

答:
If the language in the contract he signed with you includes any language such as "not to exceed X hours at Y rate" then you can only charge what you agreed to charge.

However, if it was an estimate and the contract states that you would be paid for hours worked, period, then you charge the hours that you worked.

If your concern is that it took you an unreasonable amount of time (for some value of unreasonable) to get up to speed with something you had no control in using -- note that I don't know if this is the case here at all but am just throwing it out there -- and you have mixed feelings about charging someone for what you perceive to be time spent not wholly focused on their project, then don't. But that's your decision, not "right" or "wrong" or anything beyond what you feel is best.

Bottom line: if you worked on this project for 30 hours, bill for 30 hours unless the contract says you'll only bill for 12.

Title: New Job Over Budget


答:
Keeping one eye on the future is usually a good thing, but introducing a Service layer, or anything really,  when one is not needed may well just be a waste of time now, and slow down your system.

Splitting your system correctly into logical layers is deinitely a good thing and will allow you to extend your system at a later date. Reducing the coupling will make it easier to do this in the future.

As it happens I worked on a large system a couple of years ago which was a website -> service layer -> everything else.

The Service layer was introduced because all the senior architects/managers fell in love with SOA, so our system HAD to become service oriented. "other systems will use our websites middle tier functionality" was the cry.

That decision alone cost the project a year in delays.


答:
I understand that in a business point of view rejecting a client is not a good practice

You're wrong there. It is good practice for a small business to reject a client that will not work out for them. After all, if they're not going to be happy with the outcome are they going to be bringing repeat business back to you? If they're insisting on ridiculous rules, are you going to be able to deliver an acceptable outcome/product on an acceptable schedule?
Far better to say “I'm sorry, but I don't think this is going to work out for either of us.” and walk away.

That said, if you're going to continue to work on this then bear in mind that going there in person (even if just for a limited amount of time) is going to be hugely more efficient. It'll let you get an understanding of what things actually matter and what is just something put in there by a manager getting the wrong end of the stick. Once you have that initial contact done, you can probably get by just nicely with occasional teleconferences and email.  Focus on ensuring that you understand the API; you want to avoid having to learn about the internals if at all possible (and if they start to tell you, stop them!) If they can't tell you about what the API is, that takes me back to the previous paragraph…

I also advise ignoring any requirement to not use version control. Yes, use a separate private repository for the work — a public repo would be a bad idea, of course — but when it comes to what category of tool to use at all, they're simply not empowered to instruct you in the correct use of tools. After all, it would be just as ridiculous to tell a carpenter to not use a hammer or a saw; it's their job (i.e., yours) to decide what tools to use as they are the contractor.


问:
Inheritance versus Composition in a business application
I have a training management and tracking system, with a high level structure as follows:

We have a Role1, e.g. Manager, Shift-boss, miner, etc. and a Candidate, training for that Role. The role has a list of courses and their subjects the candidate needs to complete to qualify for the role. Candidate has a TrainingHistory attribute, containing the courses and subjects they have completed, their results, and the date completed.

Now I see it as a TrainingHistoryCourse is-a Course, extended to add DateCompleted etc. but something is nagging at me to rather use something like a TrainingHistoryRecord that has-a Course. How can I further analyse this to determine which pattern to use?

Then, a Role has a list of RoleTask definitions that the Candidate must be observed practising, and a Candidate has a history of RoleTaskObservation objects recording their performance at these tasks. This is very similar to the course/subject requirement and history pattern for the candidate, except for one less hierarchical level, but, a RoleTaskObservation clearly does not have an is-a relationship with RoleTask, unless I block my nose and rather use ObservedRoleTask.

I would prefer to use the same pattern for both subject/course and task/observation structures, but I think that would force me to adopt a composition pattern for TrainingHistoryCourse. What is the wisdom here? Always inherit where possible and validated by a solid is-a association, or always favour composition wherever possible?

1 Client specified this to be called JobTitle, but he isn't writing the app, and a JobTitle is only one attribute of a Role. Authorization roles are handled by the DevExpress framework and its customization hooks, so there would be very little little confusion between a business Role in my domain objects and an authorization role in lower level, framework code.

答:
Apologies for the verbosity. Skip down to What is the wisdom here? if you like.

How can I further analyse this to determine which pattern to use?

Keep identifying Use Cases. And make sure your requirements analysis is comprehensive. For example imagine how TrainingHistoryCourse is used for reporting of various detail (specific course work) and summary (final training reports, management progress reports). This could inform the structure of a training record for example.

I get a sense that you're trying to make stuff up just a bit to get a "OO design warm fuzzy" (Look - Inheritance & composition!) - and you may have gaps in requirements analysis.

subject/course

Curriculum is an idea that may coalesce your subject/course concepts. curriculum can be our general container/Class for all training requirements, customized for each specific Role

The ShiftBossCurriculum then is a composition of course*s and *roleTask*s that, when completed, qualifies a candidate as a Shift-Boss,

task/observation

The instructor observes the candidate performing a RoleTask and makes an entry in the candidate's TrainingHistoryCourse Training Record

A candidate completes a given course in a Curriculum. The completion date is entered in the training record. The instructor enters an relevant observations for that course. (hay! I tawt I taw a use case!).

TrainingHistoryCourse

This concept does not make sense. If it is primarily a course completion date, that seems to be a logical extension of a Training record, not THE course itself.

Training Record

From the above discussions, it looks like a training record is a composition of course work, roleTasks, and observations.

Potential Inheritance Bases

Role, Task, Course, curriculum, training record, candidate... In fact any of your general actors and objects. It depends on any identified (or future/potential) specialization/customization required of these general things. So far we have identified specialized curriculum, Roles, courses, and Tasks. But even then this does not guarantee we will use inheritance; the devil is in the details.

Potential Composition

Clearly curriculum and training record are composites. But not because of the simplistic observation that they contain things (what object doesn't?). Read on, Macduff.

What is the wisdom here?

Always inherit where possible and validated by a solid is-a association, or always favour composition wherever possible?

That is wrong. The maxim is favor composition over inheritance. "Always" ain't in there. Following this heuristic means your software tends to be more flexible, easier to maintain, extend, and reuse.

Don't go inventing inheritance hierarchy where it does not exist. In your business model, is there really a need to handle courses as "math courses" or "shift-boss courses", etc.? Or are they just courses that are logically associated in a "shift boss curriculum"? The course name, course department, etc./whatever properties will be filled in at runtime to give us a particular course.

Likewise a curriculum is also just a curriculum. What makes it a "shift boss" curriculum? Simply a different set of courses vis-a-vis the "manager" courses.

So we have identified general "curriculum", and that by composing it with different instances of courses makes a different curriculum. Thus we have composition to make a "manager" curriculum, not a ManagerCurriculum sub-class of curriculum.

Having identified a general concept it can be coded as an interface (interfaces can be literally interfaces or abstract classes). What you do to any specific course you do with any course. NOW we have flexible, re-usable, extensible, maintainable code.

OwnerDisplayName: ProfK


答:
I would also tend to rewrite, but you need to be 100% sure you understand the current functionality fully as well as any functionality which is broken, missing or inadequate. The latter two are important as you mentioned adjusting and calculating prices. Do you fully understand the consequences of adding this feature?

I once worked on what was supposed to be a "website", but was in actual fact taking over a custom Access based CRM style tool from the late 1990s and bringing it into the modern, web based, world. The original developer was long gone, the Database had been modified umpteen times, original documentation was thus out of date and no one really understood how the system worked. But they knew how to use it, just. Probably 80% of the budget for this project went on three things:

gathering requirements

understanding the current system

coming up with a meaningfull database schema for how they intended to use the software

The project was, financially, not a success!


答:
Have you considered the option "Don't do it yet"?

While doing this work in a seperate branch is probably the best approach, you are setting yourself up for a massive painful merge down the line.

The other guys are presumably adding lots of new functionality, changing existing functionality and possibly removing some functionality.

Once mainstream dev worked has slowed down a bit at some point in the future, then you could be in a much easier position to refactor.


问:
How to make hardware sizing sheet?
We build some software platform, and now we need to make hardware sizing sheet for the server-side piece of this software. So, I should prepare some mathematical model that, for example, given the number of concurrent users, can predict the number of physical servers or storage capacity or network bandwidth. How to make such model?</p>

答:
I think the advice to prototype is right on.  Run it, see how it runs with X users.  Then, add in a "fudge factor" on top of your results so that you have some breathing room with your customers.  So if your test results find that you need 512 MB of RAM for 100 users, write 768 MB or 1 GB in your recommended specs.

The big guys (HP, Microsoft, Oracle) all have recommendations.   Routinely those recommendations are either loosely adhered to in development and test environments, or ignored completely because the hardware used is "whatever is available".  Just a thought about that.

Title: How to make hardware sizing sheet?


问:
Understanding Data Binding for Windows Phone 7
I want to develop a simple app for the Windows Phone 7 platform. It's basically a vocabulary based game that involves the user moving word tiles from one area to another to score points.

I want to know what is the best way of tying the UI to the game's backend? I saw the Windows Phone 7 jumpstart videos, there they touch up on Data Binding but don't really go into any depth.

I'm a newbie and don't have any experience with designing the architecture for a phone app,
It'd be great if someone could explain what steps I should be taking or guide me to a resource from where I could learn more.

答: If you think you already know the basics and still need guidance, I suggest you get a good book on the subject. For example, Charles Petzold offers a free e-book on Windows Phone 7 that can be downloaded here.</p>


问:
Data structures in functional programming
I'm currently playing with LISP (particularly Scheme and Clojure) and I'm wondering how typical data structures are dealt with in functional programming languages.

For example, let's say I would like to solve a problem using a graph pathfinding algorithm.  How would one typically go about representing that graph in a functional programming language (primarily interested in pure functional style that can be applied to LISP)?  Would I just forget about graphs altogether and solve the problem some other way?

答:
It's been a while since I've worked in LISP, but as I recall, the basic non-atomic structure is a list. Everything else is based on that. So you could have a list of atoms where each atom is a node followed by a list of edges that connect the node to other nodes. I'm sure there's other ways to do it too.

Maybe something like this:

```<code>(
  (a (b c)),
  (b (a c)),
  (c (a b d)),
  (d (c))
)
</code>```

could give a graph like this:

```
a<-->b<-->c<-->d
^         ^
|         |
+---------+
```

If you want to get fancy, you could add weights to it as well:

```<code>(
  (a (b 1.0 c 2.0)),
  (b (a 1.0 c 1.0)),
  (c (a 1.3 b 7.2 d 10.5)),
  (d (c -10.5))
)
</code>```

You might also be interested in this: CL-Graph (found by google-searching the phrase "lisp graph structure" )

Body:
It's been a while since I've worked in LISP, but as I recall, the basic non-atomic structure is a list. Everything else is based on that. So you could have a list of atoms where each atom is a node followed by a list of edges that connect the node to other nodes. I'm sure there's other ways to do it too.

Maybe something like this:

(
  (a (b c)),
  (b (a c)),
  (c (a b d)),
  (d (c))
)

could give a graph like this:

a<-->b<-->c<-->d
^         ^
|         |
+---------+

If you want to get fancy, you could add weights to it as well:

(
  (a (b 1.0 c 2.0)),
  (b (a 1.0 c 1.0)),
  (c (a 1.3 b 7.2 d 10.5)),
  (d (c -10.5))
)

You might also be interested in this: CL-Graph (found by google-searching the phrase "lisp graph structure" )


问:
Purpose of the csx folder in Azure projects?
I'm fairly new to Azure but I noticed that Visual Studio auto-creates the following folders (among others)

```<code>...
/<nameOfAzureProject>/bin
/<nameOfAzureProject>/obj
/<nameOfAzureProject>/csx <==
...
</code>```

Now the bin and obj folders are fairly standard. But I'm not clear about the purpose of the csx folder. Any ideas?

答:
It contains a packaged version of your project. I found a blog entry mentioning it.

Before an Azure package can be deployed to the emulator it must first be packaged. Since v1.4 of the Windows Azure Tools, the csx folder and its contents are no longer generated during compilation... So in order to force the generation of the csx folder we need to specify that the package should be generated for the compute emulator within the Azure project file...

:: Deploying to the Azure Compute Emulator

Now that we have the csx package folder generated after each compilation run we can use the CSRun command-line tool to deploy the folder to the emulator...


答:
Well it would depend on whether your graph is directed/undirected, weighted/unweighted but one way to represent a directed, weighted graph (which would be the most general) is with a map of maps (in Clojure)

```<code>{
 :a {:b 3 :c 4}
 :b {:a 1}
 :c {}
}
</code>```

would represent a map with nodes :a :b and :c. :a points to :b with a weight of 3 and :c with a weight of 4. :b points to :a with a weight of 1. :c doesn't point to anything.

Title: Data structures in functional programming

Body:
I'm currently playing with LISP (particularly Scheme and Clojure) and I'm wondering how typical data structures are dealt with in functional programming languages.

For example, let's say I would like to solve a problem using a graph pathfinding algorithm.  How would one typically go about representing that graph in a functional programming language (primarily interested in pure functional style that can be applied to LISP)?  Would I just forget about graphs altogether and solve the problem some other way?

Body:
Well it would depend on whether your graph is directed/undirected, weighted/unweighted but one way to represent a directed, weighted graph (which would be the most general) is with a map of maps (in Clojure)

{
 :a {:b 3 :c 4}
 :b {:a 1}
 :c {}
}

would represent a map with nodes :a :b and :c. :a points to :b with a weight of 3 and :c with a weight of 4. :b points to :a with a weight of 1. :c doesn't point to anything.


问:
Why should we use low level languages if a high level one like python can do almost everything?
I know python is not suitable for things like microcontrolers, make drivers etc, but besides that, you can do everything using python, companys get stuck with speed optimizations for real hard time system but does forget other factors which one you can just upgrade your hardware for speed proposes in order to get your python program fit in it, if you think how much cust can the company have to maintain  a system written in C, the comparison is like that:
for example: 10 programmers to mantain a system written in c
and just one programmer to mantain a system written in python,
with python you can buy some better hardware to fit your python program, I think that low level languages tend to get more cost, since programmers aren't so cheaply than a hardware upgrade,
then, this is my point, why should a system be written in c instead of python?

答:
Because if the "system" is a scientific library or a go playing program it might require top performances, that's why. If you buy hardware that's 10 times faster, the low level implementation will still perform better.

And then there's a quite philosophic reason, in my opinion: we have to keep in touch with the lowest level of our machines. Losing the knowledge of basic instruments like the C language would be like covering every inch of the earth with cement and build a perfectly working "system" upon it, forgetting about what was down there once that gave us birth and condemning the human race to eternal ignorance.

Kernighan and Ritchie would be very upset about it.


答:
In Haskell the list is the basic data structure and if you want a more advanced data struktures you often use recursive struktures like a tree is either null or a node and two trees</p>

```<code>data Tree a = Null | Node Tree a Tree
</code>```

Body:
In Haskell the list is the basic data structure and if you want a more advanced data struktures you often use recursive struktures like a tree is either null or a node and two trees

data Tree a = Null | Node Tree a Tree


答:
Functional languages deal with data structures the same way that non-functional languages do: by separating interface from implementation, creating abstract data types.

You can create abstract data types in Lisp.  For instance, for a graph, you might want a couple of functions:

```<code>(define (get-vertices graph) ;; gets all the vertices from a graph
  ...)

(define (get-edges graph) ;; gets all the edges from a graph
  ...)

(define (get-weight vertex-from vertex-to) ;; get the weight of a specific vertex
  ...)
</code>```

Once you've created that interface to a graph, you can implement the actual data structures in many different ways, possibly optimizing such factors as programmer efficiency, flexibility, and computational efficiency.

The key is to make sure that the code that uses graphs only uses the graph interface, and doesn't access the underlying implementation.  This will keep the client code simpler as its uncoupled from the actual implementation.

Body:
Functional languages deal with data structures the same way that non-functional languages do: by separating interface from implementation, creating abstract data types.

You can create abstract data types in Lisp.  For instance, for a graph, you might want a couple of functions:

(define (get-vertices graph) ;; gets all the vertices from a graph
  ...)

(define (get-edges graph) ;; gets all the edges from a graph
  ...)

(define (get-weight vertex-from vertex-to) ;; get the weight of a specific vertex
  ...)

Once you've created that interface to a graph, you can implement the actual data structures in many different ways, possibly optimizing such factors as programmer efficiency, flexibility, and computational efficiency.

The key is to make sure that the code that uses graphs only uses the graph interface, and doesn't access the underlying implementation.  This will keep the client code simpler as its uncoupled from the actual implementation.


答:
One thing people often fail to consider is that a clean architecture doesn't only speed up long term maintenance, it also speeds up development right now.  Don't try to insulate your changes from your colleagues until they are "done."  Your changes will help them be more productive and less prone to bugs.

The most frequent mistake people make when undertaking a large refactor is to not merge often enough, instead trying to do it in one "big bang."  The right way to do it is to make the smallest possible refactor you can, test it, then merge it into your colleague's branch, and teach him about the change so he can incorporate it going forward.  Ideally you're doing one merge per day, or one per week at the very least.


问:
Storing data offline with javascript
My question is about storing data offline and potentially whether I will need to bring in an outside programmer or could this be learned within a few weeks?

The website I am working on will have an interface where users will login and go through a series of quizzes in the form of checkbox, drop down menus, and others. Each page/quiz area could have 20-100 total checkboxes in a series of 3-5 rows because of the comprehensive nature of course.

This I can do - I know how to code the quiz and return a correct or incorrect answer based on each individual checkbox and present a cumulative score (ie: you got 57% correct).

The issue lies in the fact that I would like to save the users results and keep them informed of their progress. When they complete all of the quizzes, I would like to have a visual output of their performance in each area. Storing the output from their results offline is where I think I may run into a problem with my lack of coding experience. I would also like to have a sidebar with their progress of each section (10-15) with a green percentage completion bar or a % correct which would draw from this.

I have never had to code something that stores information like this offline - so back to my question - would it be better to learn the language needed or bring in a coder/developer for the back end stuff.

答:
Its very easy and you can learn it in like an hour or so tops.

you can also consider using some library like this

http://www.jstorage.info/

I am using it for one of my project.

Title: Storing data offline with javascript


问:
How can I justify software testing to management?
I work for a small company (less than 200 employees) whose software group only makes up a small part of our staff (4 employees, occasionally with a few contractors).  The four of us have been making strides in transitioning to better practices, and one of the next logical steps is to improve our testing.

As anyone who has done any meaningful tests knows, testing takes a lot of time - and at my company, it takes too much time to justify to management, so we generally do what little we do on the sly.  I don't think this is serving us well, as we keep coming up against otherwise avoidable problems when we ship under-tested software.

I would like to be able to come to management with a justification for hiring a dedicated software test engineer (someone who can both write automated tests and perform manual ones).  Are there any good published studies that show the benefits of adding such a position to a small company?  Where can I find information about costs associated with the position?  I plan on doing a little number crunching on our own history, but having some external sources to point to would help bolster my case.

答:
It sounds like you have a critical first step:

As anyone who has done any meaningful tests knows, testing takes a lot of time - and at my company, it takes too much time to justify to management, so we generally do what little we do on the sly. I don't think this is serving us well, as we keep coming up against otherwise avoidable problems when we ship under-tested software.

It sounds like you need to make the business case for testing at all and embedding into the schedule before you do anything else.

Here's how I did something similar:

Projects were using classic Big Bang testing.  There are plenty of resources showing that this method is the least reliable, most costly and (therefore) most likely to be cut for the purposes of "savings."

In order to "hide" testing inside the project (rather than at the end), I dedicated every fourth week to testing and planning.  This means that no developer was ever more than three weeks from something that they'd been working on.  It also meant that every task was tested more than zero.

Then I made the business case to the project managers.  My justification was that (a) people have to test just to know if they've actually finished their tasking and (b) with early testing, I could easily claim a net cost savings of at least 50% savings.

That last point was a bit dramatic for some people.  Considering that post-release bug fixes are considered to be at least ten times more expensive to find and fix, it was a fairly easy argument to win.

The four of us have been making strides in transitioning to better practices, and one of the next logical steps is to improve our testing.

I agree but I don't agree that the first step is to hire.  You're talking about an increase in your group's salary budget of 20% without first demonstrating the return on investment.  Invest in the testing capabilities and resources of the people that you have now.  Demonstrate the value of testing as a core development practice.  Then start working on the business case for a new hire when you have the history to back you up.


问:
Why is there no facility to overload static properties in PHP?

Intro

PHP allows you to overload method calls and property accesses by declaring magic methods in classes. This enables code such as:

```<code>class Foo {
    public function __get($name) { return 42; }
}

$foo = new Foo;
echo $foo->missingProperty; // prints "42"
</code>```

Apart from overloading instance properties and methods, since PHP 5.3.0 we can also overload static methods calls by overriding the magic method __callStatic.

Something missing

What is conspicuously missing from the available functionality is the ability to overload static properties, for example:

```<code>echo Foo::$missingProperty; // fatal error: access to undeclared static property
</code>```

This limitation is clearly documented:

Property overloading only works in object context. These magic methods
  will not be triggered in static context. Therefore these methods
  should not be declared static. As of PHP 5.3.0, a warning is issued if
  one of the magic overloading methods is declared static.

But why?

My questions are:

Is there a technical reason that this functionality is not currently supported? Or perhaps a (shudder) political reason?

Have there been any aborted attempts to add this functionality in the past?

Most importantly, the question is not "how can I have dynamic static properties in userland PHP?". That said, if you know of an especially cute implementation based on __callStatic that you want to share then by all means do so.

答:
Quoting http://marc.info/?l=php-internals&m=121578194822276&w=2

Was static member overloading added in PHP 5.3? I noticed that static
  method overloading was (__callStatic). The two would complement each
  other and it just seems natural to add these as well. I did notice that
  they are apart of the "static-class" RFC and a bug report, but it would
  be nice to see these in 5.3. With this addition and LSB, php classes can
  do so much! Ex:

```<code>__setStatic()
__getStatic()
__issetStatic()
__unsetStatic()
</code>```

Quoting follow-up http://marc.info/?l=php-internals&m=121578318524848&w=2

if the RFC for static classes will be accepted, static property
  interceptors will be a part of the next PHP major version (might it be
  5.4 or 6). So it won't make it into 5.3, but we will have that hopefully
  in the future.

Link to Static Classes RFC:

https://wiki.php.net/rfc/static-classes

The Status of the RFC is "in the works" but given that it is from 2008 you might want to ask on the php.internals mailing list or on #php.pecl on EFNet IRC to find out what has become of it.

OwnerDisplayName: Jon

Body:
Quoting http://marc.info/?l=php-internals&m=121578194822276&w=2

Was static member overloading added in PHP 5.3? I noticed that static
  method overloading was (__callStatic). The two would complement each
  other and it just seems natural to add these as well. I did notice that
  they are apart of the "static-class" RFC and a bug report, but it would
  be nice to see these in 5.3. With this addition and LSB, php classes can
  do so much! Ex:

__setStatic()
__getStatic()
__issetStatic()
__unsetStatic()

Quoting follow-up http://marc.info/?l=php-internals&m=121578318524848&w=2

if the RFC for static classes will be accepted, static property
  interceptors will be a part of the next PHP major version (might it be
  5.4 or 6). So it won't make it into 5.3, but we will have that hopefully
  in the future.

Link to Static Classes RFC:

https://wiki.php.net/rfc/static-classes

The Status of the RFC is "in the works" but given that it is from 2008 you might want to ask on the php.internals mailing list or on #php.pecl on EFNet IRC to find out what has become of it.

OwnerDisplayName: Gordon


问:
What is message passing in OO?
I've been studying OO programming, primarily in C++, C# and Java. I thought I had a good grasp on it with my understanding of encapsulation, inheritance and polymorphism.

One frequently referenced concept when discussing OO is "message passing". Apparently, this is something that is not used whilst OO programming in today's mainstream languages, but is supported by Smalltalk.

My questions are:

What is message passing?

Is there any support for this "message passing" in C++, C# or Java?

答:
Message passing architectures are simply systems where each component is independent of the others, with a common mechanism for passing data between them. You can consider method calls as a form of message passing, but it's not practical to do so - it confuses the issue. This is because if you have a class with well-defined methods, and some code that calls those methods, the entire thing must be compiled together, thus coupling the code and the object. you can see how it is close (as a message is being passed, and the compiler is enforcing correctness, but it loses much of the flexibility of a decoupled system).

Message passing architectures often allow objects to be added at runtime, and more often than not allow messages to be redirected to one or more objects. So I can have some code that broadcasts a 'data x is updated' message to all objects that have been loaded into the system, and each one of them can take whatever action they like with that information.

A weird example is the web. HTTP is a message passing system - you pass a command verb and a 'data packet' to a server process. (eg GET http:\myserver\url) Neither your browser, nor the webserver cares anything about the data you send, or where you send it to. The server will pass it on to the code that will package up another 'packet' of data and send it back to you. None of the component in this system know anything about the others work or what they do, they just know the protocol used for the message communication.

ContentLicense: CC BY-SA 4.0

Title: What is message passing in OO?


问:
Did the developers of Java consciously abandon RAII?
As a long-time C# programmer, I have recently come to learn more about the advantages of Resource Acquisition Is Initialization (RAII).  In particular, I have discovered that the C# idiom:

```<code>using (var dbConn = new DbConnection(connStr)) {
    // do stuff with dbConn
}
</code>```

has the C++ equivalent:

```<code>{
    DbConnection dbConn(connStr);
    // do stuff with dbConn
}
</code>```

meaning that remembering to enclose the use of resources like DbConnection in a using block is unnecessary in C++ !  This seems to a major advantage of C++.  This is even more convincing when you consider a class that has an instance member of type DbConnection, for example

```<code>class Foo {
    DbConnection dbConn;

    // ...
}
</code>```

In C# I would need to have Foo implement IDisposable as such:

```<code>class Foo : IDisposable {
    DbConnection dbConn;

    public void Dispose()
    {
        dbConn.Dispose();
    }
}
</code>```

and what's worse, every user of Foo would need to remember to enclose Foo in a using block, like:

```<code>   using (var foo = new Foo()) {
       // do stuff with "foo"
   }
</code>```

Now looking at C# and its Java roots I am wondering... did the developers of Java fully appreciate what they were giving up when they abandoned the stack in favor of the heap, thus abandoning RAII?

(Similarly, did Stroustrup fully appreciate the significance of RAII?)

答:
I'm pretty old. I've been there and seen it and banged my head about it many times.

I was at a conference in Hursley Park where the IBM boys were telling us how wonderful this brand new Java language was, only someone asked ... why isn't there a destructor for these objects. He didn't mean the thing we know as a destructor in C++, but there was no finaliser either (or it had finalisers but they basically didn't work). This is way back, and we decided Java was a bit of a toy language at that point.

now they added Finalisers to the language spec and Java saw some adoption.

Of course, later everyone was told not to put finalisers on their objects because it slowed the GC down tremendously. (as it had to not only lock the heap but move the to-be-finalised objects to a temp area, as these methods could not be called as the GC has paused the app from running. Instead they would be called immediately before the next GC cycle)(and worse, sometimes the finaliser would never get called at all when the app was shutting down. Imagine not having your file handle closed, ever)

Then we had C#, and I remember the discussion forum on MSDN where we were told how wonderful this new C# language was. Someone asked why there was no deterministic finalisation and the MS boys told us how we didn't need such things, then told us we needed to change our way of designing apps, then told us how amazing GC was and how all our old apps were rubbish and never worked because of all the circular references. Then they caved in to pressure and told us they'd added this IDispose pattern to the spec that we could use.  I thought it was pretty much back to manual memory management for us in C# apps at that point.

Of course, the MS boys later discovered that all they'd told us was... well, they made IDispose a bit more than just a standard interface, and later added the using statement. W00t! They realised that deterministic finalisation was something missing from the language after all. Of course, you still have to remember to put it in everywhere, so its still a bit manual, but it's better.

So why did they do it when they could have had using-style semantics automatically placed on each scope block from the start? Probably efficiency, but I like to think that they just didn't realise. Just like eventually they realised you still need smart pointers in .NET (google SafeHandle) they thought that the GC really would solve all problems. They forgot that an object is more than just memory and that GC is primarily designed to handle memory management. they got caught up in the idea that the GC would handle this, and forgot that you put other stuff in there, an object isn't just a blob of memory that doesn't matter if you don't delete it for a while.

But I also think that the lack of a finalise method in the original Java had a bit more to it - that the objects you created were all about memory, and if you wanted to delete something else (like a DB handle or a socket or whatever) then you were expected to do it manually.

Remember Java was designed for embedded environments where people were used to writing C code with lots of manual allocations, so not having automatic free wasn't much of a problem - they never did it before, so why would you need it in Java? The issue wasn't anything to do with threads, or stack/heap, it was probably just there to make memory allocation (and therefore de-alloc) a bit easier. In all, the try/finally statement is probably a better place to handle non-memory resources.

So IMHO, the way .NET simply copied Java's biggest flaw is its biggest weakness. .NET should have been a better C++, not a better Java.


问:
Tips for achieving "continual" delivery
A team is experiencing difficulty releasing software on a frequent basis (once every week). What follows is a typical release timeline:

During the iteration:

Developers work on stories on the backlog on short-lived (this is enthusiastically enforced) feature branches based on the master branch.

Developers frequently pull their feature branches into the integration branch, which is continually built and tested (as far as the test coverage goes) automatically.

The testers have the ability to auto-deploy integration to a staging environment and this occurs multiple times per week, enabling continual running of their test suites.

Every Monday:

there is a release planning meeting to determine which stories are "known good" (based on the testers' work), and hence will  be in the release. If there is a known issue with a story, the source branch is pulled out of integration.

no new code (only bug fixes requested by the testers) may be pulled into integration on this Monday to ensure the testers have a stable codebase to cut a release from.

Every Tuesday:

The testers have tested the integration branch as much as they possibly can have given the time available and there are no known bugs so a release is cut and pushed out to the production nodes slowly.

This sounds OK in practise, but we have found that it is incredibly difficult to achieve. The team sees the following symptoms

"subtle" bugs are found on production that were not identified on the staging environment.

last minute hot-fixes continue into the Tuesday.

problems on the production environment require roll-backs which blocks continued development until a successful live deployment is achieved and the master branch can be updated (and hence branched from).

I think test coverage, code quality, ability to regression test quickly, last minute changes and environmental differences are at play here. Can anyone offer any advice regarding how best to achieve "continual" delivery?

答:
Why not use actual continuous deployment, where a commit (or push) causes the tests to run, and if the tests pass, a deployment to occur?

Then if you are unsure of a change you do it on a separate branch, which still causes the tests to run but no deployment.

I think there's more stress in trying to get a broken trunk/master to stability than there is in, you know, just keeping it stable.

OwnerDisplayName: Ben Aston

Title: Tips for achieving "continual" delivery


问:
Opensource showcase for MVC in Java Swing
I've allready created small desktop CRUD applications using Java/Swing. In hindsight I'm not quite sure if the overall design of these applications is good. I've also done some reading on MVC and looked at different Swing-tutorials.
My problem is, that I've got a very theroatical knowledge of MVC and on the other hand, most Swing-resources don't implement the MVC-pattern.

Now I would like to get my hands dirty and see how MVC is implemented in Swing in a real-world-application. Are there any opensource project you could recommend? It would be also interesting to have more than one project, to see different approaches.

Best fit would be a software, that uses a relational database in the backend, to see an overall design, that I can compare to my former applications.

答:
In my opinion, a full blown app would be more complicated to understand if you are struggling with basic steps.

Having said that, if you are comfortable with individual pieces, perhaps, you can look at different frameworks/tools which assist you in taking over the plumbing and you focus on the business aspect of things.

For instance, there is the

Swing Application Framework (not sure about its current status) http://java.sun.com/developer/technicalArticles/javase/swingappfr/

Use Netbeans as a platform, an example is available at http://netbeans.org/kb/70/java/gui-db.html. Another example with hibernate is available at http://netbeans.org/kb/docs/java/hibernate-java-se.html. Full list of examples are available at http://netbeans.org/kb/samples/.

Ecplipse also has a similar facility where you can use it to develop desktop apps.

You can also use code generators/frameworks such as Hibernate/JPA (for ORM), Spring (for misc things), or mix and match things.

There is also the intellij platform. As of now (jan 2014) it is more suited towards ide type of applications, but it may change some point in future.

In the end there is no "right" way to do something. If you are exploring, perhaps make a list of whatever you read. Explore them one by one. Do a simple todo application, and figure out what benefits/pains you encounter. Even modelling a simple app, will allow you to think about different things.

most Swing-resources don't implement the MVC-pattern

I am surprised you suggest that. Frames, Panels, Text Components are excellent examples. Perhaps it is worth mentioning, that swing library does not only use the MVC pattern. It also uses a bunch of other patterns, so this might be the source of your confusion.

Wrapping up, I would say, majority of applications could do with some sort of library which handles the windowing/other boiler plate, so you hook your code and are up and running fast. I personally use Netbeans as my IDE, and it allows me even to generate a sample CRUD database application (provided you have a schema). You can use it to prototype and tweak things as you like.


问:
Good resources for language design
There are lots of books about good web design, UI design, etc. With the advent of Xtext, it's very simple to write your own language. What are good books and resources about language design?

I'm not looking for a book about compiler building (like the dragon book) but
something that answers:

How to create a grammar that is forgiving (like adding optional trailing commas)?

Which grammar patterns cause problems for users of a language?

How create a compact grammar without introducing ambiguities. Here, think "clean language", not "parser builder warnings". Maybe "how do I avoid confusing the developer using my language?"

答:
I'm not aware of a canonical book.  That may be because design best practices are likely to be domain-specific.  A language for mathematicians should look very math-like, a language for chemists should look very chemistry-like, etc.  Some things that make no sense in one domain are essential in another.

For example, I write software for networking equipment, which has its own language for configuration.  The command for shutting down a port is, intuitively enough, shutdown.  However, the command for enabling a port is no shutdown.  To me, that's the stupidest design ever, but it's very natural for our users from a historical perspective.

Keep in mind, unless you're squarely in the target demographic, you're probably the worst person to design the language.  You will tend to want something with an efficient grammar, or easy implementation, or consistency with programming languages you know, but the user doesn't care about those things.  Start out by reading something an end user has written, and consider your job to be refinement of that based on criteria like parseability, consistency, and removing ambiguity.

For example, I'm currently working on a language for keeping track of all the numbers associated with pen and paper roleplaying games.  Rather than starting with the grammar, or looking at other programming languages I could adapt, I started by looking at how those numbers are described in existing published rule books.  They have a lot of phrases like "-2 penalty to armor class when cowering," so that's what my syntax looks like, with words like penalty, to, and when being keywords.  There are obviously some restrictions necessary to make it readable by computer, but most of the time a user is going to be able to copy directly from a rule book with only minor modifications.

Title: Good resources for language design


答:
In designing language syntax, you have such a wide range of choices that it's really a matter of taste, not engineering.  If you want a tried, tested, and familiar syntax, rip off a language or three of your choice.  If you want to explore and invent something new, the range of potential pitfalls is also so wide that existing examples may not help.

There's a long tradition of comparative language design books, which present a selection of contemporary languages -- with commentary, but generally not much in the way of conclusions.  Nonetheless, you could do worse than to find a university engineering library and go through a few of them.

Also, keep in mind that grammar is arguably the least important aspect of the language.  More important aspects include:  the type system, the module system, support of large systems, issues of name scope, abstraction, semantics, resource management, concurrency, et cetera.

Addition: Principles of Language Design and Evolution is a web-available article on programming language design (ca. 1999) by Bertrand Meyer, the designer of Eiffel.

It focuses on simplicity and consistency, but with a pragmatic edge.  Interestingly, Meyer's take on syntax is that it actually matters quite a bit. Aside from the practical aspect of supporting actual users, he notes that unsatisfactory syntax is frequently a pointer to deeper, semantic problems.

Title: Good resources for language design

Body:
There are lots of books about good web design, UI design, etc. With the advent of Xtext, it's very simple to write your own language. What are good books and resources about language design?

I'm not looking for a book about compiler building (like the dragon book) but
something that answers:

How to create a grammar that is forgiving (like adding optional trailing commas)?

Which grammar patterns cause problems for users of a language?

How create a compact grammar without introducing ambiguities. Here, think "clean language", not "parser builder warnings". Maybe "how do I avoid confusing the developer using my language?"


问:
Is unit testing or test-driven development worthwhile?
My team at work is moving to Scrum and other teams are starting to do test-driven development using unit tests and user acceptance tests. I like the UATs, but I'm not sold on unit testing for test-driven development or test-driven development in general.

It seems like writing tests is extra work, gives people a crutch when they write the real code, and might not be effective very often.

I understand how unit tests work and how to write them, but can anyone make the case that it's really a good idea and worth the effort and time?

Also, is there anything that makes TDD especially good for Scrum?

答:
Is unit testing or test-driven development worthwhile?

Definitely yes (see the other answers)

[Is it] really a good idea and worth the effort and time?

Yes if you start something new (add a new module or a completely new application)

No if there is already a lot of existing code that was not developed test-driven and that must be extended (legacy).

In my opinion test-driven development is most effective if you write the unit tests before the actual code. this way the code that fulfills the tests becomes clearly separated with a minimum of external references that is easy testable.

If the code already exists without the unit tests there it is usually a lot of extra work to write the unit tests afterwards because the code was not written for easy testing.

If you do TDD the code automatically is easy testable.


问:
Software solution from the 2000's, should I attempt to patch or remake the whole thing?
I was sent out to discuss a system that a certain company is currently using and what should be done with it.

The company manufactures various carton displays. This system was developed to keep track of clients, orders and prices. Lots have happened since the system was created and the system is now, as the manager described it, "locked up" and "problematic", which I translate as "not dynamic" and "unstable".

Some info about the system

It was developed around the year 2000

Fairly small system, 2-5 users, 6 forms, ~8 tables with average quantities of data

Built on early Visual Basic, forms created with the drag and drop design. Interface is basically just a window with a menu and some forms

Uses MSSQL database (SQL2005 server) to store data and ODBC driver to query, data was migrated from excel before this system, and before excel it was handled, calculated and written by hand and paper

Users work in Microsoft XP environment (and up)

Their main problem is that they can't adjust and calculate prices, can't add new carton types etc, correctly anymore because they can't (or rather, they don't know how to) touch the data on the server.

I suggested 3 possible solutions

Attempt to patch the current system

Create a fresh new interface (preferably similar environment, VB.net or VB based)

Bring it back to an Excel solution, considering it is such a small system

There might be more options, but these are the ones I could think of.

My questions are

What should I recommend and why?

What is or could be the pros and cons of these alternatives?

Are there other (possibly better) alternatives?

答:
Rewrites often have a tendency to run out of budget... Badly.

But having a modern skeleton for the application, might be a good investment, especially if no one knows how old system works, and if things break as soon as you start touching them.

Also, VB6 is bad for support. When you'll need to find specialists in 10 years, that will be pretty problematic.