问:
How much inconsistency arises from Javascript's high flexibility?
I'll admit it, I haven't yet mastered the language, but my experience with it tells me that Javascript is a highly flexible language, allowing prototypal inheritance, dynamic typing, functions as first class citizens and so many more cool stuff. I think such features bring some inconsistencies, but that's nothing new, most people would agree with me. I wanted to discuss specific examples that have been annoying me, like "for in" loops:

```<code>for(var role in rolesToAdd){
                if(rolesToAdd.hasOwnProperty(role)){
                    // for body
                }
}
</code>```

Why should I need to do this? Doesn't this break the concept of classes and inheritance? I might not want to loop through the whole prototype, but what if I still need some of the attributes/methods from an object's direct parent, for example?

Also, I would be most grateful if someone could explain me why the interpreter doesn't allow synonymous global/local variables to share the same scope, when there is certainly a way it could distinguish one from the other. Like in:

```<code>var foo = function() {
        var wth = bar();
        var bar = wth;
        // body...
}();

function bar(){
    return 'bar mitzvah';
}
</code>```

You can see that, even though our local bar has been declared after the call to our global bar, bar's value in foo's scope will always reflect the local bar, which will hold 'undefined'. Isn't that a strange behavior? I would love if senior Js programmers enlightened me on this and showed me what is gained from these seemingly strange features and if the disadvantages I mentioned here are valid.

答:
Why should I need to this? Doesn't this break the concept of classes and inheritance? I might not want to loop through the whole prototype, but what if still need some of the attributes/methods from an object's direct parent, for example?

JavaScript is essentially a functional language that has imperative style. JavaScript can fake classes and inheritance, but they aren't well-supported first class concepts. As such, you'll naturally hit some walls when you want to express ideas that way. There are some good treatments of JavaScript as OOP around the Internet. Chances are good that if you're hitting your head against a wall with JavaScript, somebody else before you did as well.

Also, I would be most grateful if someone could explain me why the interpreter doesn't allow synonymous global/local variables to share the same scope, when there is certainly a way he could distinguish one from the other.

The dynamic type system means that the interpreter cannot say what the type of bar is. As a bonus side note, JavaScript also performs hoisting automatically.

When I executed your example code, I got a complaint because foo is an immediately invoked function expression, so bar isn't defined at that point.

```<code>TypeError: bar is not a function
var wth = bar();
</code>```

But suppose that wasn't the case. When you assign wth to bar(), it sees that you're attempting to invoke bar as a callable. function bar() is almost syntactic sugar for var bar = function(). Note the link in Neil's comment for why it's "almost."

The type system cannot differentiate between var bar = 5; and var bar = function() { return 5; } because you can do evil things like the following:

```<code>var i = 5;
console.log(typeof i);
i = 'hello';
console.log(typeof i);
i = function() { return 'f'; }
console.log(typeof i);
console.log(typeof i());
</code>```

The output will be:

```<code>number
string
function
string
</code>```

This is what I mean by the dynamic type system cannot say what the type of bar is; a variable just holds data and the data has a type. So if you try to do something like:

```<code>var i = 5;
console.log(i());
</code>```

You'll end up with a type error because i isn't a callable and you're trying to use it as one.

Body:
Why should I need to this? Doesn't this break the concept of classes and inheritance? I might not want to loop through the whole prototype, but what if still need some of the attributes/methods from an object's direct parent, for example?

JavaScript is essentially a functional language that has imperative style. JavaScript can fake classes and inheritance, but they aren't well-supported first class concepts. As such, you'll naturally hit some walls when you want to express ideas that way. There are some good treatments of JavaScript as OOP around the Internet. Chances are good that if you're hitting your head against a wall with JavaScript, somebody else before you did as well.

Also, I would be most grateful if someone could explain me why the interpreter doesn't allow synonymous global/local variables to share the same scope, when there is certainly a way he could distinguish one from the other.

The dynamic type system means that the interpreter cannot say what the type of bar is. As a bonus side note, JavaScript also performs hoisting automatically.

When I executed your example code, I got a complaint because foo is an immediately invoked function expression, so bar isn't defined at that point.

TypeError: bar is not a function
var wth = bar();

But suppose that wasn't the case. When you assign wth to bar(), it sees that you're attempting to invoke bar as a callable. function bar() is almost syntactic sugar for var bar = function(). Note the link in Neil's comment for why it's "almost."

The type system cannot differentiate between var bar = 5; and var bar = function() { return 5; } because you can do evil things like the following:

var i = 5;
console.log(typeof i);
i = 'hello';
console.log(typeof i);
i = function() { return 'f'; }
console.log(typeof i);
console.log(typeof i());

The output will be:

number
string
function
string

This is what I mean by the dynamic type system cannot say what the type of bar is; a variable just holds data and the data has a type. So if you try to do something like:

var i = 5;
console.log(i());

You'll end up with a type error because i isn't a callable and you're trying to use it as one.


问:
How should I behave as a developer in a project that's headed for failure?
I am a developer in a 5-member team and I believe our project is headed for disaster. I'll describe why in a moment, but my question is: how should I behave?

The deadline is in 1.5 months, and I feel no matter what we do, this project will fail. I'm of the opinion that we should just terminate the project and stop wasting our time, but politically I think it's impossible for our manager to do that.

What should I do in this case? Should I put in extra effort, or should I just take it easy? And what should I say to the manager?

Reasons this project is headed for failure:

With deadline approaching many of the must-have features are not finished

Application is unstable and very difficult to use

System is very convoluted, code very hard to understand, very difficult to change - Data model is too driven by a complex relational database (100+ tables)

Unclear leadership; the manager responds to new information with major changes

Almost no automated tests or unit test

Heavily depends on other systems, but no integration tests yet

In fact, we actually just inherited this project (along with the mess) around 1-2 months ago from another dev team under the same manager, who has worked on it for a few months.

答:
Work hard; but not at the expense of your family or your health.

Keep a record of all critical design decisions; especially as they pertain to your work.

Keep networking, and keep your options open if the situation becomes too difficult or you become a victim of a mass layoff.

Try not to think of your project as a "failed project". Everyone likes people who stay positive and fight hard in the face of adversity. So for as long as possible, try to be that person. A positive outlook, grit, and determination are always good for the workplace.

