问:
I cannot understand the application of oops How can I develop the understanding of application of oops?
I am a developer in PHP technology, I am aware of almost all the basics of OOPS, but still cannot find out the way to apply these concepts over a procedural programming.

I do it in very orthodox way, but I don't know why I am coding it in that way. I never have reasoning to justify my OOPS applications, which has inferred me that I am worst in OOPS, Please help me guys to understand the application of OOPS.

答:
Firstly, it's pretty difficult to summarise something as complicated as OO in a few sentences.  I would recommend that you find yourself some good books on the topic, and read them, while practicing what they preach.

That said, a short explanation would be: object orientation is simply one particular way to structure code.  You are trying to create pieces of code which are loosely coupled and cohesive.  Loosely coupled meaning that they don't unnecessarily rely on each other, and cohesive meaning that things that should be close together, are.  Encapsulation is the principle of making a class appear as simple as possible to the outside world, while containing whatever complexity is necessary, inside itself.  You are also trying to reduce repetition and duplication of code and logic (DRY, etc).

These are the general principles, and you should spend a lot of time trying to understand why these are good principles, and what they mean.  They tend to be fairly universal, so you will be able to apply it outside of OO.  Once you have these "basics" (and they are not simple) down, you will understand the whys, and can make your own judgement calls on design.  Unfortunately, I can't think of any way to go into any more detail without writing pages and pages, so I'll leave it at that.  Last tips: try to make sure you understand why you are doing something; but be patient - I've almost never seen anyone who was more than barely competent in OO with less than 5 years of experience.


问:
Is it best practice to have a file only of "includes/requires"?
I have 5-10 files on one server that all catch XMLRPC-PHP requests.  There's about 20 lines of require_once in each one that are all the same.  It'd make life simpler for me to create a separate file that only has the requires and require that in my XMLRPC files.  Is this best practice, or does it open up issues that I don't know about?

答:
Yes it would definitely make your life simpler. As mentioned by others before, I would recommend using the autoloading mechanism.

There is an implementation in the PHP manual, I found it pretty useful. It might look something like this:

```<code>function my_autoloader($class) {
    include 'classes/' . $class . '.class.php';
}

spl_autoload_register('my_autoloader');

// Or, using an anonymous function as of PHP 5.3.0
spl_autoload_register(function ($class) {
    include 'classes/' . $class . '.class.php';
});
</code>```

If you are on PHP 5.3, also consider using namespaces. It's actually even easier to have a good structure and a simple autoloader implemented by default:

```<code>spl_autoload_extensions(".php"); // comma-separated list
spl_autoload_register();
</code>```

However, I remember a bug there. Usually I have a 'bootstrap' file, with this autoloader:

```<code>spl_autoload_register(function($class) {
    if(file_exists('./lib/' . str_replace('\\', '/', $class) . '.php')) {
        require_once './lib/' . str_replace('\\', '/', $class) . '.php';
    }
});
</code>```

Using this mechanism, you have a folder structure that mimics your namespace structure. With this approach, you have a good structure, and do not need to care about including your libraries and other classes.

ContentLicense: CC BY-SA 3.0

Body:
Yes it would definitely make your life simpler. As mentioned by others before, I would recommend using the autoloading mechanism.

There is an implementation in the PHP manual, I found it pretty useful. It might look something like this:

function my_autoloader($class) {
    include 'classes/' . $class . '.class.php';
}

spl_autoload_register('my_autoloader');

// Or, using an anonymous function as of PHP 5.3.0
spl_autoload_register(function ($class) {
    include 'classes/' . $class . '.class.php';
});

If you are on PHP 5.3, also consider using namespaces. It's actually even easier to have a good structure and a simple autoloader implemented by default:

spl_autoload_extensions(".php"); // comma-separated list
spl_autoload_register();

However, I remember a bug there. Usually I have a 'bootstrap' file, with this autoloader:

spl_autoload_register(function($class) {
    if(file_exists('./lib/' . str_replace('\\', '/', $class) . '.php')) {
        require_once './lib/' . str_replace('\\', '/', $class) . '.php';
    }
});

Using this mechanism, you have a folder structure that mimics your namespace structure. With this approach, you have a good structure, and do not need to care about including your libraries and other classes.


答:
Its really very basic. Its about binding together the data and the logic that manipulates that data.

So you have:-

Encapsulation.
all logic and data definitions related to the object are encapsulated in a class.

Interfaces.
some data and methods need to be exposed to the rest of the world if the class is to be useful. Data and Methods so exposed form the interface.

Inheritance.
You can make a more specialized class by inheriting the features and methods of a base class so you don't need to code the logic again.

All the other stuff Polymorphism, Abstract Classes, Sub Classes, Super Classes is pretty much icing on the cake and varies greatly form language to language.

Title: I cannot understand the application of oops How can I develop the understanding of application of oops?

Body:
I am a developer in PHP technology, I am aware of almost all the basics of OOPS, but still cannot find out the way to apply these concepts over a procedural programming.

I do it in very orthodox way, but I don't know why I am coding it in that way. I never have reasoning to justify my OOPS applications, which has inferred me that I am worst in OOPS, Please help me guys to understand the application of OOPS.


问:
What to do when a client has unrealistic expectations?
I've been working on a project for the past six months at a client site, since they require data confidentiality and didn't want us to work at our own office.

When I showed up alone to this client site, I was told that I needed to finish the project in two months.

Since the client is not a software company, and because of various policies, it took around 20-25 days just to give me rights on my machine to install stuff like Eclipse, Tomcat, etc. Even after the delay in getting the environment setup, they were still expecting me to complete the project in the same two month period.

They did not give me any requirement documents, but since I'm working at the client site, we used to have meeting regularly to discuss the requirements.

After six months the application is still not finished, and everyone is blaming me, but they fail to realize that we have added many more features than those discussed in the first few meetings.

I've had to redo many things during this period, e.g. separate a form into two sections; a few weeks later, they asked me to merge the two forms again as it's confusing, and so on.

The scope of the application is increasing every day but they still think it's a two month project that got delayed. When I told them that scope has increased they ask why I didn't ask for requirements at the beginning.

I already work 11-12 hours everyday and travel 3-4 hours, and now they expect me to come on Saturdays also.

I have to do everything here: take requirements, design, code and test.

Please advise me what to do in such a case?

Additional details:
We did have a list of deliverables, but then they added a few more things to it saying these are also important. They also changed a few deliverables. They don't even have their UAT server, they test on my development machine itself via its IP address.

答:
The important thing in such situations is to build a CYA paper trail. Nothing should be done without having it written, especially in a complicated business relationship. Sticking to the initial schedule though they needed 20 days to even let you work is a big red flag that it will become complicated.

You hold a meeting where additional features are required? Write it down afterwards, tag "+X days to the current schedule" on each item and mail it to everyone involved. If you only use the internal mail system of the customer, additionally print it out, including the to:, cc: and bcc: recipients list and carefully archive it away. Beside that, as GrandmasterB said, the customer should sign off such changes to the original requirements.

If the required schedule can't be held, write it to them. If any change occur, write it to them, including the consequences. And so on.

This is not for "I've told you so." when the mess finally hits the wall -- they won't listen to it, anyway. This is your insurance when the customer sues you because he thinks that you didn't fulfill the contract, or when your company sues the customer because he denies payment.


问:
PHP - Internal APIs/Libraries - What makes sense?
I've been having a discussion lately with some colleagues about the best way to approach a new project, and thought it'd be interesting to get some external thoughts thrown into the mix.

Basically, we're redeveloping a fairly large site (written in PHP) and have differing opinions on how the platform should be setup.

Requirements:

The platform will need to support multiple internal websites, as well as external (non-PHP) projects which at the moment consist of a mobile app and a toolbar. We have no plans/need in the foreseeable future to open up an API externally (for use in products other than our own).

My opinion:

We should have a library of well documented native model classes which can be shared between projects. These models will represent everything in our database and can take advantage of object orientated features such as inheritance, traits, magic methods, etc. etc. As well as employing ORM.

We can then add an API layer on top of these models which can basically accept requests and route them to the appropriate methods, translating the response so that it can be used platform independently. This routing for each method can be setup as and when it's required.

Their opinion:

We should have a single HTTP API which is used by all projects (internal PHP ones or otherwise).

My thoughts:

To me, there are a number of issues with using the sole HTTP API approach:

It will be very expensive performance wise. One page request will result in several additional http requests (which although local, are still ones that Apache will need to handle).

You'll lose all of the best features PHP has for OO development. From simple inheritance, to employing the likes of ORM which can save you writing a lot of code.

For internal projects, the actual process makes me cringe. To get a users name, for example, a request would go out of our box, over the LAN, back in, then run through a script which calls a method, JSON encodes the output and feeds that back. That would then need to be JSON decoded, and be presented as an array ready to use.

