问:
Should you write your back-end as an API?
I had a heated discussion today about our MVC application. We have a website written in MVC (ASP.NET), and it usually follows the pattern of do something in the view -> hit the controller -> controller builds a model (calls a Manager that gets the data, builds the model in the controller method itself) -> model goes to view -> rinse & repeat.

He said that our code was too tightly coupled. For example, if we wanted a desktop application as well, we would not be able to use our existing code.

The solution and best practice he said is to build an API, and then build your website on top of your API, and then building a desktop application, mobile app, etc. is very simple.

This seems like a bad idea to me for various reasons.

Anyway I can't seem to find anything by googling that might discuss this practice. Does anyone have any information about pros, cons, why you should, why you shouldn't or further reading?

Some reasons I think it's a bad idea:

It's way too abstract to run your backend off an API. You're trying to make it too flexible which will make it an unmanagable mess.

All the stuff built into MVC seems useless, like roles and authentication. For example, [Authorize] attributes and security; you will have to roll your own.

All your API calls will require security information attached, and you will have to develop a token system and whatnot.

You will have to write complete API calls for every single function your program will ever do. Pretty much every method you want to implement will need to be ran off an API. A Get/Update/Delete for every user, plus a variant for each other operation eg update user name, add user to a group, etc. etc. and each one would be a distinct API call.

You lose all kinds of tools like interfaces and abstract classes when it comes to APIs. Stuff like WCF has very tenuous support for interfaces.

You have a method that creates a user, or performs some task. If you want to create 50 users, you can just call it 50 times. When you decide to do this method as an API your local webserver can named-pipes connect to it and no problem - your desktop client can hit it too, but suddenly your bulk user creation will involve hammering the API over the Internet 50 times which isn't good. So you have to create a bulk method, but really you're just creating it for desktop clients. This way, you end up having to a) modify your API based on what's integrating with it, and you can't just directly integrate with it, b) do a lot more work to create an extra function.

YAGNI. Unless you're specifically planning to write two identically functioning applications, one web and one Windows application for example, it is a huge amount of extra development work.

Debugging is much harder when you can't step through end-to-end.

Lots of independent operations that will require lots of back and forth, for example some code might get the current user, check the user is in the administrator role, get the company the user belongs to, get a list of other members, send them all an email. That would require a lot of API calls, or writing a bespoke method the specific task you want, where that bespoke method's only benefit would be speed yet the downside would be it would be inflexible.

Probably some more reasons these are just off the top of my head.

It just seems to me like unless you really need two identical applications, then it's really not worth it. I've never seen an ASP.NET application built like this either, you'd have to write two separate applications (the API and your code) and version control them both as well (if your user page gets a new field, you'd have to update the API and your consuming code simultaneously to ensure no ill-effects or put lots of extra work into keeping it robust).

Edit: Some great responses, really starting to get a good idea of what this all means now. So to expand on my question, how would you structure an MVC app to follow this API structure?

For example, you have a website that displays info about a user. Under MVC, you have:

View - (CS)HTML page that displays a UserViewModel
Controller - Calls GetUser() and creates a UserViewModel that it passes to the view
Manager class (sort of your API) that has a GetUser method.

The controller does GetUser() but you want a desktop app too. This means your GetUser needs to be exposed via some kind of API. You might want a TCP connection, either WCF, or perhaps Remoting. You also want a mobile app which will be RESTful since persistent connections are flaky.

So would you then write an API for each one, a WCF web service that has a method GetUser() and the code just does return new UserManager().GetUser() ? And an mvc 4 web api method that does the same thing? While continuing to call GetUser directly in your MVC controller method?

Or would you choose the solution that would work for all three (web api REST service) and build everything on that, so all three apps make API calls (the mvc ones, to the local machine).

And is this just a theoretical perfect scenario? I can see large overheads in developing this way, especially if you have to develop in a way that will let you do operations in a RESTful manner. I think some of this has been covered in the replies.

Edit 2: After reading more stuff, I've put a comment below that I think might explain it. The question is a bit of a trick question I think. Should you write your back-end as an API had me confused thinking there should be a single webservice that everything (mvc app, desktop app, mobile app) calls to do stuff.

The conclusion I have come to is that what you should really do is make sure your business logic layer is correctly decoupled. Looking at my code, I do this already - the controller will call GetUser() on a manager, then create a view model from it to render with a View. So really, the business logic layer is an API. If you want to call it from a desktop app though, you'll need to write something like a WCF service to facilitate calling it. Even just having a WCF method called GetUser() that contains the code return MyBusinessLayer.GetUser() would be sufficient. So the API is the business logic, and WCF / web api etc. are just titbits of code to let external applications in to call it.

So there is some overhead, in that you have to wrap your business logic layer in different APIs depending on what you need, and you will have to write an API method for each operation you want your other apps to do, plus you will need to sort out a way to do authentication, but for the most part it's the same. Stick your business logic in a separate project (class library), and you will probably have no issue!

Hopefully this interpretation is correct. Thanks for all the discussion/comments it has generated.

答:
Yes you should.

It not only makes your back end re-usable but allows for more security and better design. If you write your backend as part of a single system, you're making a monolithic design that's never easy to extend, replace or enhance.

One area where this is popular at the moment is in Microservices. Where the backend is split into many little (or even large) services that each provide an API that the client system consumes. If you imagine using many 3rd party sources of data in your application you realise you might be doing this already.

One other benefit is that the construction and maintenance of each service can be handed off to a different team, they can add features to it that do not affect any other team producing product. Only when they are done and release their service do you them start to add features to your product to consume them. This can make development much smoother (though potentially slower overall, you would tend to get better quality and understandable)

Edit: OK I see your problem. You think of the API as a remote library. It's not. Think of the service as more of a data providing service. You call the service to get data and then perform operations on that data locally. To determine if a user is logged on you would call "GetUser" and then look at the 'logged on' value, for example. (YMMV with that example, of course).

Your example for bulk user creation is just making excuses - there is no difference here, whatever you could have done in a monolithic system can still be done in a service architecture (e.g. you would have passed an array of users to bulk-create, or a single one to create. You can still do exactly the same with services).

MVC is already based around the concept of isolated services, only the MVC frameworks bundle them into a single project. That doesn't mean you lose anything except the bundled helpers that your framework is giving you. Use a different framework and you'll have to use different helpers. Or, in this case, rolling your own (or adding them directly using a library).

Debugging is easy too - you can thoroughly test the API in isolation so you don't need to debug into it (and you can debug end-to-end, Visual Studio can attach to several processes simultaneously).

Things like extra work implementing security is a good thing. Currently, if you bundle all the code into your website, if a hacker gains access to it, they also gain access to everything, DB included. If you split it into an API the hacker can do very little with your code unless they also hack the API layer too - which will be incredibly difficult for them (ever wondered how attackers gain vast lists of all website's users or cc details? It's because they hacked the OS or the web server and it had a direct connection to the DB where they could run "select * from users" with ease).

I'll say that I have seen many web sites (and client-server applications) written like this. When I worked in the financial services industry, nobody would ever write a website all-in-one, partly as it's too much of a security risk, and partly because much development is pretty GUIs over stable (i.e. legacy) back-end data processing systems. It's easy to expose the DP system as a website using a service style architecture.

2nd Edit: Some links on the subject (for the OP):

Note that when talking about these in context of a website, the web server should be considered the presentation layer, because it is the client that calls the other tiers, and also because it constructs the UI views that are sent to the browser for rendering. It's a big subject, and there are many ways to design your application - data-centric or domain-centric (I typically consider domain centric to be 'purer', but YMMV), but it all comes down to sticking a logic tier in between your client and your DB. It's a little like MVC if you consider the middle, API, tier to be equivalent to your Model, only the model is not a simple wrapper for the DB, it's richer and can do much more (e.g. aggregate data from 2 data sources, post-process the data to fit the API, cache the data, etc.):

Multitier architecture

Building an N-Tier Application in .NET

Youtube tutorial - see the related links too, inc one to implement in C#

Pluralsight training course (free trial or paid)


问:
Testing a Conversion class
I have a class that is responsible for performing conversions from/to twenty-something types. Let's call this class ConvertUtils.

For C# programmers out there - this class expands .Net's Convert class.

It looks something like this:

```<code>public static class ConvertUtils {
    public static object ChangeType(object obj, Type newType) {
        if (conversionSupportedByFramework)
            return Convert.ChangeType(obj, newType);
        else
            ConvertSpecialCases(obj, newType);
    }
}
</code>```

How would you go about testing it? I'm assuming we do need to black-box test this code.

The two ways we thought about, are:

Writing 400+ unit tests - cover all to/from combinations that we can think of.