If you're anticipating a failed project, then you're anticipating a post-mortem meeting. At the post-mortem meeting, everyone will be held to account. Be prepared to defend all of your code. [Note: As a general rule, you should always write clean code so that it's easy to defend it later.] If you have email or design document that inspired your decisions, then that's even better.

At that post-mortem meeting, try to stay positive; and only present your email and design document evidence if your judgement, effort, or workmanship is called into question.

ContentLicense: CC BY-SA 3.0


问:
Why do so few large websites run a Microsoft stack?
Off the top of my head, I can think of a handful of large sites which utilize the Microsoft stack

Microsoft.com

Dell

MySpace

PlentyOfFish

StackOverflow

Hotmail, Bing, WindowsLive

However, based on observation, nearly all of the top 500 sites seem to be running other platforms.What are the main reasons there's so little market penetration?

Cost?

Technology Limitations?

Does Microsoft cater to corporate / intranet environments more then public websites?

I'm not looking for market share, but rather large scale adoption of the MS stack.

答:
Are you talking about Microsoft Platform or IIS Platform?. Many third party web servers are running on it. Like Apache does also run on windows platform. There are many public facing banking sites like citibank.com and etc using Java as platform. There is some technological limitation. Running Java on IIS is big hard task but IIS is improving and it is now scalable for larger organization. PHP on IIS is working perfectly fine now with Fastcgi support it is faster. With IIS 7/7.5 SEO friendly and open source software like PHP running website is possible.

If you check While Microsoft dominates 34% of total Web Server operating system which compares to Unix is half but they have improved a lot compare to past years and you can see that IIS is improving a lot. You can check following URL:

http://w3techs.com/technologies/overview/web_server/all

Cost?

Yes, Microsoft License is costly compare to NIX environment but if you compare but TCO on linux is higher. Normal System Administrator on Liux cost much more compare to Windows System Administrator.

Technology Limitations?

Till now, MS has technological limitation for large scale organization also Java works very well in enterprise and financial sector website but after IIS 7/IIS 7.5 scenario is changing with Web development environment like .Net framework and Portal like Share Point Portal Microsoft is improving a lot.

Does Microsoft cater to corporate / intranet environments more then public websites?

Yes, with newer version of Windows and IIS Microsoft is catering public websites and they will surely do well in future.

Gaurav Maniar MCP | MCSE | MCST | MCITP | ITILv3 Certified

ContentLicense: CC BY-SA 2.5


问:
Which design pattern would be best for this case?
I have a class, called PolicyProvider, at present with the following (abridged) interface:

```<code>public interface IPolicyProvider
{
    List<Policy> GetRenewalPolicies(Client client, int financialYear);
}
</code>```

The purpose is quite obvious - every year, the insurance renews for the client, and they will get a number of new policies.

The thing is, the policies change year by year.  Therefore, a concrete implementation of the class needs to be changed every year (or amended with lots of ugly little "if's" evaluating the financial year).  I can see that over time this will become horrendous.

In this case, what design pattern is most appropriate?

答:
You should use the Domain Model Pattern because "policies" (especially as you've described them) are subject to frequent change and you need to keep them sufficiently isolated so that you will not confuse or disrupt the "normal" path of execution.

Reasons to Use the Domain Model

In those cases where the behavior of the business is subject to a lot of change, having a domain model will decrease the total cost of those changes. Having all the behavior of the business that is likely to change encapsulated in a single part of our software decreases the amount of time we need to perform a change because it will all be performed in one place. By isolating that code as much as possible, we decrease the likelihood of changes in other places causing it to break, thus decreasing the time it takes to stabilize the system.


问:
Is it poor programming practice to pass parameters as Objects?
So, we've got a guy who likes to write methods that take Objects as parameters, so they can be 'very flexible.' Then, internally, he either does direct casting, reflection or method overloading to handle the different types.

I feel like this is a bad practice, but I can't explain exactly why, except that it makes it more difficult to read. Are there other more concrete reasons why this would be a bad practice? What would those be?

So, some folks have asked for an example. He has an interface defined, something like:

```<code>public void construct(Object input, Object output);
</code>```

And he plans to use these by putting several in a list, so it sort of builds bits and adds them to the output object, like so:

```<code>for (ConstructingThing thing : constructingThings)
    thing.construct(input, output);
return output;
</code>```

Then, in the thing that implements construct, there is a rickety reflection thing that finds the right method that matches the input/output and calls it, passing input/output.

I keep telling him, it works, I understand it works, but so does putting everything into a single class. We're talking about reuse and maintainability, and I think he's actually constraining himself and has less reuse than he thinks. The maintainability, while probably high for him right now, will likely be very low for him and anyone else in the future.

答:
I actually had to work on a package like that once, it was a GUI package--the designer said he came from a Pascal background and thought passing around nothing but a base class everywhere was an awesome idea.

In 20 years, working with this toolkit was one of the most annoying experiences of my career.

Until you have to work with code like that you don't notice how much you rely on the data types in your parameters to guide you. If I said I had a method "connect(Object dest)", what does it mean?  Even if you see "connect(Object website)" it's not much help, but "connect(String website)" or "connect(URL website)" you don't even have to think about it.

You might think "connect(Object website)" is a GREAT idea because it can take a string or a URL, but that just means I have to guess which cases the programmer decided to support and which he didn't.  At best it moves most of the trial and error part of development from coding time to compile time, at worst it it make the whole development process muddy and annoying.

I (And most Java programmers, I believe) constantly figure out API call chains by examining a group of parameters to constructors to see which constructor to use, then how to build the objects you need to pass until you get to objects you have or can make--it's like putting a puzzle together instead of searching crappy documentation for incomplete examples (my pre-java experience with C).

Although building code like a puzzle seems ad-hock, it works amazingly well--all the time.

I know this has been answered, but this was an annoying enough experience that I really felt motivated to make sure as few people as possible need to go through it again.

OwnerDisplayName: Risser


问:
Naming functions that retrieve a value
I have this personal rule to start all function/method names with a verb. My verb of choice for functions or methods that get a value based on some data structure or object is get. I'm wondering if that's a good idea.

The good thing about get is that it doesn't really say anything about how that value is being retrieved, just get it. Something like calculate (apart from being awfully long) may be too much information.

This applies to both functions and methods, i.e.:

```<code>float get_magnitude(Vector2d vector)
{
    return sqrt(pow(vector.x, 2), pow(vector.y, 2));
}
</code>```

or

```<code>float Vector2d::get_magnitude() const
{
    return sqrt(pow(x, 2), pow(y, 2));
}
</code>```

On the other hand, I sometimes end up with getter methods for read-only properties. It may make sense to use a more meaningful verb for anything that doesn't just return some property, and may not run in linear time.

Is there a case to be made for either approach or is it just a matter of taste?

答:
For methods aimed at retrieving a value, some people just omit the verb, considering that this is just an access to a property:</p>

```<code>float Celsius() { return self.celsius; }

float Fahrenheit() { return self.celsius * 9.0/5.0 + 32.0; }
</code>```

Title: Naming functions that retrieve a value

Body:
For methods aimed at retrieving a value, some people just omit the verb, considering that this is just an access to a property:

float Celsius() { return self.celsius; }

float Fahrenheit() { return self.celsius * 9.0/5.0 + 32.0; }


答:
Consistent clear naming is good, so "get_thingy()" is good, but I don't see that read only versus mutable makes any difference here as you are only "reading" the value.

I like "of" as a suffix id you need to pass a parameter as in "get_square_of(3)", and, if you know there is a lot more involved than a simple retrieval or calculation then maybe another verb like "obtain" can be used to indicate this as in "obtain_meaning_of_life()", also some people favor "retrieve_" to indicate the method involves some sort of I/O or external interaction.

Title: Naming functions that retrieve a value

Body:
I have this personal rule to start all function/method names with a verb. My verb of choice for functions or methods that get a value based on some data structure or object is get. I'm wondering if that's a good idea.

The good thing about get is that it doesn't really say anything about how that value is being retrieved, just get it. Something like calculate (apart from being awfully long) may be too much information.

This applies to both functions and methods, i.e.:

```<code>float get_magnitude(Vector2d vector)
{
    return sqrt(pow(vector.x, 2), pow(vector.y, 2));
}
</code>```

or

```<code>float Vector2d::get_magnitude() const
{
    return sqrt(pow(x, 2), pow(y, 2));
}
</code>```

On the other hand, I sometimes end up with getter methods for read-only properties. It may make sense to use a more meaningful verb for anything that doesn't just return some property, and may not run in linear time.

Is there a case to be made for either approach or is it just a matter of taste?


答:
Consistency in naming functions is good, but you can also overdo it.

If every function that returns a value is called getSomething, you are probably overdoing it. My advise would be to reserve the get prefix for things that are conceptually properties of the object that the function works on, even if the value is not explicitly stored in the object (like the get_magnitude in your example).

If returning a value is not the most important aspect of the function, but merely a side-effect of the function's true purpose or design, then I would name the function after what it does. For example, there is no way that I would give C's fopen function a get prefix, even though the function returns an important value (a handle to the file just opened).

Title: Naming functions that retrieve a value


答:
Hmmm ... Well it's almost always a personal preference isn't it. In general, I think that naming conventions should be such that not only I understand what's going on in my source code, but also so does whoever else comes across my code.  Also, I tend to be a minimalist in code documentation; unless I am doing something very tricky, my code should be smart enough to explain itself to me even if I see it 3 years from when I wrote it in a drunken stupor. So consistency across your projects, for internal sanity is important too.

For instance, when I use C on *nix systems, I invariably use 0 as success and negative numbers for flagging failures; with the exception on I/O functions where return is size_t; then positive number is amount of I/O; 0 is a halt on I/0 and (size_t)-1 is a fault with errno set to a system error;  this is consistent with C library behavior on the systems so I know that everyone will understand what is going on.

When I used to write programs under Win32 using C the convention of Win32 was a bit different and I followed that convention. There, the names use camelCase in C (which is annoying to me but I follow it) and use Hungarian notation (which is even MORE annoying) but I stick to using that.

However if I were to write equivalent code in C++ I would switch the way I report errors. Throwing exceptions or using boolean return values for simpler methods.

If I am in kernel programming mode, then I use the conventions used by kernel developers;

I figure that I do NOT want to spend time explaining my code to others (which includes me 3 - 5 years from now because I'd have changed) so I use the dialect that they'd understand on their own rather than me having to explain MY logic to them (they really aren't that smart, and I am getting stupider by the year).

I think whatever you use, keep it consistent along some logic path that can survive across languages, across systems and your growth between now and 10 years from now.

Title: Naming functions that retrieve a value


问:
What UML diagram should I use to show a platform's architecture?
I have been learning UML and have a basic understanding now, but I keep seeing these sort of high level architecture diagrams. Here's one from Microsoft:

Source: A bad picture is worth a thousand long discussions.

Is this a UML diagram? Are there any rules to follow for creating these types of diagrams?

I would like to represent something similar, i.e. the realtionship between different installed systems / APIs... i.e. Platform architecture.

答:
The more appropriate UML diagram to depict a platform's architecture is a component diagram. If you want to go a level lower, then you'd also need to draw one or more package diagrams, and perhaps even a deployment diagram.

The diagram you linked to is not a UML diagram, it's a "marchitecture / marketecture" diagram. It's not really supposed to be technically accurate, its main purpose is to look good on a presentation slide. You can of course chose to go with such a diagram instead of a more formal UML diagram, however there aren't any concrete rules on how to draw them. It should convey a basic idea of your components and how they work together, and... look good ;)


问:
What aspects should I be wary of when choosing a web development framework?
I am a relatively new to the world of software development and I've used the Ruby on Rails framework to develop relatively simple applications before. I know that frameworks can be extremely useful in terms of getting applications up and running quite quickly. </p>

<p>However I also know about the well documented problems that Rails had in terms scalability, and I was wondering if there were any other factors that I should be wary of before deciding to use a web frameworks in general aside from scalability, particularly when designing non-trivial business applications.  </p>

答:
First and foremost, I would look for a framework that

has an active, helpful community

is well-documented

is written in a way you understand

has a history of responding quickly to bugs in general and security problems in particular

It is important that you understand what the framework does. While a framework helps you to avoid boilerplate code and also often gives you a hand up with structuring your application, like any abstraction layer, you still need to understand how it works and what that means for your application (in regards to structure, performance, security...). So look for a framework you feel comfortable with and that does not look like lots of voodoo magic to you.


问:
Choosing how to approach Geocoding Requests
I am about to begin writing a program in c# that will read Addresses from a source file create a Geocoding request, sent it to Google Maps API, get the response choose the coordinates from the xml and then store them in a database.

My question is what is the proper type of source file considering performance and easy implementation.

I have the option to supply the source addresses as txt file or xml file.
The number of addresses need to get geolocated is about 100.000 which is a big number so what is the proper approach to handling this kind of requests?
Should i provide the addresses source file as txt or xml or something else?

答:
Question: I have the option to supply the source addresses as TXT file or XML file.
Answer: I would use an XML file because it's a standard document type and you can serialize it inside any language or database.

When you get an address file as a XML you might have something like this.

```<code><addresses>
    <address></address>
    <address></address>
</addresses>
</code>```

So when you have an XML file like that you could serialize it into a C# object as a list of addresses and loop though that list and get he info from Google. That can be stored into a database.

The only bottleneck would be your looping algorithm. A standard for loop you will have a worst case of O (n) in this case O(100). However there are other algorithms out there which could decrease that to a O(log n).

Hope this helps?

Body:
Question: I have the option to supply the source addresses as TXT file or XML file.
Answer: I would use an XML file because it's a standard document type and you can serialize it inside any language or database.

When you get an address file as a XML you might have something like this.

<addresses>
    <address></address>
    <address></address>
</addresses>

So when you have an XML file like that you could serialize it into a C# object as a list of addresses and loop though that list and get he info from Google. That can be stored into a database.

The only bottleneck would be your looping algorithm. A standard for loop you will have a worst case of O (n) in this case O(100). However there are other algorithms out there which could decrease that to a O(log n).

Hope this helps?


问:
MVC framework that uses classes instead of methods for actions
In most MVC frameworks, Controller class contains multiple methods, each representing one action. Then annotations and reflection is used to call those methods appropriately. But from OOP point of view, the whole class has many responsibilities, eg. one for each action. Then each action should be represented by it's own class.

Does MVC framework that implements actions like this exist? And is there some kind of discussion that discusses pros and cons of both approaches?

I believe it would be much cleaner to do it class-way, because it would allow simple extensibility through inheritance without need for annotations. But there would be 'overhead' of many more classes, making it harder to maintain the code.

答:
To make it clear, what you're talking about with "expressing methods through classes" is incarnated in the Command Pattern (http://en.wikipedia.org/wiki/Command_pattern).

Many implementations of MVC pattern use the Command Pattern in order to turn the controller less monolithic. An example for an implementation in Java is avant (http://code.google.com/p/avant/).

Well, from the OOP point of view, there are quite a lot of pros:

Monolithic classes (many responsibilities) violate the Seperation of Concerns principle and the associated quality maintainability

By using the Command Pattern and its interface, it's easy to extend your controller by new commands

If you'd like to implement something like an undo operation, you could as well do it with the command pattern easily

Incarnating methods to objects lay the groundwork for decoupling, since you can pass the command objects around and invoke them at the appropriate place in your program

A small con exists though:

The pros don't come for nothing: you have to write a class for each and every method, that's kind of overhead and might blur the application's big picture in huge applications


问:
Dataset with coordinates of borders of countries
I am creating an application that visually displays world regions, e.g. to place markers within an administrative region.

Does a dataset exist with geometrical or geographical (long/lat) descriptions of the world's current country borders (and possibly other administrative divisions)?  Ideally the dataset would be in a format that I could easily generate border images of the size that I require.

答:
http://gadm.org/ seems to have exactly what you want (and more).

GADM database of Global Administrative Areas

GADM is a spatial database of the location of the world's administrative areas (or adminstrative boundaries) for use in GIS and similar software. Administrative areas in this database are countries and lower level subdivisions such as provinces, departments, bibhag, bundeslander, daerah istimewa, fivondronana, krong, landsvæðun, opština, sous-préfectures, counties, and thana. GADM describes where these administrative areas are (the "spatial features"), and for each area it provides some attributes, such as the name and variant names...


问:
OOP Design: relationship between entity classes
I have at first sight a simple issue but can't wrap my head around on how to solve. I have an abstract class Compound. A Compound is made up of Structures. Then there is also a Container which holds 1 Compound.

A "special" implementation of Compound has Versions. For that type of Compound I want the Container to hold the Versionof the Compound and not the Compound itself.

You could say "just create an interface Containable" and a Container holds 1 Containable. However that won't work. The reason is I'm creating a framework and the main part of that framework is to simplify storing and especially searching for special data type held by Structure objects. Hence to search for Containers which contain a Compound made up of a specific Structure requires that the "Path" from Containerto Structure is well defined (Number of relationships or joins).

I hope this was understandable. My question is how to design the classes and relationships to be able to do what I outlined.

EDIT:

Kind of translation issue. with version i did not mean in terms of "versioning" but more in terms of "different variety" but fundamentally the same. There is no active / inactive. All are active.

EDIT 2:

Also note that these classes are entity classes and hence complex inheritance and hierarchies can be problematic.

EDIT 3:

Just don't see how either pattern (Composite, decorator) can work. I tried but the problem is the "path traversal", eg. implementing it in the context of Spring-data and QueryDSL.

I've created Class diagramm with comments that might help to understand the issue. Batch = Version.

答:
The solution I used is this:

And to reference the image in the question, a Batch extends Containable.


问:
Need advice on framework design: how to make extending easy
I'm creating a framework/library for a rather specific use-case (data type). It uses diverse spring components, including spring-data. The library has a set of entity classes properly set up and according service and dao layers. The main work or main benefit of the framework lies in the dao and service layer.

Developers using the framework should be able to extend my entity classes to add additional fields they require. Therefore I made dao and service layer generic so it can be used by such extended entity classes.

I now face an issue in the IO part of the framework. It must be able to import the according "special data type" into the database. In this part I need to create a new entity instance and hence need the actual class used. My current solution is to configure in spring a bean of the actual class used. The problem with this is that an application using the framework could only use 1 implementation of the entity (the original one from me or exactly 1 subclass but not 2 different classes of the same hierarchy.

I'm looking for suggestions / designs for solving this issue. Any ideas?

EDIT:

only idea I have is to add a parameter to the affected methods that takes a Class object. That would be the easy and pragmatic solution but it seems very ugly?

答:
I now use a completely different solution, namely for each entity a separate service must be created. That service can extend the one provided by my framework and optional add additional methods. This gets rids of the configuration above because you don't need any constructor arguments anymore:

```<code><bean id="testCompoundService"  autowire="byType"
      class="TestCompoundServiceImpl">
</bean>

<bean id="registrationCompoundService"  autowire="byType"
      class="RegistrationCompoundServiceImpl">
</bean>
</code>```

and the default constructor:

```<code>public TestCompoundServiceImpl() {
    super(TestCompound.class);
}
</code>```

Body:
I now use a completely different solution, namely for each entity a separate service must be created. That service can extend the one provided by my framework and optional add additional methods. This gets rids of the configuration above because you don't need any constructor arguments anymore:

<bean id="testCompoundService"  autowire="byType"
      class="TestCompoundServiceImpl">
</bean>

<bean id="registrationCompoundService"  autowire="byType"
      class="RegistrationCompoundServiceImpl">
</bean>

and the default constructor:

public TestCompoundServiceImpl() {
    super(TestCompound.class);
}


问:
Using a try-finally (without catch) vs enum-state validation
I have been reading the advice on this question about how an exception should be dealt with as close to where it is raised as possible.

My dilemma on the best practice is whether one should use a try/catch/finally to return an enum (or an int that represents a value, 0 for error, 1 for ok, 2 for warning etc, depending on the case) so that an answer is always in order, or should one let the exception go through so that the calling part would deal with it?

From what I can gather, this might be different depending on the case, so the original advice seems odd.

For example, on a web service, you would always want to return a state of course, so any exception has to be dealt with on the spot, but lets say inside a function that posts/gets some data via http, you would want the exception (for example in case of 404) to just pass through to the one that fired it. If you don't, you would have to create some way to inform the calling part of the quality of the outcome (error:404), as well as the outcome itself.

Though it IS possible to try-catch the 404 exception inside the helper function that gets/posts the data, should you? Is it only I that use a smallint to denote states in the program (and document them appropriately of course), and then use this info for sanity validation purposes (everything ok/error handling) outside?

Update: I was expecting a fatal/non-fatal exception for the main  classification, but I didn't want to include this so as not to prejudice the answers. Let me clarify what the question is about: Handling the exceptions thrown, not throwing exceptions. What the desired effect is: Detect an error, and try to recover from it. If recovery isn't possible, provide the most meaningful feedback.

Again, with the http get/post example, the question is, should you provide a new object that describes what happened to the original caller? If this helper was in a library you are using would you expect it to provide you with a status code for the operation, or would you include it in a try-catch block? If you are designing it, would you provide a status code or throw an exception and let the upper level translate it to a status code/message instead?

Synopsis: How do you chose if a piece of code instead of producing an exception, returns a status code along with any results it may yield?

答:
I used a combination of both solutions: for each validation function, I pass a record that I fill with the validation status (an error code). At the end of the function, if a validation error exists, I throw an exception, this way I do not throw an exception for each field, but only once.

I also took advantage that throwing an exception will stop execution because I do not want the execution to continue when data is invalid.

For example

```<code>procedure Validate(var R:TValidationRecord);
begin
  if Field1 is not valid then
  begin
    R.Field1ErrorCode=SomeErrorCode;
    ErrorFlag := True;
  end;
  if Field2 is not valid then
  begin
    R.Field2ErrorCode=SomeErrorCode;
    ErrorFlag := True;
  end;
  if Field3 is not valid then
  begin
    R.Field3ErrorCode=SomeErrorCode;
    ErrorFlag := True;
  end;

  if ErrorFlag then
    ThrowException
end;
</code>```

If relying on boolean only, the developer using my function should take this into account writing:

```<code>if not Validate() then
  DoNotContinue();
</code>```

but he may forgot and only call Validate() (I know that he should not, but maybe he might).

So, in the code above I gained the two advantages:

Only one exception in the validation function.

Exception, even uncaught, will stop the execution, and appear at test time

Body:
I used a combination of both solutions: for each validation function, I pass a record that I fill with the validation status (an error code). At the end of the function, if a validation error exists, I throw an exception, this way I do not throw an exception for each field, but only once.

I also took advantage that throwing an exception will stop execution because I do not want the execution to continue when data is invalid.

For example

procedure Validate(var R:TValidationRecord);
begin
  if Field1 is not valid then
  begin
    R.Field1ErrorCode=SomeErrorCode;
    ErrorFlag := True;
  end;
  if Field2 is not valid then
  begin
    R.Field2ErrorCode=SomeErrorCode;
    ErrorFlag := True;
  end;
  if Field3 is not valid then
  begin
    R.Field3ErrorCode=SomeErrorCode;
    ErrorFlag := True;
  end;

  if ErrorFlag then
    ThrowException
end;

If relying on boolean only, the developer using my function should take this into account writing:

if not Validate() then
  DoNotContinue();

but he may forgot and only call Validate() (I know that he should not, but maybe he might).

So, in the code above I gained the two advantages:

Only one exception in the validation function.

Exception, even uncaught, will stop the execution, and appear at test time


答:
There isn't one answer here -- kind of like there isn't one sort of HttpException.

It makes alot of sense that the underlying HTTP libraries throw an exception when they get a 4xx or 5xx response; last time I looked at the HTTP specifications those were errors.

As for throwing that exception -- or wrapping it and rethrowing -- I think that really is a question of use case. For example, if you are writing a wrapper to grab some data from the API and expose it to applications you could decide that semantically a request for a non-existent resource that returns a HTTP 404 would make more sense to catch that and return null. On the other hand a 406 error (not acceptable) might be worth throwing an error as that means something has changed and the app should be crashing and burning and screaming for help.

Title: Using a try-finally (without catch) vs enum-state validation

Body:
I have been reading the advice on this question about how an exception should be dealt with as close to where it is raised as possible.

My dilemma on the best practice is whether one should use a try/catch/finally to return an enum (or an int that represents a value, 0 for error, 1 for ok, 2 for warning etc, depending on the case) so that an answer is always in order, or should one let the exception go through so that the calling part would deal with it?

From what I can gather, this might be different depending on the case, so the original advice seems odd.

For example, on a web service, you would always want to return a state of course, so any exception has to be dealt with on the spot, but lets say inside a function that posts/gets some data via http, you would want the exception (for example in case of 404) to just pass through to the one that fired it. If you don't, you would have to create some way to inform the calling part of the quality of the outcome (error:404), as well as the outcome itself.

Though it IS possible to try-catch the 404 exception inside the helper function that gets/posts the data, should you? Is it only I that use a smallint to denote states in the program (and document them appropriately of course), and then use this info for sanity validation purposes (everything ok/error handling) outside?

Update: I was expecting a fatal/non-fatal exception for the main  classification, but I didn't want to include this so as not to prejudice the answers. Let me clarify what the question is about: Handling the exceptions thrown, not throwing exceptions. What the desired effect is: Detect an error, and try to recover from it. If recovery isn't possible, provide the most meaningful feedback.

Again, with the http get/post example, the question is, should you provide a new object that describes what happened to the original caller? If this helper was in a library you are using would you expect it to provide you with a status code for the operation, or would you include it in a try-catch block? If you are designing it, would you provide a status code or throw an exception and let the upper level translate it to a status code/message instead?

Synopsis: How do you chose if a piece of code instead of producing an exception, returns a status code along with any results it may yield?


问:
Overriding - Access to Members with Reference Reassignment
I have recently been moving through a couple of books in order to teach myself Java and have, fortunately, mostly due to luck, encountered very few difficulties. That has just changed.

I read a section on the following under inheritance and the whole superclass subclass setup

When a new superclass object is created, it is, like all objects, assigned a reference (superReference in this example)

If a new subclass object (with the defining subclass extending the superclass) is created, and then the superReference reference is set to refer to that instead of the original object, it is my understanding that, since the reference is made for a superclass, only members defined by the superclass may be accessed from the subclass.

First - is this correct?

Second:
If I am overriding a method and therefore have one in the super and one in the sub, and I create a superclass object and then assign its reference, as I did above, to a subclass object, by the principle called something like Dynamic Method Dispatch, a called overridden method should default to accessing the subclass method right?

Well, my question is:

If a reference to a superclass-object is retooled for a subclass-object and will deny direct object.member access to subclass-defined members, only supporting superclass-defined members, how can, if a superclass reference is retooled for a subclass object, an overridden method apply to the subclass-object if access is limited by the superclass-originated-reference

答:
If you look at the Java Language Specification (http://docs.oracle.com/javase/specs/) you will find a distinction between the static type and the dynamic type of object references.

The static type of any reference refers to the type declared in your program at development time.

The dynamic type of the reference refers to the type of object which is actually stored at the reference address at runtime.

So if you have a simple hierarchy, where A is the superclass and B is a subclass of A.

```<code>class A {
  public String a = "super";
  void m() {...}
}

class B extends A {
  public String a = "sub";
  @Override
  void m() {...}
}

A refA = new A();
A refB = new B();
B refB2 = new B();
refA.m();
refB.m();
System.out.println(refA.a);
System.out.println(refB.a);
System.out.println(refB2.a);
</code>```

For example, refB's static type is A but its dynamic type is B. What does this imply at runtime?

Instance variables are statically bound, i.e. you can only access the instance variables of the static type, so the first two println() statements will print "super", since A is the static type of refA and refB. The last println() statement will in contrast print "sub", because in this case B is the static type.

Methods are dynamically bound, i.e. the invoked method is first searched in the dynamic type of the reference and if it isn't found, the class hierarchy is traversed up until a definition of the overriden method is found (this mechanism is called dynamic dispatch). This means that in case refA.m() method void m() of A is invoked and in case refB.m(), void m() of B is invoked.

Body:
If you look at the Java Language Specification (http://docs.oracle.com/javase/specs/) you will find a distinction between the static type and the dynamic type of object references.

The static type of any reference refers to the type declared in your program at development time.

The dynamic type of the reference refers to the type of object which is actually stored at the reference address at runtime.

So if you have a simple hierarchy, where A is the superclass and B is a subclass of A.

class A {
  public String a = "super";
  void m() {...}
}

class B extends A {
  public String a = "sub";
  @Override
  void m() {...}
}

A refA = new A();
A refB = new B();
B refB2 = new B();
refA.m();
refB.m();
System.out.println(refA.a);
System.out.println(refB.a);
System.out.println(refB2.a);

For example, refB's static type is A but its dynamic type is B. What does this imply at runtime?

Instance variables are statically bound, i.e. you can only access the instance variables of the static type, so the first two println() statements will print "super", since A is the static type of refA and refB. The last println() statement will in contrast print "sub", because in this case B is the static type.

Methods are dynamically bound, i.e. the invoked method is first searched in the dynamic type of the reference and if it isn't found, the class hierarchy is traversed up until a definition of the overriden method is found (this mechanism is called dynamic dispatch). This means that in case refA.m() method void m() of A is invoked and in case refB.m(), void m() of B is invoked.


问:
Is it possible to use the Intel C/C++ compiler on Linux to create object files to be linked on Windows?
Why?

Depending on your source the Intel compiler is likely or most definitely the compiler generating the fastest executables for the x86 architecture (5 to 100 % execution time improvement).

Intel offers its compilers for Linux under a non-commercial license for free (I think I read it is free somewhere on their page: Intel - Non-Commercial Software Development).
There is also a free non-commercial license for students, but this license is not applicable although tools are offered for all three major operating systems (link dropped  due to reputation restriction).

Goal

I (as a non-student) would like to be able to use the Intel compilers for possible execution speed improvements under the non-commercial license to compile object files that can be linked to create executables and dynamic link libraries for Windows (and possibly OS X)

More Details:

What I inferred from this document is that the Intel compilers create object files that are compatible to the dominant compilers of the platform.

Sub-questions:

What are the object file formats of gcc, g++, cl, mingw32, icc, icpc, and icl on Windows and Linux (current versions)?

Could parts of the mingw32 cross-compiler toolchain be used to accomplish the goal?

Am I right that the metadata in the generated object files is the main issue?

ad 2:

mingw32-objcopy seems to be able to convert the Intel compiler output on Linux (presumably ELF) to Microsoft-compatible COFF (with the possible exception of relocateable object files). Could someone confirm that this actually works (for non-trivial applications), please?

答:
The answer is almost certainly yes. I know that cross-compiling Windows binaries (via mingw32) on a Linux box is easily possible using gcc - obviously you won't be able to run the program on Linux (unless it works under Wine), but I know several programs that get Windows binaries this way.

However, I don't know if the Intel compiler has the options for this, I should think it does.

The object format for Windows is PE, whereas for Linux its ELF.


问:
How do the Application and Database Interface Layers interact at their boundary?
I was watching one of Uncle Bob's videos and he brought up the Database Interface Layer.  He had this diagram showing it:

These arrows show that the DB Interface Layer is aware of and calls the Application and Database layer, but not vice versa.

The DB Interface Layer has "data records" in it.  These are "classes" that have the name of the table and the fields of the columns.  These are what I usually call DTOs.  But these data records have all public fields and no/few methods.

The DB Interface layer is responsible for grabbing the data from the database, populating the "data records" and implementing an interface in the Application Layer like so:

I'm a little confused because I've never heard about this separation before.  Every project I've worked on uses the DTOs in the view which is apparently wrong (at least according to Uncle Bob's video).

Also, I've never worked on a project where the DB Interface Layer calls the Application Layer.  It's always the Application layer asking the DB Interface Layer for information.  For example, by using a DAO.

But this is starting to make sense.  Whenever I use hibernate I'm always pulling my hair out because I try to make the DTOs more OO and the library always fights me.

So, I guess what I'm trying to ask is, what does the code look like on/at the boundary between the Application and the Database Interface Layer?  For example, how does the Application get the implementation of the Order Gateway Implementation?  Is the Order Gateway Implementation a DAO?  I don't have a clear picture of how the POS can use the Order Gateway vs how/when the Order Gateway gets populated with data.

答:
I think you interpreted the pictures in a wrong way! The arrows do not represent call direction in my opinion.

When you look at the 2nd picture, it's obvious that Order Gateway Implementation implements the Order Gateway interface and objects of type Order Gateway are used from the client type POS. So the actual direction of call is top down as you would expect it.

This is just an application of the Strategy Pattern in order to separate your database structure which lies inside the DB I/F layer from its interface the application layer uses.
If you hadn't the DB I/F layer your application layer would probably directly access specific DB structures, which would definitely not be the right way to go in being flexible with the DB technology.

Edit:

Well, let's bring the notion of DTOs to our mind: Those are objects containing certain amounts of data (no behaviour) aggregated for a specific purpose, usually to push them over the net in distributed systems. Although they're used in this context as Order Table and Line Item Table, there is no contradiction to using DTOs for views since views are also usually only bound to data.

The DAO's purpose is in the first place to encapsulate as much as possible from data source technologies. Since the DAO isn't only a single object, but a pattern including the interface and its implementation, you can map the DAO pattern directly to Order Gateway interface and Order Gateway Implementation resulting in no dependencies from application layer to specific data structures.


问:
Objective C - nested messages ... confusion about
Wonder if anyone could shed some light on this messaging construct:

The documentation says that messages appear btwn brackets [] and
that the msg target/object is on the left, whilst the msg itself (and any parameters) is on the right:

[msgTarget msg], e.g., [myArray insertObject:anObject atIndex:0]

OK, simple enough... but then they introduce the idea that it's convenient to nest msgs in lieu of the use of temporary variables--I'll take their word for it--so the above example becomes:

[[myAppObject theArray] insertObject:[myAppObject objectToInsert] atIndex:0]

In other words, [myAppObject theArray]  is a nested msg, one, and, two, 'theArray' is the 'message'.  Well, to say I find this confusing is a bit of an understatement ... Maybe it's just me but 'theArray' doesn't evoke a message semantically or grammatically.  What this looks like to a guy who knows Java is a type/class.  In Java we do things like

Class objectInstance = new Class() ...

the bit to the left of the assignment operator is what this so-called nested message reminds me of ... with object and class/type positions switched of course.  Anyway, any insight much appreciated.

答:
In Objective-C, by convention, you refer to properties with dot notation. Thus, you write myAppObject.theArray instead [myAppObject theArray].

In Objective-C the default getter is the name of the variable instead getVariable. For example, writing

```<code>@property NSArray *theArray;
</code>```

creates an instance variable _theArray and generates the following accessor:

```<code>-(NSArray*) theArray { return _theArray; }
</code>```

So by sending theArray as a message you are actually invoking a method. But again, use only dot notation for properties.

Body:
In Objective-C, by convention, you refer to properties with dot notation. Thus, you write myAppObject.theArray instead [myAppObject theArray].

In Objective-C the default getter is the name of the variable instead getVariable. For example, writing

@property NSArray *theArray;

creates an instance variable _theArray and generates the following accessor:

-(NSArray*) theArray { return _theArray; }

So by sending theArray as a message you are actually invoking a method. But again, use only dot notation for properties.


问:
Is it a good idea to put declaration of protocols for delegates in a private category interface?
I have a View Controller or a View that implements delegate and dataSource methods of UITableView.

These methods are not going to be used outside this class.

So is it a good idea to make the declaration of the UITableViewDataSource and UITableViewDelegate inside the .m file with a private category?

For example :

Instead of doing this:

MyViewController.h

```<code>@interface MyViewController:UIViewController<UITableViewDataSource,UITableViewDelegate>
{}
@end
</code>```

I put the declaration in the private category inside as there is no need for other objects to know whether my View Controller uses a TableView or not.

MyViewController.m

```<code>@interface MyViewController()<UITableViewDataSource,UITableViewDelegate>
@end
</code>```

and Implementation in the .m file being the same in both the cases.

答:
Technically, it's of no consequence. Interface Builder will recognize that your class implements the protocols and offer a connection.

Apple code puts the protocols implemented in the header, and it's common practice. So anyone browsing your code will expect to see them there.

I think you are over thinking it hiding the protocols. I can't imagine an scenario where it is harmful to expose that information. Can you?


答:
So is it a good idea to make the declaration of the
  UITableViewDataSource and UITableViewDelegate inside the .m file with
  a private category?

That depends. Is the fact that MyViewController these protocols a private implementation detail, or something that you want to communicate to anyone using the class?

Header files are there to communicate your class's public interface, not just to the compiler but also to anyone using the class. If you would include the fact that your class implements a given protocol in the written documentation, then you should declare the use of the protocol in the header. If you wouldn't put that in the docs, and instead want to send the message that nobody should count on the class implementing that protocol, put it in the implementation file.

Title: Is it a good idea to put declaration of protocols for delegates in a private category interface?

Body:
I have a View Controller or a View that implements delegate and dataSource methods of UITableView.

These methods are not going to be used outside this class.

So is it a good idea to make the declaration of the UITableViewDataSource and UITableViewDelegate inside the .m file with a private category?

For example :

Instead of doing this:

MyViewController.h

```<code>@interface MyViewController:UIViewController<UITableViewDataSource,UITableViewDelegate>
{}
@end
</code>```

I put the declaration in the private category inside as there is no need for other objects to know whether my View Controller uses a TableView or not.

MyViewController.m

```<code>@interface MyViewController()<UITableViewDataSource,UITableViewDelegate>
@end
</code>```

and Implementation in the .m file being the same in both the cases.


问:
Issue deploying Asp.Net MVC 4 website to Azure
How do you deploy your website in Azure so that it looks exactly like when you run it in your localhost? This is a very simple website that I created following the ASP.NET MVC4  tutorials. However, I added a new background image and it doesn't show. Is there anything else I need to do to make sure all of my files are being deployed?

Here is the code that "should" be on my site. This is the pone in my solution.

```<code> <head profile="http://gmpg.org/xfn/11">
 <title>LOTUS Marketing Solutions</title>
 <meta http-equiv="Content-Type" content="text/html; charset=iso-8859-1" />
 <meta http-equiv="imagetoolbar" content="no" />
 <link href="~/favicon.ico" rel="shortcut icon" type="image/x-icon" />
 <meta name="viewport" content="width=device-width" />
 <link rel="stylesheet" href="Content/Site.css" type="text/css" />
 <script type="text/javascript" src="Scripts/jquery-1.4.1.min.js"></script>
 <script type="text/javascript" src="Scripts/jquery.jcarousel.pack.js"></script>
 <script type="text/javascript" src="Scripts/jquery.jcarousel.setup.js"></script>
 @Styles.Render("~/Content/css")
 @Scripts.Render("~/bundles/modernizr")
 </head>
</code>```

this is what I "actually" showing on the site view source code

```<code>  <head>
    <meta charset="utf-8" />
    <title>Home Page - LOTUS Marketing Solutions</title>
    <link href="/favicon.ico" rel="shortcut icon" type="image/x-icon" />
    <meta name="viewport" content="width=device-width" />
    <link href="/Content/css?v=Zxt_kvPMVcEtaCRbYJCSpGOy25BUARXyn8EetggjSF01" rel="stylesheet"/>

    <script src="/bundles/modernizr?v=qVODBytEBVVePTNtSFXgRX0NCEjh9U_Oj8ePaSiRcGg1"></script>

  </head>
</code>```

clearly, something is wrong. The  contents are not remotely alike!

I was able to pull this out

CA0058 Error Running Code Analysis CA0058 : The referenced assembly 'DotNetOpenAuth.AspNet, Version=4.0.0.0, Culture=neutral, PublicKeyToken=2780ccd10d57b246' could not be found. This assembly is required for analysis and was referenced by: C:\Users\lotusms\Desktop\LOTUS MARKETING\ASP.NET\WebsiteManager\WebsiteManager\bin\WebsiteManager.dll, C:\Users\lotusms\Desktop\LOTUS MARKETING\ASP.NET\WebsiteManager\packages\Microsoft.AspNet.WebPages.OAuth.2.0.20710.0\lib\net40\Microsoft.Web.WebPages.OAuth.dll. [Errors and Warnings] (Global)

CA0001 Error Running Code Analysis CA0001 : The following error was encountered while reading module 'Microsoft.Web.WebPages.OAuth': Assembly reference cannot be resolved: DotNetOpenAuth.AspNet, Version=4.0.0.0, Culture=neutral, PublicKeyToken=2780ccd10d57b246. [Errors and Warnings] (Global)

Could this have something to do with the problem?

答:
It should just work assuming your project solution is correct.

Make sure the file is actually included in the solution (Show all files, right click, include in project).

View the source, is the image tag you have used at least in the HTML?

How are you deploying it?
What output is there in Visual Studio when you do a deploy?

Or are you packaging then uploading on the Azure Management website? Make sure you are uploading the correct package. You may have changed build configuration (built under Release for example) then when you try to upload the package, the Azure wbesite File,Open windows is still defaulted to your packaged debug folder.


问:
Features that encourage use of project management software
I'm a student and I work as an undergrad in an IT department. They are very effective programmers, but as far as documenting what they do and tracking what time is spent on specific tasks - not so much.

I was put in charge of setting up project management software. So far, I've created a satisfactory solution with Trac. But still, programmers use it because "the boss says so" and do so grudgingly.

No one likes having to go to a separate webpage, logging what they did, checking boxes, and what not - so my question is this:

As a programmer, what incentives or features in project management software would encourage you (or least make it more bearable) to use it?

答: I'm one of the developer of Teamwork, for those that did not know it, it is a quite famous project management software. As you may guess, for us, understanding which are the features that make the difference in the adoption is one of the main points. In my experience the adoption of a pm software is very hard, basically because people are lazy to change their routine, moreover because they do not have any benefits in using it. And this has been our focus: we tried to add a lot of features that give benefit not only to the pm but also to the worker. I could list these features but it could not be so important because they depends on how your team works, my suggestion is to find the tool that give as much benefits as possible to the worker. For example, if your team works with issues, try to find the best tool for managing it in a friendly way for the user and so on. Hope it helps!!</p>


问:
Why isn't there a private deployment option for the .NET framework?
Here are reasons why one would want this:
1) We often don't use all the dlls but we force customers to install the entire .NET framework. It would be great to just deploy the dlls we need.

2) We often want to update our application and the framework but that sometimes requires a machine reboot because other applications are using it.

3) A full .NET installation usually takes quite a bit of time. An xcopy type private deployment could be much faster.

It seems to me that mono allows private deployment which solves all these issues.

Thanks

答: One thing that I can think of is that a consistent environment exists for .NET applications if the entire framework is installed. That is not to say that most developers couldn't determine which of the .NET assemblies would have to be present in a private deployment scenario. Installing the framework, however, guarantees that a .NET application will at least successfully start.</p>


答:
Since you are interested in "... some kind of discussion that discusses pros and cons of both approaches" here are my cons:

If you have domainlogic in your controller
( Antipattern Fat Controller )

then you can resolve this by

refactoring the fat controller into seperate fat actionclasses with its own domainlogic or

refactoring the domainlogic from the fat controller into fat models and/or fat services and create a thin controller.

Many developers prefer to have thin MVC Controllers.

If you already have a thin controller then the proposed actionclass would be to small.

Title: MVC framework that uses classes instead of methods for actions

Body:
In most MVC frameworks, Controller class contains multiple methods, each representing one action. Then annotations and reflection is used to call those methods appropriately. But from OOP point of view, the whole class has many responsibilities, eg. one for each action. Then each action should be represented by it's own class.

Does MVC framework that implements actions like this exist? And is there some kind of discussion that discusses pros and cons of both approaches?

I believe it would be much cleaner to do it class-way, because it would allow simple extensibility through inheritance without need for annotations. But there would be 'overhead' of many more classes, making it harder to maintain the code.


答:
There is a simple reason why MS does not like this model - if any program contains its own version of the .NET framework DLLs, Windows Update would not effectively be able to supply any security updates / bug fixes any more for the .NET framework DLLs. And this is not a hypothetical issue: every few months, a new patch or security update for the framework DLLs was deployed by MS in the past.

The situation that MS gave specific run time DLLs to the application vendors, and let the vendors be responsible for deploying and updating the DLLs themselves, is not a new one. For example, the MFC-DLLs, the GDI+ DLLs and some other libraries were often deployed that way. But this almost always lead to a situation where users had troubles in getting important updates for these DLLs. See, for example, here, for the case from 2004 where gdiplus.dll had to be updated - and what trouble that meant for the users, compared to a relatively flawless update using the "Windows Update" mechanisms. From that experience I guess MS came to the conclusion not to give the responsibility for updates out of their hands.

To your arguments:

1) We often don't use all the dlls but we force customers to install the entire .NET framework. It would be great to just deploy the dlls we need.

Newer Windows version already contain .NET FW 3.5 or 4.0  And if not, the framework has to be installed once per machine (ok, 3.5 once and 4.0 once), not again and again for every application which needs it

2) We often want to update our application and the framework but that sometimes requires a machine reboot because other applications are using it.

You typically don't want to update the framework by yourself, Windows Update does that for you. And if you are going to use a newer framework version which so far is not installed on the machine, there obviously cannot be another application using the newer framework so far.

3) A full .NET installation usually takes quite a bit of time. An xcopy type private deployment could be much faster.

Yes, but only once per machine, not once per application.

@BryantB's answer is also true. Especially, because the execution model of .NET assemblies does not check if all needed assemblies are installed before the JITer compiles a function call to one of those assemblies. This means, if you forget to deploy a framework DLL, your program might start flawlessly, but will crash later when the first feature is used which needs the forgotten DLL. This behaviour is quite different from native DLLs (not delay-loaded ones, of course), and would be a dangerous error-trap.

Title: Why isn't there a private deployment option for the .NET framework?

Body:
Here are reasons why one would want this:
1) We often don't use all the dlls but we force customers to install the entire .NET framework. It would be great to just deploy the dlls we need.