Working with arrays, as appose to objects, makes me sad in a modern PHP framework.

Their thoughts (and my responses):

Having one method of doing thing keeps things simple. - You'd only do things differently if you were using a different language anyway.

It will become robust. - Seeing as the API will run off the library of models, I think my option would be just as robust.

What do you think?

I'd be really interested to hear the thoughts of others on this, especially as opinions on both sides are not founded on any past experience.

答:
Well, basically you are right. Your arguments are valid and really heavyweight.

But they are right, too. It's simple and robust. It's decoupled. A HTTP api is the way to go, if you ask me.

There would be a third way. What keeps you from implementing HTTP api in PHP? This way you can reuse everything.

Here's how I'd do it: Having the HTTP api, you can abstract it in your application. There will be no difference to a model using the database directly or the HTTP api. After all, it's CRUD either way. It will be slower, yes. But if it runs on the same box, it won't be a show stopper, because request will never leave your machine. JSON encoding and decoding is pretty fast too.

In the HTTP api I'd go for Java, using JPA and JAX-RS. This way it's pretty straightforward.


问:
How to determine whether Design Pattern is implemented correctly?
I am successfully able to scale all my old applications which were not using documented Design Patterns. Whatever pattern it is I don't know. To a large extent, I only felt a need to use simple OOP concepts.

The Design Patterns  concept is complex and hard to understand. When implemented, how to determine whether the implementation is correct and the application possess real loose coupling?

答:
To keep the answer concise, i would say if the following characteristics are visible in your code, you can be confident that the patterns are in place even if you have not made deliberate efforts (which is not an issue) towards it.

Desired Characteristics:

Your code base is testable at unit level

Whenever you are implementing any change requests then you are making changes only to relevant classes which co-related in the domain.

Your code base is not exhibiting software entropy.

If your still curious to identify and tag your code with the real patterns names, i would recommend a to perform following actions to get the ball rolling.

Reverse engineer your code base to generate a few UML daigrams.

Visually compare the diagrams with any ready reference of patterns reference material.

This should give you a fair idea.


问:
Algorithm for appointment reminders
My program allows users to store appointments in a calendar.  What has been requested of me is the ability for SMS reminders to be sent to people to remind them of their appointment.  The SMS would need to be sent out about 2 days prior to their appointment.

I thought the best way to achieve this is to choose a time of the day (eg. midday) for the software to check to see which appointments are in 2 days time and then send out the SMS reminders to the people who have those appointments.

Would this be an advisable approach to this problem?  Is it advisable to have this happen at one time of the day, or would it be better to somehow spread it out over a longer time?

I am assuming at this point that a background thread would be a good idea for this type of activity.

答:
If its two days prior to the appointment it would in my opinion be sufficient to check once a day. I think outlook does it at startup when you say: remind me 2 days before the event. For me it wouldn't make much sense to check that hourly, because it probably wont matter if I read the SMS at 8 AM or 6 PM.

Maybe the best way to be sure is to have a use case or requirement of the end user, and ask him when he expects the notification.

Unfortunately I don't know which language you program in. If it's Java or C#, you may want to take a look at Quartz (Java, C#). You can easily specify how often and when exactly a task should be executed. Maybe you can use it.

Title: Algorithm for appointment reminders


答:
From what you describe, it appears that you are participating in a classical Death March project:

In project management, a death march is any of several types of pathologic projects involving a dysphemistic, dark-humor analogy to real death marches, such as being gruelingly overworked, and (often and most especially) being gruelingly overworked for ill-founded reasons on a project that is obviously at high risk of bad outcome (i.e., project failure, and possibly threat of personal and group reputation damage). Thus the name "death march" may be applied to a project that is ultimately successful but involves a home stretch of unsustainable overwork, or (perhaps more often) to a project that any intelligent, informed member can see is destined to fail (or is at very high risk of failure) but that the members are nevertheless forced to act out by their superiors anyway...

Phenomenon is well known and there are a lot of literature about how to proceed - including of course the seminal Edward Yourdon's book Death March: The Complete Software Developer's Guide to Surviving 'Mission Impossible' Project.

Wikipedia article quoted above makes a good starting point to look for more information, research and recommendations for those involved / interested in death march projects.

Walking in your shoes, first thing I'd consider would be passing a reference to above article to my manager.

That way would let them know I am aware of what is going on, and possibly even help them guide me in terms of framework provided for this notion, like "Look, our current state is close to one described in chapter X at Yourdon. Check it out, along with closely related chapter Y etc..."

In (not very likely) case that manager is not aware about this field of study, referring could give them plenty food for thought helping to identify the situation and decide on how to handle it.

Title: What to do when a client has unrealistic expectations?

Body:
I've been working on a project for the past six months at a client site, since they require data confidentiality and didn't want us to work at our own office.

When I showed up alone to this client site, I was told that I needed to finish the project in two months.

Since the client is not a software company, and because of various policies, it took around 20-25 days just to give me rights on my machine to install stuff like Eclipse, Tomcat, etc. Even after the delay in getting the environment setup, they were still expecting me to complete the project in the same two month period.

They did not give me any requirement documents, but since I'm working at the client site, we used to have meeting regularly to discuss the requirements.

After six months the application is still not finished, and everyone is blaming me, but they fail to realize that we have added many more features than those discussed in the first few meetings.

I've had to redo many things during this period, e.g. separate a form into two sections; a few weeks later, they asked me to merge the two forms again as it's confusing, and so on.

The scope of the application is increasing every day but they still think it's a two month project that got delayed. When I told them that scope has increased they ask why I didn't ask for requirements at the beginning.

I already work 11-12 hours everyday and travel 3-4 hours, and now they expect me to come on Saturdays also.

I have to do everything here: take requirements, design, code and test.

Please advise me what to do in such a case?

Additional details:
We did have a list of deliverables, but then they added a few more things to it saying these are also important. They also changed a few deliverables. They don't even have their UAT server, they test on my development machine itself via its IP address.


答:
This is a queue problem. When you set the reminder, you create a "task". That task has some status, like open and a minimum date time before it may start. So, you check the task list. You can just do that multiple times per day, could even be a continuous process.

When you start working on a task you set it to pending and when done remove it or close it. Depending on the amount of history you want. That way you can always just restart the service, run it on many machines etc. As long as your locking is OK on changing the task status you will be OK.

In general it is advisable if you do this with real queue software. Creating one yourself which is scalable is quite hard actually because of locking issues, servers which get down etc.

Title: Algorithm for appointment reminders

Body:
My program allows users to store appointments in a calendar.  What has been requested of me is the ability for SMS reminders to be sent to people to remind them of their appointment.  The SMS would need to be sent out about 2 days prior to their appointment.

I thought the best way to achieve this is to choose a time of the day (eg. midday) for the software to check to see which appointments are in 2 days time and then send out the SMS reminders to the people who have those appointments.

Would this be an advisable approach to this problem?  Is it advisable to have this happen at one time of the day, or would it be better to somehow spread it out over a longer time?

I am assuming at this point that a background thread would be a good idea for this type of activity.

ContentLicense: CC BY-SA 4.0


问:
How to distribute a web app (that's hosted by the customer)
We're developing a web app that visualizes financial data. We have our first customer, but hope to get more. The terms are that

the customers pay a setup fee, to customize the app for their needs

the customers pay a monthly fee to license the app

the customers install and host the app on their own servers

(Some details: the server just requires a simple node.js installation. There is no database required. Everything is easily installed via npm. All the modules used a open source.)

Our source code is not public, but it doesn't need to be obfuscated or hidden from the customer.

My Questions:

How should we distribute the source code to customers? GitHub seems logical, with the idea that customers just use git to deploy and update. But a customer should only have access to the source code with the customizations made for them – not for other customers. What's a good approach to setting up repositories for distributing these different versions? Where do those live in relation to the development branch?

How do we go about licensing the code?

That's a big question. Hopefully not too big. Partial answers or links to articles are welcomed. Thanks...

答:
You need to have a separate branch of customized web-app project per each client. Because, it sounds like all your customization are done particularly for a specific client.

Example of licencing that might be good to look are listed below:

How to Create Your Own Software License Agreement

How to License Software

CREATIVE COMMONS - might NOT be 100% applicable but good to know

Software licensing in Wiki

Edit: Depending on your country of residence the software licencing may have different regulations. I would also strongly advice to contact a lawyer who is specialized in licencing matters.


问:
Searching in a repository
I'm very new to source control management and one thing puzzles me: is it possible to search through the whole repository for a string? For example I'm tracking one file, which has 100 commits and I would like to see all the version of the file which contain "xyz" inside.

Is this possible? I'm using various GUI clients and non of them has this..? Yes, they can search trough commit messages but I want to find a version even when the commit message does not contain the string.

To put it differently, which GUI client has such a feature? I don't care about which SCM it uses - git, hg, bazaar, all are fine.

答:
In git, that's one of the central features, called pickaxe:

```<code>git log -Stext
git log -Gregexp
</code>```

That will look up revisions that add or remove matching text anywhere. You can of course combine it with path filters and revision ranges and any other options.

Title: Searching in a repository

Body:
In git, that's one of the central features, called pickaxe:

git log -Stext
git log -Gregexp

That will look up revisions that add or remove matching text anywhere. You can of course combine it with path filters and revision ranges and any other options.


问:
Are the terms stable and reliable interchangeable?
Is there a difference between stability and reliability (at least in software engineering context) or can they be used interchangeably? If not, what would be some examples of reliable but not necessarily stable systems, and vice versa?

答:
Stability and Reliability are different things in software development, however they both used as the sister-terms :)