Write tests only for the new conversions - the ones not supported by the Convert class - actually testing only the ConvertSpecialCases() function [which isn't our goal, as stated above]

The con of the first possibility is to have too many tests - which prolongs the build time, involves maintaining more code, etc.

The con of the second possibility is to not fully check the responsibility of the class -
what if a certain if statement decides to implement (wrong) custom logic, instead of letting Convert do it's job? e.g. just before if (conversionSupportedByFramework) someone decides to call some custom logic?

What do you think about this issue?

答:
The fact that your class is a conversion class, the fact that it is static, and the fact that it expands an existing framework class are all irrelevant.  This question is an instance of the more general question of black-box vs. white-box testing.

In lack of any very good reason to perform white-box testing, all
  testing should be black-box testing.

This means that your testing code should not be making any assumptions about the internals of the system-under-test.

This in turn means that your testing code should not assume that your conversion class delegates to some other conversion class.  (Precisely because it may delegate, and then again who knows, it might not delegate.)  So, testing the entire public interface of your conversion class is the way to go.

That having been said, let me add that since you are writing a static class which expands on the functionality of another static class, the way to reduce your testing code is by expressly refraining from duplicating the functionality of the existing framework class.  If you want one of the conversions provided by the framework class, invoke the framework class.  If you want one of the conversions provided by your class, invoke your class.  There is no reason to wrap the functionality of a static framework class inside a static custom class, there is not even any real wrapping going on, only pretending, because the functionality of the framework class is still publicly available to any piece of code that wishes to invoke it.

ContentLicense: CC BY-SA 3.0

Title: Testing a Conversion class


问:
Flag arguments in an html factory class
I have been told that flag arguments(boolean arguments) are a bad thing because it complicates the signature of the method and means that the method does more than one thing.

An issue I have with this rule is what if I have a html factory class that builds raw html from arguments passed in. Then lets say I want an option to make the form element required. This would obviously make most sense as a boolean argument. But this is contradictory to what I have been told.

So my questions is: is this an exception to this rule, does this rule even make sense, or what is the correct way to do a required option in an html factory class?

答:
The problem of using boolean parameters to me, is that when you encounter a call to such method, it is unclear what that boolean is representing. You would have to look it up, while I would rather focus on the problem I'm trying to solve.

I find it more readable to create a seperate method for it, such as addRequiredTextBox() and addOptionalTextBox() instead of addTextBox(true|false). To prevent code duplication, have the addRequiredTextBox() and addOptionalTextBox() call to a private method addTextBox(true|false).

Title: Flag arguments in an html factory class


问:
Create new object or reset every property?
```<code> public class MyClass
    {
        public object Prop1 { get; set; }

        public object Prop2 { get; set; }

        public object Prop3 { get; set; }
    }
</code>```

Suppose I have an object myObject of MyClass and I need to reset its properties, is it better to create a new object or reassign each property? Assume I don't have any additional use with the old instance.

```<code>myObject = new MyClass();
</code>```

or

```<code>myObject.Prop1 = null;
myObject.Prop2 = null;
myObject.Prop3 = null;
</code>```

答:
You should definitely prefer creating a new object in the vast majority of cases. Problems with reassigning all properties:

Requires public setters on all properties, which drastically limits the level of encapsulation you can provide

Knowing whether you have any additional use for the old instance means you need to know everywhere that the old instance is being used. So if class A and class B are both passed instances of class C then they have to know whether they'll ever be passed the same instance, and if so whether the other one is still using it. This tightly couples classes which otherwise have no reason to be.

Leads to repeated code- as gbjbaanb indicated, if you add a parameter to the constructor, everywhere that calls the constructor will fail to compile, there's no danger of missing a spot. If you just add a public property, you'll have to be sure to manually find and update every place where objects are "reset".

Increases complexity. Imagine you're creating and using an instance of the class in a loop. If you use your method, then you now have to do separate initialization the first time through the loop, or before the loop starts. Either way is additional code you have to write to support these two ways of initializing.

Means your class can't protect itself from being in an invalid state. Imagine you wrote a Fraction class with a numerator and denominator, and wanted to enforce that it was always reduced (i.e. the gcd of the numerator and denominator was 1). This is impossible to do nicely if you want to allow people to set the numerator and denominator publicly, as they may transition through an invalid state to get from one valid state to another. E.g. 1/2 (valid) -> 2/2 (invalid) -> 2/3 (valid).

Isn't at all idiomatic for the language you're working in, increasing the cognitive friction for anybody maintaining the code.

These are all pretty significant problems. And what you get in return for the extra work you create is... nothing. Creating instances of objects is, in general, incredibly cheap, so the performance benefit will almost always be totally negligible.

As the other answer mentioned, the only time performance might be a relevant concern is if your class does some significantly expensive work on construction. But even in that case, for this technique to work you'd need to be able to separate out the expensive part from the properties you're resetting, so you'd be able to use the flyweight pattern or similar instead.

As a side note, some of the problems above could be mitigated somewhat by not using setters and instead having a public Reset method on your class which takes the same parameters as the constructor. If for some reason you did want to go down this reset route, that would probably be a much better way of doing it.

Still, the additional complexity and repetition that adds, along with the points above that it doesn't address, are still a very persuasive argument against doing it, especially when weighed up against the nonexistent benefits.


问:
Is Apple sample code the "correct" way to go?
I'm in a place were I know how to build apps and have submitted at least 5 for different clients to the app store and wanted to step up my game. So of course I went to Apple resources and analyse the code deeply (I've used Apple code resources before but just to find answers and move on). And I realised their code is really different from any other iOS Dev I know. Example: https://developer.apple.com/library/prerelease/ios/samplecode/LazyTableImages/Introduction/Intro.html#//apple_ref/doc/uid/DTS40009394

Is this how you guys would load a tableView with images and names? I think something like this wouldn't even come across my mind when thinking on how to do it.

答:
Apple's sample code is just that, sample code. No guarantee that it works, that it is bug free, that it is the best way to achieve something. Use it to study some area that you don't know much about, until you are knowledgable in that area by yourself. And then throw the sample code away.

Which is what you should do with any code that you find on the Internet.

In this case, the structure of the downloading code is nice. I'd save the icons in the tmp directory, and I would prepare for the table view changing while a download is running, and I would just invalidate a row of the tableview instead of modifying the cell. On the other hand, their code to avoid downloading while scrolling, and to avoid multiple downloads of the same data, that is nice.

So while everyone has his own style, their sample code will send you into the right direction.


问:
Benefits of this data format
I'm integrating with a bluetooth blood pressure monitor, and I've come across one of the most bizarre data formats I've ever seen.

The systolic, diastolic and pulse rate (all ints, should all be below 200) are transmitted like this:

the int value is converted to hex

the last two characters of the hex value are taken and transmitted in adjacent bytes

For example, a pulse rate of 80 is transformed to 0x50, the character '5' is transmitted in byte 1, and '0' is transmitted in byte 2.

What could be the reason for this format? Is there a name for it?

I realise this could elicit mostly opinion based answers, but I'm hoping this is a well known method in some circles, with a name that I can use for further research.

答: It is possible the data format was originally developed for a serial port. A reason to use characters instead of binary is to avoid the the control characters that have special meanings to serial drivers such as control-s and control-q, EOF, etc... A reason to use hex is for 2 byte values instead of 3 byte values, which you would need for base 10.</p>

Title: Benefits of this data format


答:
Given the very generic example, it's hard to tell.  If "resetting the properties" makes semantic sense in the case of the domain, it will make more sense to the consumer of your class to call

```<code>MyObject.Reset(); // Sets all necessary properties to null
</code>```

Than

```<code>MyObject = new MyClass();
</code>```

I would NEVER require making the consumer of your class call

```<code>MyObject.Prop1 = null;
MyObject.Prop2 = null; // and so on
</code>```

If the class represents something that can be reset, it should expose that functionality through a Reset() method, rather than relying on calling the constructor or manually setting its properties.

Title: Create new object or reset every property?

Body:
```<code> public class MyClass
    {
        public object Prop1 { get; set; }

        public object Prop2 { get; set; }

        public object Prop3 { get; set; }
    }
</code>```

Suppose I have an object myObject of MyClass and I need to reset its properties, is it better to create a new object or reassign each property? Assume I don't have any additional use with the old instance.

```<code>myObject = new MyClass();
</code>```

or

```<code>myObject.Prop1 = null;
myObject.Prop2 = null;
myObject.Prop3 = null;
</code>```

Body:
Given the very generic example, it's hard to tell.  If "resetting the properties" makes semantic sense in the case of the domain, it will make more sense to the consumer of your class to call

MyObject.Reset(); // Sets all necessary properties to null

Than

MyObject = new MyClass();

I would NEVER require making the consumer of your class call

MyObject.Prop1 = null;
MyObject.Prop2 = null; // and so on

If the class represents something that can be reset, it should expose that functionality through a Reset() method, rather than relying on calling the constructor or manually setting its properties.


答:
My company has one application built like this. Initially we were commissioned to build a back end with API for a front end that another developer was creating. When the other developer couldn't develop that front end we were commissioned to build the front end too. While there are definitely benefits to this approach there is a huge disadvantage: cost. The initial build will be significantly more expensive, and ongoing maintenance will be more expensive, due to more code to maintain and having two separate systems too deploy. Due to the extra cost, this should always be a business decision, not taken on a whim by developers.

To put a figure on it, I'd estimate the project I mention above cost 20% more due to this approach. You don't describe what type of project you're working on what sort of company you work for, but if you're a start up building their product that extra cost could be the difference between shipping a few extra features that make your product a success.

Another reason not to, at least not universally, is that if or when you decide to create that second interface, there's a rarely a one to one mapping of functionality. If you make a mobile app, for example, they tend to have less features. This means some of your API methods won't ever be reused. Therefore a compromise with your colleague could be to decide between you the most crucial/critical calls and add those to an API, and use more traditional methods for everything else.

Another point to consider is that your colleague is saying you won't be able to reuse your existing code, which isn't true if you have some separation of your business logic. You simply need to create a thin web service wrapper around your internal APIs, which isn't a particularly big task. It would be naive to think you could reuse a web service layer for another front end anyway with no changes at all.