2) We often want to update our application and the framework but that sometimes requires a machine reboot because other applications are using it.

3) A full .NET installation usually takes quite a bit of time. An xcopy type private deployment could be much faster.

It seems to me that mono allows private deployment which solves all these issues.

Thanks


答:
It is possible to create Windows executables on a Linux build machine by using a cross-compiler. But, Intel does not provide such cross compilers.

To answer the sub-questions:

What are the object file formats of gcc, g++, cl, mingw32, icc, icpc, and icl on Windows and Linux (current versions)?

The format for the object files is effectively determined by the operating system (or rather, the compiler used to build it). For Windows, this is the Portable Executable (PE) format and for Linux the ELF format.

Could parts of the mingw32 cross-compiler toolchain be used to accomplish the goal?

No. The relevant part is the code generator, which is both the part responsible for generating the right object format and the part on the Intel compilers that gives their generated code the speed edge.

Am I right that the metadata in the generated object files is the main issue?

No. It is one issue, but there are more. A more fundamental problem is the potential difference in how parameters are passed to the kernel and/or standard library. IIRC, those conventions are different between Windows and Linux.

Title: Is it possible to use the Intel C/C++ compiler on Linux to create object files to be linked on Windows?

Body:
Why?

Depending on your source the Intel compiler is likely or most definitely the compiler generating the fastest executables for the x86 architecture (5 to 100 % execution time improvement).