I agree with some mentioned previous comments and would like to add my 2 cents.

Reliability is the extent to which an experiment, test, or any measuring procedure yields the same result on repeated trials.

Stability reliability (sometimes called test, re-test reliability) is the agreement of measuring instruments over time. To determine stability, a measure or test is repeated on the same subjects at a future date. Results are compared and correlated with the initial test to give a measure of stability.

More references on this topic are provided :

Reliability Best Practices

Security, Reliability, Scalability, and Availabili

Improving System Stability & Reliability


问:
Open Source Project: Company to register copyright
I'm releasing an open source project. I want to make it as inclusive as possible for any community that might embrace it. Specifically, I don't want the code copyrighted in my name when an entire community might work on it; that approach seems self-centred and alienating. My immediate thought to avoid this issue is to assign the copyright to a company rather than myself. How do I do this? Do I have to register a corporation? Can I just give the name of a group and call that a company? What legal hurdles are there? I honestly have no idea when it comes to this sort of thing.

(I'm in Canada and want to use the GPL, if that helps.)

答:
(Note: not a lawyer.  For legal advice worth the paper its printed on, go talk to one)

You may not have much of a choice if you want worldwide appeal.

First, for Berne Convention signatories, Copyright is automatically applied to a work the moment it's created.  So your initial choice that is closest to what you want is to explicitly relinquish the copyright: enter it into the Public Domain.  However, in some countries this is not possible.  Germany is a notable example: Public Domain exists there, but only for works by authors who have been long dead (It's a fairly safe bet this isn't the case on this one, unless you're a brain in a jar writing this through zombie electrical impulses.  If so, kudos!)  This means that it would be illegal for people in Germany to use or contribute to your work without a little more effort on your part.

So the next best thing, I feel, is to use some kind of free software licence.  These in general state "This stuff is mine, use it however you feel."  I personally use the MIT licence for this, because I don't mind if other people use my stuff (in fact, I'm happy if they do), but don't particularly care to control it.  If they go and make millions out of it, all the best to them.  Also, if they use it in their nuclear reactor, that's their problem, not mine.  Other licences exist with slightly different intents.

For contributors to the project, do ensure that they agree to have their contributions distributed under the same licence, because their contributions also have their copyright automatically assigned to them (so you'd have to deal with this anyway).


问:
Practices for navigating and changing "long" code files?
Many a times I have to deal with code files which are quite long - about 5 screen pages at the minimum. Almost always there is something towards the top/bottom that I need to refer when I'm at the bottom/top (respectively). It's a mammoth overhead to constantly scroll back-n-forth between the file parts.

It's a cognitive overload to just remember each and everything throughout the file and it's quite necessary to be able to refer to parts of the file.

Yes, the Outline view in some editors like Eclipse/NetBeans helps, but sometimes they will work well only for parts recognizable by that parser. Sometimes outline views don't show up e.g. when coding in CoffeeScript or JavaScript using closures/namespaced functions etc. The fallback is then just manual scroll overhead.

So as programmers what are some of the techniques/practices that can be employed to reduce this ridiculous overhead?

Yes, I can shorten the files, but specifically javascript libraries like Backbone.js etc. are all as one file since you really can't split them into multiple file due to lack of Java-like packages. So under the constraints of inability of splitting a file and the outline views not working, what are some of the techniques I can use to navigate through long source files? I work a lot on Eclipse/Netbeans and Aptana and sometimes Vi (but seldom in production environments). It'd be great to be able to split a window into two and see the same file on one side and code in the other. Not doable with Eclipse/NB/Aptana IMO. Vi, yes but can't use it all the time.

PS: As of now, I split the file among multiple editors e.g. Eclipse and Aptana. It'd be great to have it at one place, but is that the best that we can do? :)

UPDATE - Seems Eclipse has way for doing this and can be found here

答:
Personally I rely on my memory. I remember the scroll bar position where I am looking at some important code. Ofcourse, you can only scroll to approximate location, but in most cases a PgUp / PgDown gets you right there. After a while, it becomes a habit.

You can easily remember about 4-5 scroll locations for a file. It would work great for files upto apprx. 2-3kloc. After that, the scroll bar would reach its minimum size and start losing its precision.


问:
Existing buggy code or a brand new one? (From time perspective)
I am facing some issues with a buggy library I currently have and it's used in my current project,  I need to finish this project as soon as possible in order to deliver it to our client.

However, this library is horrible!

Lots of bugs, lots of errors and bad performance, I thought to write my own library to handle what that library handles (GUI/Graphics and some Data manipulation) but I lack time to do it.

I have wasted a lot of time repairing this library thus I am very close to my deadline with 85% completion and still lots of bugs I face and fix everyday.

Maybe you will ask me the following question:

Why did you use it in the first place if you knew it was buggy?

I will answer that question, the reason why is because the buggy library is considered a standard in out company; plus, I am not the only one who thinks that library is buggy, almost all developers hates it!

My question is, should I deliver the current project with that library then develop a new library and use it to enhance the project after that deliver it to the client again as an update, or develop the new library and restart the whole project using the new one? and why?

答:
As you have also mentioned, first wrap-up your project and try to deliver on time as soon as you can. However, while delivering project replace dependencies on your so called "buggy library" through introduction of the Design by contract principle.

In some terminology it is called Programming with Contracts, where a contract merely defines the requirements of a particular class; it does not actually control the class implementation. The purpose of a contract is to make sure that the intended design specifications are satisfied and not at conflict with each other. In other words a contract helps identify design flaws.


答:
I would consider writing a set of unit tests for the library in question, which exercise just the functionality you NEED from the library (but do so fully), and then see if the library works correctly for just what you need or if you trigger enough bugs for it to be unusable.

If not you now have a set of unittests from which you can easily create your own library.

Title: Existing buggy code or a brand new one? (From time perspective)

Body:
I am facing some issues with a buggy library I currently have and it's used in my current project,  I need to finish this project as soon as possible in order to deliver it to our client.

However, this library is horrible!

Lots of bugs, lots of errors and bad performance, I thought to write my own library to handle what that library handles (GUI/Graphics and some Data manipulation) but I lack time to do it.

I have wasted a lot of time repairing this library thus I am very close to my deadline with 85% completion and still lots of bugs I face and fix everyday.

Maybe you will ask me the following question:

Why did you use it in the first place if you knew it was buggy?

I will answer that question, the reason why is because the buggy library is considered a standard in out company; plus, I am not the only one who thinks that library is buggy, almost all developers hates it!

My question is, should I deliver the current project with that library then develop a new library and use it to enhance the project after that deliver it to the client again as an update, or develop the new library and restart the whole project using the new one? and why?


答: As I was told: "A 80% solution in time is better than a 100% solution too late". I'd finish it using the legacy library and deliver an update later. It is important to plan this update in advance, ideally now. As mentioned by ElYusubov, Design by Contract is a good keyword. You could keep the interface of the library, in that way there would be a sooth shift, even in other projects. If the interface itself is that flawed and rusty, a Bridge might be helpful.</p>


问:
Are unit tests really that useful?
I just graduated with a degree in CS and I currently have a job as a Junior .NET Developer (C#, ASP.NET, and web forms). Back when I was still in university, the subject of unit testing did get covered but I never really saw the benefits of it. I understand what it's supposed to do, namely, determine whether or not a block of code is fit for use. However, i've never actually had to write a unit test before, nor did I ever feel the need to.

As I already mentioned, I'm usually developing with ASP.NET web forms, and recently I've been thinking of writing some unit tests. But I've got a few questions about this.

I've read that unit testing often happens through writing "mocks". While I understand this concept, I can't seem to figure out how I'm supposed to write mocks for websites that are completely dynamic, and where almost everything depends on data that comes from a database. For example: I use lot's of repeaters who have ItemDataBound events etc. (again depending on data that is "unknown").

So question number 1: Is writing unit tests for ASP.NET web forms something that is done often, and if it is: how do I resolve the "dynamic environment" issue?

When I'm developing I go through a lot of trial-and-error. That doesn't mean I don't know what I'm doing, but I mean that I usually write some code, hit Ctrl F5 and see what happens. While this approach does the job most of the time, sometimes I get the feeling that I'm being a little clueless (because of my little experience). I sometimes waste a lot of time like this as well.

So, question number 2: Would you guys advise me to start writing unit tests? I think it might help me in the actual implementation, but then again I feel like it might slow me down.

答:
On a practical level Unit tests can be extremely useful for one very important reason:
 You can test one bit of a code at a time.

When you are writing a whole sequence of complex steps and debug them at the end, you tend to find many bugs, and the process is generally harder because you are further along in the process. In Visual Studio you can generate a quick test, change it a little and run ONLY that test.. You then know that for instance a method calling that method can rely on it. So it increases confidence.

Unit tests dont prove that your program is correct!: Unit tests check for regressions in sensitive code and allow you to test new methods you write.

Unit tests are not meant to test front-ends: Think of a unit test as that small project you create to test a new method you are writing or something, not as some sort of condition that your code needs to meet.

Unit testing works great for collaborative environments: If I have to supply a method to a colleague that is using a completely different technology to mine, like for instance he is calling it from iOS, then I can quickly write a unit test to see if the method he wants
a) Retruns the correct data
b) Performs according to his specifications
c) Doesn't have any nasty bottlenecks.