Title: Should you write your back-end as an API?

Body:
I had a heated discussion today about our MVC application. We have a website written in MVC (ASP.NET), and it usually follows the pattern of do something in the view -> hit the controller -> controller builds a model (calls a Manager that gets the data, builds the model in the controller method itself) -> model goes to view -> rinse & repeat.

He said that our code was too tightly coupled. For example, if we wanted a desktop application as well, we would not be able to use our existing code.

The solution and best practice he said is to build an API, and then build your website on top of your API, and then building a desktop application, mobile app, etc. is very simple.

This seems like a bad idea to me for various reasons.

Anyway I can't seem to find anything by googling that might discuss this practice. Does anyone have any information about pros, cons, why you should, why you shouldn't or further reading?

Some reasons I think it's a bad idea:

It's way too abstract to run your backend off an API. You're trying to make it too flexible which will make it an unmanagable mess.

All the stuff built into MVC seems useless, like roles and authentication. For example, [Authorize] attributes and security; you will have to roll your own.

All your API calls will require security information attached, and you will have to develop a token system and whatnot.

You will have to write complete API calls for every single function your program will ever do. Pretty much every method you want to implement will need to be ran off an API. A Get/Update/Delete for every user, plus a variant for each other operation eg update user name, add user to a group, etc. etc. and each one would be a distinct API call.

You lose all kinds of tools like interfaces and abstract classes when it comes to APIs. Stuff like WCF has very tenuous support for interfaces.

You have a method that creates a user, or performs some task. If you want to create 50 users, you can just call it 50 times. When you decide to do this method as an API your local webserver can named-pipes connect to it and no problem - your desktop client can hit it too, but suddenly your bulk user creation will involve hammering the API over the Internet 50 times which isn't good. So you have to create a bulk method, but really you're just creating it for desktop clients. This way, you end up having to a) modify your API based on what's integrating with it, and you can't just directly integrate with it, b) do a lot more work to create an extra function.

YAGNI. Unless you're specifically planning to write two identically functioning applications, one web and one Windows application for example, it is a huge amount of extra development work.

Debugging is much harder when you can't step through end-to-end.

Lots of independent operations that will require lots of back and forth, for example some code might get the current user, check the user is in the administrator role, get the company the user belongs to, get a list of other members, send them all an email. That would require a lot of API calls, or writing a bespoke method the specific task you want, where that bespoke method's only benefit would be speed yet the downside would be it would be inflexible.

Probably some more reasons these are just off the top of my head.

It just seems to me like unless you really need two identical applications, then it's really not worth it. I've never seen an ASP.NET application built like this either, you'd have to write two separate applications (the API and your code) and version control them both as well (if your user page gets a new field, you'd have to update the API and your consuming code simultaneously to ensure no ill-effects or put lots of extra work into keeping it robust).

Edit: Some great responses, really starting to get a good idea of what this all means now. So to expand on my question, how would you structure an MVC app to follow this API structure?

For example, you have a website that displays info about a user. Under MVC, you have:

View - (CS)HTML page that displays a UserViewModel
Controller - Calls GetUser() and creates a UserViewModel that it passes to the view
Manager class (sort of your API) that has a GetUser method.

The controller does GetUser() but you want a desktop app too. This means your GetUser needs to be exposed via some kind of API. You might want a TCP connection, either WCF, or perhaps Remoting. You also want a mobile app which will be RESTful since persistent connections are flaky.

So would you then write an API for each one, a WCF web service that has a method GetUser() and the code just does return new UserManager().GetUser() ? And an mvc 4 web api method that does the same thing? While continuing to call GetUser directly in your MVC controller method?

Or would you choose the solution that would work for all three (web api REST service) and build everything on that, so all three apps make API calls (the mvc ones, to the local machine).

And is this just a theoretical perfect scenario? I can see large overheads in developing this way, especially if you have to develop in a way that will let you do operations in a RESTful manner. I think some of this has been covered in the replies.

Edit 2: After reading more stuff, I've put a comment below that I think might explain it. The question is a bit of a trick question I think. Should you write your back-end as an API had me confused thinking there should be a single webservice that everything (mvc app, desktop app, mobile app) calls to do stuff.

The conclusion I have come to is that what you should really do is make sure your business logic layer is correctly decoupled. Looking at my code, I do this already - the controller will call GetUser() on a manager, then create a view model from it to render with a View. So really, the business logic layer is an API. If you want to call it from a desktop app though, you'll need to write something like a WCF service to facilitate calling it. Even just having a WCF method called GetUser() that contains the code return MyBusinessLayer.GetUser() would be sufficient. So the API is the business logic, and WCF / web api etc. are just titbits of code to let external applications in to call it.

So there is some overhead, in that you have to wrap your business logic layer in different APIs depending on what you need, and you will have to write an API method for each operation you want your other apps to do, plus you will need to sort out a way to do authentication, but for the most part it's the same. Stick your business logic in a separate project (class library), and you will probably have no issue!

Hopefully this interpretation is correct. Thanks for all the discussion/comments it has generated.


问:
When do micro-benchmarks make sense?
I've been researching micro-benchmarks (e.g. using JMH or Caliper, though not necessarily limited to Java). Now, there are many articles which describe how to write a benchmark but I haven't found much on when to write a benchmark (and when not to). There were a few things that go in that direction, e.g.

Continuous delivery, continuous testing… is one thing, but continuous measuring is another step.

or

Always Measure

Before you start optimizing, make sure you have a problem that you need to solve. Make sure you can accurately measure your existing performance, or you won't be able to measure the benefit of the alternatives you try.

But that's only of limited value to me.

So my question is: In which scenarios do micro-benchmarks make sense? When don't they? What should and shouldn't they be used for? And does anyone here have real life experience with micro-benchmarking in a large project?

答:
Micro-Benchmarks can be used in addition to a profiler to find and fix problematic parts of your code. So, you can run a profiler to identify the problematic regions and then test those specific regions with micro-benchmarks.

Generally speaking, micro-benchmark frameworks (such as Caliper and JMH) are designed to prevent many of the common mistakes and make it easier to create meaningful benchmarks (as is described in the answer to this question). These are in many cases problems which don't occur in the same form when you're testing larger pieces of code; therefore it makes sense to keep micro-benchmarks small. (That's why they're called micro-benchmarks after all.)

Some things I've come up with are the following.

Measure:

if you've found a bottleneck and you may have a better solution

if you're comparing several technologies which can do the same job (e.g. xml parsers) and want to know which one is fastest before using them in your real code

if you have nothing else to improve about your code

Don't measure:

if the code has time wise unreliable outside dependencies (e.g. it talks over a network)

if the measured piece of code won't be called very often (or if you're unsure) unless your application is REALLY time sensitive.
(= If you rarely run a piece of code, don't try optimize it. It probably won't be worth the time.)

if the operation will take longer than a few milliseconds to complete

just because your boss, manager or someone else who is in charge thinks that it's a good idea to do so

Also, while some people run micro-benchmarks regularly (as you would run unit tests), since I use them only to analyze problems I already know about (thanks to the profiler), these benchmarks are not something I'll need to run very often. There may be situations in which this would make sense (and if you know of one, please comment!) but that would probably be a totally different way of using such tools.

Title: When do micro-benchmarks make sense?


答:
If the intended usage pattern for a class is that a single owner will keep a reference to each instance, no other code will keep copies of the references, and it will be very common for owners to have loops which need to, many times, "fill in" a blank instance, use it temporarily, and never need it again (a common class meeting such a criterion would be StringBuilder) then it may be useful from a performance standpoint for the class to include a method to reset an instance to like-new condition.  Such an optimization isn't likely to be worth much if the alternative would only require creating a few hundred instances, but the cost of creating millions or billions of object instances can add up.

On a related note, there are a few patterns that can be used for methods that need to return data in an object:

Method creates new object; returns reference.

Method accepts a reference to a mutable object, and fills it in.

Method accepts a reference-type variable as a ref parameter and either uses the existing object if suitable, or changes the variable to identify a new object.

The first approach is often the easiest semantically.  The second is a little awkward on the calling side, but may offer better performance if a caller will frequently be able to create one object and use it thousands of times.  The third approach is a little awkward semantically, but can be helpful if a method will need to return data in an array and the caller won't know the required array size.  If the calling code holds the only reference to the array, rewriting that reference with a reference to a larger array will be semantically equivalent to simply making the array bigger (which is the desired behavior semantically).  While using List<T> may be nicer than using a manually-resized array in many cases, arrays of structures offer better semantics and better performance than lists of structures.


答:
No you shouldn't. If you don't have immediate plans to create alternative frontends (like mobile or desktop apps or separate web application) which access the same backend, then you shouldn't introduce a web service layer. YAGNI.

Loose coupling is always desirable (along with high cohesion), but it is a design principle and does not mean you have to physically separate objects on different servers! And a badly designed service API can create tight coupling across server boundaries, so having an API does not guarantee loose coupling.

If the need for a service API should arise in the future you can always introduce it at that point. As long as you keep your code nicely layered (data access and business logic cleanly separated form UI logic), it will not be harder to introduce later than it is now. And the resulting design will be much better when designed to meet actual requirements.

Note I'm assuming the question is if you should create a web service API or not. The question just says API, but API can also just mean the interface of a library, and then of course every layer will have an API by definition. Bottom line is that your business logic and data access layers should be cleanly separated form the UI logic at the design level, but you shouldn't introduce a web service layer if you don't need it.