Intel offers its compilers for Linux under a non-commercial license for free (I think I read it is free somewhere on their page: Intel - Non-Commercial Software Development).
There is also a free non-commercial license for students, but this license is not applicable although tools are offered for all three major operating systems (link dropped  due to reputation restriction).

Goal

I (as a non-student) would like to be able to use the Intel compilers for possible execution speed improvements under the non-commercial license to compile object files that can be linked to create executables and dynamic link libraries for Windows (and possibly OS X)

More Details:

What I inferred from this document is that the Intel compilers create object files that are compatible to the dominant compilers of the platform.

Sub-questions:

What are the object file formats of gcc, g++, cl, mingw32, icc, icpc, and icl on Windows and Linux (current versions)?

Could parts of the mingw32 cross-compiler toolchain be used to accomplish the goal?

Am I right that the metadata in the generated object files is the main issue?

ad 2:

mingw32-objcopy seems to be able to convert the Intel compiler output on Linux (presumably ELF) to Microsoft-compatible COFF (with the possible exception of relocateable object files). Could someone confirm that this actually works (for non-trivial applications), please?


问:
Can we use Java for commercial use?
The Java is GPL license (reference from wikipedia). I am not sure I can use it in in commercial projects. I already have a website written in Java and I plan to use this for commercial use. Is that illegal?</p>

