答:
I've been a freelancer off and on for the past 16 years (5 years freelance, 9 years in a single permanent role and then back freelance).  A freelance developer should be the equivalent of a senior developer (if that's the role) and whether or not you are an expert in every area on a wishlist it doesn't always matter as the client invariably asks you to work in some other tech area/language/plug-in/whatever.

Also you should be prepared to be given tasks that are a paygrade or two below what you would be doing as a senior developer, and not be involved in decisions or meetings that you might expect to be in if you were permanent.

But in essence if you are self-motivated, don't mind constantly moving between clients, pick skills up quickly and can deal with your own career - then you'll be fine.

Title: Does freelancing require supreme ability on programming?

Body:
I can write independent java, python, c, c++ code but I do not know every aspect of them. For example, I don't how to code with database in python/c/c++. I have few experience with GUI programming.

I was aware that most of the jobs isn't just need us to write an simple code. They may need some GUI and you need to upload the programming result to a FTP server via some ftp code with some I-don't-know-the-name plugin/library. I have seen a job of web scrapping by python, and the client wants the program to insert the data into a database immediately after the web scrapping, and delete old data older than 6 month.

A client won't accept a contractor to say "I will need to figure this xyz-technology for sometime before I can tell you whether I can do it". What is worse, is that you find you are incapable of doing his job for whatever the reason, you are screwed.

I am wondering, do you apply for a freelance job if you don't feel like an expert to all the fields/technology listed in the job requirement?


问:
Code Smell: Inheritance Abuse
It's been generally accepted in the OO community that one should "favor composition over inheritance". On the other hand, inheritance does provide both polymorphism and a straightforward, terse way of delegating everything to a base class unless explicitly overridden and is therefore extremely convenient and useful.  Delegation can often (though not always) be verbose and brittle.

The most obvious and IMHO surest sign of inheritance abuse is violation of the Liskov Substitution Principle.  What are some other signs that inheritance is The Wrong Tool for the Job even if it seems convenient?

答:
I would say, taking the risk of being shot down, that Inheritance is a code smell in itself :)

The issue with inheritance is that it can be used for two orthogonal purposes:

interface (for polymorphism)

implementation (for code reuse)