答:
I know microservices are all the rage right now, but they aren't always worth it. Yes, loosely coupled code is the goal. But it shouldn't come at the expense of a more painful development cycle.

A good middle ground would be to create a separate data project in your solution. The data project would be a .NET class library. Your ASP.NET MVC project would then add a reference to the data library, and all models would be pulled from the data project. Then when the time came to create a desktop or mobile app, you could reference the same code. So it may not be an official API, but it will function as one. If you wanted to make it accessible as an API, you could create a simple web project that acts as a wrapper on the data project.

Microsoft has been promoting this concept, which they call Portable Class Libraries.


问:
What's wrong about extending a class with prototype methods?
I was at a bar last night with a few of my colleagues. They said that it's a bad idea to extend the functionality of basic JavaScript Objects with a prototype method.

For example, let's say you created a method for finding the factorial

```<code>Number.prototype.factorial = function(n) {
  return n == 0 ? 1 : factorial(n - 1)
</code>```

}

They said there was some danger to creating prototypes. Why would this be a bad practice?

答:
Abhi explained on Stack Overflow why you don't want to do it to common objects, but for your own class, that's the way of doing it. So in short, the answer is DEPENDS.

When you extend an object, you change its behaviour.

Changing the behaviour of an object that will only be used by your own
  code is fine. But when you change the behaviour of something that is
  also used by other code there is a risk you will break that other
  code.

When it comes adding methods to the object and array classes in
  javascript, the risk of breaking something is very high, due to how
  javascript works. Long years of experience have taught me that this
  kind of stuff causes all kinds of terrible bugs in javascript.

If you need custom behaviour, it is far better to define your own
  class (perhaps a subclass) instead of changing a native one. That way
  you will not break anything at all.

The ability to change how a class works without subclassing it is an
  important feature of any good programming language, but it is one that
  must be used rarely and with caution.

Abhi Bekert
Stack Overflow Answer

Also, there is a performance aspect of this as well.

Let's say you added a property to a prototype of some class. The way JS works, is when you try to access a property on any object, it will try to find it on this object, if not found, JS will proceed to check it's prototype, and prototype of the prototype.. and so on, until it hits the very top where no more prototype is found. If you add the property to immediate prototype of your class, you are essentially producing more efficient code than adding to prototype of a common object in JS.

But, again, what this means is - use this carefully with understanding what it does. Anything is bad when used inappropriately.


答:
The problem is the global scope. In other words, every change you make affects the whole code base, and yours may in turn be affected in any location of the code base.

Imagine that you want to loop through all elements of an array; imagine that browsers don't support it yet. For that, you create a method forEach which is called this way:

```<code>[5, 7, 1, 1, 3].forEach(function (element) {
    // Do something here.
});
</code>```

You implemented this method, thought about some edge cases (what about an empty array, for example?) and everything is fine, except a slight performance bug you missed: in some cases, the enumeration is very slow.

Now, somewhere else, your colleague had this great idea of having a forEach method, but doesn't know you have already implemented one; actually, he even tried to call forEach on an array to ensure the method doesn't exist yet, but since your code is not executed on every page, [].forEach returns undefined.

So he creates his own implementation, but forgets to test it for an empty array, and, in fact, when the array is empty, his code fails.

Back to your code, one day you find a bug report telling that there is a error around forEach: when the array is empty, it fails. You don't know that your colleague had his own implementation of forEach which overwrites yours on some pages. Therefore, you think that it's your code which is concerned, so you spend hours wondering why is it failing, while your unit tests pass.

You end up finding the culprit, that is the duplicated forEach, and you decide to remove the code of your colleague—yours is better. The next day, a new bug report tells that [].forEach returns undefined on some pages—that is pages where your code is not executed. WTF!

Together with your colleague, you spend additional two hours resolving this issue. Finally, you are now sure that your code is executed on every page, and you have a clean code where the prototype is added only if there is no forEach method already:

```<code>if (![].forEach) {
    Array.prototype.forEach = function (...) {
        ...
    };
}
</code>```

Meanwhile, the small performance bug you had in your code is discovered, but it appears that it is more a feature, and several of your colleagues are relying on this bug: in several locations, they absolutely need the enumeration to be slow in order to have enough time to show a few images. Since rewriting their code seems to be a nightmare, you decide to keep the bug.

A year later, one morning, you discover dozens of bug reports from dozens of customers. Something is going on. Somebody on your team discovers that all bug reports are from users of Chrome, and further analysis finds that the JavaScript engine of the newly released version of Chrome has forEach, with the difference that it doesn't have your bug/feature your colleagues were relying on. Now, your team will spend two days adapting the code to the new, bug-less implementation of forEach.

Title: What's wrong about extending a class with prototype methods?

Body:
I was at a bar last night with a few of my colleagues. They said that it's a bad idea to extend the functionality of basic JavaScript Objects with a prototype method.

For example, let's say you created a method for finding the factorial

```<code>Number.prototype.factorial = function(n) {
  return n == 0 ? 1 : factorial(n - 1)
</code>```

}

They said there was some danger to creating prototypes. Why would this be a bad practice?

Body:
The problem is the global scope. In other words, every change you make affects the whole code base, and yours may in turn be affected in any location of the code base.

Imagine that you want to loop through all elements of an array; imagine that browsers don't support it yet. For that, you create a method forEach which is called this way:

[5, 7, 1, 1, 3].forEach(function (element) {
    // Do something here.
});

You implemented this method, thought about some edge cases (what about an empty array, for example?) and everything is fine, except a slight performance bug you missed: in some cases, the enumeration is very slow.

Now, somewhere else, your colleague had this great idea of having a forEach method, but doesn't know you have already implemented one; actually, he even tried to call forEach on an array to ensure the method doesn't exist yet, but since your code is not executed on every page, [].forEach returns undefined.

So he creates his own implementation, but forgets to test it for an empty array, and, in fact, when the array is empty, his code fails.

Back to your code, one day you find a bug report telling that there is a error around forEach: when the array is empty, it fails. You don't know that your colleague had his own implementation of forEach which overwrites yours on some pages. Therefore, you think that it's your code which is concerned, so you spend hours wondering why is it failing, while your unit tests pass.

You end up finding the culprit, that is the duplicated forEach, and you decide to remove the code of your colleague—yours is better. The next day, a new bug report tells that [].forEach returns undefined on some pages—that is pages where your code is not executed. WTF!

Together with your colleague, you spend additional two hours resolving this issue. Finally, you are now sure that your code is executed on every page, and you have a clean code where the prototype is added only if there is no forEach method already:

if (![].forEach) {
    Array.prototype.forEach = function (...) {
        ...
    };
}

Meanwhile, the small performance bug you had in your code is discovered, but it appears that it is more a feature, and several of your colleagues are relying on this bug: in several locations, they absolutely need the enumeration to be slow in order to have enough time to show a few images. Since rewriting their code seems to be a nightmare, you decide to keep the bug.

A year later, one morning, you discover dozens of bug reports from dozens of customers. Something is going on. Somebody on your team discovers that all bug reports are from users of Chrome, and further analysis finds that the JavaScript engine of the newly released version of Chrome has forEach, with the difference that it doesn't have your bug/feature your colleagues were relying on. Now, your team will spend two days adapting the code to the new, bug-less implementation of forEach.


问:
Clear JQuery Listeners Before Ajax Load of Similar Data
I have a tree structure on the left side of my page from which the user can drill down and select items. Each branch has similar items. When clicking a leaf node, I make a JQuery .load(...) call that loads the leaf's data into a div on the right side of the page.

The user can view and/or make changes to the displayed data. If the user selects a sibling leaf, I use .empty() to clear the right side div, a new .load() call is made, and the new data is loaded.