答: You can compile an application using gcc, which is free software. Then you can license your app as you please, but not the gcc compiler.</p>

OwnerDisplayName: Shisoft

Title: Can we use Java for commercial use?


问:
Naming functions that retrieve a value
I have this personal rule to start all function/method names with a verb. My verb of choice for functions or methods that get a value based on some data structure or object is get. I'm wondering if that's a good idea.

The good thing about get is that it doesn't really say anything about how that value is being retrieved, just get it. Something like calculate (apart from being awfully long) may be too much information.

This applies to both functions and methods, i.e.:

```<code>float get_magnitude(Vector2d vector)
{
    return sqrt(pow(vector.x, 2), pow(vector.y, 2));
}
</code>```

or

```<code>float Vector2d::get_magnitude() const
{
    return sqrt(pow(x, 2), pow(y, 2));
}
</code>```

On the other hand, I sometimes end up with getter methods for read-only properties. It may make sense to use a more meaningful verb for anything that doesn't just return some property, and may not run in linear time.

Is there a case to be made for either approach or is it just a matter of taste?

答:
Depending on the language you work in, the getThingy or get_thingy might be superfluous.

Consider a typical C++/Java/C# class with a bunch of getters and setters that are just accessors to private members, which is something that for better or worse, a lot of see every day.