Having a single mechanism to get both is what leads in "inheritance abuse" in the first place, since most people expect inheritance to be about interface, but it might be used to get default implementation even by otherwise careful programmers (it's just so easy to overlook this...)

In fact, modern languages like Haskell or Go, have abandonned inheritance in order to separate both concerns.

Back on track:

A violation of the Liskov Principle is therefore the surest sign, since it means that the "interface" part of the contract is not respected.

However even when the interface is respected, you might have objects inheriting from "fat" base classes just because one of the methods was deemed useful.

Therefore the Liskov Principle in itself is not enough, what you need to know is whether or not the polymorphism is used. If it isn't, then there wasn't much point in inheriting in the first place, that's an abuse.

Summary:

enforce the Liskov Principle

check it's actually used

A way around it:

Imposing a clear separation of concerns:

only inherit from interfaces

use composition to delegate implementation

means that at least a couple keystrokes are needed for each method, and suddenly people begin to think about whether or not it's such a great idea to reuse this "fat" class for just a small piece of it.

ContentLicense: CC BY-SA 3.0

Title: Code Smell: Inheritance Abuse

ContentLicense: CC BY-SA 2.5


问:
What are the causes that lead to an overbloated software?
Today I decided to perform a clean install for Creative Sound Blaster drivers, as they always start glitching all by themselves after some time. And that meant I had to go through the whole cleanup procedure. And that took me almost 2 hours..

And honestly, I can't see a reason why?! And although Creative, IMHO, is an absolute 1st place winner for producing poor quality software that never works, the bloat problem is not exclusive to them.

PC with Canon digital camera driver will have around 10 Canon entries that are interconnected with all sorts of connections. Visual Studio is also a prime example, there is around 50 or so entries for full install, and repairing that thing is only possible with complete nuking. And once it even managed to ruin the whole OS install when I was upgrading from VS2k8 to VS2k8SP1 or something. As it turns out 5GB of free space was not enough for 300Mb patch...

So this really seem to be a widespread problem. Almost every application nowadays usually contains unpackers, multiple spywarish "friends" that are installed, drivers are usually around 600Mb for everything including printers and so on.

But why? Is it developer fault? Applications like that are nightmare to support, they never work 100% nowadays, and almost all users I know are very negative about all that bloat they get as a mandatory driver install for USB thumb drive/Printer/Camera/Sound Card/Browser.

It seems that NSIS from Nullsoft is the only clean setup system that is not bloated, from what I know, for example, Firefox install. Clean, pretty much xcopy based install without any problems.

So why people are not using simple setups and applications that are not rooted over 30 layers of interconnection? Is it because developers are lazy? Use of codegen tools? Is it because corporations force heavyweight apps as something users will love? What's the cause, and is there a hope software will return back to basics someday? What are the steps to avoid writing bloat when you start new application from scratch?

答:
My guess is that there are a lot of features that someone thought was a good idea.  However, if a lot of people all have separate ideas that get put together into one application this is how it can become so complicated.  I wouldn't blame the developer in the case of large corporate products where there should be product managers that have a responsibility for what is in the product and how to optimize it from various perspectives.

Another side to this would be the technical debt that likely doesn't get managed well in most cases as it isn't seen as a great investment of time.  I'd suspect new features and bug fixes make more sense than refactorings or other debt tasks that may appear to have little immediate business value.  How often would a team of developers get a couple of weeks to clean up legacy code if the code base is rather old?  My guess would be not often.


问:
Is it legal or ethical for me to use my previous employer's code in a new project?
I participated and wrote a large amount of code in a project which my current company outsourcing to my former company last year.

After that I left my former company and recently join in my current company. Several days ago, my current employer asks me to continue the project on top of the existing code (my current company owns the copyright and they have the code).

I think it is neither ethical nor legal to do this. So should I refuse my current employer? Could my former employer take me to court if I undertake the project?

答:
If your current company has the code and has the copyright, it means that your former company (including yourself) had already been payed for that.

It's not matter of ethic, but about how the contract between the companies was structured, and about the contract between the former company and his own developers was defined.

You're not "stoling the job of your former company". That job most likely ended at the time the code was given.


问:
Deciding between obj->func() and func(obj)
I was thinking about this when I was starting to set up some code for a new project: are there any rules of thumb for when a method should be part of an object, and when it should be a stand alone function that takes an object as a parameter?

EDIT: as pointed out in a comment, this can depend on language. I was working in C++ when it came to mind, though I'm this is an issue across a number of languages (and would still love to see answers that pertain to them).

答:
The single responsibility principle often helps, when you have to decide whether some method or more broader some functionality belongs to an object.

Please also note, that if some functionality related to some object doesn't belong to one object, it still might make sense to encapsulate it in another object, as in other->func(obj).

```<code>class Mouth {
    void say(String msg);
    void sayHello(Person to);
    void sayBye(Person to);
}
</code>```

Now the 2nd and 3rd method will actually just call the say method and they really don't belong to the responsibility of the Mouth anyway.

```<code>interface Out {
    void say(String msg);
}
class Mouth implements Out {
    void say(String msg);
}
class Phrases {
    void new(Language language);
    void sayHello(Person to, Out over);
    void sayBye(Person to, Out over);
}
</code>```

Of course it might make more sense to pass an Out-instance to Phrases upon construction. Or to wrap it in yet another class. Or whatever.

But it definitely doesn't make sense to have those methods in Mouth, as the SRP suggests.

Body:
The single responsibility principle often helps, when you have to decide whether some method or more broader some functionality belongs to an object.

Please also note, that if some functionality related to some object doesn't belong to one object, it still might make sense to encapsulate it in another object, as in other->func(obj).

class Mouth {
    void say(String msg);
    void sayHello(Person to);
    void sayBye(Person to);
}

Now the 2nd and 3rd method will actually just call the say method and they really don't belong to the responsibility of the Mouth anyway.

interface Out {
    void say(String msg);
}
class Mouth implements Out {
    void say(String msg);
}
class Phrases {
    void new(Language language);
    void sayHello(Person to, Out over);
    void sayBye(Person to, Out over);
}

Of course it might make more sense to pass an Out-instance to Phrases upon construction. Or to wrap it in yet another class. Or whatever.

But it definitely doesn't make sense to have those methods in Mouth, as the SRP suggests.


答:
Disclaimer: I am not a lawyer

Do I understand correctly that your situation is as follows:

You worked for Company A.

Company A developed a piece of software for Company B.

You were part of Company A's project team that developed the software for Company B.

Company B holds the copyright for software developed for them by Company A.

You now work for Company B.

If this is an accurate description of your situation I don't see a problem as such. As long as your current employer holds the copyright to the code they can ask anyone to build upon it.

Any non-disclosure agreement you may have had with company A seems irrelevant, because company B holds the rights to the code and thus the information that your NDA was designed to protect.

The fact that you used to work for the company that they contracted to develop that code, is only relevant in as much as the contract between company A and B may have contained non-poaching and/or non-disclosure agreements.

Any non-disclosure agreement between them would have been to ensure that Company A would not use the information/knowledge it obtained during the project to expedite development for other clients and/or developement of a competetive product. As such it would seem irrelevant to your situation.

If there was a non-poaching agreement between your employers, either it doesn't cover you or you never told company A that you were moving to company B and you may already be in trouble regardless of what you work on.

I advise you to check with both your current and former employers whether your switch from company A to B and/or working on the project would get you in trouble (when checking with your former employer I would not tell them that you are already working for your current employer - you do not need to shoot yourself in the foot). If either gives a non-satisfactory (not a clear cut) answer, consult a lawyer yourself.

Title: Is it legal or ethical for me to use my previous employer's code in a new project?

Body:
I participated and wrote a large amount of code in a project which my current company outsourcing to my former company last year.

After that I left my former company and recently join in my current company. Several days ago, my current employer asks me to continue the project on top of the existing code (my current company owns the copyright and they have the code).

I think it is neither ethical nor legal to do this. So should I refuse my current employer? Could my former employer take me to court if I undertake the project?


答:
my current company owns the copyright and they have the code

Then its ethical and legal.

It all boils down to who owns the copyright to the code, if its ambiguous or not your current company then don't do it. They already have access to your skills when hiring you, applying those skills to some of their code, even if you have prior knowledge is both legal and ethical.


问:
How to implement Continuous Delivery with Java webapp?
I've been reading about Continuous Delivery and it sounds awesome to automate the deployment process. I've been reading about possibilities how to do this with Java Webapps, but usually it ends up with CI server or maven plugin deploying to Tomcat WITHOUT restarting the Tomcat using Tomcats management API. But that leads to OutOfPermGenSpace issues and so I wouldn't use those solutions for production. In addition it is a hassle to kill an out of control Tomcat.

Is there any technology that would make it easy to deploy Java web apps to production? I use maven to build my artifacts and deploy to nexus repository.

EDIT:

I'm not trying to find ways to prevent Permgen space issues. I'm trying to automatically deploy to production. There should be no manual steps beyond choosing a version and clicking a button(or giving a version number to a commandline script). I want to find out if I have to create this kind of setup manually, or if there is a ready made solution for this. Thus far LiveRebel seems to be the only solution so far that doesn't require me to implement everything myself.

答:
You should only be doing Continuous Delivery to a development server.  Look at deploying changes to an exploded application on this server.   If this isn't suitable increase the PermGen size.  Schedule daily restarts of the server to clear the memory.

Tag and build a deployment package for the Integration Server and only deploy when requested.  This should be co-ordinated with the Integration testing team.  I find that more than once a day is usually excessive for this environment.

Deployment of the tested deployment package from the Integration Server to Production should only be done on approval.  This usually needs to be scheduled for off-hours.

EDIT: Everywhere I've worked where we had automated deployment it has been hand crafted.  There tend to be issues around privileges, approvals, schedules, etc. that might make a generic product not fit well in a particular environment.  In environments with multiple load balanced servers, there can be additional issues.

EDIT2: I have always advocated automated deployment. Continuous deployment as I have experience it is build and deploy on check-in. You don't want production to be the deploy target.  It is a good way to ensure things build in the target environment and not just on the developers desktop.

Picking off builds as deploy candidates for further testing and possible production deployment is not what I would consider continuous deployment. I do consider it a best practice if the selection and migration is automated


问:
Scheduling dependent tasks in a scrum sprint
I'm on a project right now that is using the scrum methodology with 2 week sprints.  Here's what our team looks like:

1 business analyst

1 tester

1 user experience designer

2 developers (1 for the UI and 1 for the back-end processes)

1 project manager

In a single sprint, we'll have 1 product backlog item (PBI) to design the UI for a page, another PBI to write the .Net code for the page, and 1 PBI to test the page.

How should these 3 product backlog items be scheduled so that they all get completed by the end of the sprint?  Since they are all dependent on each other and require at least 3 members of the team to work together, it seems to me like they each need deadlines in order for them to get done in time.

The scrum master keeps saying that they don't need deadlines because the cross-functional team will take care of it.  This hasn't worked in 10+ sprints, though.

Shouldn't the project manager be aware of this critical path and monitor its progress?

答:
The first issue here is that the items in your backlog are not business-value driven. The UI alone doesn't provide any value, as well as the backend code alone neither does. I'd suggest you to try to slice the features vertically, this is, instead of thinking in terms of components, take the perspective of an end-user and redefine your items as user stories, e.g.

As a user I want to search by keyword so that I can find matches that are relevant to me.

Note that this feature may include several tasks: create/modify the UI, code the logic, fetch results from the database ... Testing is not treated as a separate feature, but included in each story, and based on your "definition of done", it will include several tasks, such as unit tests, automated functional tests, manual system tests, ... The purpose of working in short time-boxed sprints is to deliver working software regularly while still keeping the capacity to adapt to changes in the priorities. Untested software simply can't be considered working software.

It may happen that a story is just too big to fit in a single sprint. In that case you'll need to split it into smaller stories, again trying not to fall into a mechanical division per component when possible. Splitting user stories is not easy and it requires a great deal of practice. There are some nice articles on the topic.

On the other hand, agile teams are cross-functional. This doesn't mean that some people won't be more skilled than others in certain areas, but that members of the team collaborate with each other to reach a shared goal, this is, to complete the stories scheduled for the sprint. In the practice, this can translate to, for instance, developers assisting in testing tasks and vice-versa. Knowledge sharing (versus expertise silos) is a key practice for a team to get the most of him.


答:
I think a lot of it has to do with layer upon layer of library code. Obviously when you use a library you don't use everything in it, so that excess adds up as you include more and more libraries.

Combine that with the fact that the cost of an hour of work from a programmer is getting increasingly expensive while the processing power/storage of the typical computer is getting cheaper by the year, you see that it is actually more cost efficient this way.

Title: What are the causes that lead to an overbloated software?

Body:
Today I decided to perform a clean install for Creative Sound Blaster drivers, as they always start glitching all by themselves after some time. And that meant I had to go through the whole cleanup procedure. And that took me almost 2 hours..

And honestly, I can't see a reason why?! And although Creative, IMHO, is an absolute 1st place winner for producing poor quality software that never works, the bloat problem is not exclusive to them.

PC with Canon digital camera driver will have around 10 Canon entries that are interconnected with all sorts of connections. Visual Studio is also a prime example, there is around 50 or so entries for full install, and repairing that thing is only possible with complete nuking. And once it even managed to ruin the whole OS install when I was upgrading from VS2k8 to VS2k8SP1 or something. As it turns out 5GB of free space was not enough for 300Mb patch...

So this really seem to be a widespread problem. Almost every application nowadays usually contains unpackers, multiple spywarish "friends" that are installed, drivers are usually around 600Mb for everything including printers and so on.

But why? Is it developer fault? Applications like that are nightmare to support, they never work 100% nowadays, and almost all users I know are very negative about all that bloat they get as a mandatory driver install for USB thumb drive/Printer/Camera/Sound Card/Browser.

It seems that NSIS from Nullsoft is the only clean setup system that is not bloated, from what I know, for example, Firefox install. Clean, pretty much xcopy based install without any problems.

So why people are not using simple setups and applications that are not rooted over 30 layers of interconnection? Is it because developers are lazy? Use of codegen tools? Is it because corporations force heavyweight apps as something users will love? What's the cause, and is there a hope software will return back to basics someday? What are the steps to avoid writing bloat when you start new application from scratch?


问:
Does freelancing require supreme ability on programming?
I can write independent java, python, c, c++ code but I do not know every aspect of them. For example, I don't how to code with database in python/c/c++. I have few experience with GUI programming.

I was aware that most of the jobs isn't just need us to write an simple code. They may need some GUI and you need to upload the programming result to a FTP server via some ftp code with some I-don't-know-the-name plugin/library. I have seen a job of web scrapping by python, and the client wants the program to insert the data into a database immediately after the web scrapping, and delete old data older than 6 month.

A client won't accept a contractor to say "I will need to figure this xyz-technology for sometime before I can tell you whether I can do it". What is worse, is that you find you are incapable of doing his job for whatever the reason, you are screwed.

I am wondering, do you apply for a freelance job if you don't feel like an expert to all the fields/technology listed in the job requirement?

答:
I am wondering, do you apply for a freelance job if you don't feel like an expert to all the fields/technology listed in the job requirement?

Learning something like programming with databases on the job takes a very fast learner and a very relaxed project. Such conditions are not common.

So to answer your question, I would say No.

I suggest you build up your expertise in the areas you know you need to or focus on projects that are in your area of expertise. It may be OK, if you need to research some subjects, but too much research on the job in short engagements is usually not possible for a freelancer.


问:
How can Continuous Delivery work in practice?
Continuous Delivery sounds good, but my years of software development experience suggest that in practice it can't work.

(Edit: To make it clear, I always have lots of tests running automatically. My question  is about how to get the confidence to deliver on each checkin, which  I understand is the full form of CD. The alternative is not year-long cycles. It is iterations every week (which some might consider still CD if done correctly), two weeks, or month; including an old-fashioned QA at the end of each one, supplementing the automated tests.)

Full test coverage is impossible. You have to put in lots of time -- and time is money -- for every little thing. This is valuable, but the time could be spent  contributing to quality in other ways.

Some things are hard to test automatically. E.g. GUI. Even Selenium won't tell you  if your GUI is wonky. Database access is hard to test without bulky fixtures, and even that won't cover weird corner cases in your data storage. Likewise security and many other things. Only business-layer code is effectively unit-testable.

Even in the business layer, most code out there is not simple functions whose arguments and return values can be easily isolated for test purposes. You can spend lots of time building mock objects, which might not correspond to the real implementations.

Integration/functional tests supplement unit tests, but these take a lot of time to run because they usually involve reinitializing the entire system on each test. (If you don't reinitialize, the test environment is inconsistent.)

Refactoring or any other changes break lots of  tests. You spend lots of time fixing them. If it's a matter of validating meaningful spec changes, that's fine, but often tests break because of meaningless low-level implementation details, not stuff that really provides important information. Often the tweaking is focused on reworking the internals of the test, not on truly checking the functionality that is being tested.

Field reports on bugs cannot easily be matched with the precise micro-version of the code.

答: Every system has risks, and every risk has potential costs.  If the cost of some tiny risk, of the kind that may take months or years to find in extensive testing and QA, is high enough (the software in your heart pacemaker), you don't ship without an extensive period of testing of a frozen release.  If the cost of failure is small enough, maybe you ship continuously with zero testing (your cat's Facebook page).</p>


答:
To quote Joel in Strategy Letter IV: Bloatware and the 80/20 Myth:

[...] there are lots of great reasons for bloatware. For one, if programmers don't have to worry about how large their code is, they can ship it sooner. [...] If your software vendor stops, before shipping, and spends two months squeezing the code down to make it 50% smaller, the net benefit to you is going to be imperceptible. [...] But the loss to you of waiting an extra two months for the new version is perceptible, and the loss to the software company that has to give up two months of sales is even worse.

A lot of software developers are seduced by the old "80/20" rule. It seems to make a lot of sense: 80% of the people use 20% of the features. So you convince yourself that you only need to implement 20% of the features, and you can still sell 80% as many copies.

Unfortunately, it's never the same 20%. Everybody uses a different set of features. [...]

When you start marketing your "lite" product, and you tell people, "hey, it's lite, only 1MB," they tend to be very happy, then they ask you if it has their crucial feature, and it doesn't, so they don't buy your product.


问:
Why isn't lazy evaluation used everywhere?
I've just learnt how lazy evaluation works and I was wondering: why isn't lazy evaluation applied in every software currently produced? Why still using eager evaluation?</p>

答:
Lazy evaluation requires book-keeping overhead- you have to know if it's been evaluated yet and such things. Eager evaluation is always evaluated, so you don't have to know. This is especially true in concurrent contexts.

Secondly, it's trivial to convert eager evaluation into lazy evaluation by packaging it into a function object to be called later, if you so wish.

Thirdly, lazy evaluation implies a loss of control. What if I lazily evaluated reading a file from a disk? Or getting the time? That's not acceptable.

Eager evaluation can be more efficient and more controllable, and is trivially converted to lazy evaluation. Why would you want lazy evaluation?


问:
What are the disadvantages of unobtrusive script patterns in web applications?
First of all, is there a name for this as a bona-fide design pattern? Currently I've just been referring to it as "unobtrusive javascript". Here is a brief example of what I am talking about:

1.) Use HTML5 data-* attributes to define values that will be used in UX scripts. Something like this:

```<code><input type="date" data-app-calendar="datepicker" />
</code>```

2.) Use script to initialize the javscript behaviors using these data attributes

```<code>(function($) {
    $.app = $.app || {};
    $.app.obtruders = $.app.obtruders || {};
    $.app.obtrude = function(selector) {
        var obtruder, obtruders = $.app.obtruders;
        for (obtruder in obtruders) {
            if (!obtruders.hasOwnProperty(obtruder)) continue;
            if (typeof obtruders[obtruder] === 'function')
                obtruders[obtruder].apply(this,
                    Array.prototype.slice.call(arguments, 0, 1) || document);
        }
    };

    $.extend($.app.obtruders, {
        calendar: function (selector) {
            $(selector).find('[data-app-calendar=datepicker]').datepicker();
        }
    });

    $(function () {
        $.app.obtrude(document);
    });

})(jQuery);
</code>```

What you end up with, imo, is presentation markup that is very cleanly separated from behavioral scripts. The above example is simple, but you can extend it to more complex scriptable UX like google maps (I am working on this right now). You can even add new "obtruders" in separate javascript files by extending the $.app.obtruders object literal.

Before we start using this pattern more widely in our app, I wanted to pick brains for opinions and try to get ideas of some potential disadvantages of an approach like this. What do you like about this pattern? What don't you like? Why would you choose not to use it?

答:
This is called injecting functionality into an application. It's a "common" pattern.

I personally use a similar pattern

```<code>["feature1", "feature2", ...].forEach(function(feature) {
  var elems = $("." + feature);
  // this document has an element that uses the feature
  if (elems.length) {
    loadFeatureByAjax(document, feature);
  }
});
</code>```

Then each feature knows how to inject itself into the selector

```<code>var Feature = function (selector) {
    $(selector).find('.featureName').datepicker();
}
</code>```

Note that we use classes rather then data- attributes because attribute CSS selectors are slow as hell and should be avoided.

The only other objection is that your particular implementation feels verbose, but might just be your coding style.

Body:
This is called injecting functionality into an application. It's a "common" pattern.

I personally use a similar pattern

["feature1", "feature2", ...].forEach(function(feature) {
  var elems = $("." + feature);
  // this document has an element that uses the feature
  if (elems.length) {
    loadFeatureByAjax(document, feature);
  }
});

Then each feature knows how to inject itself into the selector

var Feature = function (selector) {
    $(selector).find('.featureName').datepicker();
}

Note that we use classes rather then data- attributes because attribute CSS selectors are slow as hell and should be avoided.

The only other objection is that your particular implementation feels verbose, but might just be your coding style.


答:
Mainly because lazy code and state can mix badly and cause some hard to find bugs. If the state of a dependent object changes the value of your lazy object can be wrong when evaluated. It's much better to have the programmer explicitly code the object to be lazy when he/she knows the situation is appropriate.

On a side note Haskell uses Lazy evaluation for everything. This is possible because it's a functional language and doesn't use state (except in a few exceptional circumstances where they are clearly marked)

Title: Why isn't lazy evaluation used everywhere?

Body: I've just learnt how lazy evaluation works and I was wondering: why isn't lazy evaluation applied in every software currently produced? Why still using eager evaluation?</p>


答:
As @DeadMG noted Lazy evaluation requires book-keeping overhead.  This can be expensive relative to eager evaluation.  Consider this statement:

```<code>i = (243 * 414 + 6562 / 435.0 ) ^ 0.5 ** 3
</code>```

This will take a bit of calculation to calculate.  If I use lazy evaluation, then I need to check if it has been evaluated every time I use it.  If this is inside a heavily used tight loop then the overhead increases significantly, but there is no benefit.

With eager evaluation and a decent compiler the formula is calculated at compile time.  Most optimizers will move the assignment out of any loops it occurs in if appropriate.

Lazy evaluation is best suited to loading data which will be infrequently accessed and has a high overhead to retrieve.  It is therefore more appropriate to edge cases than core functionality.

In general it is good practice to evaluate things that are frequently accessed as early as possible.  Lazy evaluation does not work with this practice.  If you will always access something, all lazy evaluation will do is add overhead.  The cost/benefit of using lazy evaluation decreases as the item being accessed becomes less likely to be accessed.

Always using lazy evaluation also implies early optimization.  This is a bad practice which often results in code which is much more complex and expensive that might otherwise be the case.  Unfortunately, premature optimization often results in code that performs slower than simpler code.  Until you can measure the effect of optimization, it is a bad idea to optimize your code.

Avoiding premature optimization does not conflict with good coding practices.  If good practices were not applied, initial optimizations may consist of applying good coding practices such as moving calculations out of loops.

Body:
As @DeadMG noted Lazy evaluation requires book-keeping overhead.  This can be expensive relative to eager evaluation.  Consider this statement:

i = (243 * 414 + 6562 / 435.0 ) ^ 0.5 ** 3

This will take a bit of calculation to calculate.  If I use lazy evaluation, then I need to check if it has been evaluated every time I use it.  If this is inside a heavily used tight loop then the overhead increases significantly, but there is no benefit.

With eager evaluation and a decent compiler the formula is calculated at compile time.  Most optimizers will move the assignment out of any loops it occurs in if appropriate.

Lazy evaluation is best suited to loading data which will be infrequently accessed and has a high overhead to retrieve.  It is therefore more appropriate to edge cases than core functionality.