My problem is that the .on('click'.... code from the previous leaf is still active. The sibling's .on('click'.... code is ignored. If I click on the original leaf again (it is reloaded via .load) the .on('click'.... calls work.

Is there a way to clear the previous JQuery 'click' listeners or am I going to have to come up with a way to set a unique id for each leaf's data?

Edit:

Example code:

```<code><div id=right_side>
    <input type="text" id="firstname">Susan</input>
    <label for="nickname">Nickname? <input type="checkbox" id="nickname"></label>
</div>
<script>window.jQuery('#nickname').on('change',function(x){console.log("changed");})</script>
</code>```

The above code is loaded into the right side div whenever a leaf node in the tree is clicked. The checkbox 'nickname' ceases to work on subsequent loads for other leaf nodes. There is a checkbox with an id of 'nickname' in all of the leafs. I thought if I emptied the right side div, the associated listeners would be rendered mute (so to speak) but the initial listeners remain active even after the .empty() call.

答:
Do not bind events to elements that may appear, disappear, or change. Bind them on the parent DIV:</p>

```<code><div id="right_side">
    <input type="text" id="firstname">Susan</input>
    <label for="nickname">Nickname? <input type="checkbox" id="nickname"> </label>
</div>
<script>
    // This script must be executed only once (i.e. must not be in the loaded code).
    // Actually it would be better if it were executed from the jQuery
    // onload bootstrap call.
    // It listens on any change event on any INPUT tag inside #right_side
    // whether it has been already loaded or not.

    $('#right_side').on('change', 'input', function(x) {

        // We do not know WHICH control got changed.
        var id = $(this).attr("id");

        // We also would need some data from the left side, probably.
        // e.g. on the left side we have an A tag with data-right="foo"
        // and an onclick() that clears the .clicked class from all
        // tree's As, then adds the .clicked class to that A only.
        // This way $('#tree a.clicked').attr("data-right") will tell us
        // which A determined the loading of the right-hand panel.

        console.log("input with id " + id + " has changed");

    });
</script
</code>```

Body:
Do not bind events to elements that may appear, disappear, or change. Bind them on the parent DIV:

<div id="right_side">
    <input type="text" id="firstname">Susan</input>
    <label for="nickname">Nickname? <input type="checkbox" id="nickname"> </label>
</div>
<script>
    // This script must be executed only once (i.e. must not be in the loaded code).
    // Actually it would be better if it were executed from the jQuery
    // onload bootstrap call.
    // It listens on any change event on any INPUT tag inside #right_side
    // whether it has been already loaded or not.

    $('#right_side').on('change', 'input', function(x) {

        // We do not know WHICH control got changed.
        var id = $(this).attr("id");

        // We also would need some data from the left side, probably.
        // e.g. on the left side we have an A tag with data-right="foo"
        // and an onclick() that clears the .clicked class from all
        // tree's As, then adds the .clicked class to that A only.
        // This way $('#tree a.clicked').attr("data-right") will tell us
        // which A determined the loading of the right-hand panel.

        console.log("input with id " + id + " has changed");

    });
</script


问:
How do you keep the size of your application down (memory usage and physical storage size)?
I have a personal project that I'm working on although it's quite audio and graphic-intense and I was wondering if you guys had any suggestions or solutions as to how one could keep the size and memory-usage of their application to a minimum? My application is an iPhone application and, as Apple always make clear, the application is only allowed to use a certain amount of memory (in terms of performance and actual size).</p>

答: only load in memory what you are actively using, when done, release the resource, to free memory.</p>

ContentLicense: CC BY-SA 2.5


问:
How can I check if answer the user typed in is unique in the form submission?
So, I have a form that has security questions and textfields for the user to type in their answer. I want to prevent the user from typing in the same answer to every security question selected. So I am wondering, if there is a .NET attribute I can use to do validation on client side or server side approach that would prevent duplicate answer submission. Every answer that the user types in has to be unique.

So, How can I check if answer the user typed in is unique in the form submission?

I am using ASP.NET MVC 4

答:
Your best bet is probably having a custom validation component built for this purpose. It is reusable once implemented and follows the pattern of validators used for MVC4.

Adding Custom Validator for MVC4

To check for the uniqueness:

In C#:

Get all the input values in the text boxes into a collection.

Check if the length of unique values is the same as length of the collection: bool cintainsDuplicates = items.Distinct().Count() != items.Length;

In Javascript in case you choose to build custom validator:

Same, get all the values in a collection, probably by class that
will be assigned to all boxes of that type.

Use one of the suggested solutions here to check for duplicates: Google Search Results


问:
Language/Programming term for paired delimiters
Can someone help me find the language and/or programming term for delimiters (?) that must be paired?

Quotes, parenthesis, angle-brackets, square-brackets, etc. are often used to symbolize these constructs.

Is there a terminology distinction when the begin/end symbols are identical (such as some quotes) and when they are distinct (open/close brackets)?

Is there a term to describe the contents of such pairs?

I am writing an script that needs to be aware of delimiter pairs (?).  I would prefer to use existing (but as of this writing unknown to me) terminology for this concept to make my code content clear to others without coining new terminology.

答:
Wikipedia, here, https://en.wikipedia.org/wiki/Delimiter, says

Delimiters can be broken down into:

```<code>Field and record delimiters; and
Bracket delimiters.

Bracket delimiters (also block delimiters, region delimiters or balanced delimiters)
mark both the start and end of a region of text.
</code>```

I don't know of any formal term used in grammar programs (i.e. parser generator software), as you usually just put both the tokens of a bracket delimiter together somewhere on the same grammar rule definition, thus they both have to be present for the rule to apply, no other special pairwise matching is called out.

Body:
Wikipedia, here, https://en.wikipedia.org/wiki/Delimiter, says

Delimiters can be broken down into:

Field and record delimiters; and
Bracket delimiters.

Bracket delimiters (also block delimiters, region delimiters or balanced delimiters)
mark both the start and end of a region of text.

I don't know of any formal term used in grammar programs (i.e. parser generator software), as you usually just put both the tokens of a bracket delimiter together somewhere on the same grammar rule definition, thus they both have to be present for the rule to apply, no other special pairwise matching is called out.


问:
Efficiently find whether Binary Search Tree is Height Balanced or not?
A binary tree is height balanced if and only if the two subtrees of root are height balanced and the difference between the two subtrees height is at most 1.

I implemented a code in java to find whether a binary search tree is height balanced or not. I did it this way:

Recursively call the function isBalanced(Node) starting with root and the base condition being if node is null return true. But to calculate height of a subtree rooted at Node x, I have to call a separate function getHeight(Node) on that node and use this function to get and compare the height of two subtrees of a node and return a boolean value accordingly.

But this separate function call is making my code inefficient,because in case of skew tree when every node has one child this function will cause my program's time complexity to be O(N^2), N being number of vertices.

What I want to know is is there a way to remove this separate function call and still get the work done, so that I can have a linear time algorithm.

Here is my java code.

```<code>class BST
{
 public Node insert(Node x,int key)
 {
     if(x==null)
      return new Node(key,null,null);
     else if(key>x.key)
     {
         x.right=insert(x.right,key);
         return x;
     }
     else if(key<x.key)
     {
         x.left=insert(x.left,key);
         return x;
     }
     else {x.key=key;return x;}
 }
 public boolean isBalanced(Node root)
 {
     if(root==null)
      return true;
     else
     {
         if(isBalanced(root.left)&&isBalanced(root.right))
         {
             if(Math.abs(getHeight(root.left)-getHeight(root.right))<=1)
              return true;
             else return false;
         }
         else return false;
     }
 }
 public int getHeight(Node x)
 {
     return BFS(x,0);
 }
 public int BFS(Node x,int h)
 {
     if(x==null)
      return h;
     return Math.max(BFS(x.right,h+1),BFS(x.left,h+1));
 }
 public static void main(String []args)
 {
     BST tree1=new BST();
     Node root=null;
     root=tree1.insert(root,14);
     root=tree1.insert(root,16);
     root=tree1.insert(root,5);
     root=tree1.insert(root,3);
     root=tree1.insert(root,12);
     root=tree1.insert(root,10);
     root=tree1.insert(root,13);
     root=tree1.insert(root,20);
     root=tree1.insert(root,18);
     root=tree1.insert(root,23);
     root=tree1.insert(root,15);
     System.out.println(tree1.isBalanced(root));
 }
}
class Node
{
 Node left,right;
 int key;
 Node(int key,Node left,Node right)
 {
  this.key=key;
  this.left=left;
  this.right=right;
 }
}
</code>```

I am reposting this question here because I got a no response on Stack Overflow.

答:
If balanced means that the height is at most log_2(number_of_nodes) + 1,
I suggest an algorithm could look like this:

```<code># define a tree
tree := null | (left : tree, right : tree)

# check if a tree is balanced
is_balanced(tree) {
    maximum_height, number_of_elements = walk(tree)
    return maximum_height <= 1 + log_with_base_2(number_of_elements)
}

# walk the tree
walk(tree) {
    if tree is null return 0, 0
    left_height,  left_number_of_elements  = walk(tree.left )
    right_height, right_number_of_elements = walk(tree.right)
    height = 1 + max(left_height, right_height)
    number_of_elements = left_number_of_elements + right_number_of_elements + 1
    return height, number_of_elements
}
</code>```

The algorithm walks the whole tree once. walk(tree) = O(number_of_nodes(tree)) = O(n).

When testing keep this case in mind:

```<code>  x
  |\
  x x
 /| |\
  x x x
     \
      x
</code>```

The heights of the sub-trees are off by one but the whole tree is not balanced.

Body:
If balanced means that the height is at most log_2(number_of_nodes) + 1,
I suggest an algorithm could look like this:

# define a tree
tree := null | (left : tree, right : tree)

# check if a tree is balanced
is_balanced(tree) {
    maximum_height, number_of_elements = walk(tree)
    return maximum_height <= 1 + log_with_base_2(number_of_elements)
}

# walk the tree
walk(tree) {
    if tree is null return 0, 0
    left_height,  left_number_of_elements  = walk(tree.left )
    right_height, right_number_of_elements = walk(tree.right)
    height = 1 + max(left_height, right_height)
    number_of_elements = left_number_of_elements + right_number_of_elements + 1
    return height, number_of_elements
}

The algorithm walks the whole tree once. walk(tree) = O(number_of_nodes(tree)) = O(n).

When testing keep this case in mind:

  x
  |\
  x x
 /| |\
  x x x
     \
      x

The heights of the sub-trees are off by one but the whole tree is not balanced.


问:
How to deal with outlier programmers during sprint planning?
It is generally accepted that the best programmers produce at least an order of magnitude more than average ones. This seems like it would cause problems with the usual approaches to sprint planning that focus on whole-team metrics - mostly around estimation and velocity.

For estimation, the great programmer is likely to vote differently than the average one. Ideally, the team is using story points, so the programmers are more likely to agree about the "relative complexity" of a story, but even there, the great programmer is more likely to know a tool/trick that will allow them to simplify the problem. The team will generally vote as a whole and average/majority wins. That solves the inaccurate estimation - unless the great programmer picks up that story.

"But that doesn't matter!" I hear you say, "The great programmer just gets more story points done per sprint". Which brings us to problem #2. Velocities are very often measured for the whole team, not individuals to help even out the variances from sprint to sprint. The velocity is then used as a sort of rate to account for vacations, meeting times, etc. The problem comes that the great programmer disproportionally impacts the team velocity. If they're on vacation, far less work will be done than expected by velocity calculations. If an average programmer is on vacation, more work will be done than expected by velocity calculations.

So how to deal with this sort of inequity in performance during sprint planning? Some sort of weighting effect? Just let the errors occur and even out over time?

答:
Estimation (e.g. story points) is done based on the time and effort of a typical programmer. When you are calculating velocity, you go by a team of typical programmers. This is done for several reasons:

The highs and lows should average out. Maybe you have one rockstar, but odds are you have a knuckle-dragger too. Or two below average but not terrible programmers.

Even the best developers get stumped sometimes. I have seen awesome programmers take half the time on every task, then hit that one brick wall where a 4 hour task takes three days. Maybe it was due to an unforeseen difficulty, maybe the developer was going through personal problems, maybe he came to work hung over. Who knows. It happens.

Velocity can change based on previous sprints. If you know you can do more than you think, maybe you should plan for it (but not necessarily, see my next point).

None of this really matters, because if you get ahead you can always pull in stories from the backlog and get ahead of schedule.

Keep doing what you are doing and your other problem will not even matter. If your rockstar accounts for 20% of your team's hours and is on vacation, schedule 20% fewer stories points in that sprint. As long as you are not inflating your velocity, that will automatically compensate.

The key here is you are not just looking at each iteration in isolation, but scheduling the entire project one iteration at a time to help even out the irregularities that inevitably occur.


问:
Is having a Data Access Layer as singleton a good ideea
I'm working on a project(web application) where I have a DataManager(IDALContract dalImplementation) class that does some stuff with the data after retrieving it from the database or before saving it in the database.

My question: Is there any reason why the IDALContract object I'm passing in to the constructor should/should not be a singleton?

答:
FooManager is a smell. Managers invariably suffer problems because a "Manager" is a catchall that pushes it towards having multiple responsibilities. I strongly encourage you to not go down that road towards God objects.

Singletons are anti-patterns. Always. They force you to only ever have one object of a type, and no such thing exists. You're going to tell me that you will never, ever have more than one data access layer? You'll never need to access say, your database, a cache, or some NoSQL store at the same time? Are you really sure you want to limit your design that strongly?


答:
All sprints are not created equal and great programmers have influence beyond their own keyboard.

This is only a problem if you expect all sprints to have the same amount of work completed. If everyone is present the first 5 sprints, you're going to have to adjust eventually when anyone leaves and yes, especially the best developer.

Great programmers leverage their expertise in a given project way beyond the actual code they write. They influence other team members and the overall design of the project. Some of this gets hidden in a project. How do you measure all the things the team decided "not" to do because of the experience of the better programmer?

Over the course of time, you may discover this low-level of productivity when your best programmer is absent. Other than confirming your evaluation of this person, what else have you gained other than on a couple of sprints a year, you're going to get less done.

Title: How to deal with outlier programmers during sprint planning?

Body:
It is generally accepted that the best programmers produce at least an order of magnitude more than average ones. This seems like it would cause problems with the usual approaches to sprint planning that focus on whole-team metrics - mostly around estimation and velocity.

For estimation, the great programmer is likely to vote differently than the average one. Ideally, the team is using story points, so the programmers are more likely to agree about the "relative complexity" of a story, but even there, the great programmer is more likely to know a tool/trick that will allow them to simplify the problem. The team will generally vote as a whole and average/majority wins. That solves the inaccurate estimation - unless the great programmer picks up that story.

"But that doesn't matter!" I hear you say, "The great programmer just gets more story points done per sprint". Which brings us to problem #2. Velocities are very often measured for the whole team, not individuals to help even out the variances from sprint to sprint. The velocity is then used as a sort of rate to account for vacations, meeting times, etc. The problem comes that the great programmer disproportionally impacts the team velocity. If they're on vacation, far less work will be done than expected by velocity calculations. If an average programmer is on vacation, more work will be done than expected by velocity calculations.

So how to deal with this sort of inequity in performance during sprint planning? Some sort of weighting effect? Just let the errors occur and even out over time?


问:
Is anything in programming truly evil?
So, there are a bunch of questions appearing asking is X evil, is Y evil.

My view is that there are no language constructs, algorithms or whatever which are evil, just ones which are badly used.  Hell, if you look hard enough there are even valid uses of goto.

So does absolute evil, that is something which is utterly incompatible with best practice in all instances, exist in programming?  And if so what is it?  Or is it just bad programmers not knowing when something is appropriate?

Edit: To be clear, I'm not talking about things programmers do (such as not checking return codes or not using version control - they're choices made by bad programmers), I mean tools, languages, statements, whatever which are just bad...

