答:
The difference comes from the fact the some languages have different naming contexts for different stuff. I will speak in examples and not so precise definitions as to be more clear.

Example 1: JavaScript - single naming context

functions are callable which when called execute code, might have side effects and return value

objects are, well... anything but null and undefined, even functions, primitives etc.

all these have names, so when you use a name to connect an object or function to another object they all become properties of the new object and that's it.

So:

```<code>var object = {};
// they all share the same naming context of object
object.fn = function() {}; // adding a function property which becomes a method
object.number = 1; // adding a primitive type property
object.object = {}; // adding an object property
// object.fn = 2; // will overwrite the method
</code>```

Example 2: Java - double naming context

functions are callable, execute code, side effects, might return value

functions can't exist if they are not attached to an object by having some name thus becoming methods (method is a function which has this)

all functions share same naming context on an object, and can even have more than one  with the same name only if they have different parameters

anything other than function, which is an object or primitive, can also be connected to an object by a name and they share different naming context from methods

Thus:

```<code>class JavaObject {
    public void property(){}; // function attached to an object is called method
    public void property(int){}; // multiple functions with same name allowed
    public int property;  // the same name, but in a different context, still ok
    //public long property; // this one's name wiil clash with the int property
}
</code>```

Long story short:
Some languages can have methods and non-methods as properties with the same name, thus we try to point out which of them we talk about.

Title: Why categorization into "Property" and "Methods"

Body:
I am looking at the String class in Actionscript 3.0.

It has a property called String.length .
Internally it's a getter function (or method ?) that returns the length of string.

Why can't it be String.getLength() ?

Methods can take in 1, 2 or more values...so their significance can be understood. But what significance does "property" have? As it is, after all, a function only. So, why the categorization into properties? Is it just for adding an overhead botheration to remember that something has been categorized into a property?

In other words, as a programmer, how am I helped when I'am told that String.length is a property of the String class when I can't find any method for the same.

While writing a program, how would I know what is a property and what is a method?

I appreciate having someone shed some light on this.

V.

Body:
The difference comes from the fact the some languages have different naming contexts for different stuff. I will speak in examples and not so precise definitions as to be more clear.

Example 1: JavaScript - single naming context

functions are callable which when called execute code, might have side effects and return value

objects are, well... anything but null and undefined, even functions, primitives etc.

all these have names, so when you use a name to connect an object or function to another object they all become properties of the new object and that's it.

So:

var object = {};
// they all share the same naming context of object
object.fn = function() {}; // adding a function property which becomes a method
object.number = 1; // adding a primitive type property
object.object = {}; // adding an object property
// object.fn = 2; // will overwrite the method

Example 2: Java - double naming context

functions are callable, execute code, side effects, might return value

functions can't exist if they are not attached to an object by having some name thus becoming methods (method is a function which has this)

all functions share same naming context on an object, and can even have more than one  with the same name only if they have different parameters

anything other than function, which is an object or primitive, can also be connected to an object by a name and they share different naming context from methods

Thus:

class JavaObject {
    public void property(){}; // function attached to an object is called method
    public void property(int){}; // multiple functions with same name allowed
    public int property;  // the same name, but in a different context, still ok
    //public long property; // this one's name wiil clash with the int property
}

Long story short:
Some languages can have methods and non-methods as properties with the same name, thus we try to point out which of them we talk about.


问:
How to represent association in programs
Could someone help me in implementing association in cpp. I am trying to implement a dice game where I have two classes a diegame and a dice. </p>

答:
If you do mean one-to-one associations, they are a very broad kind of connection between types, objects, etc.

For more info have a look at given discussion - one to one association in C++.

ContentLicense: CC BY-SA 3.0


问:
Does Silverlight have a future?
Recently I have read some articles/blogs/comments about the development and history of WPF and Silverlight. In some forums many developers and users criticize the performance of WPF applications (for example Visual Studio 2010). Actually the market share of Silverlight in comparison to Flash is not very high. At PDC 2010 Bob Muglia said something like "our Silverlight strategy and focus going forward has shifted...." and Microsoft wants to push HTML5 in the future.

Additionally, Microsoft has announced HTML5 being a core part of the Windows 8 and Windows Phone 8 ("Mango") platforms.

Recently I have started learning Silverlight and now I must ask myself, if I should continue investing time in learning these (in my opinions) very nice and powerful technologies!? Does they have a future? Does (Windows) desktop (client) applications have a future? Does so called "Rich Internet Applications" have a future? Or will HTML5 become the "absolute truth" in software development?

What is your opinion and what do you think?

答:
Maybe "killing" is a bit of a strong word. I think - and it has been reported widely (Mary-Jo Foley, etc.) that Microsoft is shifting their focus from Silverlight to HTML 5. I think Silverlight will continue to be the the platform of choice for super-rich web experiences and maybe video-heavy stuff (for example, what they did with the NBC online coverage of the 2010 Winter Olympics). I also think that we'll see Silverlight increasingly in the enterprise "space" - instead of delivering "fat" clients in WPF or WinForms, I can definitely see Silverlight, esp. running out-of-browser, finding a home in enterprise software development.

From a strategic perspective, I read a post with a great take on why Microsoft is suddenly so interested in HTML 5. For a start, it gives them an "in" to the iOS market. Secondly, it shifts the game to an area where, relative to Apple, they have a huge advantage - the Cloud. Anybody who's used Apple's MobileMe service can attest to the fact that, while Apple does a lot of things well, currently the Cloud isn't one of them.

Title: Does Silverlight have a future?

ContentLicense: CC BY-SA 2.5


问:
Sporadic unittests or TDD?
I've read some basics about unit tests and TDD, but I find it hard to convince myself why TDD can have an advantage over only selected unittests.

I've read common arguments for TDD, but don't see the improvment compared to simple unittests. Maybe you can help to clarify:

TDD allows a loosely coupled, testable design -> I believe I can well imagine if a class is theoretically testable, without having to write tests; Loose coupling is a fundamental requirement that one can judge without refering to TDD?!

TDD gives confidence in refactoring -> Isn't it more efficient to add selected unittests as soon as you start refactoring? While you have to think what to cover by test, you still save writing a lot of tests.

TDD makes you define the interface first -> To me it seems some minor points are easier to decide while coding (which also agrees with agile?). It's even hard to predict a nested return data structure, but after coding I can often validate that I get what I expected. I made up the nested data while coding (a small unit) and see the behaviour. I'd save a lot of time writing the method first and using the validated result a posteriori to plug into a unittest.

from what I've read many (of course not all) sources state that TDD does require more development time even considering the benefit for debugging; merely the code quality improves -> Can it be that some programmers make different kinds of mistakes and for some TDD doesn't cover the type of mistakes they make anyway? So if my typical bugs are not approachable by predictable tests, it's not for me?

TDD aids changing teams, and larger interacting teams -> Is this a large issue? I can imagine it is, however as for the moment I program alone I cannot judge. How does TDD help teams in ways that... and here is the important point: other ways don't? It can force some discipline for less experienced team members, but apart from that any advantages?

答:
You may think your design is loosely coupled and well usable. You may even be right, if you're really, really good at designing. The trouble is, many people think they're great designers, and some of them, in fact, aren't. TDD forces you to prove that the design has the properties you think it has, much like testing in general forces you to prove (approximately, not formally) that the code is correct, rather than just assuming it is correct.

About refactoring: You could add unit tests if and when you refactor, and in fact that is precisely what is suggested for working with legacy code. However, once you are at the point where you have to refactor a big mess of code, you almost certainly have forgotten details, edge cases, semantic nuances of certain values etc. etc. that should have been properly documented, but weren't. Again, existing unit tests will already capture this detail knowledge, which is why writing them early is better than writing them late. A test written immediately before refactoring is much less likely to actually test what it should test.

Point three seems to be a mixture of other points and some things I don't really get, so: I don't know.

Point four: I don't believe it's possible to have a bias towards "typical bugs" that aren't detectable by tests. What would those be? Sure, there are issues that are much harder to test than other issues, such as problems that can only occur in extreme integration situations (e.g. going live with millions of users simultaneously), but would anyone really have a knack for writing correct code except in such situations? Seems unlikely to me.

Changes in staff are definitely a big issue - the bigger the organisation, the bigger an issue it becomes, but even if you program alone, the person who looks at the code a year from now and wonders "what idiot programmed that??" is very different from the one who actually wrote it - even if they are technically the same person. This happens to me all the time. A unit test gives you a chance to understand why and in what way the system doesn't quite work the way you thought it did.

Overall, then, the really important point (to me) is to write the tests while you still understand the system fully and with as close to 100% coverage as possible. Whether or not you actually write each test a minute before you write a routine or a minute after is actually slightly less important.

Title: Sporadic unittests or TDD?


问:
Inheritance using non-abstract base class
This post is based on the question https://stackoverflow.com/questions/49002/prefer-composition-over-inheritance/11758048#comment15634305_11758048.

Some people said - check whether there is “is-a” relationship. If it is there use inheritance. What I think is there should be a second check for using inheritance. Use inheritance only if the base class is abstract. If the base class need to be instantiated then use composition; not inheritance.

E.g 1. Accountant is an Employee. But I will not use inheritance because a Employee object can be instantiated. (When you talk to business people, they will tell you - Accountant is an Employee. But in OO world Accountant is not (should not be) an employee)