In general it is good practice to evaluate things that are frequently accessed as early as possible.  Lazy evaluation does not work with this practice.  If you will always access something, all lazy evaluation will do is add overhead.  The cost/benefit of using lazy evaluation decreases as the item being accessed becomes less likely to be accessed.

Always using lazy evaluation also implies early optimization.  This is a bad practice which often results in code which is much more complex and expensive that might otherwise be the case.  Unfortunately, premature optimization often results in code that performs slower than simpler code.  Until you can measure the effect of optimization, it is a bad idea to optimize your code.

Avoiding premature optimization does not conflict with good coding practices.  If good practices were not applied, initial optimizations may consist of applying good coding practices such as moving calculations out of loops.


答:
It's a common pattern, "unobtrusive javascript" is a widespread name for it, and it's generally considered superior the alternatives (putting JavaScript calls directly into links and event handlers).

The only disadvantage that I can think of is that it makes the behaviour harder to discover. When looking at the HTML, you have no idea what the dynamic behaviour is or even where it's defined. This can be mitigated by conventions or IDE support.

Title: What are the disadvantages of unobtrusive script patterns in web applications?

Body:
First of all, is there a name for this as a bona-fide design pattern? Currently I've just been referring to it as "unobtrusive javascript". Here is a brief example of what I am talking about:

1.) Use HTML5 data-* attributes to define values that will be used in UX scripts. Something like this:

```<code><input type="date" data-app-calendar="datepicker" />
</code>```

2.) Use script to initialize the javscript behaviors using these data attributes

```<code>(function($) {
    $.app = $.app || {};
    $.app.obtruders = $.app.obtruders || {};
    $.app.obtrude = function(selector) {
        var obtruder, obtruders = $.app.obtruders;
        for (obtruder in obtruders) {
            if (!obtruders.hasOwnProperty(obtruder)) continue;
            if (typeof obtruders[obtruder] === 'function')
                obtruders[obtruder].apply(this,
                    Array.prototype.slice.call(arguments, 0, 1) || document);
        }
    };

    $.extend($.app.obtruders, {
        calendar: function (selector) {
            $(selector).find('[data-app-calendar=datepicker]').datepicker();
        }
    });

    $(function () {
        $.app.obtrude(document);
    });

})(jQuery);
</code>```

What you end up with, imo, is presentation markup that is very cleanly separated from behavioral scripts. The above example is simple, but you can extend it to more complex scriptable UX like google maps (I am working on this right now). You can even add new "obtruders" in separate javascript files by extending the $.app.obtruders object literal.

Before we start using this pattern more widely in our app, I wanted to pick brains for opinions and try to get ideas of some potential disadvantages of an approach like this. What do you like about this pattern? What don't you like? Why would you choose not to use it?


答:
Lazy evaluation's is not always better.

The performance benefits of lazy evaluation can be great, but it is not hard to avoid most unnecessary evaluation in eager environments- surely lazy makes it easy and complete, but rarely is unnecessary evaluation in code a major problem.

The good thing about lazy evaluation is when it lets you write clearer code; getting the 10th prime by filtering an infinite natural numbers list and taking the 10th element of that list is one of the most concise and clear way of proceeding: (pseudocode)

```<code>let numbers = [1,2...]
fun is_prime x = none (map (y-> x mod y == 0) [2..x-1])
let primes = filter is_prime numbers
let tenth_prime = first (take primes 10)
</code>```

I believe it would be quite difficult to express things so concisely without lazyness.

But lazyness isn't the answer to everything. For starters, lazyness cannot be applied transparently in the presence of state, and I believe statefulness cannot be automatically detected (unless you are working in say, Haskell, when state is quite explicit). So, in most languages, lazyness needs to be done manually, which makes things less clear and thus removes one of the big benefits of lazy eval.

Furthermore, lazyness has performance drawbacks, as it incurs a significant overhead of keeping non-evaluated expressions around; they use up storage and they are slower to work with than simple values. It is not uncommon to find out that you have to eager-ify code because the lazy version is dog slow- and it is sometimes hard to reason about performance.

As it tends to happen, there is no absolute best strategy. Lazy is great if you can write better code taking advantage of infinite data structures or other strategies it allows you to use, but eager can be easier to optimize.

Body:
Lazy evaluation's is not always better.

The performance benefits of lazy evaluation can be great, but it is not hard to avoid most unnecessary evaluation in eager environments- surely lazy makes it easy and complete, but rarely is unnecessary evaluation in code a major problem.

The good thing about lazy evaluation is when it lets you write clearer code; getting the 10th prime by filtering an infinite natural numbers list and taking the 10th element of that list is one of the most concise and clear way of proceeding: (pseudocode)

let numbers = [1,2...]
fun is_prime x = none (map (y-> x mod y == 0) [2..x-1])
let primes = filter is_prime numbers
let tenth_prime = first (take primes 10)

I believe it would be quite difficult to express things so concisely without lazyness.

But lazyness isn't the answer to everything. For starters, lazyness cannot be applied transparently in the presence of state, and I believe statefulness cannot be automatically detected (unless you are working in say, Haskell, when state is quite explicit). So, in most languages, lazyness needs to be done manually, which makes things less clear and thus removes one of the big benefits of lazy eval.

Furthermore, lazyness has performance drawbacks, as it incurs a significant overhead of keeping non-evaluated expressions around; they use up storage and they are slower to work with than simple values. It is not uncommon to find out that you have to eager-ify code because the lazy version is dog slow- and it is sometimes hard to reason about performance.

As it tends to happen, there is no absolute best strategy. Lazy is great if you can write better code taking advantage of infinite data structures or other strategies it allows you to use, but eager can be easier to optimize.

ContentLicense: CC BY-SA 4.0


问:
What syntax element do you hate most in a programming language you use frequently?
No matter how much you love a programming language, there are always a few details in it that aren’t quite as nice as they could be.

In this question, I would like to specifically focus on syntax elements. In a programming language that you use frequently (perhaps your favourite programming language, or perhaps the one you are forced to use at work), which syntax element do you find most unreadable, unclear, inconvenient or unpleasant?

答:
Since people have already complained about = vs. ==, let me point out a much worse alternative. PL/I had both := and =, but when something was "obviously" an assignment, it would let you get away with using = to do it. Using := let you force something to be an assignment in a situation where the compiler would otherwise interpret it as a comparison.

Unfortunately, the compiler didn't always decided on things quite the way you might expect. Consider just one obvious example:

```<code>A = B = 0;
</code>```

Now, to most people familiar with most "ordinary" languages, the meaning of this is pretty obvious -- assign 0 to both A and B. PL/I is just a bit...different though. For reasons known only to the (insane) designers of the language, the first = is interpreted as an assignment, but the second = is interpreted as a comparison. Therefore, this compares B to 0, and then assigns the result of that comparison to A (following the C-style convention that "false" results in 0 and "true" in 1).

So, if B was 0, then A becomes 1. Otherwise, A becomes 0. In other words, rather than assigning the same value to A and B, this actually ensures that A cannot have the same value as B.

Bottom line: even though the C/C++/PHP style initially seems like a pain, the alternative is much worse1.

1Well, technically, there's another alternative: Pascal style, where = always means comparison and assignment always requires :=. After using that for a while, it's pretty obvious (at least to me) that assignment is enough more common than comparison that if you're going to require extra "stuff" to disambiguate the two, you should definitely keep assignments clean and simple and require the extra "grunge" on comparisons, not vice versa.

Body:
Since people have already complained about = vs. ==, let me point out a much worse alternative. PL/I had both := and =, but when something was "obviously" an assignment, it would let you get away with using = to do it. Using := let you force something to be an assignment in a situation where the compiler would otherwise interpret it as a comparison.

Unfortunately, the compiler didn't always decided on things quite the way you might expect. Consider just one obvious example:

A = B = 0;

Now, to most people familiar with most "ordinary" languages, the meaning of this is pretty obvious -- assign 0 to both A and B. PL/I is just a bit...different though. For reasons known only to the (insane) designers of the language, the first = is interpreted as an assignment, but the second = is interpreted as a comparison. Therefore, this compares B to 0, and then assigns the result of that comparison to A (following the C-style convention that "false" results in 0 and "true" in 1).

So, if B was 0, then A becomes 1. Otherwise, A becomes 0. In other words, rather than assigning the same value to A and B, this actually ensures that A cannot have the same value as B.

Bottom line: even though the C/C++/PHP style initially seems like a pain, the alternative is much worse1.

1Well, technically, there's another alternative: Pascal style, where = always means comparison and assignment always requires :=. After using that for a while, it's pretty obvious (at least to me) that assignment is enough more common than comparison that if you're going to require extra "stuff" to disambiguate the two, you should definitely keep assignments clean and simple and require the extra "grunge" on comparisons, not vice versa.


问:
Unit testing statically typed functional code
I wanted to ask you people, in which cases it makes sense to unit test statically typed functional code, as written in haskell, scala, ocaml, nemerle, f# or haXe (the last is what I am really interested in, but I wanted to tap into the knowledge of the bigger communities).