答:
Is anything in programming truly evil?

Absolutely.  Failure to use your brain and think about what you're doing and why you're doing it is the root of all programming evil.

Title: Is anything in programming truly evil?


问:
maintain rate of animation with requestAnimationFrame
I've noticed that HTML game developers are recommending the use of requestAnimationFrame as opposed to a timer for the animation loop. I understand that this can be optimized by the browser, but how con you insure that the speed of your animation is consistent on all devices? If a certain device has twice the frame rate then a game will appear to play at twice the speed and look odd.

Are developers designing their code to dynamically adjust to the current framerate? This seems much more complicated than simply setting a timer for 60FPS, especially if the framerate changes during play.

答: Game calculations involve a lot of real work; like any real work, it'd be ridiculous to try to mandate to the computer "Enforce that this function runs inside of 300ms". In fact, 2040's computers might run that work 10x as fast. requestAnimationFrame means "run this as often as possible". You'll find that lots of mathematical, smooth-application code in a well-developed engine tends not to run much of anything in fixed steps, but instead multiplies every number by scalar, like time (or gravity, or even a "current game speed" constant that allows your character to enter Slow Motion; or Pause easily)


问:
How to pass object generated by certain test class to another test class using webdriver and testng

I am contemplating on creating a public api for my team to use that will encapsulate the workings of webdriver and testng as it's main tools.
Primary to the concern is re usability of code when possible to cater the many test scenarios.

My idea is to allow the qa team to define a set of parameters per scenario to test through excel worksheet, being 1 worksheet per scenario.
Each scenario can involve multiple test classes created by the developer, these test classes may be testing a specific page or a set of pages together.

With webdriver in mind, I can solve for a way to mix pages on a single test class that initializes the necessary webdriver object used by the page objects.

My problem arises when trying to mix test classes together to form an orchestrated mix of test cases in a big scenario case, in a way like composing many fine grained level use cases in a single coarse level use case.

How should i pass webdriver objects and pages objects between the test classes using testng and webdriver to achieve this goal?
Is this even a sound idea in the first place?

Btw the factory A and factory B are what i thought of as scenario A and scenario B. I got blocked by the mechanisms to pass test related object between test classes for the orchestration to work.

答:
It looks like you're facing two problems. Let me address them separately.

Managing test scenarios

It sounds like some of your problems could be solved by adopting a BDD framework like Cucumber. It's possible to use with a variety of languages including Ruby, Python, PHP and a variety of .NET and JVM languages.

What it allows you to do is describe test scenarios in feature files composed of reusable steps that are basically granular pieces of code you can use to interact with the tested application. It's often used in conjunction with WebDriver in order to automate web-browsing scenarios.

The syntax of a feature file is pretty much plain text following a set of conventions. Each step can be matched (using a regular expression) to an implementation that you provide.

Here's a simple example

```<code>Feature: Subscribe to the service
   In order to receive updates on latest offers
   As a site visitor
   I want to be able to subscribe to XYZ's service

Scenario: Subscribe button displayed on the home page
   Given I am viewing the home page
   And I scroll to the bottom
   When I fill in my email in the subscription form
   And I click the Subscribe button
   Then I am redirected to a confirmation page
</code>```

The first part, starting with Feature is a piece of background information that is not backed by any code. It's just used to create a readable test report.

A feature file can contain an arbitrary number of scenarios (in this case, just one) that are backed by actual code. These units of code are called steps. The code to be executed is usually chosen by a regex pattern match against what appears in your feature file.

Here's a simple example in Java:

```<code>@Given("^I am viewing the home page$")
public void iAmViewingTheHomePage() {
    // Write code here that turns the phrase above into concrete actions
    // obtain the web driver, visit a page
}
</code>```

So far so good but this doesn't solve your problem yet. One step towards writing granular and reusable steps is the use of parameters.

Let's say you have a step that describes an interaction with a specific page.

```<code>Given I open the Subscriptions section of the site
</code>```

Instead of matching the whole step like this:

```<code>@Given("^I open the Subscriptions section of the site$")
public void visitSubscriptions(){...}
</code>```

You can pass parts of your step description as parameters

```<code>@Given("^I open the (.*) section of the site$")
public void visitSection(final String sectionName) {
   //use selenium to navigate to an arbitrary section using
   //WebDriver
}
</code>```