Title: Are unit tests really that useful?


问:
Parsing excel data in Java before saving it to database
I'm working on some project where I have to make a database to store data which is currently kept in Excel files, so I have to do some changes before writing the data into the database.

I'm going to read those files using Java and write them from Java into the database. Should I use Hibernate for that job? Or how else can I connect to those Excel sheets, read data in Java, and write to the database?

答:
If I were you, I wouldn't use dedicated code for that.

Prefer a tool like ETL (Talend, kettle, by example).

It will be more easy to parse your file and you will have lot of problems (compatibility, maintainability, etc.) already solved.


答:
It is my experience that yes, unit tests are useful.

Unit Testing is about segregating portions of the code you write and ensuring that they work in isolation.  This isolation may indeed involve creating fake or mock objects to talk to the object you're testing, or it may not.  It depends very much on the architecture of your object.

Unit testing grants various benefits:

Primarily, this ensures that the units you test work the way you, the developer, think they should work.  While this is less than it sounds: it doesn't necessarily say that the object is working correctly; only that it's working how you think it should work, it is a far stronger statement than the trial-and-error method that is necessary without unit testing.

Additionally, it ensures that units continue to work the way you, the developer, thought they should work.  Software changes, and this may impact units in unexpected ways.

Another side-effect is that it means that the units you test do work in isolation.  This generally means that you begin programming to interfaces rather than concrete classes, reducing coupling and increasing cohesion: all common hallmarks of good design.  Yes: merely enabling your units of code to have unit tests will naturally improve the design of your code.

However...

Unit Testing is not the end of testing.  Other types of testing are still required.  For example, even when you've shown that units work the way you expect them to work, you still need to show that each unit works the way the units that talk to it expect it to work.  That is, do your components integrate with each other correctly?

Title: Are unit tests really that useful?

Body:
I just graduated with a degree in CS and I currently have a job as a Junior .NET Developer (C#, ASP.NET, and web forms). Back when I was still in university, the subject of unit testing did get covered but I never really saw the benefits of it. I understand what it's supposed to do, namely, determine whether or not a block of code is fit for use. However, i've never actually had to write a unit test before, nor did I ever feel the need to.

As I already mentioned, I'm usually developing with ASP.NET web forms, and recently I've been thinking of writing some unit tests. But I've got a few questions about this.

I've read that unit testing often happens through writing "mocks". While I understand this concept, I can't seem to figure out how I'm supposed to write mocks for websites that are completely dynamic, and where almost everything depends on data that comes from a database. For example: I use lot's of repeaters who have ItemDataBound events etc. (again depending on data that is "unknown").

So question number 1: Is writing unit tests for ASP.NET web forms something that is done often, and if it is: how do I resolve the "dynamic environment" issue?

When I'm developing I go through a lot of trial-and-error. That doesn't mean I don't know what I'm doing, but I mean that I usually write some code, hit Ctrl F5 and see what happens. While this approach does the job most of the time, sometimes I get the feeling that I'm being a little clueless (because of my little experience). I sometimes waste a lot of time like this as well.

So, question number 2: Would you guys advise me to start writing unit tests? I think it might help me in the actual implementation, but then again I feel like it might slow me down.


问:
Is it wrong to push messages from server to client in a client-server application?
I practically never see any web application where server pushes messages to the client. While pushing messages from server to client is hugely used in multiplayer games, why this model is so underused in web apps?

Is it wrong? Does it destroy the client-server model?

答: I dont think it's wrong. E.g. The company I am with offers a client-server version control system, which pushes a message of in-advance notice when scheduled maintenance is up. </p>


问:
Storing and maintaining serialized objects in C#
What are the best practices to store and maintain serialized objects in C#? Any strategies or patterns that apply?

What I have come to believe so far is this:

Prefer Json over XML, both for space and for speed, but xml is easier to query/mine data via LINQ to XML for bigger data sets.

For every single property, map explicitly to a serialized name. In the future, when you need to rename a property, your serialized data won't break. Attributes help with this.

Store some kind of version info on the serialized object, in case you need to mass-migrate data in the future

Update: (that I found out the hard way)

Store all datetimes in a uniform way throughout the whole application and throughout all versions. Both concerning format and time zone.

答:
Mentioned points are practical and good to keep in mind. I would like to mention different types of serializations that might be useful to consider depending on your application needs.

Binary Serialization - it uses binary encoding to produce compact serialization for uses such as storage or socket-based network
streams.

XML serialization -  it serializes the public fields and properties of an object, or the parameters and return values of
methods, into an XML stream that conforms to a specific XML Schema
definition language (XSD) document. More info is available in System.Xml.Serialization namespace .

SOAP Serialization - it is a different flavor of XML serialization, where it can be used to serialize objects into XML streams that conform to the SOAP specification. SOAP is a protocol based on XML, designed specifically to transport procedure calls using XML. As with regular XML serialization, attributes can be used to control the literal-style SOAP messages generated by an XML Web service.

More information form official source - MSDN C# programming

Also all this need to be practices within SDLC process (meaning having environment to test, version control, etc. )


问:
Does this happen in Common Lisp?
From Steve Yegge's "Lisp is Not an Acceptable Lisp":

```<code> Lisp has a little syntax, and it shows up occasionally as, for instance, '(foo)
 being expanded as (quote foo), usually when you least expect it.
</code>```

What is he talking about with '(foo) being expanded into (quote foo) in some situations?  (As opposed, I would imagine, to (quote (foo))).

答: I don't know. I cannot think of any situation where '(foo) would be turned into (quote foo) since it's actually the same as (quote (foo)) (the ' symbol is typically a reader macro that reads the next s-exp and returns it surrounded by a call to the quote special form).

Title: Does this happen in Common Lisp?


问:
Any tips to learn how to program with severe ADHD?
I have a difficult time trying to learn how to program from straight text-books. Video training seems to work well for me in my past experiences with PHP. I am trying my hardest to stay focussed and push through. Specifically I am looking to start indie game development.

Over the last two weeks I have been trying to pick the "right" language and framework to develop with. I started going through Python, but I am not really enjoying the language so far. I am constantly looking through this website to compare this language to that, and keep getting distracted.

Aside from all of this, is it possible to become a programmer when you have trouble focussing? Has anyone been through this that can recommend some advice?

答:
Commit to a language and framework. Once you have made that commitment, forsake all others.  Be faithful to that one language and framework, at least for awhile.  Then...

Pick one thing to code, and work on that.  Focus on coding that only.  Get it done, quickly.  Then work on the next thing.  If you find yourself getting bogged down in a task, break it down into smaller pieces and work on each one individually.

If you can control your focus, you will find that you have better productivity than your non-ADHD peers.  That is the great paradox of ADHD; once you are focused, you are hyper-focused.

Do things quickly; stay in that zone.  But concentrate on one thing at a time.  That is the secret.

ContentLicense: CC BY-SA 2.5


问:
Confusion regarding def function within Python
I've been learning Python for about 2 months now (Started with Learn Python The Hard Way, now reading Dive Into Python), and within both books, I still seem to be confused over this one bit of code.

Lets just take the default code that Dive Into Python uses as an example:

```<code>def buildConnectionString(params):
    """Build a connection string from a dictionary of parameters.

    Returns string."""
    return ";".join(["%s=%s" % (k, v) for k, v in params.items()])

if __name__ == "__main__":
    myParams = {"server":"mpilgrim",
                "database":"master",
                "uid":"sa",
                "pwd":"secret"
               }

print buildConnectionString(myParams)
</code>```