I ask this because from my understanding:

One aspect of unit tests is to have the specs in runnable form. However when employing a declarative style, that directly maps the formalized specs to language semantics, is it even actually possible to express the specs in runnable form in a separate way, that adds value?

The more obvious aspect of unit tests is to track down errors that cannot be revealed through static analysis. Given that type safe functional code is a good tool to code extremely close to what your static analyzer understands, it would seem that you can shift a lot of safety towards static analysis. However a simple mistake like using x instead of y (both being coordinates) in your code cannot be covered. OTOH such a mistake could also arise while writing the test code, so I am not sure whether it is worth the effort.

Unit tests do introduce redundancy, which means that when requirements change, the code implementing them and the tests covering this code must both be changed. This overhead of course is about constant, so one could argue, that it doesn't really matter. In fact, in languages like Ruby it really doesn't compared to the benefits, but given how statically typed functional programming covers a lot of the ground unit tests are intended for, it feels like it's a constant overhead one can simply reduce without penalty.

From this I'd deduce that unit tests are somewhat obsolete in this programming style. Of course such a claim can only lead to religious wars, so let me boil this down to a simple question:

When you use such a programming style, to which extents do you use unit tests and why (what quality is it you hope to gain for your code)? Or the other way round: do you have criteria by which you can qualify a unit of statically typed functional code as covered by the static analyzer and hence without need for unit test coverage?

答:
You can think of unit tests as an example of how to use the code, together with a description of why it's valuable.

Here's an example, in which Uncle Bob was kind enough to pair with me on John Conway's "Game of Life". I think it's an excellent exercise for this kind of thing. Most of the tests are full-system, testing the entire game, but that first one tests just one function - the one which calculates the neighbours around a cell. You can see that all the tests are written in declarative form, with the behavior we're looking for clearly spelled out.

It's also possible to mock functions used in functions; either by passing them into the function (the equivalent of dependency injection), or with frameworks like Brian Marick's Midje.


答: You could restart Tomcat and be done with it. Also, Tomcat 7 has supposedly solved PermGen issues... although I haven't tried.

Title: How to implement Continuous Delivery with Java webapp?

Body:
I've been reading about Continuous Delivery and it sounds awesome to automate the deployment process. I've been reading about possibilities how to do this with Java Webapps, but usually it ends up with CI server or maven plugin deploying to Tomcat WITHOUT restarting the Tomcat using Tomcats management API. But that leads to OutOfPermGenSpace issues and so I wouldn't use those solutions for production. In addition it is a hassle to kill an out of control Tomcat.

Is there any technology that would make it easy to deploy Java web apps to production? I use maven to build my artifacts and deploy to nexus repository.

EDIT:

I'm not trying to find ways to prevent Permgen space issues. I'm trying to automatically deploy to production. There should be no manual steps beyond choosing a version and clicking a button(or giving a version number to a commandline script). I want to find out if I have to create this kind of setup manually, or if there is a ready made solution for this. Thus far LiveRebel seems to be the only solution so far that doesn't require me to implement everything myself.


问:
How do you end up with event-sourcing if you use a xDD approach?
When working in a TDD or BDD manner your unit tests are supposed to drive your design. But how do you end up with event-sourcing using a xDD techniques? As I see it event sourcing is something you need to adopt early on to take full advantage of it.

Lets say that you start without event-sourcing and do a release. Later on when you are releasing version 2.0 you realize that it would be great to use event-sourcing, but at that point you alread have missed all the events from version 1.0 so it makes it much harder to implement. Or do you take some kind of backup of your db from before event-sourcing and use that as base line and then add event-sourcing on top of that?

答:
Instead of thinking of Event Sourcing as being a purely design and technical issue, think of it as having a clear business benefit instead. For instance, if I'm using Martin Fowler's shipping example, I might have a business reason for wanting to know where a ship was on a given day.

It's possible that you don't have this business reason yet. Is there a possibility that you will have that reason, some time in the future? Some business requirements aren't just about the functionality you need now, but about keeping options open (almost the opposite of YAGNI). You can look at Chris Matts' work on Real Options to find out more.

Now that you have established the business benefit, think of TDD and BDD as helping you to establish which of those classes are responsible for that benefit. TDD and BDD don't help you to drive out good design as much as steer you away from the bad ones. They make you consider the responsibility of each of your classes, provide an example of how to use it thereby ensuring usable code, and ensure that each aspect of the class is genuinely valuable. You can still gain these benefits and come up with your own architectural requirements too.

Rather than trying to get architecture right, think about the cost of getting it wrong. Would it really be hard to adopt event sourcing later? If you discovered that the cost was prohibitive and the business didn't need it, how hard would it be to return to state-based persistence? As Chris has said in the past, if you don't know which technology is right, don't pick the right technology. Pick the one that's easy to change. It's either right already, or you'll have more information later that will help you to make better decisions. Your product owner or business expert may also be able to help decide whether the business benefit is worth paying for now.


问:
How to move to Java enterprise development after Python and Ruby?
I used to develop in Django/Python and Rails/Ruby (and before that C/C++ and C#), and I'm now at a job where we do enterprise Java development (Spring, Hibernate, RESTEasy, Maven, etc.) for web applications and web services.

Coming from the Convention over Configuration world, what's the best way to get up to speed doing enterprise Java web services development?

I know Java (the language) well, and I've written GUIs in Swing and basic JSP before, but nothing of the kind I'm doing now.

Are there any recommended tutorials to get up to speed on popular Java enterprise development tutorials?

答:
Well, the key here is familiarity. IMHO, the only way to achieve familiarity is by practice- use Spring, Hibernate, etc. and you will increase your knowledge about them. One of the strengths of the Java ecosystem is the great number of libraries/frameworks which come with great documentation- Spring's reference manual is excellent and reading it will teach you most of what there's to know about Spring, for instance.

In the end, programming is programming, and Java is yet another object-oriented imperative language and it's pretty similar to what you have been doing- esp. C#. The big thing that you might not be using to its full extent is your IDE. Java being a statically-typed language and very amenable to code manipulation can offer you some IDE features which often work better than dynamical languages- automated refactoring, better code complete, better assistence (i.e. Eclipse's ctrl+1 shortcut, it can do stuff such as:

infer the type of an expression and create a variable of the correct type and assign the expression to it

extract a code fragment to a method, inferring the parameters and return type of the method and replacing it by an invocation

rename variables and classes

...

, you also have some niceties such as ctrl+shift+up extending a selection syntactically). Of course if you did Java before or used Visual Studio, you might have already done some of this.

Also I would mention that Spring has "convention-over-configuration" in places- esp. it's MVC module, which can automatically pick up your controllers, etc. if you put them in the right place ( http://static.springsource.org/spring/docs/3.0.x/spring-framework-reference/html/mvc.html#mvc-coc ).


问:
At which point do you "know" a technology enough to list it on a resume
I recently had a programmer in for an interview, who listed Python, PHP, Rails and ASP as a few of their skills. In the interview however, they interviewee didn't enough know what control structures and basic logic were, they had only followed a few demo tutorials.

So my question is this: At which point can you add a technology to your resume accurately. Is it when you can demonstrate all basic concepts, write a useful program in it, or are just comfortable using it without having to refer to the documentation every 30 seconds.

I don't believe this is overly subjective, a baseline should easily be established based on feedback.

答:
I have a couple of sentenses describing each job. In the last paragraph of each description, I place a "Languages and Technologies used:" following by whatever tools I used in that job.

Also, I have a Skills section with a note which says something like: "Varied experience with the following languages and tools" and then I have a few bullets with languages and relevant frameworks that I have used in the past.

I don't use the "rating" system because I would not know how to rate myself in each of the languages (what does a 3 rating (from 0-to-5) in Java imply in terms of knowledge?). In order not to be dishonest, I would probably aim low when self-rating. This actually happened last year when I applied to a job and the company gave me a questionaire which requested the applicant to rate himself in a bunch of languages.

I dont list the number of years because I don't think it helps much. For example, I have 4 years of professional experience in the language / library I currently use but I'm no expert in it, since I usually stick to a certain subset of it.

Some of the languages I list I've used in jobs, others I only used in University projects and exercises (4 or more years ago). I would not be able to write code in some of those languages in the stop, but I could get back into them within some hours of studying. However, if I removed any language which I would not be able to write code in from memory without review, I would be left with only two languages - probably not a fair assessment either.