What's the difference between getCustomerId() and customerId()? I would argue that there's not much difference at all, because we know full well that both are just retrieving a member. But the latter has a number of pragmatic advantages:

getCustomerId() convention will force you type get many times a day.

if you have autocomplete, it won't meaningfully kick in until you type getC*, while in the latter case it will kick in after the first letter. My fingers already hurt, and you're forcing me to keep reaching for the shift key all day long (or the underscore for get_thingy)? Not cool.

You lose the meaningful 'get'. What I mean is, if my convention for the accessor was customerId() and all of a sudden I'd see a function called getCusomterId() I would understand that perhaps it does more, such as going to database maybe, or iteratres some list? In absence of get people are forced to use verbs that are almost synonyms, and because they are synonyms this creates confusion.

I'd like to close with the following: we should always use the minimum amount of anything required to get us to where we want to be. Efficiency is the key to doing things intelligently. The rule of 'always have a verb in a function' is one of those mantras that just doesn't pass that test imho. Personally, I blame Eclipse's auto-generating of setters and getters for the status quo.

People, please drop superfluous get s from your code. They don't actually mean anything.

Title: Naming functions that retrieve a value


问:
Why is MongoDb popular with Node.js?
I've been looking att different web stacks, mainly rails and node.js. One thing that strikes me is that while rails is often used with a relational database Node.js seem to go hand in hand with Mongodb, judging by the blogosphere.