How does the function buildConnectionString with the argument (params) know to get its data from the variable myParams?  Or params.items(), too within the return line?  Wouldn't the argument in buildConnectionString need to be set as buildConnectionString(myParams) in order for it to read properly?  How can you set the variable of your data to myParams, but have the argument of your function be params and have it read?  How does it know to read myParams as params?

And is there a reason behind not naming your variable params, or vice versa naming your argument in your function myParams?  It's just been extremely confusing seeing the argument set as one word, and then having the variable named something completely different, but having the function still be able to read your code, even when the argument name is different from your variable with the data you're printing from.

答:
It's not about Python.

But nevertheless, to answer you straightly. Lets say you have a function:

```<code>def doSomethingWithParmas(params):
    params.doSomething()
</code>```

Now you can call it later on with:

```<code>print doSomethingWithParams(myParams)
</code>```

or/and

```<code>print doSomethingWithParams(yourParams)
</code>```

It's how functions work, you can call it with whatever params you like, all that function cares, is that they are some kind of params that it can handle.

EDIT: A remark: I have never coded a line of Python in my life.

Body:
It's not about Python.

But nevertheless, to answer you straightly. Lets say you have a function:

def doSomethingWithParmas(params):
    params.doSomething()

Now you can call it later on with:

print doSomethingWithParams(myParams)

or/and

print doSomethingWithParams(yourParams)

It's how functions work, you can call it with whatever params you like, all that function cares, is that they are some kind of params that it can handle.

EDIT: A remark: I have never coded a line of Python in my life.


问:
As a programmer, should I know low and high-level programming languages?
I been contacted to do some work remote controlling LEDs displays over TCP/IP, but my experience and preparation is mostly about high-level programming language. I said that to the person who contact me about the work and he told me that:

"if you call yourself a programmer you
  should know all these things"

Should a programmer really know the details of low-level programming? Or can I treat it as a black box concept, as theoretical knowledge but not necessarily doing it or implementing  low level language solutions, having in mind that low-level programming is not my expertise?

答:
I will re-phrase

"if you call yourself a programmer you
  should know all these things"

TO

"if you call yourself a programmer you
  should know enough that you can quickly learn all these things"


答:
I've done quite a bit of serialization over the years. Here are some things we came up with:

Prefer human readable formats over binary formats. I'd generally prefer Xml to Json mainly because you can use Xslt to transform Xml when you need to upgrade the version.

Whatever you are serializing stuff as, the deserialization logic and data storage should allow for versioning of the serialized data. Version info should probably be outside the serialized data, makes it a bit easier to get at and choose the right deserialization strategy.

Your serialization should have unit tests running both ways. IE, you should have a test deserializing the data and confirming you get everything imported correctly. And you should have something serialize the data and confirm it comes out as the correct json and xml.

If the point of said serialization is cross-platform, test against the other platform. Probably not as much of a problem now as platforms have matured, but there were times when things did not agree on how json should be formatted.

Title: Storing and maintaining serialized objects in C#

Body:
What are the best practices to store and maintain serialized objects in C#? Any strategies or patterns that apply?

What I have come to believe so far is this:

Prefer Json over XML, both for space and for speed, but xml is easier to query/mine data via LINQ to XML for bigger data sets.

For every single property, map explicitly to a serialized name. In the future, when you need to rename a property, your serialized data won't break. Attributes help with this.

Store some kind of version info on the serialized object, in case you need to mass-migrate data in the future

Update: (that I found out the hard way)

Store all datetimes in a uniform way throughout the whole application and throughout all versions. Both concerning format and time zone.


问:
Equivalent of Domain Driven Design for functional programming languages
I really love the idea of domain driven design, however, as I'm learning Go, I'm wondering if there's the equivalent of DDD that's aimed at an effectively more functional language?</p>

答:
There's no equivalent. DDD needed a paradigm to support frequent rewriting in an evolutionary software development scenario. OOP looked like the only viable strategy back then. But Functional languages can serve such a scenario as well.

You might want to have a look to
Greg Young's video about DDD and Functional Programming and Patrik Fredriksson's video about implementing DDD with a functional language like Clojure


答:
I find the best way to learn to program is not through videos or books, but through trying to program. Pick a small task (that interests you) that you would want a program to do, and set about doing it. For example:

"I would like a program that read the contents of an xml file and displayed the items in a list on web page."

Don't try to write a huge piece of software, just do small exercises. I think you'll find that you learn quite a bit this way. Obviously, you'll want to use the internet as a resource for when you have questions:

How do I open the file?

How do I parse the file?

How to I write it to the page?

etc...

Not only will you avoid having to put on a video and flip through books, but it should keep you fairly engaged in the learning process to hopefully circumvent and ADHD problems. (of course maybe suggesting the internet as a resource isnt the best for that :))

This approach is also language agnostic, but I would follow the advice in Robert's answer and pick a language. I'm a fan of C# myself.

Title: Any tips to learn how to program with severe ADHD?

Body:
I have a difficult time trying to learn how to program from straight text-books. Video training seems to work well for me in my past experiences with PHP. I am trying my hardest to stay focussed and push through. Specifically I am looking to start indie game development.

Over the last two weeks I have been trying to pick the "right" language and framework to develop with. I started going through Python, but I am not really enjoying the language so far. I am constantly looking through this website to compare this language to that, and keep getting distracted.

Aside from all of this, is it possible to become a programmer when you have trouble focussing? Has anyone been through this that can recommend some advice?


问:
Good principles to explain the use of data objects
I'm in a little need of names clarification. First a brief description of my position. I prepare as debutant giving a junior developer job descriptions, which also provided another perspective on how important communication is, and to put it beyond doubt.