I'm currently job hunting, so I'm reviewing my CV (hence I'm reading programmers.SE and looking for CV tips :)) and I'm thinking about removing the languages which were only used in University projects (and this would be stuff like Prolog).


问:
Proper use of classes
I'm writing a class that draws a very complex image, with multiple parts. I also plan on adding to the class to add more functionality. Would it be right to make a function for each part, even if that function will only EVER be called in the render function? I see an upside to this since it will be easier to read the code, and easier to add parts. A downside however, would be that it would increase complexity and quite possibly make it harder to maintain. Should I keep all the code in the render function, or break apart the different steps?</p>

答: Nope, breaking down complex methods into a sequence of smaller, private methods is perfectly good design and improves maintainability, if the new methods have descriptive names.</p>

Title: Proper use of classes


答: Put it on your resume if you're confident you can answer technical questions about the language without embarrassing yourself. The goal is for the resume to be an honest reflection of your abilities, and you should assume you might be asked to prove anything you put on the resume.

Title: At which point do you "know" a technology enough to list it on a resume

Body:
I recently had a programmer in for an interview, who listed Python, PHP, Rails and ASP as a few of their skills. In the interview however, they interviewee didn't enough know what control structures and basic logic were, they had only followed a few demo tutorials.

So my question is this: At which point can you add a technology to your resume accurately. Is it when you can demonstrate all basic concepts, write a useful program in it, or are just comfortable using it without having to refer to the documentation every 30 seconds.

I don't believe this is overly subjective, a baseline should easily be established based on feedback.


答:
Disclaimer:  I'm an unpaid advisor for their product advisory board.

Zero Turnaround have very low cost products called JRebel and LiveRebel which solve a vast majority of the issues dealing with hot deploying WAR files to a web server such as Tomcat.

As smp7d correctly mentions, JRebel is the development tool version of the two.

They tend to work at the byte code level, avoiding the often broken class loading system in this space.


答:
There are two major disadvantages.

   1.  The first one was already mentioned by Michael Borgwardt: the fact that it's hard to discover what makes a page element acting as it does. For example:

```<code><div id="TopActions">
    <a id="ToggleTopPanel" onclick="javascript:ToggleTopPanel();">Expand</a>
</div>
</code>```

is straightforward: when reading this code, I an absolutely sure:

That when I click on "Expand" link, it will do something which is specified in ToggleTopPanel() method written somewhere. If I want to know more, I have just to search for the method.

That the page will not work with JavaScript disabled.

If, on the other hand, I read:

```<code><div id="TopActions">
    <a id="ToggleTopPanel" href="?topPanel=expanded">Show</a>
</div>
</code>```

I have no idea what will happen if JavaScript is enabled (and even if the behavior is different from the non-JavaScript version). Moreover, there is nothing I can do to find it with no effort. If there are thousands of lines of code, where to search? It could be:

```<code>$('#ToggleTopPanel').click(function() {
    // The magic happens here.
});
</code>```

or maybe:

```<code>$('#TopActions a').click(UI.Top.Activated($(this)));
</code>```

or something totally different. Either I have a browser with a profiler and I know how to use it, or, well...

   2.   The second reason is that unobtrusive JavaScript is not the easiest way to do the work. If it is obviously a choice for large-size web applications, it is an overkill for a small personal website visited by one person per week (excluding the person who created it).

If the deal is to make something small, and to make it fast and inexpensive, don't bother with unobtrusive JavaScript.

If the the deal is to add some annoying visual effects like those snowflakes flying all over the page or the bees hunting the cursor or the advertisement jumping in front of the page the user was about to read, don't bother with unobtrusive JavaScript.

Body:
There are two major disadvantages.

   1.  The first one was already mentioned by Michael Borgwardt: the fact that it's hard to discover what makes a page element acting as it does. For example:

<div id="TopActions">
    <a id="ToggleTopPanel" onclick="javascript:ToggleTopPanel();">Expand</a>
</div>

is straightforward: when reading this code, I an absolutely sure:

That when I click on "Expand" link, it will do something which is specified in ToggleTopPanel() method written somewhere. If I want to know more, I have just to search for the method.

That the page will not work with JavaScript disabled.

If, on the other hand, I read:

<div id="TopActions">
    <a id="ToggleTopPanel" href="?topPanel=expanded">Show</a>
</div>

I have no idea what will happen if JavaScript is enabled (and even if the behavior is different from the non-JavaScript version). Moreover, there is nothing I can do to find it with no effort. If there are thousands of lines of code, where to search? It could be:

$('#ToggleTopPanel').click(function() {
    // The magic happens here.
});

or maybe:

$('#TopActions a').click(UI.Top.Activated($(this)));

or something totally different. Either I have a browser with a profiler and I know how to use it, or, well...

   2.   The second reason is that unobtrusive JavaScript is not the easiest way to do the work. If it is obviously a choice for large-size web applications, it is an overkill for a small personal website visited by one person per week (excluding the person who created it).

If the deal is to make something small, and to make it fast and inexpensive, don't bother with unobtrusive JavaScript.

If the the deal is to add some annoying visual effects like those snowflakes flying all over the page or the bees hunting the cursor or the advertisement jumping in front of the page the user was about to read, don't bother with unobtrusive JavaScript.


问:
What open source licenses allow for combining code that compiles into a single assembly?
I'm trying to make a library that will be used by other developers. I want to obey the "don't re-invent the wheel" principle and and I also want to make the deployment a matter of dropping a single .dll into the bin folder.

So far, I've chosen an dual MIT/MS-PL license.  Is there anything stopping me from compiling other MSPL/MIT licensed code directly into the same assembly as my own?

Am I worried about nothing?

If this is a legit concern, should I go add a licence/copyright header to each file before I add other code to my code base, since there won't be a nice tidy assembly to delineate where the code came from?

Also, I will add the header for you so you can get to writing the answer faster: "You are not a lawyer, you are not giving legal advice, I should fork over my hard earned money to a profession I detest to resolve questions like this instead of asking for free advice"

答:
MIT license lets you do pretty much anything you want with the code - just include the MIT text in the file.

If you are allowing the redistribution of the code as a dynamically linked library anyway you could also use the LGPL.

What do you want to achieve with the license? Do you want to force people to feed changes and fixes back to you or do you want them to have the most freedom to reuse the code?


问:
Spending too much time debugging
Yesterday, I rolled out a v1.0 release of a Web project I've spent about 6 weeks working on (on and off, that is). I haven't made any exact records of my time, but according to my experiences I would estimate that out of all the time I spent programming, half of it was spent debugging. I estimate that to be about a good 15-20 hours spend debugging, which to me is precious time that could have better been spent writing new code or finishing the project earlier. It also especially doesn't help that I'll be a freshman in college in 5 weeks.

The thing is, I feel bad for spending all that time debugging. All that time spent debugging makes me realize that I made some pretty stupid mistakes while I was developing my project, mistakes that cost me a damn good amount of time to fix.

How can I prevent this from happening in the future? I don't want to spend 50% of my time debugging, I'd rather spend 10% debugging and the rest writing new code. What are some techniques I can try to help me reach this goal?

答:
Unit tests and asserts

Where possible, factor your code into small pieces that can be tested in isolation.  This isn't always practical, though.  Some pieces of functionality depend on extremely complicated inputs.  Some do something that can't easily be verified in an automated way, such as draw stuff to the screen.  Sometimes non-determinism is involved, etc.

When you can't write good unit tests, the next best thing is asserts.  While unit tests check to see if you get the right answer on some predetermined input, asserts check the sanity of intermediate steps on real-world inputs.  If your code has bugs, it will fail quickly, close to the root of the problem and with a clear error message, rather than far from the problem with an ambiguous error message.  Furthermore, asserts document assumptions and make your code more readable.

Title: Spending too much time debugging


问:
How can I make the life of a new hire comfortable?
As a senior member of a software team that, unfortunately, has little documentation for legacy reasons, what are the things that one could do to make a new hire comfortable?

I have been planning debug sessions with the person on specific defects/feature requests to get him/her acquainted with the code base. However the code base is real large, and its only a fixed amount of code I can expose the person to in this manner.

I am looking for suggestions in either cases when the new hire is a recent graduate or an experienced professional.

答:
Draw a quick sketch on a piece of paper. Functional blocks, and data travel among them. So that the new hire can keep this list handy, and look up where is the spot he's trying to touch, and which modules affect it hierarchically.

Everything else comes with time. But it's the big picture that's making you feel dumb when you need to change 2 lines of code, but have no idea what side effects can cause on dependent modules, code blocks, etc.


答:
When you start a project, how many alternate approaches do you identify?

Do you have from two to four different approaches, with pros and cons for each?
Do you then make a reasoned selection from among them?

Then, most important, do you weight simplicity as highly important?

The reason I ask is, in my experience, code volume, and thus the number of bugs (not to mention performance), can vary by more than an order of magnitude between one design approach and another.
What I see highly experienced people doing is getting jobs done with no more code than necessary.

They are fully competent and aware of all the data structure algorithms, features of object-oriented languages, and so on,
but their code looks as if they are not, because they use those things sparingly, or not at all, if the problem does not require them.

Title: Spending too much time debugging

Body:
Yesterday, I rolled out a v1.0 release of a Web project I've spent about 6 weeks working on (on and off, that is). I haven't made any exact records of my time, but according to my experiences I would estimate that out of all the time I spent programming, half of it was spent debugging. I estimate that to be about a good 15-20 hours spend debugging, which to me is precious time that could have better been spent writing new code or finishing the project earlier. It also especially doesn't help that I'll be a freshman in college in 5 weeks.

The thing is, I feel bad for spending all that time debugging. All that time spent debugging makes me realize that I made some pretty stupid mistakes while I was developing my project, mistakes that cost me a damn good amount of time to fix.

How can I prevent this from happening in the future? I don't want to spend 50% of my time debugging, I'd rather spend 10% debugging and the rest writing new code. What are some techniques I can try to help me reach this goal?


问:
Design Methodology for Developing Interoperable Systems?
A bit of background

The company I work for has been creating database applications since around 1980 and, until relatively recently, most of these systems have been stand-alone "silo" systems.

However, in the last few years, we've seen more of a shift towards gathering "intelligence" across all systems within our customers requirements.  For example, a system that might collect data about people's dental records may need to talk to a system that collects data about people's optician records, share information about the same person and provide search capabilities across both systems (makes sense, although the example I've used is fictional).