Cucumber also comes with a cool set of features that allows you to pass data around the steps.

You can embed any number of placeholders in your regular expression and they're going to be bound to method parameters with corresponding indices. This is how it works in Selenium-JVM but other flavours support basically the same thing. Different syntax is used across languages but the general idea is the same.

This alone will allow you to manage your test steps much better but there's more.

You mentioned your testers using CSV files. Cucumber allows you to embed tables with test data into the feature files themselves. You can easily ask your testers to write up the data in this format or just write a script that converts CSV files into it. Here's what a Data Table looks like:

```<code>Scenario: Book a flight for multiple users
  Given the following contact information
    | name    | email   | nationalId   |
    | Alice   | a@a.com | AAA222       |
    | Bob     | b@b.com | BBB333       |
    | Charlie | c@c.com | CCC444       |
  When I fill in the passenger details form
  Then the booking should be recorded
</code>```

You can then read the table in your step definition. There's a number of ways to do this. You can use the DataTable class, use a POJO that has a constructor matching the data, etc. This will be a bit different between languages but again, the principle remains the same.

You can find a broader range of examples in this blog post

Reuse of internal objects

When it comes to object reuse (WebDriver instances, etc.), Cucumber itself does not offer a solution. It is possible to call steps from within other steps but this is advised against by the community and not supported by some of the Cucumber versions (I know it can be done in Cucumber Ruby). See this SO answer for a little follow-up on the subject. That said, even if you decide to pass data around steps like this, it's not the way to manage internal objects in a sane way using this technique. WebDriver objects are implementation details that must not pollute your scenarios anyway.

What you can come up with will be specific to the language you're using. Judging by the fact that you mention TestNG, this is probably either Java or C#

The company I work for has developed a nice framework based on dependency injection (specifically, Google Guice was used) that allows us to provide this kind of objects in an easy, consistent way, as well as effortlessly compose page objects by simply @Inject-ing them. It's a proprietary piece of software so I'm afraid I cannot share more information but the whole idea should not be too complex to implement in a basic form. Whatever way you go, the management of WebDriver objects and other implementation details should never leak into the test cases themselves. You'll need a shared utility to be used by all page objects in a consistent manner.

There are some blog posts on the subject of using WebDriver with Spring but any CDI framework will greatly simplify your functional test codebase.

Please also mind that automated tests need not use the same programming language as the code itself. It's a boon if your developers can use a single language to write production code and tests but if you're working with polyglots, they might just find a different language more suitable for this purpose. From my experience, dynamically typed scripting languages like Ruby or Groovy tend to fit this role quite well.

Body:
It looks like you're facing two problems. Let me address them separately.

Managing test scenarios

It sounds like some of your problems could be solved by adopting a BDD framework like Cucumber. It's possible to use with a variety of languages including Ruby, Python, PHP and a variety of .NET and JVM languages.

What it allows you to do is describe test scenarios in feature files composed of reusable steps that are basically granular pieces of code you can use to interact with the tested application. It's often used in conjunction with WebDriver in order to automate web-browsing scenarios.

The syntax of a feature file is pretty much plain text following a set of conventions. Each step can be matched (using a regular expression) to an implementation that you provide.

Here's a simple example

Feature: Subscribe to the service
   In order to receive updates on latest offers
   As a site visitor
   I want to be able to subscribe to XYZ's service

Scenario: Subscribe button displayed on the home page
   Given I am viewing the home page
   And I scroll to the bottom
   When I fill in my email in the subscription form
   And I click the Subscribe button
   Then I am redirected to a confirmation page

The first part, starting with Feature is a piece of background information that is not backed by any code. It's just used to create a readable test report.

A feature file can contain an arbitrary number of scenarios (in this case, just one) that are backed by actual code. These units of code are called steps. The code to be executed is usually chosen by a regex pattern match against what appears in your feature file.

Here's a simple example in Java:

@Given("^I am viewing the home page$")
public void iAmViewingTheHomePage() {
    // Write code here that turns the phrase above into concrete actions
    // obtain the web driver, visit a page
}

So far so good but this doesn't solve your problem yet. One step towards writing granular and reusable steps is the use of parameters.

Let's say you have a step that describes an interaction with a specific page.

Given I open the Subscriptions section of the site

Instead of matching the whole step like this:

@Given("^I open the Subscriptions section of the site$")
public void visitSubscriptions(){...}

You can pass parts of your step description as parameters

@Given("^I open the (.*) section of the site$")
public void visitSection(final String sectionName) {
   //use selenium to navigate to an arbitrary section using
   //WebDriver
}

Cucumber also comes with a cool set of features that allows you to pass data around the steps.

You can embed any number of placeholders in your regular expression and they're going to be bound to method parameters with corresponding indices. This is how it works in Selenium-JVM but other flavours support basically the same thing. Different syntax is used across languages but the general idea is the same.

This alone will allow you to manage your test steps much better but there's more.

You mentioned your testers using CSV files. Cucumber allows you to embed tables with test data into the feature files themselves. You can easily ask your testers to write up the data in this format or just write a script that converts CSV files into it. Here's what a Data Table looks like:

Scenario: Book a flight for multiple users
  Given the following contact information
    | name    | email   | nationalId   |
    | Alice   | a@a.com | AAA222       |
    | Bob     | b@b.com | BBB333       |
    | Charlie | c@c.com | CCC444       |
  When I fill in the passenger details form
  Then the booking should be recorded

You can then read the table in your step definition. There's a number of ways to do this. You can use the DataTable class, use a POJO that has a constructor matching the data, etc. This will be a bit different between languages but again, the principle remains the same.

You can find a broader range of examples in this blog post

Reuse of internal objects

When it comes to object reuse (WebDriver instances, etc.), Cucumber itself does not offer a solution. It is possible to call steps from within other steps but this is advised against by the community and not supported by some of the Cucumber versions (I know it can be done in Cucumber Ruby). See this SO answer for a little follow-up on the subject. That said, even if you decide to pass data around steps like this, it's not the way to manage internal objects in a sane way using this technique. WebDriver objects are implementation details that must not pollute your scenarios anyway.

What you can come up with will be specific to the language you're using. Judging by the fact that you mention TestNG, this is probably either Java or C#

The company I work for has developed a nice framework based on dependency injection (specifically, Google Guice was used) that allows us to provide this kind of objects in an easy, consistent way, as well as effortlessly compose page objects by simply @Inject-ing them. It's a proprietary piece of software so I'm afraid I cannot share more information but the whole idea should not be too complex to implement in a basic form. Whatever way you go, the management of WebDriver objects and other implementation details should never leak into the test cases themselves. You'll need a shared utility to be used by all page objects in a consistent manner.

There are some blog posts on the subject of using WebDriver with Spring but any CDI framework will greatly simplify your functional test codebase.

Please also mind that automated tests need not use the same programming language as the code itself. It's a boon if your developers can use a single language to write production code and tests but if you're working with polyglots, they might just find a different language more suitable for this purpose. From my experience, dynamically typed scripting languages like Ruby or Groovy tend to fit this role quite well.


答:
"Matching delimiters" refers to the pair, as in "the text between matching delimiters is automatically highlighted." Your sample

I am writing an script that needs to be aware of delimiter pairs

becomes

I am writing a script that needs to be aware of matching delimiters.

Also, "the matching delimiter" works when you're talking about one of them and want to refer to the other one. I don't know of any word that captures the distinction between the two delimiters being the same symbol or not.

Title: Language/Programming term for paired delimiters

Body:
Can someone help me find the language and/or programming term for delimiters (?) that must be paired?

Quotes, parenthesis, angle-brackets, square-brackets, etc. are often used to symbolize these constructs.

Is there a terminology distinction when the begin/end symbols are identical (such as some quotes) and when they are distinct (open/close brackets)?

Is there a term to describe the contents of such pairs?

I am writing an script that needs to be aware of delimiter pairs (?).  I would prefer to use existing (but as of this writing unknown to me) terminology for this concept to make my code content clear to others without coining new terminology.


问:
Setting up Version Control on my Development Server
I'm looking into the possibilities of integrating Version Control so that me and my team can work on code at the same time without having to worry about overwriting each others work. Previously this was easy to maintain as there were only three of us. However as our team has now grown it's become a key consideration moving forward.

I had previously worked with SVN using Springloops. The company paid a monthly fee to store the versions on their server and Springloops provided a web interface to work with the repositories.

However, I'd like to move away from using a third party and set up SVN on my own server for the team to work with. I'm wondering if this is possible and if so is it easy enough to achieve?

Security is a big issue for us and that is why we would prefer to host our code ourselves.

I'm wondering if anyone has some advice on this and possible other things to consider?

答:
I'm wondering if this is possible

Yes. Apache+SVN is a question of hours with SVN Book, svnserve'd server (but I'll recommend Apache-way) - minutes

and if so is it easy enough to achieve?

Yes


答:
As Harrison Paine and Brandin suggest, I would re-use the same object and factorize the initialization of the properties in a Reset method:</p>

```<code>public class MyClass
{
    public MyClass() { this.Reset() }

    public void Reset() {
        this.Prop1 = whatever
        this.Prop2 = you name it
        this.Prop3 = oh yeah
    }

    public object Prop1 { get; set; }

    public object Prop2 { get; set; }

    public object Prop3 { get; set; }
}
</code>```

Body:
As Harrison Paine and Brandin suggest, I would re-use the same object and factorize the initialization of the properties in a Reset method:

public class MyClass
{
    public MyClass() { this.Reset() }

    public void Reset() {
        this.Prop1 = whatever
        this.Prop2 = you name it
        this.Prop3 = oh yeah
    }

    public object Prop1 { get; set; }

    public object Prop2 { get; set; }

    public object Prop3 { get; set; }
}


问:
guideline on void methods that do not throw exceptions
In our codebase I saw a method that is similar to following:

```<code>public void doSomething() {
    try {
        ...
    } catch (Exception e) {
        ...
        //log something
        ...
    }
}
</code>```

The caller has no way to know if the method did what it is supposed to. Are there any general Java guidelines on not writing void methods that do not throw exceptions?

答:
First of all this method is not unit testable.

There is nothing in the code you quoted which prevents it from being covered by unit tests.

The presence of try/catch is irrelevant:

You can test the situation where there is no error and check whether the side effects of this method correspond to the expectations.

You can also test the situation where an exception is produced, and ensure that the expected message is indeed logged (hopefully, the logging framework can be replaced with a mock.)

This means that you can get a 100% branch coverage despite the global catch of the exception. Talking about the global catch, this is not something you really want in your code base (unless there is a throw inside a catch), but this has nothing to do with unit tests.

This would apply as well if the method was catching only a specific exception, say FileNotFoundException, but there could be other exceptions thrown, such as StackOverflowException. You can then have three tests:

The ordinary situation with expected side effects,

The situation where FileNotFoundException is thrown and the expected log message is added,

The situation where StackOverflowException is thrown; any decent unit testing framework allows you to test that the exception is effectively thrown in a tested case (and the test will fail if the method doesn't throw the expected exception).

Are there any general Java guidelines on not writing void methods that do not throw exceptions?

By “do not throw exceptions”, I suppose you rather mean “catch all the exceptions”.

Catching exceptions has nothing wrong as soon as the method knows how to deal with the exceptional cases. For instance, a method which accesses the configuration file and encounters FileNotFoundException may fallback to default configuration instead, without reporting any exception to the caller. This is fine.

Catching exceptions globally (that is catch (Exception)) is slightly more problematic. Cases where methods are able to deal with any exceptional situation are very rare. There are still two exceptions:

A method can catch any exception, and then throw the same exception (preferably without breaking the stack). This, for instance, enables logging: a method logs an exception, and then lets the caller deal with it.

A method which is on top of the stack can catch any exception, because the choice is rather limited: either you catch the exception, or you let the program crash. The developers may prefer in this case to catch everything, even exceptions they can't deal with, and, for instance, present the user with a user-friendly dialog box which makes it possible to report the exception to developers' team.


问:
Should static parameters in an API be part of each method?
I am currently creating a library that is a wrapper for an online API. The obvious end goal is to make it as easy for others to use as possible. As such I am trying to determine the best approach when it comes to common parameters for the API.

In my current situation there are 3 (consumer key, consumer secret, and and authorization token). They are essentially needed in every API call. My question is should I make these 3 parameters required for each method or is there a better way.

I see my current options as being:

Place the parameters in each method call

```<code>public ApiObject callMethod(String consumerKey, String consumerSecret, String token, ...)
</code>```

This one seems reasonable, but seems awfully repetitive to me.

Create a singleton class that the user must initialize before calling any api methods. This seems wrong, and would essentially limit them to accessing one account at a time via the API (which may be reasonable, I dunno).

Make them place them in a properties file in their project. That way I can load the properties that way and store them. This seems similar to the singleton to me, but they would not have to explicitly call something to initialize these values.

Is there another option I am not seeing, or a more common practice in this situation that I should be following?

答:
I can see two ways:

coalesce all your parameters into a single context object, at the API client side. Each time you call your API, pass the context object as parameter.

use a similar context object, but store it at the API side. Give the client a token that identifies the context object and ask the API client to pass it each time it calls the API. This is useful if you cannot easily send objects to the API (e.g. HTTP API)


答:
Generally speaking, an Exception is suited for this and the best practice you should follow is: "If a method can't do it's job, it should throw an exception."

Understandably, you may want execution flow to continue without exceptions. The .NET space handles this fairly well and provides a convention for methods that don't throw exceptions. Methods that start with "Try" always return a boolean and do not throw exceptions.

The benefit of this approach is that you can write tests on the DoWork method to test that exceptions are thrown when expected, and conversely no exceptions are thrown when calling the Try equivalent.

```<code>public void DoWork() {
   // try to do the work, and if it fails, throw
}

public bool TryDoWork() {
   try {
      DoWork();
      return true;
   }
   catch {
      return false;
   }
}
</code>```

Alternatively, if that's not your cup of tea, another approach is to mock out your Logger and write tests that capture that errors are logged.

Two supporting examples:

Clean Code - by Robert C Martin

Working Effectively with Legacy Code - by Michael Feathers

Title: guideline on void methods that do not throw exceptions

Body:
In our codebase I saw a method that is similar to following:

```<code>public void doSomething() {
    try {
        ...
    } catch (Exception e) {
        ...
        //log something
        ...
    }
}
</code>```

The caller has no way to know if the method did what it is supposed to. Are there any general Java guidelines on not writing void methods that do not throw exceptions?

Body:
Generally speaking, an Exception is suited for this and the best practice you should follow is: "If a method can't do it's job, it should throw an exception."

Understandably, you may want execution flow to continue without exceptions. The .NET space handles this fairly well and provides a convention for methods that don't throw exceptions. Methods that start with "Try" always return a boolean and do not throw exceptions.

The benefit of this approach is that you can write tests on the DoWork method to test that exceptions are thrown when expected, and conversely no exceptions are thrown when calling the Try equivalent.

public void DoWork() {
   // try to do the work, and if it fails, throw
}

public bool TryDoWork() {
   try {
      DoWork();
      return true;
   }
   catch {
      return false;
   }
}

Alternatively, if that's not your cup of tea, another approach is to mock out your Logger and write tests that capture that errors are logged.

Two supporting examples:

Clean Code - by Robert C Martin

Working Effectively with Legacy Code - by Michael Feathers


问:
Alternatives to using dictionary in parameters in C#?
I have a method that takes in a dictionary and enum value and produces a string output. Enum value defines what template string to insert the dictionary key value pairs into.

```<code>public string InsertVariables(MessageType type, Dictionary<string, string> variables) { }
</code>```

It works fine, but every time I use it, I find that it's hard to know what I should add to variables to make sure all tokens in the template are replaced and I have to glance at the templates every time.

What I was thinking would work as solution in this case is enforcing proper values added to variables during compilation time like so:

```<code>public abstract class MessageVariables { }

public class NewUserMessageVariables : MessageVariables {
    // different values go here parameters go here instantiated in the constructor
}

public string InsertVariables(MessageType type, MessageVariables variables) {
    // converts variables object into dictionary for future insertion into the template.
}
</code>```

This seems to enforce having all parameters required in the messages.

I have about 16 messages with possibility to having a few more later.

QUESTION: Is this an overkill and I should stick to using dictionary?

答:
It depends.

If there is some code above this that effectively enforces that the right variables are sent in (some form for example), then this is unlikely to break frequently, so making each message its own type seems like overkill.

If there is not some code above this and you're relying on your programmer's goodwill to make sure that stuff is well formed... That is probably a bad bet, and making a firmer interface will serve you well.

I would not have some MessageVariables base type unless it provides some benefit. And I would personally err heavily towards real classes/functions for each message. It makes things more discoverable, and at only 16 or so messages is not prohibitively maintainable.


问:
If I have two developer license accounts with Apple, can I easily switch between the two for app development and publishing?
I've been interested in iPhone development since the release of the iPhone, however, I am on a limited personal budget.  I've never been willing/able to fork out the money necessary for an iPhone and a Macbook.  I know, some may argue that it's not that expensive, but for a hobby it hasn't been worth the price.

By some twist of amazing fortune, the company that I work for is wanting me to develop an iPhone and iPod app.  This means I am getting pretty much all the hardware you would want to develop on-- an awesome Macbook, Thunderbolt display, an iPhone, an iPad, a few accessories.  In short, it's basically my "wish list" that I have dreamt of one day owning.

In my free time, I will be allowed to use the hardware to develop whatever software I desire but since my development laptop will primarily be used for my employing companies project I need assurance that any work I do under my own developer license will not affect my developer license associated with my work account.

Can I easily switch between two developer accounts when developing and publishing applications?  What if one account is a standard one and the other is an enterprise?

As of yet, I don't have any hardware or any developer licenses and I'm asking in complete ignorance.  Can I do this or will the accounts collide?

REQUESTING UPDATE/SECOND OPINION

Thanks to mouviciel for promptly answering this question with a straight-forward response.  However, I've been working with with XCode for quite a while and I've also had experience with downloading sample projects and modify them so that I can run them on my iOS device.

This lends me to believe that answering my initial question might involve tweaking PList files and other project settings, but should still be doable without having to create a separate account on my Macbook.

So I ask again, can I easily switch between two developer accounts when developing and publishing applications, strictly using one account on my Macbook?

If the answer is, yes, (which is what I assume is the case) how must I redefine my personal projects which may initially inherit user setting associated with my business account and credentials?

答: Yes, you absolutely can use multiple developer accounts with Xcode. You can set each one up in Xcode preferences, and Xcode will show each one when in places you would expect: signing apps, provisioning devices, etc.</p>