Is there a specific reason for this? I like the modularity of node but I'm also sceptical to NOSQL. I get the feeling that if having a rdbms is important I should use rails since they seem to be a second class citizen in the node ecosystem.

答:
Because they're both JavaScript. There's no other real benefit to using Node and Mongo - feel free to use another RDBMS supported by Node.

Node has https://npmjs.org/package/mysql, which will probably be less fast than Ruby's drivers (it's slower than PHP's), and https://github.com/brianc/node-postgres, which I don't have any experience with.

There is also Sequelize, http://www.sequelizejs.com, which supports postgres and SQLite, and is a bit of a clone of ORMs from other languages.

Title: Why is MongoDb popular with Node.js?


问:
Object Oriented Programming in JavaScript. Is there life without it?
At our company we have pretty large body of PrototypeJS based JavaScript code, which we are porting to jQuery for several reasons (not really important here). I'm trying to set up coding guidelines to make/keep things tidy during the porting.

One observation from wading through the prototype based implementation is that a lot of code is written in OOP style (using Prototype's Class.create), but the code is not "object oriented" in spirit.
The general pattern I've seen: one "constructor" which you are expected to call (but not call twice, because the constructor uses hardcoded DOM id's), a bunch of other "functions" and event handlers, which you are not expected to call (but the because there is no "private" in JavaScript, you don't know that) and data sharing between all these functions through this. Seen from the caller's point of view there is just one "callable" and nothing else.

I'm starting to believe that OOP in JavaScript can and maybe should be avoided in a lot of cases. At least for our use case, which is not the next generation Goole Wave UI, but simply put: a bit of AJAX based enhancements, registering some event handlers here and there, minor DOM manipulations and such.

the functionality we need seems to be implementable just fine in the typical jQuery non-OOP way, using closure magic to obtain encapsulation and privateness. As side effect, the minification efficiency of the ported code is much better.

OOP in JavaScript is non-traditional and confusing if you are coming from a "traditional" background. There are a lot of attempts and frameworks to approximate traditional OOP, but IMHO this makes things even more confusing and fragile.

One thing that Crockford's "JavaScript the good parts" taught me, is that the true power of Javascript lies in function scopes and closures, much less in OOP patterns.

I'm wondering if there is wider support for this feeling that OOP in JavaScript doesn't really cut it as the sacred mantra, like it is in other languages/platforms. And, in extension, what kind of non-OOP/closure based patterns are much more preferable.

答:
People tend to get caught up in advanced patterns with OOP. MVC, MVVM, MVVC and every other permutation of 'M', 'V', and 'C'. I've never opened up a js project with 20,000+ lines and said to myself: "Thank god this is in MVC", because the reality is that most projects with 20,000+ lines are going to be a terrible mess.

Having said that, I still think large projects are almost impossible without OOP. At the very least, the ability to write complex objects and store them in separate files and namespace-protect them from collisions using a library like dojo will save you thousands of hours of painful debugging.

"Oh", you might say to yourself, "Well, I can write modular groups of functions in separate javascript files with the best of them. I don't need to use OOP." Well, my friend- congratulations, because you're already effectively using OOP without even knowing it. So as long as that's the case, why not just go one step further and use actual classes?

It's true that javascript relies on the prototype model, however, the base of OOP is pretty much inheritance/encapsulation/polymorphism, and javascript can do that perfectly well. Take a look at dojo.js.

OwnerDisplayName: Stefaan


问:
Best Practice for Argument Checking
Say I have a web service with a method MyWebServiceMethod(string passedValue).

The web service calls a method MyServiceMethod(string passedValue) where the value from the web service is passed along.

The service calls a repository method MyRepositoryMethod(string passedValue) where again, the value from the service is passed along.

I hope that is clear enough.  I can post code if need be.

My question is around null argument checking.

Should I check passedValue and throw an exception in:

The Web Service

The Service

The Repository

Obviously, if passedValue is null in the web service, the following methods will never get invoked but should I check in case the solution changes in the future?

Edit

I should have said that I don't expect null to ever be a valid value.

Also, My worry in these situations is that someone may change the web service or create another client with no argument checking that will call the service with invalid arguments.  So I tend to think the checking should be in both places.  Then I think of YAGNI and wonder if we should cross that bridge when we come to it.

What is considered best practice in these situations?

答:
2 solutions :
 - null is  or may become a valid value for your service. In that case you have to pass it along your stack.
 - If null value is forbidden, the basic validation is better at the upper level (webservice) to avoid unnecessary calls.</p>

OwnerDisplayName: davy

Title: Best Practice for Argument Checking

OwnerDisplayName: gma


答:
Given the case, that you have a method that only calls another method and passes the arguments, at that point it is not necessary to check if a variable is null.
When the repository is called, you have to decide if null is a valid value or not. If not not, you have to test your variable against null and throw an exception.</p>

Title: Best Practice for Argument Checking

Body:
Say I have a web service with a method MyWebServiceMethod(string passedValue).

The web service calls a method MyServiceMethod(string passedValue) where the value from the web service is passed along.

The service calls a repository method MyRepositoryMethod(string passedValue) where again, the value from the service is passed along.

I hope that is clear enough.  I can post code if need be.

My question is around null argument checking.

Should I check passedValue and throw an exception in:

The Web Service

The Service

The Repository

Obviously, if passedValue is null in the web service, the following methods will never get invoked but should I check in case the solution changes in the future?

Edit

I should have said that I don't expect null to ever be a valid value.

Also, My worry in these situations is that someone may change the web service or create another client with no argument checking that will call the service with invalid arguments.  So I tend to think the checking should be in both places.  Then I think of YAGNI and wonder if we should cross that bridge when we come to it.

What is considered best practice in these situations?

OwnerDisplayName: Jan Schulte


答:
If null is not valid on the web service, then check it in the web service.

If it ever becomes valid, update the code. Don't worry about implementing things that do not currently exist and you don't know if they ever will exist.

You already know that null is invalid, so catch it immediately.

If there's only one parameter and null becomes valid you may just want to create a parameterless method as an option in the future so that your user won't need to pass null to get the functionality they need.

Title: Best Practice for Argument Checking

OwnerDisplayName: CLandry


问:
How to genericize foreign key references in table?
I am trying to design a table to store references to multiple tables as a "target" of the item in each row.

An example should clarify what I am trying to do:
Imagine you have 4 tables (images, videos, comments, likes)

with likes being similar to

```<code>CREATE TABLE `likes`
`target` int(11),
`user_id` int(11),
`created_at` timestamp
</code>```

How do you make it so the "target" could be a row of images, videos or comments (eg, you like an image, video or comment)

Also how would you go about representing this within your code? (abstract class Like and concrete classes for LikeImage, LikeImage, LikeComment?) or maybe have an interface ILikeable  and then the Like object has a ILikeable object on hand?

I'm running into this pattern more and more often making things such "like" (like an object) or "subscribing" (subscribe to changes on an object) to various targets and generating "notifications" (notify a user of a change on an object) that are generically able to target objects.

Thanks for sharing your knowledge.

Update:: Is there a nosql way to easily achieve this?

答:
This sounds to me like a SuperType - SubType relationship should be used. The SuperType is a single table that stores all of the common attributes of all the SubTypes along with key that indicates what kind of SubType it is. For example:

tblLikes (SuperType)

LikedId, (PKey)

LikedType, (1=Images, 2=Videos 3=Comments)

LikeShortDescription,

UserId,

DateStamp

tblLikedImages (SubType)

ImageId, (PKey)

LikedId, (FKey tblLikes)

...

ImageData Goes here

...

tblLikedVideo (SubType)

VideoId, (PKey)

LikedId, (FKey tblLikes)

...

VideoData Goes here

...

tblLikedComments (SubType)

CommentId, (PKey)

LikedId, (FKey tblLikes)

...

CommentData Goes here

...

The concept allows for scalability. Each SubType may or may not belong to the SuperType. A query of the SuperType table can give a high level view of all the "Liked Items". Unfortunately if you need the details of each SubType... separate querries need to be executed.


问:
Approaches to isolating tests that require a database?
Suppose I have component A,B,C that all put some data into a database. Each component depends on data in the database inserted by the previous component.

How do I test these modules in isolation? I already have tests at the unit level, but I now want to test with the database. I have seen suggestions to make a dump of the database for each step, but this is a messy thing to check in to version control and requires a lot of effort whenever the architecture changes (which where I work translates to "abandon tests!").

I really think that the best approach is to clear my test database before running tests and use some tool to specify test dependencies to ensure correct running order, but this seems to be seriously frowned upon by the opinions I've read. To me it seems the same as using a fixture for each step, except that the fixture is just a cheap way of hiding the dependency.

答:
So on a high level you create data sets in code that are applied for each test case.

After each test the database is rolled back either by dropping and recreating or truncating.

You don't mention the framework or language you are using, but many have methods for using fixtures to create data for your tests that are reset during each test cycle.

What you need to do is pick one of these frameworks and setup the core set of data elements you need for your application.  Then for each test, the test framework should have a mechanism to populate specific objects (rows) with the data you need for that test scenario.  The framework should then reload the database and and apply the default data for the next test.

https://github.com/notahat/machinist is and example of a fixture framework for Ruby on Rails.


答:
I think it has to do mostly with the cutting edge nature of both solutions, so they get talked about in the same places.

Another might be the problem domain that both are solving are similar (dealing with sets of data that may have varying properties).

Both are also used to a varying degree on projects that have a narrow focus.

Larger projects with larger data domains are more likely (but not necessarily) going to use a more robust framework and have requirements that fit better with a relational database.

Title: Why is MongoDb popular with Node.js?

Body:
I've been looking att different web stacks, mainly rails and node.js. One thing that strikes me is that while rails is often used with a relational database Node.js seem to go hand in hand with Mongodb, judging by the blogosphere.

Is there a specific reason for this? I like the modularity of node but I'm also sceptical to NOSQL. I get the feeling that if having a rdbms is important I should use rails since they seem to be a second class citizen in the node ecosystem.


问:
How do I survive in a Waterfall world?
I currently work in a company where the Waterfall model is deeply ingrained. We are pushing Agile principles but it's a long process. Meanwhile, I have to work in a Waterfall world with sequential projects phases.

My question is about the analysis phase. I must provide a list of task and how long they will take. What techniques can I use to improve the accuracy/precision of my estimates, while fulfilling the requirement of having a detailed estimate up front?

One example I know would be to use prototyping to get more knowledge before making the estimate.

答:
Gather better, more specific customer requirements.

When you refine the requirements to the point where each requirement can be satisfied with a handful of classes, and you have a pretty good idea what those classes will look like in code, it will become much clearer how long things are going to take, and it will be much easier to declare success on each requirement.

Your requirements should include detailed specifications of all of the interfaces between components, so that it will be clear to each software developer exactly what they need to do, and it will be easier to divvy up the work, or move work from one developer to another.

One thing you might want to push is smaller waterfalls.  Breaking up the project into phases will help everyone by providing checkpoints where you can monitor progress and get feedback from stakeholders (much like you would with agile).  Agile succeeds where waterfall fails because waterfall often bites off more than you can chew.

Title: How do I survive in a Waterfall world?


问:
Good practice -apply paradigm to a language that is not fit for it
For example, what happens if a coder tries to code in purely functional-style paradigm in OO-paradigm language(Java)? Will it work? Or the OO nature of Java will not let it happen?

Also, is applying wrong paradigm to language unfitting to it a bad practice or not?
Is it like trying to drive a jet on road instead of flying it?

答:
It really depends on which language and which paradigm, principle or pattern you're trying to emulate.

I'd say the best practice is to use the language that is most suitable for your requirements, and study other languages to identify ways that you can improve the coding style in the language of your choice.  But always approach a language on its own merits; utilize the unique strengths and character of the language you chose, rather than trying to shoehorn a paradigm that isn't really a good fit.


答:
For example, what happens if a coder tries to code in purely functional-style paradigm in OO-paradigm language(Java)? Will it work?

Not well.

The parts of a language are oftentimes tailored to make common behaviors easy. Once you change what the common behaviors are, that design (usually) does not translate to the new requirements.

Also, is applying wrong paradigm to language unfitting to it a bad practice or not?

It is generally a bad practice. Programming languages serve two primary purposes:

Telling the computer what to do.

Telling other programmers what the computer is doing.

When you start deviating from the normal idioms of a programming environment, you start deviating from what other programmers know/expect/understand. Since nearly all programming projects these days involve teams, it's considered a bad practice to make code that is hard to read, extend and maintain.

Title: Good practice -apply paradigm to a language that is not fit for it

Body:
For example, what happens if a coder tries to code in purely functional-style paradigm in OO-paradigm language(Java)? Will it work? Or the OO nature of Java will not let it happen?

Also, is applying wrong paradigm to language unfitting to it a bad practice or not?
Is it like trying to drive a jet on road instead of flying it?


答:
You can almost always shoehorn a paradigm in a language that doesn't support that paradigm, but you'll need lots of hacks and the resulting code will be some combination of ugly, complicated, inefficient, not idiomatic, etc.

That brings me to the second part of the question: Is it a good idea? Generally not, as it causes a great many downsides which are not worth any advantage the paradigm may have for the given problem (see above). However, I make an exception if a paradigm provides great benefits for the task and can be followed with reasonable ease, i.e., the aforementioned downsides are acceptable.


答:
I feel it's important to point out a couple of things:

OOP and classes are two fully orthogonal concepts. Classes could just as well work with structs/records (and in fact they do in some languages). They incidentally happen to be useful for constructing specific kinds of objects.

Access control is a nice tool for encapsulation, but it's not a prerequisite. In JavaScript it's common to prefix "private" members of an object with an underscore. Whether or not you choose to access those anyhow is for you to decide. In most languages there are some means to get past access control if you really want to. It's just a really silly thing in general to write code against something that was never consciously exposed by a human being for you to consume (and can for example change at any time).

OOP is certainly not about how specific parts of your system are implemented (let alone the syntax involved) and I would thus argue that the implementation cannot be "object oriented in spirit" or not. OOP is mostly a relatively clever mechanism for indirection built on encapsulation and polymorphism. In essence, it is little more than "Tell, Don't Ask".

If you want to jump through hoops to turn JavaScript into something it isn't, you may be unhappy with the result. So instead, you could pick any of the available languages that compile to JavaScript but are closer to what you might want a programming language to look like (Haxe, ParenScript, TypeScript, CoffeeScript, ScriptSharp, Dart, Java (through GWT), C/C++ (through Emscripten) ... in fact almost any other popular language can be translated to JavaScript with varying quality).

But if you use JavaScript for what it is, you will find a language that allows "class-oids", mixins/traits, AOP and what not. More often than not, you will realize than limiting yourself to Java-esque idioms might not be the best idea. Nonetheless, they undoubtedly come in handy at times.

Title: Object Oriented Programming in JavaScript. Is there life without it?

Body:
At our company we have pretty large body of PrototypeJS based JavaScript code, which we are porting to jQuery for several reasons (not really important here). I'm trying to set up coding guidelines to make/keep things tidy during the porting.

One observation from wading through the prototype based implementation is that a lot of code is written in OOP style (using Prototype's Class.create), but the code is not "object oriented" in spirit.
The general pattern I've seen: one "constructor" which you are expected to call (but not call twice, because the constructor uses hardcoded DOM id's), a bunch of other "functions" and event handlers, which you are not expected to call (but the because there is no "private" in JavaScript, you don't know that) and data sharing between all these functions through this. Seen from the caller's point of view there is just one "callable" and nothing else.

I'm starting to believe that OOP in JavaScript can and maybe should be avoided in a lot of cases. At least for our use case, which is not the next generation Goole Wave UI, but simply put: a bit of AJAX based enhancements, registering some event handlers here and there, minor DOM manipulations and such.

the functionality we need seems to be implementable just fine in the typical jQuery non-OOP way, using closure magic to obtain encapsulation and privateness. As side effect, the minification efficiency of the ported code is much better.

OOP in JavaScript is non-traditional and confusing if you are coming from a "traditional" background. There are a lot of attempts and frameworks to approximate traditional OOP, but IMHO this makes things even more confusing and fragile.

One thing that Crockford's "JavaScript the good parts" taught me, is that the true power of Javascript lies in function scopes and closures, much less in OOP patterns.

I'm wondering if there is wider support for this feeling that OOP in JavaScript doesn't really cut it as the sacred mantra, like it is in other languages/platforms. And, in extension, what kind of non-OOP/closure based patterns are much more preferable.


答:
One observation from wading through the prototype based implementation is that a lot of code is written in OOP style (using Prototype's Class.create), but the code is not "object oriented" in spirit. The general pattern I've seen: one "constructor" which you are expected to call (but not call twice, because the constructor uses hardcoded DOM id's), a bunch of other "functions" and event handlers, which you are not expected to call (but the because there is no "private" in JavaScript, you don't know that) and data sharing between all these functions through this. Seen from the caller's point of view there is just one "callable" and nothing else.

Not every Javascript project needs OOP.  I wouldn't go there unless I were using an existing OO framework like ExtJS.  In your case, where it seems the only use of OOP is misuse, I think you should skip it entirely.  Since you are switching to jQuery, just follow the jQuery plugin architecture.  Write custom plugins when convenient.


问:
Why is the use of constructors discouraged when creating prototypes?
Quick background: In JavaScript, the constructor function for each object type has a prototype property. The prototype refers to an object that each constructed object uses as the next step up in its prototype chain. When you want one type to inherent from another type, you can set the prototype of the child type to a new instance of the parent type.

For example:

```<code>var Parent = function() { /* constructor business */ }
Parent.prototype.parentProp = "some parent property";

var Child = function() { /* constructor business */ }
Child.prototype = /*** !! Some prototype object goes here !! ***/
</code>```

My question asks about what code should go in the "Some prototype object goes here" spot in the above code. My first instinct is to construct an instance of the parent (i.e., new Parent()), but in a comment to an answer on Is this a safe way of copying one objects prototype to another?, one user writes:

No, do not use new bar() for the prototype object!

(...which is an opinion I've seen in many SO answers and comments, but this is the only example I have on hand at the moment.)

The other option is to use Object.create(Parent.prototype) as Child.prototype. As far as I know, this also creates a new Parent instance, but it does not run the Parent constructor.

Can someone explain why running the constructor function should be avoided when generating a prototype object from a parent type? Is there some significant technical problem that arises (perhaps with multiple levels of inheritance)? Or is such a pattern a misuse of constructors that clashes with some prototypical best practice (e.g., running the constructor when creating a prototype violates some separation of concerns)?

答:
Because it's a function that doesn't need to be called. new is not that different from a regular function call in Javascript.

A constructor can do more than simply set fields. For instance, if it validates incoming data, then you will cause a validation
error when you were simply trying to set inheritance chain.

And you don't need Object.create, this is sufficient:

```<code>function objectCreate( proto ) {
    function T(){}
    T.prototype = proto;
    return new T();
}
</code>```

Body:
Because it's a function that doesn't need to be called. new is not that different from a regular function call in Javascript.

A constructor can do more than simply set fields. For instance, if it validates incoming data, then you will cause a validation
error when you were simply trying to set inheritance chain.

And you don't need Object.create, this is sufficient:

function objectCreate( proto ) {
    function T(){}
    T.prototype = proto;
    return new T();
}