E.g 2. Book is a SellingItem. A SellingItem cannot be instantiated - it is abstract concept. Hence I will use inheritance. The SellingItem is an abstract base class (or interface in C#)

What I am looking for here is an example that will challenge my argument –that is a scenario in which inheritance is better than composition even though the base class is non-abstract (base class can be instantiated). Can you please provide such an example?

Note: It would be more helpful if you can provide a scenario based on Bank domain, HR domain, Retail domain or any other popular domain.

Note: In the design, please assume that we have full control of the code. That is we are not using any external API. Also we are starting from beginning.

I will mark as answered if there is an example that explains a scenario that proves my argument is wrong. It is not a mere discussion on whether to use Composition or Inheritance.

I support @anon answer in https://stackoverflow.com/questions/3351666/why-use-inheritance-at-all?lq=1

The main reason for using inheritance is not as a form of composition - it is so you can get polymorphic behaviour. If you don't need polymorphism, you probably should not be using inheritance.

@MatthieuM. says in Code Smell: Inheritance Abuse

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

interface (for polymorphism)

implementation (for code reuse)

REFERENCE

Employee- Accountant Example https://stackoverflow.com/questions/11759120/issue-in-using-composition-for-is-a-relationship

Selling Item Example  - https://codereview.stackexchange.com/questions/14077/is-it-proper-tpt-inheritance

Programming SOLID Principles

Code Smell: Inheritance Abuse

答:
I don't think there is any necessity of a challenging example. What you say is a nice design principle which is named dependency inversion. That is, higher components should never depend on lower components. Lower components should depend on higher components only.

Like every rule, this one might have exceptions, too. But there are no rules without exceptions!


问:
Return magic value, throw exception or return false on failure?
I sometimes end up having to write a method or property for a class library for which it is not exceptional to have no real answer, but a failure. Something cannot be determined, is not available, not found, not currently possible or there is no more data available.

I think there are three possible solutions for such a relatively non-exceptional situation to indicate failure in C# 4:

return a magic value that has no meaning otherwise (such as null and -1);

throw an exception (e.g. KeyNotFoundException);

return false and provide the actual return value in an out parameter, (such as Dictionary<,>.TryGetValue).

So the questions are: in which non-exceptional situation should I throw an exception? And if I should not throw: when is returning a magic value perferred above implementing a Try* method with an out parameter? (To me the out parameter seems dirty, and it is more work to use it properly.)

I'm looking for factual answers, such as answers involving design guidelines (I don't know any about Try* methods), usability (as I ask this for a class library), consistency with the BCL, and readability.

In the .NET Framework Base Class Library, all three methods are used:

return a magic value that has no meaning otherwise:

Collection<T>.IndexOf returns -1,

StreamReader.Read returns -1,

Math.Sqrt returns NaN,

Hashtable.Item returns null;

throw an exception:

Dictionary<,>.Item throws KeyNotFoundException,

Double.Parse throws FormatException; or

return false and provide the actual return value in an out parameter:

Dictionary<,>.TryGetValue,

Double.TryParse.

Note that as Hashtable was created in the time when there were no generics in C#, it uses object and can therefore return null as a magic value. But with generics, exceptions are used in Dictionary<,>, and initially it didn't have TryGetValue. Apparently insights change.

Obviously, the Item-TryGetValue and Parse-TryParse duality is there for a reason, so I assume that throwing exceptions for non-exceptional failures is in C# 4 not done. However, the Try* methods didn't always exist, even when Dictionary<,>.Item existed.

答:
As others have noted, the magic value (including a boolean return value) is not that great a solution, except as an "end-of-range" marker. Reason: The semantics are not explicit, even if you examine the methods of the object. You have to actually read the full documentation for the entire object right down to "oh yeah, if it returns -42 that means bla bla bla".

This solution may be used for historical reasons or for performance reasons, but should otherwise be avoided.

This leaves two general cases: Probing or exceptions.

Here the rule of thumb is that the program should not react to exceptions except as to handle when the program /unintentionally/ violates some condition. Probing should be used to ensure that this doesn't happen. Hence, an exception either means that the relevant probing was not performed in advance, or that something entirely unexpected has happened.

Example:

You want to create a file from a given path.

You should use the File object to evaluate in advance whether this path is legal for file creation or writing.

If your program somehow still ends up trying to write to a path that is illegal or otherwise not writable, you should get an excaption. This could happen due to a race condition (some other user removed the directory, or made it read-only, after you probl)

The task of handling an unexpected fail (signalled by an exception) and checking if the conditions are right for the operation in advance (probing) will usually be structured differently, and should therefore use different mechanisms.

OwnerDisplayName: Virtlink


问:
Java sql annotations ManyToMany relationships
I was wondering your thoughts on the best way to implement a SQL ManyToMany relationship in Java using annotations - in this case eBeans - where there is extra data associated with the join.

I have created a db diagram to help explain:

Using @ManyToMany on the organisation and users classes would create the join table but without the extra Job Title.

Is the best way to implement this to create the Org_has_users class and use @OneToMany and @ManyToOne annotations?
Would cascade on save ensure that I can access the full join relationships from both the Users and Organisations classes?

I hope this is enough to get started. I am more interested in how you would implement this.

Thanks!
Anthony

答:
The easiest way to implement this is to place an entity between the two Entities, which holds the additional values.

There are downsides to this approach: You need to reference the table from one or two sides, what makes it harder to maintain the correct values and adds in the worst case additional linking tables - all values must be removed in both sides of the collection and all JoinTables must be correct.

I don't know exactly about eBeans, but there are ways to do this, see here (especially the comment to the answer):
https://stackoverflow.com/questions/5127129/mapping-many-to-many-association-table-with-extra-columns


问:
What are the benefits of using Dependency Injection and IoC Containers?
I'm planning to do a talk on Dependency Injection and IoC Containers, and I'm looking for some good arguments for using it.

What are the most important benefits of using this technique, and these tools?

答: When DI is used to expose inner objects for the purpose of testing, the pattern has been abused.</p>


问:
Why categorization into "Property" and "Methods"
I am looking at the String class in Actionscript 3.0.

It has a property called String.length .
Internally it's a getter function (or method ?) that returns the length of string.

Why can't it be String.getLength() ?

Methods can take in 1, 2 or more values...so their significance can be understood. But what significance does "property" have? As it is, after all, a function only. So, why the categorization into properties? Is it just for adding an overhead botheration to remember that something has been categorized into a property?

In other words, as a programmer, how am I helped when I'am told that String.length is a property of the String class when I can't find any method for the same.

While writing a program, how would I know what is a property and what is a method?

I appreciate having someone shed some light on this.

V.

答:
String.Length is a read/only property, so it's possibly not the best place to start.

Imagine you have a Person class that needs to store a persons full name.

In Java, you might create a pair of methods, setName() and getName(), to handle this value. That's two methods, required to handle a single value.

It's only convention that links those two methods together. Someone who didn't know the convention - say, someone self taught - might instead write AssignName() and Name() methods. It is, after all, just a convention.

By formalising the relationship into something called a property, C# (and other languages) remove the need for developers to know about, and to adhere to, the same convention as everyone else.

Once you have the unified property, there are other benefits. For example, you can pass a property as an out or ref parameter if you want, you can't do that with a pair of methods.

As you look across other programming languages, there are other examples of this approach to be found.

An Interface is "just" a pure abstract class.

A Delegate is "just" a function as a value.

MethodMissing() and dynamic are "just" ways for a class to allow you to call methods that don't exist.

An event is "just" the way the language supports the Observer pattern.

The async and await keywords in C# 5.0 are "just" another way to write asynchronous code.

Extension Methods are "just" static methods.

Except that all of these things are more than what they are "just". They increase the expressiveness of the language involved, allowing better abstractions and more effective code.


答:
I think you've actually got there is a good rule of thumb for choosing to make a class abstract: if there are (or you can forsee the need for) variants of a class with slightly different behaviour, then it's often a good idea to create an abstract base class.

Bottom line though, in my experience: as long as the relationship you're dealing with is really is-a (e.g. your Accountant-Employee example is more suited to composition than inheritance, as per this answer) then it's very rarely harmful/problematic to inherit from non-abstract classes.

A couple of examples when you might want/have to ignore your rule. Both assume you require Poodle to be substitutable for Dog:

Dog is a class in an external API and there's no IDog interface for Poodle to implement.

Dog is already instantiated in dozens of different places in your (already tested) code.

Admittedly, these are both cases where a better original design might have helped, but in the real world designs are never perfect!

Title: Inheritance using non-abstract base class

Body:
This post is based on the question https://stackoverflow.com/questions/49002/prefer-composition-over-inheritance/11758048#comment15634305_11758048.

Some people said - check whether there is “is-a” relationship. If it is there use inheritance. What I think is there should be a second check for using inheritance. Use inheritance only if the base class is abstract. If the base class need to be instantiated then use composition; not inheritance.

E.g 1. Accountant is an Employee. But I will not use inheritance because a Employee object can be instantiated. (When you talk to business people, they will tell you - Accountant is an Employee. But in OO world Accountant is not (should not be) an employee)