Simply; I like to understand what he mean with "Context" and I like to give a  adopted description of what a POCO is. Now, this is not the exactly problematic words. We haven't even spoken yet. I describe it more as the semantic problem and focus on data and IoC, because there is the place we're going to met (He = GUI, I'm BL).

I give a manual-typed sample just as a reference for naming different part of it. Some terms are local to a Manufacturer or tool and some are used more Generic, which I prefer the latter.

```<code>// Poco, Model?
public class Customer
{
    public int CustomerId { get; set; }
    public string Name { get; set; }
}

// A short sign of repository pattern
public class CustomerContext
{

   // Is this a context or even a entity?
   List<Customer> cust;
   public CustomerContext()
   {
      cust = new List<Customer>();
      cust.Add(new Customer() { CustomerId = 1, Name = "Doe" });
      cust.Add(new Customer() { CustomerId = 2, Name = "John" });
      cust.Add(new Customer() { CustomerId = 3, Name = "Zelda" });
      cust.Add(new Customer() { CustomerId = 4, Name = "Kim" });
   }

   public IQueryable<Customer> Get()
   {
      return cust;
   }
}
</code>```

*What terms fit best? *

Are 'Customer' a Model (tooked from MVC)?
Does we, simply put, mean the same with POCO?

What do I call the sample typed data above? Mocks? Simply "Data"?

What do I call the object CustomerContext? A repository? A Context? Is it an Entity?

Are there other terms that have escaped this scope?

It appears common to write about repositories and generics, even though fell into a scope of a manufacturer (where i.e. 'Entity' commonly means Entity Framework). A strong indication of what terms means what (and when), would be of help.

答:
Are 'Customer' a Model? Which it appear to be called in MVC?

Yes, it can be called a Model.  Often in MVC, the Model is not simply a single business entity - it could, for example, be a collection of multiple entities and various user settings rolled into one, everything the View needs to be able to do its job.

Does we, simply put, mean the same with POCO?

Yes, it's a POCO, because you are not implementing any specific interfaces, or inheriting from some entity framework.

What do I call the static typed data (in such case)? Mocks? Simply "Data"?

I would probably call it test data.  It's kind of hard to call it a "mock" since it seems to be your primary implementation at this point.  I've never encountered the word mock being used outside the context of unit testing, what you have here seems to be more in line with the term "fake" (see Wikipedia's article on these particular terms).

What do I call the object CustomerContext? A repository? A Context? Is it an Entity? I often confuse these terms with what I mean.

It looks like it's the beginnings of a Repository Pattern.

As an aside, List<Customer> cust; is a fairly bad naming convention - try not to use abbreviations.  It will be confusing when the Custodian, Custard and other similar classes start making appearances in your code :)


问:
How to manage a copyright notice in an open source project?
I'm working on, and adding to, a GitHub-hosted project that includes this LICENCE.md (apparently the MIT licence verbatim):

```<code>Copyright (c) 2012 [Acme Corp]

Permission is hereby granted, free of charge, to any person obtaining a copy
of this software and associated documentation files (the "Software"), to deal
in the Software without restriction, including without limitation the rights
to use, copy, modify, merge, publish, distribute, sublicense, and/or sell
copies of the Software, and to permit persons to whom the Software is
furnished to do so, subject to the following conditions:

The above copyright notice and this permission notice shall be included in
all copies or substantial portions of the Software.
</code>```

I've made changes, improvements etc (say 10% of the code, in ballpark figures) and publish the code to my own GitHub fork.

What should I do with this copyright notice? I'd like to update it (eg, just to add the name of my own organisation), but it says not to. How are these things normally managed? Add a separate copyright file?

答:
I wouldn't worry too much about the copyright bit. I believe in most cases copyright applies automatically whether you claim it or not so the (c) 2012 blah headers are mostly noise. That being said you don't want to mislead people so as you're including the license you should indicate that by saying the software was originally licensed as... or that parts of the software are licensed as...

As the source is already publicly available it should already be clear who the author(s) are, and, as it seems that no money is changing hands, it would be pretty hard to make a claim for damages even in the event that the authorship is contested.

Perhaps a more pressing is issue is that of being a good web citizen. People that provide open source software are doing the community a service, and we should strive to make that a positive experience for all. So my advice is to ask your question directly to [Acme Corp] and try to establish a relationship with them whereby you both benefit.


问:
Reasons NOT to use JSF
I am new to StackExchange, but I figured you would be able to help me.

We're crating a new Java Enterprise application, replacing an legacy JSP solution. Due to many many changes, the UI and parts of the business logic will completely be rethought and reimplemented.

Our first thought was JSF, as it is the standard in Java EE. At first I had a good impression. But now I am trying to implement a functional prototype, and have some really serious concerns about using it.

First of all, it creates the worst, most cluttered invalid pseudo-HTML/CSS/JS mix I've ever seen. It violates every single rule I learned in web-development. Furthermore it throws together, what never should be so tightly coupled: Layout, Design, Logic and Communication with the server. I don't see how I would be able to extend this output comfortably, whether styling with CSS, adding UI candy (like configurable hot-keys, drag-and-drop widgets) or whatever.

Secondly, it is way too complicated. Its complexity is outstanding. If you ask me, it's a poor abstraction of basic web technologies, crippled and useless in the end. What benefits do I have? None, if you think about. Hundreds of components? I see ten-thousands of HTML/CSS snippets, ten-thousands of JavaScript snippets and thousands of jQuery plug-ins in addition. It solves really many problems - we wouldn't have if we wouldn't use JSF. Or the front-controller pattern at all.

And Lastly, I think we will have to start over in, say 2 years. I don't see how I can implement all of our first GUI mock-up (Besides; we have no JSF Expert in our team). Maybe we could hack it together somehow. And then there will be more. I'm sure we could hack our hack. But at some point, we'll be stuck. Due to everything above the service tier is in control of JSF. And we will have to start over.

My suggestion would be to implement a REST api, using JAX-RS. Then create a HTML5/Javascript client with client side MVC. (or some flavor of MVC..) By the way; we will need the REST api anyway, as we are developing a partial Android front-end, too.

I doubt, that JSF is the best solution nowadays. As the Internet is evolving, I really don't see why we should use this 'rake'.

Now, what are pros/cons? How can I emphasize my point to not use JSF? What are strong points to use JSF over my suggestion?

答:
There is at least one very good reason for considering JSF.

It is a standard part of the Java EE stack, and hence will be available - and working - in ALL Java EE containers for a very, very long time.  And maintained too, without you needing to do so if you have adhered strictly to the Java EE specification.

If this is a concern for you, then you should consider it.  Most software live longer than their designers think, especially if taken in consideration when being written.

Title: Reasons NOT to use JSF


问:
What to do when a client has unrealistic expectations?
I've been working on a project for the past six months at a client site, since they require data confidentiality and didn't want us to work at our own office.

When I showed up alone to this client site, I was told that I needed to finish the project in two months.

Since the client is not a software company, and because of various policies, it took around 20-25 days just to give me rights on my machine to install stuff like Eclipse, Tomcat, etc. Even after the delay in getting the environment setup, they were still expecting me to complete the project in the same two month period.

They did not give me any requirement documents, but since I'm working at the client site, we used to have meeting regularly to discuss the requirements.

After six months the application is still not finished, and everyone is blaming me, but they fail to realize that we have added many more features than those discussed in the first few meetings.

I've had to redo many things during this period, e.g. separate a form into two sections; a few weeks later, they asked me to merge the two forms again as it's confusing, and so on.

The scope of the application is increasing every day but they still think it's a two month project that got delayed. When I told them that scope has increased they ask why I didn't ask for requirements at the beginning.

I already work 11-12 hours everyday and travel 3-4 hours, and now they expect me to come on Saturdays also.

I have to do everything here: take requirements, design, code and test.

Please advise me what to do in such a case?

Additional details:
We did have a list of deliverables, but then they added a few more things to it saying these are also important. They also changed a few deliverables. They don't even have their UAT server, they test on my development machine itself via its IP address.

答:
I've found Gantt Charts can be very good in these kind of situations.  They can illustrate to clients the current schedule and can be useful in illustrating the effect of adding in any new features/changes.  Sometimes telling a client that feature x will effect the delivery by y days doesn't register with them.  By having it clearly on a graph they can grasp it better.

Ideally this should be done from the start of the project.  It might not be as useful to explain the "delays" up to this point, but might help with the project going forward.

From Wiki:

Gantt charts illustrate the start and finish dates of the terminal
  elements and summary elements of a project.


答:
Are 'Customer' a Model? Which it appear to be called in MVC?

In my opinion: Customer, is a DTO (Data Transfer Object). As it is right now, there's no logic or behaviour built into Customer - this is generally what separates it from being a business entity, domain entity or anything of that sort. Because of that, I wouldn't necessarily call it a model exactly, or I'd say that your model is anemic (or you've just over-simplified the example and this doesn't apply).

Does we, simply put, mean the same with POCO?

This you really could have just looked up first. Either way, POCO is often used in the context of an ORM. It simply means that you aren't forced to inherit some base entity type that is required by your persistence framework.

What do I call the static typed data (in such case)? Mocks? Simply "Data"?

As Daniel B states, it's test data. A mock is an object where you provide the expectations that the object should return (at run/test time). A Fake is roughly the same thing, except that the expectations are often provided at design time. There's a good writeup here.

What do I call the object CustomerContext? A repository? A Context? Is it an Entity? I often confuse these terms with what I mean.

Based on all of your questions, I suggest some reading/research:

Repository Pattern

Context Pattern

And, last, and most important of all: the major benefit of design patterns is that they provide the ability to communicate about code at a more efficient and more abstract level. I highly suggest a few good patterns books as this is exactly the problem you're having. There are many questions on the SE network that have wonderful answers. For example.

Title: Good principles to explain the use of data objects

Body:
I'm in a little need of names clarification. First a brief description of my position. I prepare as debutant giving a junior developer job descriptions, which also provided another perspective on how important communication is, and to put it beyond doubt.

Simply; I like to understand what he mean with "Context" and I like to give a  adopted description of what a POCO is. Now, this is not the exactly problematic words. We haven't even spoken yet. I describe it more as the semantic problem and focus on data and IoC, because there is the place we're going to met (He = GUI, I'm BL).

I give a manual-typed sample just as a reference for naming different part of it. Some terms are local to a Manufacturer or tool and some are used more Generic, which I prefer the latter.

```<code>// Poco, Model?
public class Customer
{
    public int CustomerId { get; set; }
    public string Name { get; set; }
}

// A short sign of repository pattern
public class CustomerContext
{

   // Is this a context or even a entity?
   List<Customer> cust;
   public CustomerContext()
   {
      cust = new List<Customer>();
      cust.Add(new Customer() { CustomerId = 1, Name = "Doe" });
      cust.Add(new Customer() { CustomerId = 2, Name = "John" });
      cust.Add(new Customer() { CustomerId = 3, Name = "Zelda" });
      cust.Add(new Customer() { CustomerId = 4, Name = "Kim" });
   }

   public IQueryable<Customer> Get()
   {
      return cust;
   }
}
</code>```

*What terms fit best? *

Are 'Customer' a Model (tooked from MVC)?
Does we, simply put, mean the same with POCO?

What do I call the sample typed data above? Mocks? Simply "Data"?

What do I call the object CustomerContext? A repository? A Context? Is it an Entity?

Are there other terms that have escaped this scope?

It appears common to write about repositories and generics, even though fell into a scope of a manufacturer (where i.e. 'Entity' commonly means Entity Framework). A strong indication of what terms means what (and when), would be of help.


问:
How important is it to implement a caching system in an MVC style framework?
I am writing my own PHP framework (...waits for the groans to subside) for the purpose of learning (best practices, design principals etc.) as I'm entirely self-taught and consequently there are gaps in my knowledge.

I understand that most mainstream frameworks incorporate some form of caching system, which I'm guessing is for keeping regularly used classes and/or other files close by for fast loading (right?).

Ideally I envisage a system that is somewhat self monitoring and self managing in that it tracks class/file usage, memory limits and request processing performance, removing items from cache automatically when no longer needed or increasing the cache size when performance drops too low etc. (even some form of basic garbage collection is better than nothing, right?).

So my questions are:

Firstly: Have I understood everything correctly so far?

How important is it to implement this kind of system over regular include/require methods?

How can I determine memory usage and other system performance metrics?

To cache classes do I have to use the '_sleep()' and '_wakeup()' magic methods?

I also gather that to be stored a class has to be serialized. Should I use a $_SESSION variable, a temporary DB table or some kind of flat-file / SQLite DB as the cache?

Thanks for any and all help / suggestions.

答:
From my experience, caching is necessary only when it is very slow to initialize some classes (for example they read system information which takes a long time to process).

For these problems you can use PHP's Memcache. I see absolutely no point in inventing another caching mechanism for PHP.


答:
For simple apps with small numbers of layers to test (Main window -> sub menu), perhaps compiling to run to check changes is ok.

For larger apps where it takes 30s navigation to get ot the page you're testing, this ends up being very expensive..

Title: Are unit tests really that useful?


答: I wouldn't bother, as long as your execution time is not terribly slow. You can keep objects in the shared memory if you like, so no serialization is needed. This would probably also be the most elegant way.</p>

Title: How important is it to implement a caching system in an MVC style framework?

Body:
I am writing my own PHP framework (...waits for the groans to subside) for the purpose of learning (best practices, design principals etc.) as I'm entirely self-taught and consequently there are gaps in my knowledge.

I understand that most mainstream frameworks incorporate some form of caching system, which I'm guessing is for keeping regularly used classes and/or other files close by for fast loading (right?).

Ideally I envisage a system that is somewhat self monitoring and self managing in that it tracks class/file usage, memory limits and request processing performance, removing items from cache automatically when no longer needed or increasing the cache size when performance drops too low etc. (even some form of basic garbage collection is better than nothing, right?).

So my questions are:

Firstly: Have I understood everything correctly so far?

How important is it to implement this kind of system over regular include/require methods?

How can I determine memory usage and other system performance metrics?

To cache classes do I have to use the '_sleep()' and '_wakeup()' magic methods?

I also gather that to be stored a class has to be serialized. Should I use a $_SESSION variable, a temporary DB table or some kind of flat-file / SQLite DB as the cache?

Thanks for any and all help / suggestions.


问:
Compiler Linking: How to handle circular references?
I'm currently writing a compiler for a new language and I'm struggling with the linking aspect of new Types when there exists a circular reference.

I've created a dependency tree so that I can compile the Types in the order of their dependencies which seemed to have fixed my problem... that is until I hit circular references like an example below (posted in c#):

```<code>public class A
{
  public A() {  var b = new B(); }
}

public class B
{
  public B() { var a = new A(); }
}
</code>```

My limitation is that I can only create 1 Type at a time, and in the case of circular references, either A needs to be created first, or B needs to be created first, both of which poses the problem that I can't create either unless it's dependencies are first created!

How do compilers overcome this?

答:
In general, you create A and add it to the scope. When you get to resolve B, you go and build B. When that gets to resolving A, it finds a (partially) constructed type and grabs that reference. Then you return back to building A.

There are other situations that are more problematic (like cyclical inheritence, dll references, recursive type declarations) that often require placeholder types or are simply not viable given other design constraints. In general, keeping each compilation phase thin helps prevent issues. For example, you can only do the partial type trick if nothing needs to know the members of A in B.


答:
I understand that most mainstream frameworks incorporate some form of caching system, which I'm guessing is for keeping regularly used classes and/or other files close by for fast loading (right?).

It's a bit more complicated than that; the frameworks typically provide mechanisms for caching an entire view's results.  E.g. you may have a (sub) view which provides the top 5 articles.  If you let the framework know that this view must only be re-rendered every 5 minutes, it will try to cache it on the first request.  Subsequent requests will be given the same pre-generated response, until the five minutes has elapsed.  Typically you also have ways of specifying whether this behaviour is global, or per-session, which URL parameters define a unique request which needs to be cached, etc.  This is an optimisation, and can provide large benefits in many cases.  Symfony 2's documentation has a very good explanation of the principles.

You may also choose to cache things at a lower level.  E.g. retrieving the list of countries from the DB for each request is a waste of resources, and can be avoided by caching that list on the first request.  This may or may not be a core part of a framework, but even in this case, you shouldn't roll your own, as others have pointed out.  In general, the previous mode of caching seems to favoured, since it prevents even the view logic from being run, a greater saving.

In terms of how necessary any of this is; it really depends on your situation.  In my experience, unless you're expecting large numbers of users (say, more than a few dozen on your site at the same time), you don't need caching.  A site like StackOverflow, on the other hand, would not be able to function without a very well thought out caching strategy.


答:
While I agree that this is a management failure, it is also a failure on your part. At this stage it will be very hard to fix, so some of what you need to get out of this is how to handle future projects.

First, you need to insist ona a requirements baseline document at the start of the project. Doesn't have to be fancy or formal, but you cannot successfully build anything until the client specifies what is expected. If you don't have this in writing, the chances of the customer being pleased with the end result are aproximately 0%. So this is critically important. It is also your job to look for the ambiguities in this document and get them cleared up as soon as possible. When you come across one of these and you aren't sure how to interpret it, don't make a guess as to what you think it means, make sure you and the client are on the same page about what it means. Yes this means more talking to people and more meetings and less coding. But it takes much less time to clear up an unclear requirement than to code it wrong and then have to recode it. Further, you often have to give them the re-coding for free and that is not good for the company you work for.

Next, you tell them how long it takes to do the work and that sets the deadline. You do not ever accept a deadline that is based on anything other than the amount of hours it will take to do the work to meet the requirements.  If you do, you will be in a death march again. Show them how the deadline is not possible to meet by having a detailed explantion for the hours it will take. You can't fit 200 hours of development time into a week with only 1 developer no matter how much the client wants it. At that point when the deadline is immovable, you ask what items should be moved to the next iteration.

Do not forget that devlopment time is only a small portion of project time when doing project time estimates. You also have to account for meetings and email/phone communications, testing, deployment, documentation, physical set-up of servers, workstations, software. Further, in planning the deadline, you can only assume that you have 6 hours a day available not 8. This is to account for leave, bereavement, sick time, unavoidable delay (such as when you had to wait for them to get you permissions on the network etc.), training, non project-related work (time sheets, HR meetings, etc.). One of the biggest reasons why people don't meet their deadlines is that they make the assumption that they will be only doing development and working 8 hours solid at it every single day. This is simply not a realistic assumption.

And every time they add another piece on, you tell them how much longer it will take and how much the additional work will move the deadline. You don't ask to move the deadline, you tell them that is is moving due to the new requirement. Now you should go through your manager for this, but it is first of all your reponsiblity to make sure your manager knows every time the requirement is changed and how much that will add to the project. Make sure all of this is in writng, so you can defend yourself if need be.

Next, do not allow yourself to be abused into working 11-hour days and weekends. This is OK in short spurts (Of less than 1 week every six months or so), but for the long term this is simply not acceptable. Tired people code slower and they make more mistakes. You can get more done with higher quality working regularly 8 hours than regularly 11 hours. and weekends.


答: I think you're trying to solve in the compiler something that should be resolved by the linker.  Both A and B should compile to whatever intermediate code they use (traditionally an object file) and just list the other type as an external symbol.  When you generate the executable form, you go through the symbol table for each object file and resolve the external references.  See this for a good introduction to traditional linkers.</p>

Title: Compiler Linking: How to handle circular references?

Body:
I'm currently writing a compiler for a new language and I'm struggling with the linking aspect of new Types when there exists a circular reference.

I've created a dependency tree so that I can compile the Types in the order of their dependencies which seemed to have fixed my problem... that is until I hit circular references like an example below (posted in c#):

```<code>public class A
{
  public A() {  var b = new B(); }
}

public class B
{
  public B() { var a = new A(); }
}
</code>```

My limitation is that I can only create 1 Type at a time, and in the case of circular references, either A needs to be created first, or B needs to be created first, both of which poses the problem that I can't create either unless it's dependencies are first created!

How do compilers overcome this?


问:
How to keep track effectively of cache keys to invalidate them accordingly?
In an ordinary application, the same information may be retrieved from the database in several ways. If all those ways implement caching, you need to invalidate all those cache entries when updating an entry in the database.

Some pairing between updates and selects is easy to do. Let's take an example of a product 123 in the category 9 with a price of $12.50. If you select a product by ID:

```<code>select [...] from [Shop].[Product] where [ProductId] = 123
</code>```

caching it with a key Product<Id:123>, it's not so difficult to invalidate this cache entry after updating a price of a product identified by its ID:

```<code>update [Shop].[Product] set [Price] = 14.99 where [ProductId] = 123
</code>```

Things become more difficult when you have also to remember to invalidate the cache with the key MostExpensive<CategoryId:9> corresponding to the query:

```<code>select max([Price]) from [Shop].[Product] where [CategoryId] = 9
</code>```

What is an effective way to keep track of cache entries? How to find, during development or code review, what entries must be invalidated when one or another piece of data is changed?

答:
MySQL invalidates its query caches based on the underlying table. If the table used in the query is edited with any INSERT, UPDATE, or DELETE, any query cached with references to that table is invalidated.  (I know MySQL isn't the shining example of best practices, but in this case it works very well.)

So, in your example, if you ever update [Shop].[Product] you could invalidate all caches with references to it.  You would need a second set of meta-data that relates every table to related cache entry keys, e.g. [Shop].[Product] => (Product<Id:123>, MostExpensive<CategoryId:9>).

A slightly more efficient route would be to NOT invalidate those keys that reference the table's primary key when those records are not updated.  So if you update record with ProductId 345, do not invalidate key Product<Id:123>.

If you pass all of your queries through a caching layer that quickly grabs table names out of each query and handles all cache entries it's manageable.  I feel like there's probably a completely different solution that's more direct, but I can't think of one at the moment.


答:
How do compilers overcome this?

Some languages (C++, Objective-C) allow forward declarations which introduce the type but don't define it. It'd go something like:

```<code>public class B;  // now the compiler knows that B is a class that will be defined later

public class A
{
  public A() {  var b = new B(); }
}

public class B
{
  public B() { var a = new A(); }
}
</code>```

That said, even a forward declaration won't solve the circular problem in your example: Creating a new A will create a new B, which in turn will create another A, which will create another B, and so on. If you want one A and one B that point to each other, you'll need to create constructors that take a reference to an existing object, like:

```<code>public class A
{
  public A(B _b) { var b = _b; }
  public A()     { var b = new B(this); }  // 'this' is a C++-style pointer to the current object
}
</code>```

Body:
How do compilers overcome this?

Some languages (C++, Objective-C) allow forward declarations which introduce the type but don't define it. It'd go something like:

public class B;  // now the compiler knows that B is a class that will be defined later

public class A
{
  public A() {  var b = new B(); }
}

public class B
{
  public B() { var a = new A(); }
}

That said, even a forward declaration won't solve the circular problem in your example: Creating a new A will create a new B, which in turn will create another A, which will create another B, and so on. If you want one A and one B that point to each other, you'll need to create constructors that take a reference to an existing object, like:

public class A
{
  public A(B _b) { var b = _b; }
  public A()     { var b = new B(this); }  // 'this' is a C++-style pointer to the current object
}


问:
Optimal communication pattern to update subscribers
What is the optimal way to update the subscriber's local model on changes C on a central model M? ( M + C -> M_c)

The update can be done by the following methods:

Publish the updated model M_c to all subscribers. Drawback: if the model is big in contrast to the change it results in much more data to be communicated.

Publish change C to all subscribes. The subscribers will then update their local model in the same way as the server does. Drawback: The client needs to know the business logic to update the model in the same way as the server. It must be assured that the subscribed model stays equal to the central model.

Calculate the delta (or patch) of the change (M_c - M = D_c) and transfer the delta. Drawback: This requires that calculating and applying the delta (M + D_c = M_c) is an cheap/easy operation.

If a client newly subscribes it must be initialized. This involves sending the current model M. So method 1 is always required.

Think of playing chess as a concrete example: Subscribers send moves and want to see the latest chess board state. The server checks validity of the move and applies it to the chess board. The server can then send the updated chessboard (method 1) or just send the move  (method 2) or send the delta (method 3): remove piece on field D4, put tower on field D8.

答:
You've forgotten about conflict handling. Is there only one place where the model is changed? What if two subjects are trying to change the model at the same time?
What if one of the subscribers did not get one message because of an error?

For method 2 and 3 you'll need some kind of versioning and resync mechaism in case of errors or missed messages. In method 1 you're just overwriting local model with incoming one.

What is more, when new client subsribes it has no model. It'll need to ask for a full model in approach 2 and 3. That will fore you to have two-way communication.

What I'am saying is that approach 2 and 3 are way more complicated than 1. On the other hand this is a common pattern: colaborative document editing, version control systems (I mean Git, SVN), multiplayer online games. Look for standard solutions of such problems.


问:
Should I charge a client for mistakes that I made?
After developing a website for a client, I've realized that the load time is too extreme, and some changes need to be made. The extreme load times are attributed to the bloated css/js frameworks that I've been using. Much of the code that was included with these frameworks is not even being used and is slowing the site load time. My plan is to get rid of the css framework and just use a bare bones responsive css framework which is only like 1kb in size, and just add only the code needed. So my question is, should I charge the client for back-stepping and fixing this mistake? </p>

答: You could but I wouldn't. Fix it and send a bill with the actual cost and with a 100% discount so the client can appreciate the value. You will keep a good professional relationship and reputation.</p>


答:
Depends if you have a fixed-amount contract or an hourly contract.

If you have a fixed-amount contract then, no, typically you only modify or charge additional to fixed-amount contracts when the functionality requested is changed. Fixed amount contracts protect the developer against scope-creep at the expense of just such a problem you are describing, one where you end up having to do large refactors (that you won't be compensated for) so that your software meets the contract requirements.

If you have an hourly contract, then things become more muddled. Typically, the hourly rate that freelancers charge is in direct proportion to their knowledge and skill. I started out charging $50/hr when I was first freelancing and junior to the software world. I charge $95/hr now and that reflects that I'm a much better programmer and get things done generally in less time. (That ends up balancing the cost for the client) Because you didn't foresee the potential error in your approach, you need to spend more time. If I were billing hourly I wouldn't feel bad about billing the time you spend refactoring. It's part of the exploration that goes into non-fixed-rate development, and hopefully your rate reflects that kind of potential issue.

Title: Should I charge a client for mistakes that I made?

Body: After developing a website for a client, I've realized that the load time is too extreme, and some changes need to be made. The extreme load times are attributed to the bloated css/js frameworks that I've been using. Much of the code that was included with these frameworks is not even being used and is slowing the site load time. My plan is to get rid of the css framework and just use a bare bones responsive css framework which is only like 1kb in size, and just add only the code needed. So my question is, should I charge the client for back-stepping and fixing this mistake? </p>


答:
In my opinion, and please don't take this as being a criticism of you - after all I have not a clue who you are, what this website is etc etc:

You can't charge for this and to highlight the work to your client, even charging with 100% discount runs the risk of making you look amateurish; and that's not what someone pays you for.

From the client's point of view, you are paid for your expertise and to make decisions that they wouldn't be able to make.  Use of third party libraries should be done with suitability in mind - and a key element of that has to be performance (stress-testing can be done to a point in the lab).  Therefore you have to take responsibility for not having chosen the correct technology.

Okay, if this is pre-existing technology, or a mandated technology (i.e. pre-chosen by the client, like the time I went to a company and they'd already spent tens of thousands on a couple of BizTalk licenses they didn't need, but wanted to use anyway to justify the cost. :'( ) then this might not be the case.  I think the key is if it was your choice.

So I think you need to take it on the chin.  If you can, just fix it without telling the client (avoiding the conversation), but if you need to you can probably tell them that you are doing it for free because of unforeseen problems with the library(ies) and that you 'won't be using those things again' yada yada.


问:
Next step after creating mock-up screens
I have created some mockup screens for my app in HTML/CSS. I have 4 screens in total.

They contain no client-side coding i.e. Javascript or jQuery.

The screens themselves are quite bland at the moment, and I realise they require some further work. Some of my plans for the app going forward are:-

Introducing client-side templating : eg Mustache/Dust.js

Add some effects and transitions using jQuery

Improve the visual look of the screens (through css and images)

I'm indecisive on the best way forward. My main aim is that I want changes to be easy to manage, and that's why I did mockup screens first as per the recommendation in the Getting Real book by 37Signals.

I'm currently in the process of gathering feedback for the mockup screens.

From a programming point of view, which of the 3 steps above, would be a good logical step forward considering my requirement of making changes easy to manage?

I should point out that i am very new to programming and development, and this is the first time i am learning programming. Some terms may not make sense to me and you may have to elaborate.

答: Step 4, work on navigation and usability, at this stage very easy to work on alternative flow and navigation ideas. I suppose step 3 could be part of this, depends on how visual heavy your apps needs to be or if you just have a few icons etc.</p>