In the fictional example above, the dental and optician systems may or may not both be written by the company I work for (in other words we are looking at both internally-developed interfaces and interfaces to systems from third-party providers).

What we've done so far

We have a basic web-services API (.asmx) for one of our products, but I'm concerned about the change management, in terms of keeping it up-to-date as we add new features to the main product (in terms of providing the new features through the API without breaking compatibility with older interfaces).

We have also produced one WCF service.  The rigid contracts put my mind slightly more at ease than working with the ASMX service, but I think a lack of experience within the company is holding us back, so I'm looking for some guidance on best practice that I can read up on to help move us along (or at least point us in the right direction).

The question

Is there a particular methodology or programming practice for designing systems to maximise their ability to interface to other systems?

Are there any good online (or offline) resources for these programming practices (assuming they exist)?

Any other advice you can provide based on the information above would be appreciated, but not essential.

We primarily develop in Microsoft .NET (mainly ASP.NET, with some windows forms applications as well) with a SQL Server/Oracle database back-end, although I expect the programming practices might be language independent.  (I've used the .NET tag as an afterthought, but I might take it out later..!)

Thanks for your time.

答:
we've seen more of a shift towards gathering "intelligence" across all systems within our customers requirements.

You clearly need a BI System\Data Warehouse (Business Intelligence). Building one basically entails creating a new central Data store, where all systems push (or have pulled) data into that systems on a regular basis. That data is all married together somehow, then optimized for data retrieval & reporting speed.

Because you are a .Net Shop, I am going to recommend you look at SSAS & SSRS (SQL Server Analysis services and SQL Server Reporting services.)

Obligatory Link : http://en.wikipedia.org/wiki/Business_intelligence

Is there a particular methodology or programming practice for designing systems to maximise

their ability to interface to other systems?

There really is no correlation between methodology and design. I have never heard of a particular methodology claiming to work better for particular programming patters, design or technologies.


答:
Others have mentioned testing and code review. These are both extremely useful but have a key difference - when is best to perform them. Testing is best done very close to originally writing the code, so you can more easily remember why you did things a certain way and can more quickly locate the problem when it fails the test. Code review, on the other hand, is better done a little bit later on. You want to have to look at the code without perfect recollection so that you don't gloss over details that you remember thinking about but didn't put in. You want to realize places where your code is not clear. You want the little extra effort of having to figure out what the code is doing. You want to be able to apply any new knowledge you have acquired about the problem or interactions with other code or new techniques. Basically, you want a change of perspective on the code.

All of this is still tangent to your question, though. In order to spend less time debugging, you have to understand why you had to debug in the first place. Misunderstanding the problem, imperfect knowledge of your tools and technologies, and just plain running into "the real data didn't match the sample data" types of issues are all going to manifest in different ways and need different techniques and types of practice to avoid in the future.

The last point I will make is experience. There is no easy way to get this, you just have to put in the time. As you gain experience you will spend less time debugging because you will write better code to begin with, notice problems earlier, and develop a better intuition for what the source of a problem might be. Keep at it and you will grow this steadily over your career.

Title: Spending too much time debugging


问:
FP and OO orthogonal?
I have heard this time and again and I am trying to understand and validate the idea that FP and OO are orthogonal.

First of all, what does it mean for 2 concepts to be orthogonal ?

FP encourages immutability and purity as much as possible.
and OO seems like something that is built for state and mutation(a slightly  organized version of imperative programming?). And I do realize that objects can be immutable. But OO seems to imply state/change to me.

They seem like opposites. Does that meant they are orthogonal ?

A language like Scala makes it easy to do OO and FP both, does this affect the orthogonality of the 2 methods ?

答:
The term "orthogonal" comes from maths, where it has a synonym: "perpendicular". In this context, you could understand it as "the two things have nothing to do with each other."

When people compare FP and OO they often confuse two separate axes.

On the one hand you have functional programming versus imperative programming. Jonas gives a good comparison of the two. The one-sentence version says that "data flow versus control flow".

The other axis is data abstraction. Languages like Haskell use abstract data types to, well, abstract data. Smalltalk uses objects, which fuse the data and operations on that data into a single unit. William Cook explains better than I could in his paper On Understanding Data Abstraction, Revisited.

It's perfectly understandable that most people end up thinking that FP and OO are opposites: most OO languages are imperative, so if you compare, say, Haskell and Java, you have data flow + ADT versus control flow + object. But there are other possibilities! Matthias Felleisen explains how to happily marry FP and OO in his talk Functional Objects.

Title: FP and OO orthogonal?


答: Definitely break it up!  Break your steps into logical parts.  This makes the code much easier to troubleshot, especially when you are employing unit tests, which itself will save you loads of troubleshooting time in the long run.</p>

Title: Proper use of classes

Body: I'm writing a class that draws a very complex image, with multiple parts. I also plan on adding to the class to add more functionality. Would it be right to make a function for each part, even if that function will only EVER be called in the render function? I see an upside to this since it will be easier to read the code, and easier to add parts. A downside however, would be that it would increase complexity and quite possibly make it harder to maintain. Should I keep all the code in the render function, or break apart the different steps?</p>


问:
Is Perl still a useful, viable language?
I know it may have been asked before, but here goes nothing...

Is Perl still something that would be considered useful? If someone was a new programmer (either completely new to programming or just a few month/years of experience) would Perl be something to be considered worthwhile to learn?

Is Perl still used with frequency? Is it still popular?

Or is Perl dying out compared to languages like Python, Ruby, PHP, ASP.NET, etc.?

Basically it boils down to this:

Is it still used/is it still used frequently? If yes, is it dying? If no, will it make a come back?

Is it something that would be worth learning?

How does it compare in demand to languages like Python in both popularity and usability/viability? Could languages like Python or Ruby be considered replacements for Perl?

Also, will newer versions of Perl really bring a large improvement to the Perl community, and perhaps bring Perl back to centerstage compared to other languages?

EDIT:

Okay, I suppose here's a better, reworded question:

Is Perl still growing, or is it "dying"? Is it still a language worth learning and using? What projects does it really "shine" in compared to other languages? What makes Perl a language to choose? Essentially: is Perl growing obsolete compared to other languages, and if so, do you expect that to change, or to continue?

And thank you to everyone who has answered so far, the discussion has been really interesting!

答:
For a while Perl5 development stagnated because of the focus on Perl6 which caused a long delay between the release of 5.8 and 5.10.  Since then the community has really started to realize that Perl5 and Perl6 are different languages and there have been very regular new releases recently.

Perl recently won a web app competition using Catalyst (Although I prefer Mojolicious) and some of the new Modern Perl practices bring a lot of cleaner OO ideas to Perl with things like Moose.

In my opinion, as a Perl developer, Perl has a great legacy as well as a bright future not only being the duct-tape that holds corporate networks together but also a place in the new hotness of web applications.


答:
Implementing small parts of an algorithm in separate methods that are all called from a "controlling" method, your render method, is an example of using the Template Method Pattern. It is an appropriate way to manage the complexity in your scenario.

As you decide how to refactor functionality into smaller methods, you will want to consider how to support your planned modifications while adhering to the Open-Closed Principle.  That is, try to break the methods down in ways that you can implement your changes by overriding individual methods in subclasses.

Title: Proper use of classes


问:
Question about Creating a Scripting Language
Say, for example, I wanted to pay somebody to create a programming language or scripting language for me. What type of document would they need, in order to fully understand what it is exactly that I want.

I mean, are there standard documents that describe the new programming/scripting language in question?

答:
You can describe your language's grammar in BNF.

For instance, this is Python's grammar.


问:
What kind of documentation should UX designers provide to the developer?
It would be interesting to hear what is used besides sketches from UX engineers during development of a GUI. Unfortunately our UX team provides just a minimum of requirements for GUI screens.
I believe that a better solution would be to use some tables with requirements and state machines or may be just some text description of GUI behavior? Is that something you use ?

I tried speaking to our UX team but looks like it's impossible to get anything besides graphic sketches from them and I am wondering what others use.

Our project is for iPhone currently, but it is could be useful to hear any advice even if you develop for any other platform or even desktop or web.

Thanks!

答:
Our team had used Balsamiq Mockups for this purpose, and it works well.

From their website :

Mockups also excels as a communication tool, a way for the whole team
  to come together around the right design.

it enables Product
  Managers to better present requirements with a tool as easy to use as
  Powerpoint

it’s polished enough for UX Designers to use, with all
  the familiar keyboard shortcuts of the Creative Suite tools

it’s fast, geeky and very power-user-friendly. Developers love that

it’s so easy to learn, clients and customers can use it (for free even), to
  describe their needs more clearly


答:
This is going to vary from place to place, but at a minimum I would expect a sketch that with markup explaining the basic expected behavior and field descriptions.

Ideally your designers are also going to be familiar with any data that you will be working with and will also list the data sources of any part of the interface that displays or is driven by data.

Title: What kind of documentation should UX designers provide to the developer?

Body:
It would be interesting to hear what is used besides sketches from UX engineers during development of a GUI. Unfortunately our UX team provides just a minimum of requirements for GUI screens.
I believe that a better solution would be to use some tables with requirements and state machines or may be just some text description of GUI behavior? Is that something you use ?

I tried speaking to our UX team but looks like it's impossible to get anything besides graphic sketches from them and I am wondering what others use.

Our project is for iPhone currently, but it is could be useful to hear any advice even if you develop for any other platform or even desktop or web.

Thanks!


答:
What you need to write is called a language specification.

It should contain a description of the language's grammar (preferably in Extended Backus-Naur-Form) and its semantics.

For the latter part you could either write a description in your own words (but take care to be precise) or a formal semantics.

Title: Question about Creating a Scripting Language

Body:
Say, for example, I wanted to pay somebody to create a programming language or scripting language for me. What type of document would they need, in order to fully understand what it is exactly that I want.

I mean, are there standard documents that describe the new programming/scripting language in question?


问:
What kind of interface should a double container offer?
I want to write a class which offers two sequences of elements to its users. The first one (lets call it "primary") is the main of the class and will be use 80% of the time. The second one (lets call it "secondary") is less important, but still need to be in the same class. The question is: what interface should the class offer to its users?

By looking at STL style, a class with a single sequence of elements should offer begin() and end() functions for traversal and function like insert() and erase() for modifications.

But how should my class offer the second sequence?

For now, I have two ideas:

Expose the two containers to the user (what about the Law of Demeter ?)

Provide the main container with STL interface and expose only the second one.

Here is an example.

```<code>#include <vector>

class A {
    public:
        std::vector<int>&  primary();
        std::vector<char>& secondary();

    private:
        std::vector<int>  m_primary;
        std::vector<char> m_secondary;
};

class B {
    public:
        std::vector<int>::iterator begin();
        std::vector<int>::iterator end();
        std::vector<char>& secondary();

    private:
        std::vector<int>  m_primary;
        std::vector<char> m_secondary;
};

// Classes implementation
// ...

int main() {

    // --------------------------------------------------
    // Case 1
    // --------------------------------------------------

    A a;

    for(auto it = a.primary().begin(); it != a.primary().end(); ++it) {
        // ...
    }
    for(auto it = a.secondary().begin(); it != a.secondary().end(); ++it) {
        // ...
    }

    // --------------------------------------------------
    // Case 2
    // --------------------------------------------------

    B b;

    for(auto it = b.begin(); it != b.end(); ++it) {
        // ...
    }
    for(auto it = b.secondary().begin(); it != b.secondary().end(); ++it) {
        // ...
    }
}
</code>```

What is the more C++ish way to do that? Is one best than the other or is there an other solution?

Context

This problem came in the context of an exercise in which I am writing a simple database access framework. Here are the classes involved in the question:

table

column

row

field

The table class consists of a sequence of columns and an other sequence of rows. The main use of the table is manipulating (access, add and remove) the rows.

Deeper in the hierarchy, a row is made of column and field so a user can ask the value (field) corresponding to a given column or column name. Each time a column is add/modify/remove from the table, every rows will need to be modify to reflect the modification.

I want the interface to be simple, extensible and combining well with existing code (like STL or Boost).

答:
Since you are effectively re-implementing Boost.MultiIndex and most C++ developers should be at least vaguely familiar with Boost libraries, consider duplicating their interface. They use one index object per index and container which publishes begin() and end():

```<code>class A {
    struct primary {
        struct iterator;
        iterator begin();
        iterator end();
    };
    struct secondary {
        struct iterator;
        iterator begin();
        iterator end();
    };
    primary primary_view();
    secondary secondary_view();
};
</code>```

One of the advantages is that you can give the view objects to any function expecting containers or boost ranges.

Body:
Since you are effectively re-implementing Boost.MultiIndex and most C++ developers should be at least vaguely familiar with Boost libraries, consider duplicating their interface. They use one index object per index and container which publishes begin() and end():

class A {
    struct primary {
        struct iterator;
        iterator begin();
        iterator end();
    };
    struct secondary {
        struct iterator;
        iterator begin();
        iterator end();
    };
    primary primary_view();
    secondary secondary_view();
};

One of the advantages is that you can give the view objects to any function expecting containers or boost ranges.


问:
What are the causes that lead to an overbloated software?
Today I decided to perform a clean install for Creative Sound Blaster drivers, as they always start glitching all by themselves after some time. And that meant I had to go through the whole cleanup procedure. And that took me almost 2 hours..

And honestly, I can't see a reason why?! And although Creative, IMHO, is an absolute 1st place winner for producing poor quality software that never works, the bloat problem is not exclusive to them.

PC with Canon digital camera driver will have around 10 Canon entries that are interconnected with all sorts of connections. Visual Studio is also a prime example, there is around 50 or so entries for full install, and repairing that thing is only possible with complete nuking. And once it even managed to ruin the whole OS install when I was upgrading from VS2k8 to VS2k8SP1 or something. As it turns out 5GB of free space was not enough for 300Mb patch...

So this really seem to be a widespread problem. Almost every application nowadays usually contains unpackers, multiple spywarish "friends" that are installed, drivers are usually around 600Mb for everything including printers and so on.

But why? Is it developer fault? Applications like that are nightmare to support, they never work 100% nowadays, and almost all users I know are very negative about all that bloat they get as a mandatory driver install for USB thumb drive/Printer/Camera/Sound Card/Browser.

It seems that NSIS from Nullsoft is the only clean setup system that is not bloated, from what I know, for example, Firefox install. Clean, pretty much xcopy based install without any problems.

So why people are not using simple setups and applications that are not rooted over 30 layers of interconnection? Is it because developers are lazy? Use of codegen tools? Is it because corporations force heavyweight apps as something users will love? What's the cause, and is there a hope software will return back to basics someday? What are the steps to avoid writing bloat when you start new application from scratch?

答:
Quite a large part of it is to do with dependencies of a product.  Your operating system ships with a lot of standard libraries for all kinds of things.  However, these standard libraries have different versions throughout the evolution of the OS, and any generic installer cannot assume that the specific version it was built against will actually be present on the OS.

Therefore the full installer will need to include the correct version of every dependency to make sure that everything will definitely work after installation, no matter what the initial state of each dependency on the target computer.  This can be quite a significant bloat for certain types of applications, for example .NET-based applications that need to be deployed to Windows XP systems.

Until recently, one installer system that I worked with needed every single previous .NET version to be installed to be able to deploy the latest version, so that meant any .NET 3.5 application required installation binaries for .NET 1, 2, 2.5 and 3 ON TOP of 3.5.  In this case, only the installer is bloated.

One workaround is a web installer, which downloads only those components that are actually not present on the target system - and this can be a gigantic size/bloat benefit.  Of course it does limit your installations to systems that have internet connectivity.


答:
if you're using .NET, here is something I stumbled across some time back. I only gave it a curious glance, but maybe it would be use to you:  irony.

Irony is a development kit for implementing languages on .NET platform.


问:
Why pointer symbol and multiplication sign are same in C/C++?
I am writing a limited C/C++ code parser. Now, multiplication and pointer signs give me really a tough time, as both are same. For example,

```<code>int main ()
{
  int foo(X * p); // forward declaration
  bar(x * y);  // function call
}
</code>```

I need to apply special rules to sort out if * is indeed a pointer. In above code, I have to find out if foo() is a forward declaration and bar() is a function call. Real world code can be lot more complex. Had there been different symbol like @ for pointers, then it would have been straight forward.

The pointers were introduced in C, then why some different symbol was not chosen for the same ? Was keyboard so limited ?

[It will be an add-on if someone can throw light on how modern day parser deal with this ? Keep in mind that, in one scope X can be typename and another scope it can be a variable name, at the same time.]

答:
Yes, the same symbols are being reused, because there were no UTF32 back there. So you have * as a pointer type, * as a dereference operator, * as a multiplication operator, and that's just in C. You also have a similar problem with "&" for example ("&" as address-off, "&" as bitwise-end and "&" as part of "&&" - logical and), and others.

The lexical parsers differentiate between them based on the context.

in your example, you have two different paths in your parser: one that starts with a type (a variable/forward declaration) and one that doesn't (function call). If there's an ambiguity - you get a compilation error.

If you're using a subset of C - you need to make sure you get the right subset of the grammar that handles this issue.