E.g 2. Book is a SellingItem. A SellingItem cannot be instantiated - it is abstract concept. Hence I will use inheritance. The SellingItem is an abstract base class (or interface in C#)

What I am looking for here is an example that will challenge my argument –that is a scenario in which inheritance is better than composition even though the base class is non-abstract (base class can be instantiated). Can you please provide such an example?

Note: It would be more helpful if you can provide a scenario based on Bank domain, HR domain, Retail domain or any other popular domain.

Note: In the design, please assume that we have full control of the code. That is we are not using any external API. Also we are starting from beginning.

I will mark as answered if there is an example that explains a scenario that proves my argument is wrong. It is not a mere discussion on whether to use Composition or Inheritance.

I support @anon answer in https://stackoverflow.com/questions/3351666/why-use-inheritance-at-all?lq=1

The main reason for using inheritance is not as a form of composition - it is so you can get polymorphic behaviour. If you don't need polymorphism, you probably should not be using inheritance.

@MatthieuM. says in Code Smell: Inheritance Abuse

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

interface (for polymorphism)

implementation (for code reuse)

REFERENCE

Employee- Accountant Example https://stackoverflow.com/questions/11759120/issue-in-using-composition-for-is-a-relationship

Selling Item Example  - https://codereview.stackexchange.com/questions/14077/is-it-proper-tpt-inheritance

Programming SOLID Principles

Code Smell: Inheritance Abuse


答:
I think inheriting concrete class is OK and actually quite valuable feature.

The "is-a" rule is only good for extremely simple models and domains. The way I see it, is that classes represent behavior and encapsulate state where the state can be another class. What kind of behavior Accountant, Employee, Book and Selling item have in relation to our model? That is the question you should ask. And based on that use either inheritance of composition.

Also, many real-world object are not good examples, because they are usually composites of different behaviors, that can be shared between different real-world objects. Many animal species walk on all 4. That is good example of behavior.

Extending already existing behavior by inheritance is great way to simplify and modularise the model of the domain. And for our walk behavior example, we can extend WoundedWalk class, that does exactly what its name says.


答:
Let's address different point first: what do you understand by "simple unit test"? You'll write one test for happy-path only? Only methods you think might break? It's difficult to tell what you have on mind, but for the remainder of this post I'll assume you'll write only some tests where you consider them useful, instead of doing close-to-full coverage like TDD would result in.

Few notes to your points:

TDD makes you define the interface first: that's not really an argument for TDD, as you can define interface first without it. What TDD does instead, is make you focus on high-level details of piece you're working on at the given moment, without being disturbed diving deep into dependencies. But then again, this is not TDD specific.

TDD requires more time even considering debugging benefits: this is true, simply because in TDD you write more code. Indirect advantage is, that due to the fact you'll have much better coverage than "sporadic unit test" approach, regression will be less painful.

"if my typical bugs are not approachable by predictable tests (...)": is it really a bug when you know about it upfront and write code to prevent it before it actually happens?

I think you're comparing wrong approaches. TDD vs "sporadic unit testing", while it should be full testing vs sporadic testing. TDD will result in full testing, but you can achieve that without TDD just as well.

You need to decide how valuable you consider decent code coverage (not the delusive magical-fairy-tale 100%) vs "some" coverage; weight time spent on writing extra test code vs time gained when tests actually help you discover and fix regression related bugs, as this will be their main advantage over no-tests approaches.

Title: Sporadic unittests or TDD?

Body:
I've read some basics about unit tests and TDD, but I find it hard to convince myself why TDD can have an advantage over only selected unittests.

I've read common arguments for TDD, but don't see the improvment compared to simple unittests. Maybe you can help to clarify:

TDD allows a loosely coupled, testable design -> I believe I can well imagine if a class is theoretically testable, without having to write tests; Loose coupling is a fundamental requirement that one can judge without refering to TDD?!

TDD gives confidence in refactoring -> Isn't it more efficient to add selected unittests as soon as you start refactoring? While you have to think what to cover by test, you still save writing a lot of tests.

TDD makes you define the interface first -> To me it seems some minor points are easier to decide while coding (which also agrees with agile?). It's even hard to predict a nested return data structure, but after coding I can often validate that I get what I expected. I made up the nested data while coding (a small unit) and see the behaviour. I'd save a lot of time writing the method first and using the validated result a posteriori to plug into a unittest.

from what I've read many (of course not all) sources state that TDD does require more development time even considering the benefit for debugging; merely the code quality improves -> Can it be that some programmers make different kinds of mistakes and for some TDD doesn't cover the type of mistakes they make anyway? So if my typical bugs are not approachable by predictable tests, it's not for me?

TDD aids changing teams, and larger interacting teams -> Is this a large issue? I can imagine it is, however as for the moment I program alone I cannot judge. How does TDD help teams in ways that... and here is the important point: other ways don't? It can force some discipline for less experienced team members, but apart from that any advantages?


问:
Class design for internationalized object
I'm looking for some pointers on class design for a global application.

Let's say I have to make a class structure  to manage products, and the products are sold in different countries.  Some of the fields for the product will have the same value across all countries (eg. product code, ERP Description) I will call these "international" fields, and some fields will be specific to a single country (eg. Local Description), lets call these "local" fields.  Of course, some "local" fields will be the same for groups of countries (es. weight : 1 kilogram / 2 pounds). Also I expect that not all countries will have values for all fields.

Which fields are "international" and which fields are "local" may change from one installation to another and I am reluctant to bake this into the design as I'm sure it will bite me later on.

So, I'm trying to figure out how to structure the objects so that I can use a product at an international level and always refer to the same "product", but also maintain and use the local information when necessary?

Just to be clear, I'm not talking about user-locale, number or date formatting etc. The source data is coming from different database schemas (one for each country). The end product will be written in C#.

I'm wondering if anyone has experience or can point me to a pattern that would provide a good solution to this before I go and reinvent the wheel?

答:
Define a table for products which contains

ProductCode, ERP Description and other "constant" fields.

Define a table for properties which contains only 4 columns:

PropertyId(long),
PropertyOwnerId(long),
PropertyType(int, predefined in C# code, enumeration for instance),
PropertyValue(nvarchar, will be parsed depending on PropertyType in C# code, Object in C# code).

This is enough to bind the properties with thier owners. Later, if the properties change, all you have to do is insert new records to the second table.

The classes should have the same structure. This design is a little uncomfortable in sence that you'll have to parse a property read from DB or cast a property in C# code, but it is extremely flexible.

P.S if you think that some of the "constant" fields are likely to change, insert them as properties into the second table.


问:
REST API Library Conventions
Most API libraries define one method for each endpoint. If there is an endpoint for getting user information, you might have a method like:

```<code>getUserInfo(userId);
</code>```

That simple method is often a wrapper around another function that actually does the api call:

```<code>apiCall('/user/info', {userId: userId});
</code>```

Another option I see less frequently is for the library to only contain the method that makes the API call.

The first method only has the advantages of code discoverability, but it isn't that big of an issue for dynamic languages. Some say it also removes the need for the developer to read documentation for the APIs, but why would you ever want somebody using APIs without reading the documentation?

The second method has three advantages that I see:

The library is dramatically smaller

Methods don't need to be updated if the API ever changes

There is no need to maintain documentation for the library; the API documentation fulfills that purpose

But I don't see the second method used very often, so perhaps I'm missing something. When is it appropriate or inappropriate to use either method of writing API libraries?

答: getUserInfo(userId) looks like a simple local function call. You don't care if it's doing any REST or SOAP connection to retrieve the user, or if's retrieved from a database. At this level of abstraction it may be valuable to do so; when you're dealing with business rules involving users, you are not necessarily interested about the details of how this data is retrieved. Also by designing your code this way you have the possibility of changing these details (e.g. modifying the REST interface) without changing all the code that calls this function.

Title: REST API Library Conventions


问:
Do accompanying tools/scripts also need to be licensed to put my bash script under GPLv3?
This is some sort of follow up to an older question of me.

So I put the GPLv3 license into the project which contains my script and also added the copyright notice and copying permission statement to the top of my script.

Now, apart from the script, the package also contains files which are helpful for using the script (e.g. a bash completion file and unit tests) but which are not relevant for the script to actually work. Do I also need to put copyright notice/permission in there?

I've looked into some projects on github, and most don't seem to add these information to accompanying things.

Still, I'm unsure what's the best approach.

答: You should put a copyright and license header into each file, even if you publish them under a different license. This way, you avoid that your users experience the same confusion that made you ask your question.</p>


问:
Should Agile teams deliver new features daily?
My company is in the midst of a transition from waterfall-style development to Agile/Scrum.  Among other things, we're told that the expectation is for us to have new working, testable (by QA) features at the end of each day.

Most of our devs lose around 2 hours a day to meetings and other enterprisey overhead.  This means that in any given 6-hour (at best) period, we have to design, write, unit-test, build, and deploy (with release notes) enough code to produce a complete feature for QA to play with.  I understand that the build/deploy/release notes could be automated with a proper CI setup but we're not there yet.

We also have a large offshore contingent writing our server-side code, and the 12-hour time difference makes this even more difficult.

We attempt to task out stories into narrow, deep vertical slices in order to complete features end-to-end as fast as possible, but most days feel rather frantic and I often catch people taking stupid, fragile shortcuts to ensure QA has their build.  This problem is compounded after a sprint has been in progress for a couple of days, when the inevitable defects start rolling in and have to fit into the same 6-hour window.

Is this a normal pace for Agile teams?  Even if we manage to implement a CI setup, I can't see how we'll be able to sustain this pace and still create quality software.

Edit:  There are several good answers here.  It made me realize that what I was really asking is, should Agile teams deliver new features daily.  I updated the title accordingly.

答: I think you are confused about the idea of "CI" . You may want to visit this excellent article by Martin Fowler on how CI works in practice.That should answer your question correctly .</p>


答:
I would always vote for the getUserInfo(userId) style methods to be included, for these reasons:

discoverability;

less written documentation needed (as the methods, their context, their names and their parameters document themselves mostly);

methods describe available functionality;

library may not be significanltly smaller as these methods are themselves really small;

hiding details such as JSON <-> Object conversions and error handling;

save different users from having to write similar code to use the API;

if the API changes, only the library has to change. Otherwise, all code ever written for the API has to change.

Furthermore, with such methods you get the ability to:

validate arguments before sending the query;

do custom formatting on input arguments and custom parsing on return values, invisible to the library user;

put the methods in logical classes and namespaces: cleaner API;

use and return custom objects that encapsulate data commonly found together (such as a User or BlogPost objects);

include workarounds for bugs or provide a logical/consistent API view of an illogical/inconsistent API (design);

convert error return values into exceptions.

Title: REST API Library Conventions

Body:
Most API libraries define one method for each endpoint. If there is an endpoint for getting user information, you might have a method like:

```<code>getUserInfo(userId);
</code>```

That simple method is often a wrapper around another function that actually does the api call:

```<code>apiCall('/user/info', {userId: userId});
</code>```

Another option I see less frequently is for the library to only contain the method that makes the API call.

The first method only has the advantages of code discoverability, but it isn't that big of an issue for dynamic languages. Some say it also removes the need for the developer to read documentation for the APIs, but why would you ever want somebody using APIs without reading the documentation?

The second method has three advantages that I see:

The library is dramatically smaller

Methods don't need to be updated if the API ever changes

There is no need to maintain documentation for the library; the API documentation fulfills that purpose

But I don't see the second method used very often, so perhaps I'm missing something. When is it appropriate or inappropriate to use either method of writing API libraries?


答:
You use inheritance over composition when you need code reuse . Inheritance helps in evolving classes really fast . However , you should be careful not to overuse it . use it judiciously only when it makes sense (ie when you are absolutely sure that there is a "IS-A" relationship between every objects of both the classes .You need to make sure that the subclass objects respects the Liskov Substitution principle . Even then it might not be good idea everytime if you add a value component to a subclass and the super class also has the notion of a value component. From Effective Java :

There is no way to extend an instantiable class and add a value
  component while preserving the equals contract, unless you are willing
  to forgo the benefits of object-oriented abstraction.

On the other hand composition has multiple advantages over inheritance and so most of the times it is preferred over inheritance but that wasn't your question. Spring's *Dependency Injection principle * is primarily based on this premise .


答:
The entire 'is a' vs 'has a' discussion never made any sense to me. There is already a good definition about when to use inheritance, so called "Liskov substitution principle", which states:

Let q(x) be a property provable about objects x of type T. Then q(y) should be provable for objects y of type S where S is a subtype of T.

The first thing you'll notice is, that it is generally a bad idea to let people with PhD explain a simple problem.

Second, this exactly states when to use inheritance. If I may use Wikipedia's article and apply it to your accountant/employee example:

Liskov's notion of a behavioral subtype defines a notion of substitutability for mutable objects; that is, if Accountant is a subtype of Employee, then objects of type Employee in a program may be replaced with objects of type Accountant without altering any of the desirable properties of that program (e.g., correctness).

The entire Principles paragraph of the Wikipedia article contains some more interesting principles.

Apparently most answers refer to LSP in one way or the other. Baqueta cleverly disguised it as a easy-to-miss-link and Geek edited his post to include LSP seconds before I posted my answer. So, LSP seems to be the most reasonable way to create your hierarachy.

Some examples of where your principle doesn't hold:

bicycle and a mountain bike

circle and a sphere

A button and an image button or toggle button.

In WPF, the concrete System.Windows.Controls.Button has the following subclasses:

CalendarButton

CalendarDayButton

In Java and C#, everything extends directly or indirectly from object, which isn't abstract.

Also in WPF: DatePickerTextBox is a subclass of (the concrete) TextBox. There are lots more examples. These respect LSP and the base class is not abstract.

As an extra note. I think the reason you found this principle is because it is generally a good idea to keep your hierarchy very flat, because inheritance introduces coupling. One or two levels deep is more than enough. Abstract classes will (almost) always be subclassed somewhere, since that is the purpose of making a class abstract, so that others can make it specialized. Most concrete classes don't need to be specialized in any way. That may be the reason you haven't found an example yet.


问:
What is the regarded current best practises regarding the "this" keyword in front of field and methods in c#?
Unless it is needed to differentiate between a variable and field with the same name, I never put this. in front of a field or any member access in C#.  I see this as no different to m_ prefix that used to be common in C++, and think if you really need to specify that it's a member, your class is too big.

However, there are a number of people in my office that strongly disagree.

What is considered current best practises regarding this.?

EDIT: To clarify, I never use m_ and only use this. when absolutely necessary.

答:
EDIT: My answer is clearly not an answer. So here is an edit. The Microsoft coding guidelines state:

2.6 Naming

Do not use a prefix for member variables (, m, s_, etc.). If you want to distinguish > between local and member variables you should use  “this.” in C# and “Me.” in VB.NET.

Can be found at: Link

So it would seem that at least from MS there is no clear guideline, although another answer does state that StyleCop makes it a guideline. There is no authority on these things, so I would suggest you make up your own mind, or in this case give in to your team. It's not such a big deal.

My original answer
I personally agree with you, but maybe a reading comprehension test pitting the two methods against each other would be valuable. Otherwise these style things are just mudslinging.

My salvo to follow:
My opinion is that people are unnecessarily complicating their code style, and if they need to indicate that something is a class level variable there might be some other serious structural issues in the code, like the age old recipe-method of putting private variables at the top of the class which force you to constantly scrolling up and down.

this strikes me as one of those "what this is" conventions versus the correct "what it does" naming conventions. Brevity should be favoured above being explicit. This is a lesson that is repeated often by dynamic languages. We don't need all the fluff!

ContentLicense: CC BY-SA 4.0


问:
How should a website validate a users mailing address?
This is for a site that relies on shipping items via UPS or FedEx. I know there is software out there that does it (http://en.wikipedia.org/wiki/Coding_Accuracy_Support_System), but if you are trying to build your own solution for a simple website.</p>

答: Some payment processors will require ship to address verification, meaning only allowing shipments to the bill to address. Some offer this feature as an option. You may want to see if this is available to you. For example, PayPal can be configured to only allow shipments to a valid address, as determined by the credit card bill to address. This can limit options for your customer though, so it's a trade-off.</p>


答:
I always use "this".  The reasoning is based on two simple facts:

Reading code is more difficult than writing code.

You read code more often than you write code.

The use of "this" makes it quite explicit to anyone reading (i.e. not just the author, but may include the author in 6 months time after specifics of the implementation have been completely forgotten about) that yes, this is a class member we're talking about here.  "m_" and the like is just a convention, and like any other convention it can be misused (or not used at all) - there is nothing to enforce "m_"/etc at either compile time or run-time.  "this" is stronger: you can put "m_" on a local variable and the compiler won't complain; you can't do that with "this".

If anything I consider it regrettable that use of "this" was not made mandatory in language specs.

As a nice bonus, when debugging you can hover over (or add a watch for) the "this" and gain inspection of all other class members too - valuable information.

Title: What is the regarded current best practises regarding the "this" keyword in front of field and methods in c#?

Body:
Unless it is needed to differentiate between a variable and field with the same name, I never put this. in front of a field or any member access in C#.  I see this as no different to m_ prefix that used to be common in C++, and think if you really need to specify that it's a member, your class is too big.

However, there are a number of people in my office that strongly disagree.

What is considered current best practises regarding this.?

EDIT: To clarify, I never use m_ and only use this. when absolutely necessary.


答:
Using things like the this. prefix/keyword that are neither necessary nor change the outcome are always subjective. However, I think we can agree that most of us want to differentiate fields from local variables. Some use an underscore prefix (which I find ugly and a kind of Hungarian notation), others use the this. keyword. I am one of the latter. It is all just about readability and understandability. I never mind typing a little extra if it is clearer or more readable. I want to differentiate fields and variables in the blink of an eye.

I always define fields named similar to myField and parameter names and local variable names also similar to myField. No underscores, no prefixes. I use this everywhere I refer to a field. This way I can distinguish fields from local variables and arguments without any kind of prefix. Of course, in a case like this the this keyword is required:

```<code>public Person(string firstName)
{
    this.firstName = firstName;
}
</code>```

My properties therefore look like this (yes, I always put the field with the property, and not somewhere unrelated at the top of my file):

```<code>private string firstName;
public string FirstName
{
    get { return this.firstName; }
}
</code>```

It reads nicely: return this first name.

Body:
Using things like the this. prefix/keyword that are neither necessary nor change the outcome are always subjective. However, I think we can agree that most of us want to differentiate fields from local variables. Some use an underscore prefix (which I find ugly and a kind of Hungarian notation), others use the this. keyword. I am one of the latter. It is all just about readability and understandability. I never mind typing a little extra if it is clearer or more readable. I want to differentiate fields and variables in the blink of an eye.

I always define fields named similar to myField and parameter names and local variable names also similar to myField. No underscores, no prefixes. I use this everywhere I refer to a field. This way I can distinguish fields from local variables and arguments without any kind of prefix. Of course, in a case like this the this keyword is required:

public Person(string firstName)
{
    this.firstName = firstName;
}

My properties therefore look like this (yes, I always put the field with the property, and not somewhere unrelated at the top of my file):

private string firstName;
public string FirstName
{
    get { return this.firstName; }
}

It reads nicely: return this first name.


答: I'd just create a class with all the fields you need, then delegate instance creation to a factory.  The factory will create instances of the class based on whatever locale criteria you discover is best (whether you specify the locale in the create method or specify a locale in the factory's constructor).  The factory will hold all the logic for assembling objects from whatever tables you have.  You can have different strategies for handling missing or default values (if these vary based on locale), and which fields are "localized".  This concentrates all the logic in one place, yet gives you good flexibility.

Title: Class design for internationalized object

Body:
I'm looking for some pointers on class design for a global application.

Let's say I have to make a class structure  to manage products, and the products are sold in different countries.  Some of the fields for the product will have the same value across all countries (eg. product code, ERP Description) I will call these "international" fields, and some fields will be specific to a single country (eg. Local Description), lets call these "local" fields.  Of course, some "local" fields will be the same for groups of countries (es. weight : 1 kilogram / 2 pounds). Also I expect that not all countries will have values for all fields.

Which fields are "international" and which fields are "local" may change from one installation to another and I am reluctant to bake this into the design as I'm sure it will bite me later on.

So, I'm trying to figure out how to structure the objects so that I can use a product at an international level and always refer to the same "product", but also maintain and use the local information when necessary?

Just to be clear, I'm not talking about user-locale, number or date formatting etc. The source data is coming from different database schemas (one for each country). The end product will be written in C#.

I'm wondering if anyone has experience or can point me to a pattern that would provide a good solution to this before I go and reinvent the wheel?


答:
I assume you have a database of some sort. I'd create a factory class that creates the objects (e.g. Product) from the data in the database.

Let's say your designing the Product class. It has some of your international fields:

public class Product
{
    private string ean;
}
```

<p>For internationalized things like weights  I'd write some structs <code>Weight</code> that allows you to set the unit (pounds, kilograms). Use one consistent unit of weight in your database (for example kilograms) and use that to create the object. Then code your <code>ToString</code> to return the value localized in the specified unit. This is similar to how <code>DateTime</code> can take a date/time in UTC and 'localized' it to the user's timezone.</p>

<p>When there is no weight, use for example a weight of -1 and declare this as <code>static readonly Weight None = new Weight(-1)</code>.</p>

<pre class="lang-cs prettyprint-override"><code>public class Product
{
    private string ean;
    private Weight weight;
    private DateTime availableFrom;
}

public struct Weight
{
    private static readonly Weight None = new Weight(-1);

    private int weightInKG;

    public Weight(int weightInKG)
    {
        this.weightInKG = weightInKG;
    }

    public WeightUnit Unit
    { get; set; }

    public string ToString()
    { /* Implement */ }
}
</code>```

Then, if you have pieces of text that are localized (translated) then I'd just use strings. The factory class should get the appropriate localized string from the database. If there is no such string, use null.

public class Product
{
    private string ean;
    private Weight weight;
    private DateTime availableFrom;
    private string description;
}
```

<p>Lastly, if you have information that is always used together localized (for example, specs for the product) then create a class <code>Specs</code> (or a hierarchy <code>SpecsBase</code> <code>MonitorSpecs</code> <code>HardDiskSpecs</code> if there are multiple kinds) for this. When there are none, use <code>null</code>. You can share these objects among multiple products if the information is the same. Again, the factory should take care of creating it.</p>

<p>You can also use these objects for fields that might be international or local depending on the installation.</p>

<pre class="lang-cs prettyprint-override"><code>public class Product
{
    private string ean;
    private Weight weight;
    private DateTime availableFrom;
    private string description;
    private Specs specs;
}
</code>```

For all objects, override the ToString method to return the right (localized) strings.

Body:
I assume you have a database of some sort. I'd create a factory class that creates the objects (e.g. Product) from the data in the database.

Let's say your designing the Product class. It has some of your international fields:

public class Product
{
    private string ean;
}

For internationalized things like weights  I'd write some structs Weight that allows you to set the unit (pounds, kilograms). Use one consistent unit of weight in your database (for example kilograms) and use that to create the object. Then code your ToString to return the value localized in the specified unit. This is similar to how DateTime can take a date/time in UTC and 'localized' it to the user's timezone.

When there is no weight, use for example a weight of -1 and declare this as static readonly Weight None = new Weight(-1).

public class Product
{
    private string ean;
    private Weight weight;
    private DateTime availableFrom;
}

public struct Weight
{
    private static readonly Weight None = new Weight(-1);

    private int weightInKG;

    public Weight(int weightInKG)
    {
        this.weightInKG = weightInKG;
    }

    public WeightUnit Unit
    { get; set; }

    public string ToString()
    { /* Implement */ }
}

Then, if you have pieces of text that are localized (translated) then I'd just use strings. The factory class should get the appropriate localized string from the database. If there is no such string, use null.

public class Product
{
    private string ean;
    private Weight weight;
    private DateTime availableFrom;
    private string description;
}

Lastly, if you have information that is always used together localized (for example, specs for the product) then create a class Specs (or a hierarchy SpecsBase MonitorSpecs HardDiskSpecs if there are multiple kinds) for this. When there are none, use null. You can share these objects among multiple products if the information is the same. Again, the factory should take care of creating it.

You can also use these objects for fields that might be international or local depending on the installation.

public class Product
{
    private string ean;
    private Weight weight;
    private DateTime availableFrom;
    private string description;
    private Specs specs;
}

For all objects, override the ToString method to return the right (localized) strings.


答:
No, there should not be an expectation of delivering new features every single day. Not all features can be broken down to such a small size as to be able to have a developer finish the feature in ~6 hours of development time.

If you are doing scrum you should be doing at the minimum 2 week sprints, with features sized to take roughly from 0 to 8 days to be finished. The promise to the product owner is to deliver new, tested and verified correct working code that could be put into production at the end of the sprint. (NOTE: You don't have to actually put it into production but the goal is it could be if you wanted to)

Good methodology suggested you setup a CI (Continous Integration) server in which you automated the creation of at least one daily build of working software. The idea being you check in your code as soon as you finish the feature so it can be in the next build cycle and then in the hands of QA for testing.

Remember the goal is to to have features done and tested by the end of the sprint! You wouldn't want to have to make QA wait until the last day of the sprint for you to make the build and then have them test all the features. They won't have time to test it all and you won't have time to fix any bugs...

If you cannot setup a CI server then the practice should be that you need to manually create a new build for QA each time a developer checks in his finished code and claims he is done with a feature and ready to hand off to QA.

Title: Should Agile teams deliver new features daily?

Body:
My company is in the midst of a transition from waterfall-style development to Agile/Scrum.  Among other things, we're told that the expectation is for us to have new working, testable (by QA) features at the end of each day.

Most of our devs lose around 2 hours a day to meetings and other enterprisey overhead.  This means that in any given 6-hour (at best) period, we have to design, write, unit-test, build, and deploy (with release notes) enough code to produce a complete feature for QA to play with.  I understand that the build/deploy/release notes could be automated with a proper CI setup but we're not there yet.

We also have a large offshore contingent writing our server-side code, and the 12-hour time difference makes this even more difficult.

We attempt to task out stories into narrow, deep vertical slices in order to complete features end-to-end as fast as possible, but most days feel rather frantic and I often catch people taking stupid, fragile shortcuts to ensure QA has their build.  This problem is compounded after a sprint has been in progress for a couple of days, when the inevitable defects start rolling in and have to fit into the same 6-hour window.

Is this a normal pace for Agile teams?  Even if we manage to implement a CI setup, I can't see how we'll be able to sustain this pace and still create quality software.

Edit:  There are several good answers here.  It made me realize that what I was really asking is, should Agile teams deliver new features daily.  I updated the title accordingly.


答: That is why we still doing good old-school WinAPI programming using Delphi. Better spend time for task solving than waste it on so called "new technologies". All that "new" in .NET existed a long before it in Borland Delphi. Personally, I think that technology should stay around at least 10 years before one should try it and depend on it.</p>

Title: Does Silverlight have a future?

Body:
Recently I have read some articles/blogs/comments about the development and history of WPF and Silverlight. In some forums many developers and users criticize the performance of WPF applications (for example Visual Studio 2010). Actually the market share of Silverlight in comparison to Flash is not very high. At PDC 2010 Bob Muglia said something like "our Silverlight strategy and focus going forward has shifted...." and Microsoft wants to push HTML5 in the future.

Additionally, Microsoft has announced HTML5 being a core part of the Windows 8 and Windows Phone 8 ("Mango") platforms.

Recently I have started learning Silverlight and now I must ask myself, if I should continue investing time in learning these (in my opinions) very nice and powerful technologies!? Does they have a future? Does (Windows) desktop (client) applications have a future? Does so called "Rich Internet Applications" have a future? Or will HTML5 become the "absolute truth" in software development?

What is your opinion and what do you think?


问:
Pattern(s) about hierarchical settings overwriting
Assume that you have a hierarchy of organizational units:

```<code>- Company
-- Branches
--- Departments
---- Teams
</code>```

Lets say I have some settings (for simplicity assume that they have the same properties) for each level of hierarchy:

Max nr of documents

Min something else

Can do X

Can do Y

many other properties

So, the sub-units can reuse as default the parents settings, or they have only one or two of these settings modified. Same for their sub-units.

What would be the proper pattern to follow - both as code structures, as well as db storage to support that, with the idea that each unit's settings can be modified independently, and sub-unit's settings override the default of the parent.

We were thinking about key/value pairs, and then lookup for each one going up the hierarchy until we find the right setting, but this can become ugly pretty fast.

Another option we were considering is that each unit has it's own record of the settings, and update accordingly when parent's settings changed.

I'd appreciate any suggestion of well known approaches/patterns in that regard.

答:
The design I follow is to only set what's overridden.  So I would have a full set of default settings.  Then at the company level I would override only those that are different.  At the branch level I would only override those that are different than the company or default.  And so on.  In that way the settings build up from the base.  Changing a lower level setting will "bubble up".  This also keeps your data set as small as possible.

At the application level, assuming the set is relatively small, I would load all of the defaults, then the relevant company's overrides, then the relevant department's overrides, etc. into one data set.  You can then look up any setting from that one list.


答:
I'm not sure there's an actual, well known OO design pattern for this, but it's quite similar to how ACL (permissions) are applied in most file systems, so you could read up on that.

Matt S's suggestion is pretty much correct.  I would recommend storing the settings as full sets, with an option for "unspecified".  TortoiseHg, the popular Mercurial front-end for Windows, does it as follows:

Notice the options to leave things "unspecified", which would leave the setting to whatever was set at a higher level.  Also, notice that there's 3 levels here:

Factory defaults -> "User's global settings" -> "Repository Settings"

Each getting progressively more specific.  As long as you can resolve your hierarchy into a simple linear format like this, the task is quite simple.  Start with the least specific set (which should have actual values for everything), and then simply apply the next level of settings to it.  If anything is "Unspecified", leave it alone.  When you run out of levels of settings, you've successfully resolved the settings for the user.

It might be a good idea to keep track of which setting level applied each setting, if only for debugging / information purposes.

Title: Pattern(s) about hierarchical settings overwriting

Body:
Assume that you have a hierarchy of organizational units:

```<code>- Company
-- Branches
--- Departments
---- Teams
</code>```

Lets say I have some settings (for simplicity assume that they have the same properties) for each level of hierarchy:

Max nr of documents

Min something else

Can do X

Can do Y

many other properties

So, the sub-units can reuse as default the parents settings, or they have only one or two of these settings modified. Same for their sub-units.

What would be the proper pattern to follow - both as code structures, as well as db storage to support that, with the idea that each unit's settings can be modified independently, and sub-unit's settings override the default of the parent.

We were thinking about key/value pairs, and then lookup for each one going up the hierarchy until we find the right setting, but this can become ugly pretty fast.

Another option we were considering is that each unit has it's own record of the settings, and update accordingly when parent's settings changed.

I'd appreciate any suggestion of well known approaches/patterns in that regard.


问:
Is there ever a reason to do all an object's work in a constructor?
Let me preface this by saying this is not my code nor my coworkers' code. Years ago when our company was smaller, we had some projects we needed done that we did not have the capacity for, so they were outsourced. Now, I have nothing against outsourcing or contractors in general, but the codebase they produced is a mass of WTFs. That being said, it does (mostly) work, so I suppose it's in the top 10% of outsourced projects I've seen.

As our company has grown, we've tried to take more of our development in house. This particular project landed in my lap so I've been going over it, cleaning it up, adding tests, etc etc.

There's one pattern I see repeated a lot and it seems so mindblowingly awful that I wondered if maybe there is a reason and I just don't see it. The pattern is an object with no public methods or members, just a public constructor that does all the work of the object.

For example, (the code is in Java, if that matters, but I hope this to be a more general question):

public class Foo {
  private int bar;
  private String baz;

  public Foo(File f) {
    execute(f);
  }

  private void execute(File f) {
     // FTP the file to some hardcoded location,
     // or parse the file and commit to the database, or whatever
  }
}
```
<p>If you're wondering, this type of code is often called in the following manner:</p>
<pre class="lang-java prettyprint-override"><code>for(File f : someListOfFiles) {
   new Foo(f);
}
</code>```

Now, I was taught long ago that instantiated objects in a loop is generally a bad idea, and that constructors should do a minimum of work. Looking at this code it looks like it would be better to drop the constructor and make execute a public static method.

I did ask the contractor why it was done this way, and the response I got was "We can change it if you want". Which was not really helpful.

Anyway, is there ever a reason to do something like this, in any programming language, or is this just another submission to the Daily WTF?

答:
Ok, going down the list:

I was taught long ago that instantiated objects in a loop is generally a bad idea

Not in any languages I've used.

In C it is a good idea to declare your variables up front, but that is different from what you said. It might be slightly faster if you declare objects above the loop and reuse them, but there are plenty of languages where this increase in speed will be meaningless (and probably some compilers out there that do the optimization for you :) ).

In general, if you need an object within a loop, create one.

constructors should do a minimum of work

Constructors should instantiate the fields of an object and do any other initialization necessary to make the object ready to use. This is generally means constructors are small, but there are scenarios where this would be a substantial amount of work.

is there ever a reason to do something like this, in any programming language, or is this just another submission to the Daily WTF?

It's a submission to the Daily WTF. Granted, there are worse things you can do with code. The problem is that the author has a vast misunderstanding of what classes are and how to use them. Specifically, here's what I see that is wrong with this code:

Misuse of classes: The class is basically acting like a function. As you mentioned, it should either be replaced with a static function, or the function should just be implemented in the class that is calling it. Depends on what it does and where it is used.

Performance overhead: Depending on the language, creating an object can be slower than calling a function.

General confusion: It is generally confusing to the programmer how to use this code. Without seeing it used, no one would know how the author intended to use the code in question.


问:
Writing Unit Tests for a Class That Starts External EXE
I wrote a C# class that is used to start a list of EXEs (not one of mine - third party EXEs I have to run) and keep them running (will check occasionally to make sure it is still running, and start them if not).

I am able to test the basic logic of adding, removing, etc fine.  How do I Unit Test that the actual work of keeping EXEs will work?

My initial thought is to start some dummy EXE that closes itself after 1 second, then use that to test.  Is that out of the realm of Unit Testing?

答:
When strictly following the philosophy of unittesting (emphasis on unit), you should not create an Exe-file, but instead test if your class calls the interfaces to spawning and monitoring that process correctly.
After all, you want to test your class, not the library responsible for process handling.

But from a pragmatic point of view, your approach is fine, though 1 second seems to be a little long.


答:
My initial thought is to start some dummy EXE that closes itself after 1 second, then use that to test. Is that out of the realm of Unit Testing?

Is this a good test? Sure, so create it. Is it "a Unit Test" in the real sense of the word? I don't think so, I would call this a "system test" or something like that, but that does not make the test less valuable.

Title: Writing Unit Tests for a Class That Starts External EXE

Body:
I wrote a C# class that is used to start a list of EXEs (not one of mine - third party EXEs I have to run) and keep them running (will check occasionally to make sure it is still running, and start them if not).

I am able to test the basic logic of adding, removing, etc fine.  How do I Unit Test that the actual work of keeping EXEs will work?

My initial thought is to start some dummy EXE that closes itself after 1 second, then use that to test.  Is that out of the realm of Unit Testing?


问:
What is better for coding - desktop or laptop?
Use of desktops are decreasing day by day in daily life but for coding purpose are there any reasons for using desktop over laptop? </p>

答:
Assuming you have an external monitor and keyboard to connect to your laptop the difference is small. </p>

<p>It is always better to work in a desktop like setting (bigger screen realestate, more ergonomic environment), but you can't take your work with you without a laptop. So if portability is important, get a laptop and a good external screen and keyboard to connect it to. Otherwise you might as well stay with a desktop. </p>

Body:
Assuming you have an external monitor and keyboard to connect to your laptop the difference is small.

It is always better to work in a desktop like setting (bigger screen realestate, more ergonomic environment), but you can't take your work with you without a laptop. So if portability is important, get a laptop and a good external screen and keyboard to connect it to. Otherwise you might as well stay with a desktop.


答:
For me, it is a bit of a surprise when you get an object doing much work in the constructor, so just on that I'd recommend against it (principle of least surprise).

An attempt at a good example:

I'm not sure if this usage is an anti-pattern, but in C# I've seen code which was along the lines of (somewhat made up example):

```<code>using (ImpersonationContext administrativeContext = new ImpersonationContext(ADMIN_USER))
{
    // Perform actions here under the administrator's security context
}
// We're back to "normal" privileges here
</code>```

In this case, the ImpersonationContext class does all of its work in the constructor and the Dispose method.  It takes advantage of the C# using statement, which is fairly well understood by C# developers, and thus guarantees that the setup which occurs in the constructor is rolled back once we're outside of the using statement, even if an exception occurs.  This is probably the best usage I've seen for this (i.e. "work" in the constructor), although I'm still not sure I'd consider it "good".  In this case, it's fairly self-explanatory, functional and succint.

An example of a good, and similar pattern would be the command pattern.  You definitely don't execute the logic in the constructor there, but it's similar in the sense that the entire class is equivalent to a method invocation (including the parameters needed to invoke the method).  In this way, method invocation information can be serialised or passed for later usage, which is immensely useful.  Perhaps your contractors were attempting something similar, although I highly doubt it.

Comments on your example:

I would say it's a very definite anti-pattern.  It adds nothing, goes against what's expected, and performs overly long processing in the constructor (FTP in the constructor?  WTF indeed, although I guess people have been known to call web services in this fashion).

I'm struggling to find the quote, but Grady Booch's book "Object Solutions" has an anecdote about a team of C developers transitioning to C++.  Apparently they had been through training, and were told by management that they absolutely had to do things "object oriented".  Brought in to figure out what's wrong, the author used a code metric tool, and found that the average number of methods per class was exactly 1, and were variations of the phrase "Do It".  I must say, I've never encountered this particular problem before, but apparently it can be a symptom of people being forced to create object oriented code, without really understanding how to do so, and why.

Title: Is there ever a reason to do all an object's work in a constructor?

Body:
Let me preface this by saying this is not my code nor my coworkers' code. Years ago when our company was smaller, we had some projects we needed done that we did not have the capacity for, so they were outsourced. Now, I have nothing against outsourcing or contractors in general, but the codebase they produced is a mass of WTFs. That being said, it does (mostly) work, so I suppose it's in the top 10% of outsourced projects I've seen.

As our company has grown, we've tried to take more of our development in house. This particular project landed in my lap so I've been going over it, cleaning it up, adding tests, etc etc.

There's one pattern I see repeated a lot and it seems so mindblowingly awful that I wondered if maybe there is a reason and I just don't see it. The pattern is an object with no public methods or members, just a public constructor that does all the work of the object.

For example, (the code is in Java, if that matters, but I hope this to be a more general question):

public class Foo {
  private int bar;
  private String baz;

  public Foo(File f) {
    execute(f);
  }

  private void execute(File f) {
     // FTP the file to some hardcoded location,
     // or parse the file and commit to the database, or whatever
  }
}
```
<p>If you're wondering, this type of code is often called in the following manner:</p>
<pre class="lang-java prettyprint-override"><code>for(File f : someListOfFiles) {
   new Foo(f);
}
</code>```

Now, I was taught long ago that instantiated objects in a loop is generally a bad idea, and that constructors should do a minimum of work. Looking at this code it looks like it would be better to drop the constructor and make execute a public static method.

I did ask the contractor why it was done this way, and the response I got was "We can change it if you want". Which was not really helpful.

Anyway, is there ever a reason to do something like this, in any programming language, or is this just another submission to the Daily WTF?

Body:
For me, it is a bit of a surprise when you get an object doing much work in the constructor, so just on that I'd recommend against it (principle of least surprise).

An attempt at a good example:

I'm not sure if this usage is an anti-pattern, but in C# I've seen code which was along the lines of (somewhat made up example):

using (ImpersonationContext administrativeContext = new ImpersonationContext(ADMIN_USER))
{
    // Perform actions here under the administrator's security context
}
// We're back to "normal" privileges here

In this case, the ImpersonationContext class does all of its work in the constructor and the Dispose method.  It takes advantage of the C# using statement, which is fairly well understood by C# developers, and thus guarantees that the setup which occurs in the constructor is rolled back once we're outside of the using statement, even if an exception occurs.  This is probably the best usage I've seen for this (i.e. "work" in the constructor), although I'm still not sure I'd consider it "good".  In this case, it's fairly self-explanatory, functional and succint.

An example of a good, and similar pattern would be the command pattern.  You definitely don't execute the logic in the constructor there, but it's similar in the sense that the entire class is equivalent to a method invocation (including the parameters needed to invoke the method).  In this way, method invocation information can be serialised or passed for later usage, which is immensely useful.  Perhaps your contractors were attempting something similar, although I highly doubt it.

Comments on your example:

I would say it's a very definite anti-pattern.  It adds nothing, goes against what's expected, and performs overly long processing in the constructor (FTP in the constructor?  WTF indeed, although I guess people have been known to call web services in this fashion).

I'm struggling to find the quote, but Grady Booch's book "Object Solutions" has an anecdote about a team of C developers transitioning to C++.  Apparently they had been through training, and were told by management that they absolutely had to do things "object oriented".  Brought in to figure out what's wrong, the author used a code metric tool, and found that the average number of methods per class was exactly 1, and were variations of the phrase "Do It".  I must say, I've never encountered this particular problem before, but apparently it can be a symptom of people being forced to create object oriented code, without really understanding how to do so, and why.


答:
TDD allows a loosely coupled, testable design -> I believe I can
  well imagine if a class is theoretically testable, without having to
  write tests; Loose coupling is a fundamental requirement that one can
  judge without refering to TDD?!

You are right TDD helps you learn how to design this way, by forcing you to.  But riding a bike with training wheels isn't always necessary, it's possible to design well without TDD.

TDD gives confidence in refactoring Isn't it more efficient to add
  selected unittests as soon as you start refactoring? While you have to
  think what to cover by test, you still save writing a lot of  tests.

The problem is you may not remember what unit tests to add when you revisit the code days or months later.  You may need to refactor just to add unit tests, breaking things unexpectedly.  At the same time, unit tests may need to be refactored as well, increasing the overhead.  Or unit tests may give you false confidence.  It is very situational whether or not test-first or test-after is more effective.

TDD makes you define the interface first - To me it seems some minor
  points are easier to decide while coding (which also agrees with
  agile?). It's even hard to predict a nested return data structure, but
  after coding I can often validate that I get what I expected. I made
  up the nested data while coding (a small unit) and see the behaviour.
  I'd save a lot of time writing the method first and using the
  validated result a posteriori to plug into a unittest.

Thinking test-first takes practice, but has the advantage of ensuring your code is unit-testable without refactoring.  BTW don't write an Interface first if that's what you are thinking, you write a interface first (all classes have interfaces).

From what I've read many (of course not all) sources state that TDD
  does require more development time even considering the benefit for
  debugging; merely the code quality improves -> Can it be that some
  programmers make different kinds of mistakes and for some TDD doesn't
  cover the type of mistakes they make anyway? So if my typical bugs are
  not approachable by predictable tests, it's not for me?

TDD can take far less time than normal, but you need to practice it enough and learn what tests are most effective.  Do pure TDD on a pet project to see what it's like, but don't do pure TDD everywhere - it's a waste of time.  Instead apply your TDD skill selectively (mix of hand/unit/integration tests some test-first some after), again this requires experience.

TDD aids changing teams, and larger interacting teams - Is this a
  large issue? I can imagine it is, however as for the moment I program
  alone I cannot judge. How does TDD help teams in ways that... and here
  is the important point: other ways don't? It can force some discipline
  for less experienced team members, but apart from that any advantages?

TDD takes a long time to learn and will send a project into a nosedive if you apply it to a team that doesn't know it at all.

Title: Sporadic unittests or TDD?


答:
Mock it out at a higher level than that. Create a proxy class around Process.Start(), fake that out in the test and check the input.

```<code>public interface IProcessProxy
{
     ProcessInfo Start(string application, string[] arguments);
}

public class ProcessProxy : IProcessProxy
{
    public ProcessInfo Start(string application, string[] arguments)
    {
        return Process.Start(application, arguments);
    }
}

// You could use a mocking framework for this, but for the purposes
// of this example ...
public class FakeProcessProxy : IProcessProxy
{
    private string _expectedApplication;
    private string[] _expectedArguments;
    private ProcessInfo response;

    public FakeProxy(string expectedApplication, string[] expectedArguments, ProcessInfo response)
    {
         _expectedApplication = expectedApplication;
         _expectedArguments = expectedArguments;
    }

    public ProcessInfo Start(string application, string[] arguments)
    {
         // compare input to expectations and throw exception if not matching
         return _response;
    }
}

// You can also use an IoC framework to inject your IProcessProxy, but I won't.
public class ClassUnderTest
{
    public ClassUnderTest(IProcessProxy proxy)
    {
        _proxy = proxy;
    }

    public ClassUnderTest() : this(new ProcessProxy())
    {
    }

    public void MethodUnderTest()
    {
        // Do stuff

        ProcessInfo process = _proxy.Start(@"C:\Program Files\App\App.exe", new[] { "arg1", "arg2" });
        process.WaitForExit();

        if (process.ExitCode == 0)
        {
            // Act on success
        }
        else
        {
            // Act on failure
        }
    }
}
</code>```

Wherever you need to consume ClassUnderTest in application code, use the default constructor. In your tests, pass a FakeProcessProxy to the other constructor, using your expected Proxy Start parameters and your test result in the fake's constructor.

Body:
Mock it out at a higher level than that. Create a proxy class around Process.Start(), fake that out in the test and check the input.

public interface IProcessProxy
{
     ProcessInfo Start(string application, string[] arguments);
}

public class ProcessProxy : IProcessProxy
{
    public ProcessInfo Start(string application, string[] arguments)
    {
        return Process.Start(application, arguments);
    }
}

// You could use a mocking framework for this, but for the purposes
// of this example ...
public class FakeProcessProxy : IProcessProxy
{
    private string _expectedApplication;
    private string[] _expectedArguments;
    private ProcessInfo response;

    public FakeProxy(string expectedApplication, string[] expectedArguments, ProcessInfo response)
    {
         _expectedApplication = expectedApplication;
         _expectedArguments = expectedArguments;
    }

    public ProcessInfo Start(string application, string[] arguments)
    {
         // compare input to expectations and throw exception if not matching
         return _response;
    }
}

// You can also use an IoC framework to inject your IProcessProxy, but I won't.
public class ClassUnderTest
{
    public ClassUnderTest(IProcessProxy proxy)
    {
        _proxy = proxy;
    }

    public ClassUnderTest() : this(new ProcessProxy())
    {
    }

    public void MethodUnderTest()
    {
        // Do stuff

        ProcessInfo process = _proxy.Start(@"C:\Program Files\App\App.exe", new[] { "arg1", "arg2" });
        process.WaitForExit();

        if (process.ExitCode == 0)
        {
            // Act on success
        }
        else
        {
            // Act on failure
        }
    }
}

Wherever you need to consume ClassUnderTest in application code, use the default constructor. In your tests, pass a FakeProcessProxy to the other constructor, using your expected Proxy Start parameters and your test result in the fake's constructor.


问:
How to properly design classes for a big project?
If we need to represent classes in a class diagram for a big project that is not completely designed yet, and the classes have to be actual tables in a database, how would we predict and design the classes?

Let's say we have a project that is going to have more than 15 tables, do all these tables need to be classes in the class diagram?

How would classes be designed in this kind of situation? The language that is being used is Java and the class diagram has to prepared in UML. I know how to design them, I just don't know if the tables should represent the classes in this case.

答:
For such a generic question, I can only give you a generic answer: it depends.

There are data-driven applications (which are very boring to create) that deliver exactly what the customer wants. In that case, your domain (if you really need one) is an exact duplicate of your database schema.

There are also applications where the database is nothing more than a way to persist state in case of an application crash. In that case, the database design is not that important (assuming it won't have a lot of concurrent users) and the database model will probably be an duplicate of your domain model.

There are also applications where the database is modelled using the right modelling techniques and the application domain is modelled using the right OOAD techniques. The difference between them could be resolved using a ORM or manual mappers.


答:
It seems to me that the person doing this was trying to hack around the limitation of Java that does not allow to pass functions around as first class citizens. Whenever you have to pass a function, you have to wrap it inside a class with a method like apply or similar.

So I guess he just used a shortcut and used directly a class as a function replacement. Whenever you want to execute the function, you just instantiate the class.

It is definitely not a good pattern, at least because we are here trying to figure it out, but I guess it may be the least verbose way to do something similar to functional programming in Java.


答: For me the rule of thumb is not to do anything in the constructor, except for initialising member variables. The first reason for that is that it helps to follow SRP principle, as usually a lengthy initialization process is an indication that the class does more than it should do, and the initialization should be done somewhere outside of the class. The second reason is that this way only the necessary parameters are passed, so you create less coupled code. A constructor with complicated initialisation usually needs parameters which are used only to construct another object, but which are not used by the original class.</p>


问:
Can someone help me understand this GPL license
I can't understand the last line of this GPL license.

Copyright (C) 2011 Some Name

This program is free software; you can redistribute it and/or modify
  it under the terms of the GNU General Public License as published by
  the Free Software Foundation; either version 2 of the License, or (at
  your option) any later version. This program is distributed in the
  hope that it will be useful, but WITHOUT ANY WARRANTY; without even
  the implied warranty of MERCHANTABILITY or FITNESS FOR A PARTICULAR
  PURPOSE. See the GNU General Public License for more details.

You should have received a copy of the GNU General Public License
  along with this program; if not, write to the Free Software
  Foundation, Inc., 51 Franklin St, Fifth Floor, Boston, MA 02110-1301
  USA

Linking SOMEAPP statically or dynamically with other modules is making
  a combined work based on SOMEAPP. Thus, the terms and conditions of
  the GNU General Public License cover the whole combination.

In addition, as a special exception, the copyright holders of SOMEAPP
  give you permission to combine a portion of SOMEAPP with other binary
  code ("Program") under any license the copyright holders of Program
  specified, provided the combined work is produced by SOMEAPP.

I want to know can I use this code in a shareware application.

答:
No, you cannot use this code unless your shareware application is also licensed under the GPL.

You could ask the original copyright holder to license the code to you under a different license.


问:
Advice for solo programmer whose team will expand in the near future
For 4 years now, I've been the solo developer for a small company. We have a handful of well establish products in a niche industry. We will be hiring 1-2 developers soon, and that will likely change the way things operate around here.

While I won't have a "real" title, I will be "in charge" of this team. What I want to do is establish a very organized and productive programming department for my company. I got this solo job right out of college, so while I've become proficient as a programmer in this industry, I lack a lot of team programming experience. I feel that starting out on the right foot will be key.

Right now it's just me, a few computers, and an SVN server. I'm looking for any general guidance on building a team from the ground up.

答: The book Brownfield Application Development in .Net has some ideas that I think should help. Part of the advice is how to set things up so that they're repeatable across team members, and across time. </p>


问:
Using business objects in view models
When using reusable business objects, what is considered best practice when building view models?

We use an object we call Builder to build our view models. One builder for each logical unit of views (orders, users etc), where each unit can contain a number of different view models (orders contains summary, order lines etc).

A builder may pull data through one or more standard business objects in order to build a view model.

What is considered the better practice when it comes to using business objects/models in view models?

Approach 1

Allow the use of business objects in the view model?

```<code>//Business object in some library
public class Order
{
    public int OrderNum;
    public int NumOrderLines;
    //...
}

//Order builder in website
public class OrderBuilder
{
    public OrderSummary BuildSummaryForOrder(int OrderNum)
    {
        Some.Business.Logic.Order obOrder = Some.Business.Logic.GetOrder(OrderNum);
        //Any exception handling, additional logic, or whatever

        OrderSummary obModel = new OrderSummary();
        obModel.Order = obOrder;

        return obModel;
    }
}

//View model
public class OrderSummary
{
    public Some.Business.Logic.Order Order;
    //Other methods for additional logic based on the order
    //and other properties
}
</code>```

Approach 2

Take only the necessary data from the business objects

```<code>//Business object in some library
public class Order
{
    public int OrderNum;
    public int NumOrderLines;
    //...
}

//Order builder in website
public class OrderBuilder
{
    public OrderSummary BuildSummaryForOrder(int OrderNum)
    {
        Some.Business.Logic.Order obOrder = Some.Business.Logic.GetOrder(OrderNum);
        //Any exception handling, additional logic, or whatever

        OrderSummary obModel = new OrderSummary()
        {
            OrderNum = obOrder.OrderNum,
            NumOrderLnes = obOrder.NumOrderLines,
        }

        return obModel;
    }
}

//View model
public class OrderSummary
{
    public int OrderNum;
    public int NumOrderLines
    //Other methods for additional logic based on the order
    //and other properties
}
</code>```

I can see the benefits and drawbacks to both, but I wonder if there's an accepted approach? In approach 1, there's no duplication of code around the models, but it creates a dependency on the business logic. In approach 2, you take only the data needed for the view, but you duplicate code around models.

答:
Option 1 creates a tight-coupling between the domain model and the view. This contravenes the very problem view models are designed to solve.

A view models "reason to change" is if the view itself changes. By putting a domain model object in the view model, you're introducing another reason to change (eg the domain changed). This is a clear indication of a violation of the single responsibility principle. Having two or more reasons to change leads to view models which require a lot of maintenance - probably more so than the perceived maintenance cost of duplication across domain/view models.

I would always advocate approach 2. It's often the case that view models might look very similar, even identical to domain model objects, but the distinction as I mentioned is their differing reasons for change.

Title: Using business objects in view models


问:
How best to enable a web service consumer to integration test a transactional web service?
I want to allow consumers of a web services layer (web services are written in Java) to create automated integration tests to validate that the version of the web services layer that the consumers will use will still work for the consumer (i.e. the web services are on a different release lifecycle than the consumers and their APIs or behavior might change-- they shouldn't change wihtout notifying the consumer, but the point of this automated test is to validate that they haven't changed)

What would I do if the web service actually executes a transaction (updates database tables). Is there a common practice for how to handle this without having to put logic into the web service itself to know its in a unit test and rollback the transaction once finished? (basically baking in the capability to deal with testing of the web service). Or is that the recommended way to do it?

答: Break up your logic and have a REST object delegate to a DAO.  Then have the DAO injected at runtime, if a specific parameter is supplied as part of the REST call (test=true) inject an alternate DAO that will rollback the transaction after the assertions pass.</p>


问:
How do I tell the cases when it's worth to use LINQ?
Many things in LINQ can be accomplished without the library. But for some scenarios, LINQ is most appropriate.

Examples are:

SELECT - https://stackoverflow.com/questions/11883262/wrapping-list-items-inside-div-in-a-repeater

SelectMany, Contains - https://stackoverflow.com/questions/11778979/better-code-pattern-for-checking-existence-of-value

Enumerable.Range - https://stackoverflow.com/questions/11780128/scalable-c-sharp-code-for-creating-array-from-config-file

WHERE https://stackoverflow.com/questions/13171850/trim-string-if-a-string-ends-with-a-specific-word

What factors to take into account when deciding between LINQ and regular .Net language elements?

答:
There are a number of different types of technologies which fall under the umbrella term of LINQ:

LINQ-to-Objects

LINQ-to-SQL

LINQ-to-Datasets

LINQ-to-XML

LINQ-to-Entities

And there are more provided by others as well, such as LINQ-to-CSV, LINQ-to-NHibernate, etc.

In every one of these cases, the purpose of LINQ is the same: to query sets of data. So anytime you have some sort of set (0, 1 or more items) of a particular type of data, LINQ is a succinct solution to deal with it. Many questions seem to arise over whether it performs better than a hand-written approach, but that's not the point. LINQ specifies intent rather than implementation.