问:
Should exceptions do things other than tell the user something went wrong?
I created a general class that accepts a string when it is constructed, and it spits out that string when a user calls what().  This is all it does; on throw, it returns the initializing string.

```<code>class Exception_As {
private:
    std::string message
public:
    Exception_As(const std::string& message) { // constructor
        this->message ="EXCEPTION: " +message;
    }

    virtual const char* what() const throw() {
        return message.c_str();
    }
}
</code>```

How I use my custom exception class:

```<code>bool check_range(
    const std::vector<std::string>& list,
    const unsigned& idx_start,  // where to start checking
    const unsigned& idx_end,    // where to stop checking
    const std::string& key
) {
    if ( idx_start > idx_end ) {
        throw Exception_As("check_range: start index > end index: now fix it! :D");
    }

    ... rest of code
} // end of check_range
</code>```

How a user would use check_range:

```<code>// some other user code using my check_range
void main() {
    try {
        ... set up variables

        my_hero_qualified = check_range(semi_finalists, third_place, first_place, my_hero);
        ...rest of code
    }

    catch (const Exception_As& e) {
        std::cout << e.what() << std::endl;
    }
}
</code>```

If the try/catch was not there, it would abort the program because of the thrown Exception_As.  If it was there, the user would be notified that "check_range: start index > end index: now fix it! :D".  For me, sure beats writing tons of BadEvent1Exception, BadEvent2Exception, etc classes.

I can see I'm being lazy with this method, and yeah, I can't do anything fancy like modify values based on exceptions or morph an object's state; but if you just entered unexpected territory, who knows if you're handling it correctly?  May as well just end it so you can fix what's up and develop properly.

So, question: if all exceptions do is break the program on unexpected circumstances, won't a single exception class that returns the problem be enough?

...Or should exceptions be doing other things anyway?  If not, why create so many classes of Exceptions that have different names, sure, but from what I've seen, only report that something went wrong.

答:
Yes: they should state what is wrong & the type of error.

Lets look at a couple of examples for exceptions.

Under C++, if you run out of memory, the new command will throw an exception. This is IMHO a good use. Its something which does happen & you will need to catch & deal with it.

Another exception you might have is an exception thrown if the files you are reading from is incorrectly formatted.

Now lets consider a function which reads from a file & stores it into memory.
It could easily throw either of these two exceptions, but they should be handled differently. The bad-format exception can be a simple popup message box.  The out-of-memory exception is a much more serious occurrence and should probably save the current state of the program and exit.

If you use the same exception, you cannot tell the two apart, unless you start parsing the string. So in this case I would go for two different exceptions so you can have two different handlers.

So there is a good example of the reason for the various exception types.


问:
What would you add in this Software Development Project Checklist?
I'm a big fan of checklists. There is Travel Checklist, Moving Checklist and even a Scrum Checklist.

Context: you have been hired by a large corporation and given the mission to setup the whole software development environment, processes, team, etc. You have "carte blanche". You will be responsible for the creation of the working increments of the software. Project size: 2000 man/days.

What items would you add to the following (intentionally small and incomplete) checklist:

Install a Continuous Integration Server

Write a DoD

Write a one page coding guidelines

Create a product backlog

Install a Bug Tracking System

Schedule Regular Face Time

答:
1. Take it to the team

Ask the programmers! Really, that's the most important thing. You'll meet lots of resistance if the devs are not directly involved in this change. After all, it's about how they work, not you. It goes without saying, but trying to force methods and tools on people usually backfires horrible.

2. Inspect and adapt

Have the team figure out the best way to work, using your experience to gently help them get on the chosen track. Then, regularly and collaboratively, look back on how you (they) are doing and adapt the process to make it better.

ContentLicense: CC BY-SA 2.5


问:
Why are inheritance and interfaces restricted to instance members?
Disclaimer: I think the rules are almost the same in most OO languages, but since I'm most familiar with C# I'll be relating to this specific language.

I think that the use of attributes and reflection could be largely reduced if static members would apply the same principles as OO instances.

Static properties and methods can be "overridden" by decedents by using the new keyword, but they cannot be forced to implement one via an interface, neither can the 'base' keyword be used (only explicitly naming the base type is supported). To make things worse, the members cannot be referenced via an instance, but have to always be specifically qualified with the exact type.

Constructors also have limited "inheritance" support, one can choose which base constructor is called, but you cannot force an object to support a constructor that takes certain parameters by defining it in an interface.

The best hint I could find to answer this question so far is this one on stack overflow (answering a different question).

In his answer Jörg points out three principals that apply to Object Orientation:

messaging,

local retention and protection and hiding of state-process, and

extreme late-binding of all things.

Now I fully understand that if you want to pass on a state-full class from one method to another as an object, these principles make sense. However in my opinion the principle of inheritance, overriding base methods with alternative or additional functionality, could also be beneficial to stateless business logic.

One example where forcing an object to implement a certain constructor would be helpful is with de-serialization. For example where the constructor should accept an XML node. In C# it is dynamically implementable using reflection, but having compile-time errors and avoiding the reflection boilerplate would add lots of value!

Static method/member interfaces would be helpful in situations where some aspects of a value are type specific, without any relation to the instance. For example a class could have a DisplayName, Unit, Weight, Factor or other aspects that are the same across all instances of the specific type, regardless of the instance value. Attributes (or Annotation) can be used to exploit these without the need to create an instance, however, there again it's extra boilerplate code and no way to enforce their implementation with compile-time errors.

I admit there are many simple ways to work around these points, I'm not looking for workarounds. Returning a static value in an instance-property is quite common, and it is not that much overhead to create an instance of an object just to read out the type-specific aspects, but I'd like to know the rationale background on why static things have been systematically excluded. I have heard about "the virtual stack" before, but don't really know how it works technically (and cannot find any simple explanation on the net).

Are the reasons of technical or philosophical nature?

Edit: elaborating on static interfaces:

An example of how I think a static interface could provide a strongly typed, compiletime checked, alternative to reflection:

```<code>public staticInterface MyStaticInterface
{
    constructor(XmlNode node);
    string DisplayName { get; }
    int Weight { get; }
}
</code>```

The usage:

```<code>public void FillNodesToolBox()
{
    MyStaticInterface[] nodes =
        assembly.GetTypes().Where(t => t.Implements<MyStaticInterface>());

    for (int i = nodes.Length - 1; i >= 0 ; i--)
    {
        Console.WriteLine(string.Concat(
            nodes[i].DisplayName, " (", nodes[i].Weight.ToString(), ")"));
    }
}
</code>```

Looking back, this actually looks like making my Type object inherit from System.Type, adding some properties to it, which is different than a static member...

string.Empty != typeof(string).Emty (the latter will not compile).

Maybe I'm starting to find the answer, but it feels like I'm walking in a paradoxical circle, it doesn't quite 'snap' yet....

答:
It simply cannot work.

Lets say you have class A that defines a "virtual" static method. Then you have classes B and C that derive from A and both override this static method. Then you call A.StaticMethod(). Which of the B or C should be called?

The reason why virtual methods are tied to instance is because the type of the instance specifies which implementation of the virtual method is called. If you don't have this information, then you can't call the proper method.

Also, if you try to argue that you have to call the static method on a type it is implemented in (eg. B.StaticMethod() or C.StaticMethod()), then that is not virtual method call and can already be implemented in C# without problems.

Now I fully understand that if you want to pass on a state-full class from one method to another as an object, these principles make sense. However in my opinion the principle of inheritance, overriding base methods with alternative or additional functionality, could also be beneficial to stateless business logic.

The business logic might seem stateless from abstraction's viewpoint. So you design your interfaces or abstract classes around that. But then, you realize you want to parametrize specific behavior at runtime. With instance virtual methods this is easy. Just create new subtype that contains state specifies this parametrization. Nothing stops you from having stateless instances with just methods, but having ability to add state without changing the abstraction is huge advantage of OOP. By having the methods static, you are removing this advantage.

If you really think that "stateless" programming is better for your project, it might be good idea to look at functional programming, which is all about composing methods with minimal state keeping.

ContentLicense: CC BY-SA 3.0


问:
Should reflection be part of design?
I'm currently designing a somewhat large program that will involve the simulation of math/physics models and collection of data (I have not implemented any code yet). One of the main problems I'm facing is how to pass data around easily without having to have multiple copies of data (that may potentially be outdated and redundant).

Initially I was thinking of having the model objects each implement a function that returns a data structure containing copies of their data, then collecting all those data structures together and passing that around. This would involve a lot of copying however, and the data wouldn't be mapped to the actual object anymore. (The data structure idea I had would involve using a trie so that the data is nice and hierarchical and lookups can be done easily by string)

So now I was thinking that instead of designing the program to use a data structure to pass data around, the program would simply pass the model, and then data can be extracted with reflection. This would pretty much avoid any redundancy and the data passed will always be up to date.

The problem is that I also need this program to be fast (it has soft realtime constraints), and I'm not sure about the performance impact of reflection. And reflection does seem kinda ugly. But at the same time, people say it's never a good idea to optimize early, so I'm on the fence here.

So should I design the program to use reflection, and if so, how liberally? Or should I try to avoid reflection as much as I can during design?

答:
Without an example, this question is a little bit too broad for my taste, so best answer I can give you is a very generic one. IMHO what you need is a more functional approach:

model your data using immutable objects. For immutable objects, there is no need to create any copies, they can be passed by reference without the risk of creating any side effects.

using only immutable data structures forces you to organize your program in a way where each function which could deliver potentially out-of-date results is called "on the fly" at the point in time when the data is needed, not earlier.

instead of solving problems imperatively by "calculating some data x and y, store it somewhere, reuse parts of it later to calculate a, b, and c", learn how to model problems in a functional way (write functions for calculating a, b, and c based on the functions for calculating x and y).

model your data flow, maybe graphically - make sure you know exactly which components in your system get data from which other components, and where the "asynchronous changes" are introduced. I recommend Flow Design for this.

reflection is most probably the wrong choice for your problem (not for performance reasons, but for actually introducing more problems than it will solve for you)

EDIT: a really good example of a physical model which seems similar to your problem is the digital circuit simulator in "Structure and Interpretation of Computer programs". And this example is indeed based on mutable data (though its also using functional elements). Maybe this approach maybe a blueprint for yours.

Title: Should reflection be part of design?

ContentLicense: CC BY-SA 4.0


答:
The reasons why an interface can't dictate a constructor signature or the presence of static methods are primarily technical.

When calling method I::foo of interface I, the runtime environment needs a bit of metadata to know if it is actually X::foo or Y::foo that should be invoked. This metadata is specific for the object on which the method is invoked and thus attached to that object.

The problem with constructors and static methods is that they are invoked when there is no object available (yet). This means that there is no metadata available for the runtime environment to determine from which class to invoke the constructor or static method.

Title: Why are inheritance and interfaces restricted to instance members?

Body:
Disclaimer: I think the rules are almost the same in most OO languages, but since I'm most familiar with C# I'll be relating to this specific language.

I think that the use of attributes and reflection could be largely reduced if static members would apply the same principles as OO instances.

Static properties and methods can be "overridden" by decedents by using the new keyword, but they cannot be forced to implement one via an interface, neither can the 'base' keyword be used (only explicitly naming the base type is supported). To make things worse, the members cannot be referenced via an instance, but have to always be specifically qualified with the exact type.

Constructors also have limited "inheritance" support, one can choose which base constructor is called, but you cannot force an object to support a constructor that takes certain parameters by defining it in an interface.

The best hint I could find to answer this question so far is this one on stack overflow (answering a different question).

In his answer Jörg points out three principals that apply to Object Orientation:

messaging,

local retention and protection and hiding of state-process, and

extreme late-binding of all things.

Now I fully understand that if you want to pass on a state-full class from one method to another as an object, these principles make sense. However in my opinion the principle of inheritance, overriding base methods with alternative or additional functionality, could also be beneficial to stateless business logic.

One example where forcing an object to implement a certain constructor would be helpful is with de-serialization. For example where the constructor should accept an XML node. In C# it is dynamically implementable using reflection, but having compile-time errors and avoiding the reflection boilerplate would add lots of value!

Static method/member interfaces would be helpful in situations where some aspects of a value are type specific, without any relation to the instance. For example a class could have a DisplayName, Unit, Weight, Factor or other aspects that are the same across all instances of the specific type, regardless of the instance value. Attributes (or Annotation) can be used to exploit these without the need to create an instance, however, there again it's extra boilerplate code and no way to enforce their implementation with compile-time errors.

I admit there are many simple ways to work around these points, I'm not looking for workarounds. Returning a static value in an instance-property is quite common, and it is not that much overhead to create an instance of an object just to read out the type-specific aspects, but I'd like to know the rationale background on why static things have been systematically excluded. I have heard about "the virtual stack" before, but don't really know how it works technically (and cannot find any simple explanation on the net).

Are the reasons of technical or philosophical nature?

Edit: elaborating on static interfaces:

An example of how I think a static interface could provide a strongly typed, compiletime checked, alternative to reflection:

```<code>public staticInterface MyStaticInterface
{
    constructor(XmlNode node);
    string DisplayName { get; }
    int Weight { get; }
}
</code>```

The usage:

```<code>public void FillNodesToolBox()
{
    MyStaticInterface[] nodes =
        assembly.GetTypes().Where(t => t.Implements<MyStaticInterface>());

    for (int i = nodes.Length - 1; i >= 0 ; i--)
    {
        Console.WriteLine(string.Concat(
            nodes[i].DisplayName, " (", nodes[i].Weight.ToString(), ")"));
    }
}
</code>```

Looking back, this actually looks like making my Type object inherit from System.Type, adding some properties to it, which is different than a static member...

string.Empty != typeof(string).Emty (the latter will not compile).

Maybe I'm starting to find the answer, but it feels like I'm walking in a paradoxical circle, it doesn't quite 'snap' yet....


问:
What are some famous one-liner or two-liner programs and equations?
I'm experimenting with a new platform and I'm trying to write a program that deals with strings that are no longer than 60 characters and I'd like to populate the data store with some famous or well-known small chunks of code and equations, since programming and math goes along with the theme of my software. The code can be in any language and the equations from any discipline of mathematics, just so long as they're less than a total of 60 characters in length. I suspect people are gonna break out some brainfuck for this one.

For example,

```<code>#include<stdio.h>
int main(){printf ("Hi World\n");return 0;}
</code>```

60 characters exactly!

Thanks so much for your wisdom!

答:
Not famous, but a hideous way of calculating the square root of n, with the result as n.

```<code>for(double r=1;r!=n;n=r==(r=0.5*(r+(n<0?-n:n)/r))?r:n);
</code>```

And yes, negative number handling is incorrect.

Body:
Not famous, but a hideous way of calculating the square root of n, with the result as n.

for(double r=1;r!=n;n=r==(r=0.5*(r+(n<0?-n:n)/r))?r:n);

And yes, negative number handling is incorrect.

OwnerDisplayName: Anon


问:
How do I handle situations when I need to use personal software for a commercial purpose?
If I work for a company and write code for them but I choose to buy a tool for myself and use it to write code for the company, do I need a commercial or personal license?

Specifically, in this case, I am asking about WebStorm IDE

JetBrains have Commercial (For companies and organizations) and Personal (For individual developers). I am an individual developer working for a company!

答:
For Jetbrains, the corporate license is a license that's not linked to an individual. The personal license is linked to a specific person.

What that means inside a company is that if you buy a corporate license for 10 users, any 10 people can use the product at any given time.

If however you buy 10 personal licenses, only the 10 specific people who are mentioned can ever use the product. Were one of them to leave the company, that license becomes useless (though they might have a means to get the license transfered to another person, you'd have to contact Jetbrains about that). If one of them is on a 6 months long sabatical, there will thus be only 9 licenses in use as a maximum. With a corporate license you could get a contractor or intern to take over for 6 months and reuse that license.

As you're buying yourself for use at work (and probably at home as well) you'd purchase a personal license. That will allow you and only you to use it on any number of computers (but only on one computer at a time, if memory serves (it's been a few years since I read the fine print, and that specific wasn't relevant to me at the time as I only had one computer per location).


问:
How to Ignore Bracketing Style in Code Comparison / Diff
How to ignore bracketing styles when doing code comparisons or diffs? We have several formats of bracketing and I would like:

```<code>function foo(){
}
</code>```

to be considered the same as

```<code>function foo()
{
}
</code>```

Right now I use Araxis merge which does a direct line-by-line comparison and we are getting a lot of "false positive" changes.

答: A tool like Semantic Merge which understands the language semantics by parsing the code  will work in this case.</p>


答: Postmortem Reviews - Since you are working on things in blocks, I would schedule a one to two hour review (depending upon team size) to have a face to face meeting (if possible) where everyone goes around and says what was done right, what could be done better, and what wasn't needed. Being able to learn from your mistakes in the development process early means that you can avoid doing them later on when you don't have as much time to work with.

Title: What would you add in this Software Development Project Checklist?

Body:
I'm a big fan of checklists. There is Travel Checklist, Moving Checklist and even a Scrum Checklist.

Context: you have been hired by a large corporation and given the mission to setup the whole software development environment, processes, team, etc. You have "carte blanche". You will be responsible for the creation of the working increments of the software. Project size: 2000 man/days.

What items would you add to the following (intentionally small and incomplete) checklist:

Install a Continuous Integration Server

Write a DoD

Write a one page coding guidelines

Create a product backlog

Install a Bug Tracking System

Schedule Regular Face Time


问:
Should static data be stored in a database or somewhere else?
I'm working on some software at them moment and I'm not sure which route to take with this. I have some data to store somewhere on a mobile device. The data will never change, and has a hierarchical relationship, and will be used to populate the display. There is a reasonably amount of this data.

I have the following options:

A set of enums/objects

An XML file

The embedded SQLite database

In this particular case I think that the enums option is the least work, but I get a smell from the data being embedded in the code like that.

The XML file makes the most sense I think, but parsing it will be a resource hit that seems like a waste since it will 'never' change.

The database should provide less of a performance hit, but seems like overkill for static data.

Which is the correct design path here?

Note: By 'Never' change I mean that it will rarely change. The data in question is a model of a set of government standards, so they may well change at some point in the future but its not going to be regularly and its not going to automatically update our software either as a change in the standards could well trigger a change in our requirements.

答:
I would use an object for this.

You said the data will never change, so you can easily store it in the application. The database would be overkill and increase the size.

The XML file would be kinda overkill too and also increases the size.

So in my opinion the best option would be an enum or object.


答:
Usually the things that "never change" are the first to change...

Whether you use a database or some other external system (like a configuration file) matters little, as long as it can be easily and quickly accessed when needed.

I tend to use a database table if I already have a database anyway, and it makes sense (say the data needs possibly to be changed by people who have no filesystem access to the server the application is deployed to, or it runs on multiple machines and the configuration needs to be kept in synch between them).

Of course a database can't hold everything. Database credentials for example will need to be stored elsewhere, most likely a configuration file.

Title: Should static data be stored in a database or somewhere else?

Body:
I'm working on some software at them moment and I'm not sure which route to take with this. I have some data to store somewhere on a mobile device. The data will never change, and has a hierarchical relationship, and will be used to populate the display. There is a reasonably amount of this data.

I have the following options:

A set of enums/objects

An XML file

The embedded SQLite database

In this particular case I think that the enums option is the least work, but I get a smell from the data being embedded in the code like that.

The XML file makes the most sense I think, but parsing it will be a resource hit that seems like a waste since it will 'never' change.

The database should provide less of a performance hit, but seems like overkill for static data.

Which is the correct design path here?

Note: By 'Never' change I mean that it will rarely change. The data in question is a model of a set of government standards, so they may well change at some point in the future but its not going to be regularly and its not going to automatically update our software either as a change in the standards could well trigger a change in our requirements.


答:
What you have here is the most generic form of Exception, which is only of any real use in a "global" Exception Handler - you know the sort of thing: show a "message" to the user, [hopefully] record the Exception into a file for [your] later diagnostic use, then allow the program to gracefully collapse in a heap, losing everything that the user has done for the last twenty-five minutes.

I regard it as a "backstop", the "Lowest Common Denominator" of Exception "handling" and, whilst it is the way that a lot of people write code, it's not what Exceptions are really about.

An Exception is something that shouldn't normally happen but, by creating an Exception [class] for it, you're acknowledging that it might and, if and when it does, your code is going to react is a pre-defined way (by throwing the Exception).

The calling code has a responsibility to catch the thrown Exception if it can do anything useful with it.  That's why we have distinct Exception classes - the "filter" used by Structured Exception Handling schemes are mostly geared-up to figure out what Type of Exception was thrown and, therefore, which "catch" block it should be directed to.  This is why Exceptions are "thrown" twice - once to find a handler (and locate any clean-up, "finally" blocks between "here" and "there") and again to actually "throw" it, ready to be handled.

Here's an example:

Method A generates a file name and called Method B, passing that name.

Method B wanders off and tries to store some data in a file of this name in some shared directory, somewhere.  But the file name cannot be reused and (for reasons I can't think of currently) Method A has no access to the underlying file system.  If Method B is called a second time in, say, the same day, the file will already exist.  In this case, Method B cannot overwrite the file without losing data.  Instead it throws a "FileAlreadyExists" exception, containing the errant file name.

Without instruction to the contrary, the default Exception Handler, right up at the root of the program (actually up in the Run-Time itself) would catch this (and every other) Exception, show the user an "Oops!" message, and then trash the program.  Not altogether useful.

Instead, Method A can catch this Type of Exception and, using the file name that it comes with, compute a new name for the file and try to call Method B again.  So long as this attempt doesn't throw another Exception, then the original Exception has been successfully "handled"; the user doesn't need to know anything about it, because the code has dealt with this "unexpected but possible" event.

So, a general-purpose, used-for-everything, "AnyOldException" class isn't much use, because the calling code can't [easily] work out what went wrong (do not try to unpick the Exception's Message property; that way lies Madness).  It's far, far better to use a typed Exception and let your code can take the strain.

Title: Should exceptions do things other than tell the user something went wrong?

Body:
I created a general class that accepts a string when it is constructed, and it spits out that string when a user calls what().  This is all it does; on throw, it returns the initializing string.

```<code>class Exception_As {
private:
    std::string message
public:
    Exception_As(const std::string& message) { // constructor
        this->message ="EXCEPTION: " +message;
    }

    virtual const char* what() const throw() {
        return message.c_str();
    }
}
</code>```

How I use my custom exception class:

```<code>bool check_range(
    const std::vector<std::string>& list,
    const unsigned& idx_start,  // where to start checking
    const unsigned& idx_end,    // where to stop checking
    const std::string& key
) {
    if ( idx_start > idx_end ) {
        throw Exception_As("check_range: start index > end index: now fix it! :D");
    }

    ... rest of code
} // end of check_range
</code>```

How a user would use check_range:

```<code>// some other user code using my check_range
void main() {
    try {
        ... set up variables

        my_hero_qualified = check_range(semi_finalists, third_place, first_place, my_hero);
        ...rest of code
    }

    catch (const Exception_As& e) {
        std::cout << e.what() << std::endl;
    }
}
</code>```

If the try/catch was not there, it would abort the program because of the thrown Exception_As.  If it was there, the user would be notified that "check_range: start index > end index: now fix it! :D".  For me, sure beats writing tons of BadEvent1Exception, BadEvent2Exception, etc classes.

I can see I'm being lazy with this method, and yeah, I can't do anything fancy like modify values based on exceptions or morph an object's state; but if you just entered unexpected territory, who knows if you're handling it correctly?  May as well just end it so you can fix what's up and develop properly.

So, question: if all exceptions do is break the program on unexpected circumstances, won't a single exception class that returns the problem be enough?

...Or should exceptions be doing other things anyway?  If not, why create so many classes of Exceptions that have different names, sure, but from what I've seen, only report that something went wrong.


答:
will it never change, or will it change? That's the question you really have to answer before you get a good response.

Static data that never changes (eg days of week names) are good to go in code;

Data that practically never changes (eg your server dns name) is also good to go in code, if it needs changing, its so rare that a code update is ok.

Data that doesn't change, but might (eg time delay between periodic refreshes) is probably best in a easily-changed location, such as a local config store (sqlite or xml, makes no real difference)

The storage is of little concern - if it never or hardly ever changes, you can read it all in at program start and cache it as program data. If, in the unlikely event it ever does need to change, a restart of the app is not so much a big deal.


答:
I am going to address not the legal issue but whether it is a good idea at all. In other words the impact on the company of you choosing to have a personal license.

If the product is something that makes your work easier but does not affect the ability of others in your company to maintain the same code, a personal license may be a good idea provided your company has no problem with you having it on your work computer (some companies especially ones with a large IT team tend to be very picky about what can be put on a computer for "security" reasons.)

However, if the code cannot be maintained except through using this tool, then you really need to have a corporate license that can move easily to another person when you are no longer there. You also should not be using such a tool without the knowledge and agreement of your company. For instance suppose you were tasked to develop some reports and your company has SQL Server which has its own reporting tool, but you personally prefer Crystal Reports so you use your personal copy of it to develop the reports. That would be unacceptable. But if you wanted to use a tool to format the code easily to meet a certain coding standard, the code is still usable by others, so it is OK.

Title: How do I handle situations when I need to use personal software for a commercial purpose?

Body:
If I work for a company and write code for them but I choose to buy a tool for myself and use it to write code for the company, do I need a commercial or personal license?

Specifically, in this case, I am asking about WebStorm IDE

JetBrains have Commercial (For companies and organizations) and Personal (For individual developers). I am an individual developer working for a company!


问:
Dependency Injection vs Mixing Levels of Abstraction
I've been reading Clean Code: A Handbook of Agile Software Craftsmanship by Robert C. Martin. One point he makes:

G34 Functions should descend only one level of abstraction

However, I'm wondering about the functions that actually create the objects for an application. Say we have dependencies

```<code>App -> Book -> Database
</code>```

Then using dependency injection, App would need to create both a Book and Database instance, and inject the database instance into Book.

Is this an acceptable breaking of the mixing level of abstraction rule?

If yes / no, why?

答:
My interpretation is that the levels of abstraction don't refer to what objects a function can see; it refers to what it's actually doing. It's not inconceivable that a function may have to receive and pass along an object from a much lower level of abstraction in the process of delegating tasks to the level immediately below it. But it shouldn't be operating on such an object directly.

If you're gluing stuff together in main, then that's one level of abstraction. I don't feel there's any violation of abstraction here, because main knows nothing about these objects except that one needs the other. If you need to do anything more complicated to glue things together, like look up something in a config file to know what to glue together, that's a different level that should be pushed somewhere else.


问:
Write to stdout and redirect or write directly to file?
I can see two ways to fill an empty file with data:

```<code>$ run_program arg1 > data_file
</code>```

or, specifically write code that manages a file and write to it?  ie. a file stream?

Which is better to implement?

答:
If you already have access to a convenient way of redirecting data to a file, e.g. UNIX's > operator, then it makes absolutely no sense to hard-code file-opening and writing logic into your program.

Even if you always want to create a specific file, you can just create a script, alias or function that knows the filename and does the right thing, while leaving other users of the program free to whatever they want with their output program. Also, your program gets smaller and less complicated, which is always good.

In short: writing to STDOUT can easily be extended to writing to a file. Using open(), write() and close() syscalls cannot easily be extended to piping, paging, ignoring, using on a read-only or full file system, etc.


答:
I always like programs that offer a -o option to specify the output file. It does not mean I never use redirection but there are times where I am not so sure about how the current command line handles the pipe and redirection, it's great to have -o option. Here is an example I am talking about:

```<code>cat thelist | xargs -I_ myprog -i _ -o _.result
</code>```

Without the -o option, I am not sure how to output to individual files with xargs. Beside, the coding is really not that tricky:

```<code>auto outf = stdout;
if (outputFilename) outf = fopen(outputFilename, "w");
// use outf for output
fprintf(outf, "blabla");
// end of using outf
if (outf != stdout) fclose(outf);
</code>```

Title: Write to stdout and redirect or write directly to file?

Body:
I can see two ways to fill an empty file with data:

```<code>$ run_program arg1 > data_file
</code>```

or, specifically write code that manages a file and write to it?  ie. a file stream?

Which is better to implement?

Body:
I always like programs that offer a -o option to specify the output file. It does not mean I never use redirection but there are times where I am not so sure about how the current command line handles the pipe and redirection, it's great to have -o option. Here is an example I am talking about:

cat thelist | xargs -I_ myprog -i _ -o _.result

Without the -o option, I am not sure how to output to individual files with xargs. Beside, the coding is really not that tricky:

auto outf = stdout;
if (outputFilename) outf = fopen(outputFilename, "w");
// use outf for output
fprintf(outf, "blabla");
// end of using outf
if (outf != stdout) fclose(outf);


问:
How do searches fit into a RESTful interface?
When designing a RESTful interface, the semantics of the request types are deemed vital to the design.

GET - List collection or retrieve element

PUT - Replace collection or element

POST - Create collection or element

DELETE - Well, erm, delete collection or element

However, this doesn't seem to cover the concept of "search".

E.g. in designing a suite of web services that support a Job Search site you might have the following requirements:

Get individual Job Advert

GET to domain/Job/{id}/

Create Job Advert

POST to domain/Job/

Update Job Advert

PUT to domain/Job/

Delete Job Advert

DELETE to domain/Job/

"Get All Jobs" is also simple:

GET to domain/Jobs/

However, how does the job "search" fall into this structure?

You could claim it's a variation of "list collection" and implement as:

GET to domain/Jobs/

However, searches can be complex and it's entirely possible to produce a search that generates a long GET string.  That is, referencing a SO question here, there are issues using GET strings longer than about 2000 characters.

An example might be in a faceted search - continuing the "job" example.

I may allow for searching on facets - "Technology", "Job Title", "Discipline" as well as free-text keywords, age of job, location and salary.

With a fluid user interface and a large number of technologies and job titles, it is feasible that a search could encompass a large number of facet choices.

Tweak this example to CVs, rather than jobs, bring in even more facets, and you can very easily imagine a search with a hundred facets selected, or even just 40 facets each of which are 50 characters long (e.g. Job Titles, University Names, Employer Names).

In that situation it might be desirable to move a PUT or POST in order to ensure that the search data will get correctly sent.  E.g.:

POST to domain/Jobs/

But semantically that's an instruction to create a collection.

You could also say you'll express this as the creation of a search:

POST to domain/Jobs/Search/

or (as suggested by burninggramma below)

POST to domain/JobSearch/

Semantically it may seem to make sense, but you're not actually creating anything, you're making a request for data.

So, semantically it's a GET, but GET isn't guaranteed to support what you need.

So, the question is - Trying to keep as true to RESTful design as possible, whilst ensuring that I'm keeping within the limitations of HTTP, what is the most appropriate design for a search?

答:
One approach to consider is treating the set of possible queries as a collection resource, e.g. /jobs/filters.

POST requests to this resource, with the query parameters in the body, will either create a new resource or identify an existing equivalent filter and return a URL containing its ID: /jobs/filters/12345.

The id can then be used in a GET request for jobs: /jobs?filter=12345. Subsequent GET requests on the filter resource will return the definition of the filter.

This approach has the advantage that it frees you from the query parameter format for filter definition, potentially providing you with more power to define complex filters. OR conditions are one example that I can think of that are difficult to accomplish with query strings.

A drawback to this approach is that you lose readability of the URL (although this can be mitigating by retrieving the definition though a GET request for the filter resource). For this reason you may also want to support the same or a subset of the query parameters on the /jobs resource as you would support for a filter resource. This could be used for shorter queries. If this feature is provided, in order to maintain cacheability between the two types of filtering, when using query parameters on the /jobs resource, the implementation should internally create/reuse a filter resource and return a 302 or 303 status indicating the URL in the form of /jobs?filter=12345.


答:
I originally wrote this answer for this question on stackoverflow, but I think the same answer applies for this question too.

There is an article by Mathias Verraes that talks about your problem here. He talks about Separating value objects in the model from concepts that serve the UI.

Quoting from the article when asked whether to model Countries as entities or value object:

There’s nothing intrinsically wrong with modelling countries as
  entities and storing them in the database. But in most cases, that
  overcomplicating things. Countries don’t change often. When a
  country’s name changes, it is in fact, for all practical purposes, a
  new country. If a country one day does not exist anymore, you can’t
  simply change all addresses, because possibly the country was split
  into two countries.

He suggested a different approach to introduce a new concept called AvailableCountry:

These available countries can be entities in a database, records in a
  JSON, or even simply a hardcoded list in your code. (That depends on
  whether the business wants easy access to them through a UI.)

```<code><?php

final class Country
{
    private $countryCode;

    public function __construct($countryCode)
    {
        $this->countryCode = $countryCode;
    }

    public function __toString()
    {
        return $this->countryCode;
    }
}

final class AvailableCountry
{
    private $country;
    private $name;

    public function __construct(Country $country, $name)
    {
        $this->country = $country;
        $this->name = $name;
    }

    /** @return Country */
    public function getCountry()
    {
        return $this->country;
    }

    public function getName()
    {
        return $this->name;
    }

}

final class AvailableCountryRepository
{
    /** @return AvailableCountry[] */
    public function findAll()
    {
        return [
            'BE' => new AvailableCountry(new Country('BE'), 'Belgium'),
            'FR' => new AvailableCountry(new Country('FR'), 'France'),
            //...
        ];
    }

    /** @return AvailableCountry */
    public function findByCountry(Country $country)
    {
        return $this->findAll()[(string) $country];
    }
}
</code>```

So it seems there is a 3rd solution which is to model look up tables as both value objects and entities.

BTW make sure u check the comments section for some serious discussions about the article.

Body:
I originally wrote this answer for this question on stackoverflow, but I think the same answer applies for this question too.

There is an article by Mathias Verraes that talks about your problem here. He talks about Separating value objects in the model from concepts that serve the UI.

Quoting from the article when asked whether to model Countries as entities or value object:

There’s nothing intrinsically wrong with modelling countries as
  entities and storing them in the database. But in most cases, that
  overcomplicating things. Countries don’t change often. When a
  country’s name changes, it is in fact, for all practical purposes, a
  new country. If a country one day does not exist anymore, you can’t
  simply change all addresses, because possibly the country was split
  into two countries.

He suggested a different approach to introduce a new concept called AvailableCountry:

These available countries can be entities in a database, records in a
  JSON, or even simply a hardcoded list in your code. (That depends on
  whether the business wants easy access to them through a UI.)

<?php

final class Country
{
    private $countryCode;

    public function __construct($countryCode)
    {
        $this->countryCode = $countryCode;
    }

    public function __toString()
    {
        return $this->countryCode;
    }
}

final class AvailableCountry
{
    private $country;
    private $name;

    public function __construct(Country $country, $name)
    {
        $this->country = $country;
        $this->name = $name;
    }

    /** @return Country */
    public function getCountry()
    {
        return $this->country;
    }

    public function getName()
    {
        return $this->name;
    }

}

final class AvailableCountryRepository
{
    /** @return AvailableCountry[] */
    public function findAll()
    {
        return [
            'BE' => new AvailableCountry(new Country('BE'), 'Belgium'),
            'FR' => new AvailableCountry(new Country('FR'), 'France'),
            //...
        ];
    }

    /** @return AvailableCountry */
    public function findByCountry(Country $country)
    {
        return $this->findAll()[(string) $country];
    }
}

So it seems there is a 3rd solution which is to model look up tables as both value objects and entities.

BTW make sure u check the comments section for some serious discussions about the article.


答:
In a strict sense, the Unix tradition would dictate to only deal with input and output streams and not duplicate the functionality of writing to files that is already present in the shell.

But of course, almost all real-world Unix utilities do have options for writing to and reading from files. And it's pretty darn convenient that they do! (Plus, not everybody works in a Unix environment.)


问:
Building a webservice with mvc
I'am planning my website over here based on MVC.

And I am thinking about a webservice (who knows, maybe one day I'll create an android app or something).

The site and the webservice will behave diferently from each other.

So what should I do? Write different controllers for each... or stuff IFs all over the place?

For example: on the site, the controller will act as such:

Password correct?

---->redirect user to welcome screen

Password incorrect?

---->render login page again

But the webservice will simple show a json like:

{message: 'wrong password/sucess'}

Which one you think is the best approach?

答:
Your "stuff IFs all over the place?" question sort of answers itself.  That's obviously not a good design.

You should separate the controllers, but have them rely on a common code base for shared actions.  For example, you should only have one place in your code that verifies a password.  Each controller should call this code and then respond with the appropriate behavior based on the context of that controller.

Title: Building a webservice with mvc


问:
When getting a list of files to process, should I store them to a list of string, or a list of Stream?
for a list of files, coming from a list like from a file dialog is it better to store the list as a list of strings or should I convert each file to opened Streams stored in a List?

For example

```<code>        List<string> files = new List<string>();

        List<FileStream> fileStreams = new List<FileStream>();

        foreach (Stream f in fileStreams)
        {
            //process stream
        }

        **VS**

        foreach (string s in files)
        {
            //open filestream
            FileStream fs = new FileStream(s, FileMode.Open);

            //process
        }
</code>```

答:
Just keep them as string as long a possible.

A stream is bound to external resources (hidden buffers, read ahead cache,...) and it is a good idea to minimized the time those are bound to your objects.

Some systems have a hard limit of how many files are open as well so if you open all streams at once it may happen that some streams don't open.


问:
Injecting dependencies (DI) in c++ applications
I am playing with dependency injection, but i am not sure I am doing it right.
Especially, I am not sure what should be the correct way to build classes with injected dependencies.

Say I have a class A that creates class B. Class B depends on class C and class C depends on class D. Who should be responsible for creating class D?

It could be class A. However, in a large system, class A might end up creating and assembling a very large number of objects.

A separate builder class that will create D, C and B. A will use this builder class.

Some other option.

In addition, I read a lot about DI containers. However, it seems that there are no major frameworks for C++. Also, if I understand correctly, DI can be performed well even without containers. Am I correct?

答:
Say I have a class A that creates class B. Class B depends on class C and class C depends on class D. Who should be responsible for creating class D?

You're jumping steps. Consider a set of conventions optimized for loose coupling and exception safety. The rules go like this:

R1: if A contains a B, then the constructor of A receives a fully constructed B (i.e. not "B's construction dependencies"). Similarly, if B's construction requires a C, it will receive a C, not C's dependencies.

R2: if a full chain of objects are required to construct an object, the chained construction is extracted/automated within a factory (function or class).

Code (std::move calls omitted for simplicity):

```<code>struct D { int dummy; };
struct C { D d; };
struct B { C c; }

struct A { B make_b(C c) {return B{c}; };
</code>```

In such a system, "who creates D" is irrelevant, because when you call make_b, you need a C, not a D.

Client code:

```<code>A a; // factory instance

// construct a B instance:
D d;
C c {d};
B = a.make_b(c);
</code>```

Here, D is created by the client code. Naturally, if this code is repeated more than once, you are free to extract it into a function (see R2 above):

```<code>B make_b_from_d(D& d) // you should probably inject A instance here as well
{
    C c {d};
    A a;
    return a.make_b(c);
}
</code>```

There is a natural tendency to skip the definition of make_b (ignore R1), and write the code directly like this:

```<code>struct D { int dummy; };
struct C { D d; };
struct B { C c; }

struct A { B make_b(D d) { C c; return B{c}; }; // make B from D directly
</code>```

In this case, you have the following problems:

you have monolithic code; If you come to a situation in client code where you need to make a B from an existent C, you cannot use make_b. You will either need to write a new factory, or the definition of make_b, and all the client code using the old make_b.

Your view of dependencies is muddled when you look at the source: Now, by looking at the source you get to think that you need a D instance, when in fact you may just need a C.

Example:

```<code>void sub_optimal_solution(C& existent_c) {
    // you cannot create a B here using existent_C, because your A::make_b
    // takes a D parameter; B's construction doesn't actually need a D
    // but you cannot see that at all if you just have:
    // struct A { B make_b(D d); };
}
</code>```

The omission of struct A { B make_b(C c); } will greatly increase coupling: now A needs to know the definitions of both B and C (instead of just C). You also have restrictions on any client code using A, B, C and D, imposed on your project because you skipped a step in the definition of a factory method (R1).

TLDR: In short, do not pass the outermost dependency to a factory, but the closest ones. This makes your code robust, easily alterable, and renders the question you posed ("who creates D") into an irrelevant question for the implementation of make_b (because make_b no longer receives a D but a more immediate dependency - C - and this is injected as a parameter of make_b).

Body:
Say I have a class A that creates class B. Class B depends on class C and class C depends on class D. Who should be responsible for creating class D?

You're jumping steps. Consider a set of conventions optimized for loose coupling and exception safety. The rules go like this:

R1: if A contains a B, then the constructor of A receives a fully constructed B (i.e. not "B's construction dependencies"). Similarly, if B's construction requires a C, it will receive a C, not C's dependencies.

R2: if a full chain of objects are required to construct an object, the chained construction is extracted/automated within a factory (function or class).

Code (std::move calls omitted for simplicity):

struct D { int dummy; };
struct C { D d; };
struct B { C c; }

struct A { B make_b(C c) {return B{c}; };

In such a system, "who creates D" is irrelevant, because when you call make_b, you need a C, not a D.

Client code:

A a; // factory instance

// construct a B instance:
D d;
C c {d};
B = a.make_b(c);

Here, D is created by the client code. Naturally, if this code is repeated more than once, you are free to extract it into a function (see R2 above):

B make_b_from_d(D& d) // you should probably inject A instance here as well
{
    C c {d};
    A a;
    return a.make_b(c);
}

There is a natural tendency to skip the definition of make_b (ignore R1), and write the code directly like this:

struct D { int dummy; };
struct C { D d; };
struct B { C c; }

struct A { B make_b(D d) { C c; return B{c}; }; // make B from D directly

In this case, you have the following problems:

you have monolithic code; If you come to a situation in client code where you need to make a B from an existent C, you cannot use make_b. You will either need to write a new factory, or the definition of make_b, and all the client code using the old make_b.

Your view of dependencies is muddled when you look at the source: Now, by looking at the source you get to think that you need a D instance, when in fact you may just need a C.

Example:

void sub_optimal_solution(C& existent_c) {
    // you cannot create a B here using existent_C, because your A::make_b
    // takes a D parameter; B's construction doesn't actually need a D
    // but you cannot see that at all if you just have:
    // struct A { B make_b(D d); };
}

The omission of struct A { B make_b(C c); } will greatly increase coupling: now A needs to know the definitions of both B and C (instead of just C). You also have restrictions on any client code using A, B, C and D, imposed on your project because you skipped a step in the definition of a factory method (R1).

TLDR: In short, do not pass the outermost dependency to a factory, but the closest ones. This makes your code robust, easily alterable, and renders the question you posed ("who creates D") into an irrelevant question for the implementation of make_b (because make_b no longer receives a D but a more immediate dependency - C - and this is injected as a parameter of make_b).


答:
Things to consider:

How static is the data? If it'll never change, than it should live in the object. In order to change the data, you might have to re-compile and redeploy. Are you happy with doing a redeployment for a minor change?

If it's a web application and you have it as part of the web.config, are you happy with application restarting when you make changes to that data?

If you put it into a database, you can always cache it on client side (desktop application) or server side (service or website). Database might be a good solution IMO.


问:
Heuristic Approach for Flexible DIFF Implementation
I have created a DIFF implementation to compare document revisions at work.  It is based on An O(ND) Difference Algorithm and Its Variations.

One thing that has become important is to take the list of changes and interpret them into human readable text.  While the current algorithm is very efficient, it is so much so that it is difficult to expand upon.

Short Question

I was thinking about trying to use A* and a heuristic that adds penalties for "turns".  The idea being to smooth out unnecessary "add, delete, add, delete, add, delete" so that it is easier to parse into something a human can read.  Basically, turn my shortest path problem into a simplest path problem.

And of course not create output that is always "Delete everything, Add everything"

Does this sound reasonable?

Is there any precedence for using a heuristic in a DIFF implementation?  What is the heuristic?

The Problem:

If a long sentence is deleted and another long sentence removed, but they do share at least one word, say "with".  Leaving the common word alone (by not both adding and deleting it) will create the shortest path.  However, this really just obfuscates the context of the change to a human trying to read a print out of the changes.

Example with current DIFF:

Old text:  Clean:  Powerwash and blow dry with shop air.

New text:  Clean:  Wipe with acetone and a lint free cloth.

Change Note List:

Change "Powerwash and blow dry" to "Wipe with acetone"

Change "shop air" to "acetone and a lint free cloth"

Note: "Change" is used instead of "delete 'shop air', add 'acetone'"

As you can see, the second note loses ALL context and without still looking at the full old and new text sets of text you cannot understand what it means.

Note about Punctuation:

I have delimited punctuation as separate "words" so that I would get

Add "("

instead of

Change "Repair" to "(Repair"

because this was obnoxious.  However, that means that if there is even a comma in both texts (as opposed to the word "with" in the previous example) the same thing happens.

Possible Solution:

I think I could use a different path finding algorithm instead that can give me the flexibility to add weight to different change "paths" that might make more sense to a person.  Maybe, I could even make traveling to nodes containing punctuation have little weight (not sure how this would effect other things).

Then I could get the previous example to list the following:

Change Note List:

Change "Powerwash and blow dry with shop air" to "Wipe with acetone and a lint free cloth"

See! Much clearer!

I know I would take a performance hit, and I might have to do a fairly major overhaul of my program, but it's more important to have the final result I want.

Bottom Line:

Again, is there any precedence for using a heuristic in a DIFF implementation, and what is it?

Other thoughts?  A reasonable time investment?  Other ideas?  Other algorithms?

Thanks in advance!

EDIT:

I tried to clarify/solidify my question and generalize my question to adding a heuristic to my algorithm, rather than using A*.  Basically the same thing in this instance, but I still think more accurate now.  This post was insightful.

答:
You might do in a vimdiff-like version:

Step 1: identifying added, deleted and modified sentences.

Step 2: for each modified sentence, locate the first and the last changed words, and cut anything not between these two words.

If you need to keep coherent more grammar structure, look at the internals of http://www.languagetool.org/ or another shown on this post.

About presentation: you may present both versions of that sentence one under the other. You might want to show the context for each change. For inspiration, look at latexdiff which can print the added text in blue at is final place in the final version of text, and the deleted text in footnotes (even compatible with \usepackage[para]{footmisc}).


问:
How to indicate to a web server the language of a resource
I'm writing an HTTP API to a publishing server, and I want resources with representations in multiple languages. A user whose client GETs a resource which has Korean, Japanese and Trad. Chinese representations, and sends Accept-Language: en, ja;q=0.7 should get the Japanese.

One resource, identified by one URI, will therefore have a number of different language representations. This seems to me like a totally orthodox use of content negotiation and multiple resource representations.

But when each translator comes to provide these alternate language representations to the server, what's the correct way to instruct the server which language to store the representation under? I'm having the translators PUT the representation in its entirety to the same URI, but I can't find out how to do this elegantly. Content-Language is a response header, and none of the request headers seem to fit the bill.

It seems my options are

Invent a new request header

Supply additional metadata in a multipart/related document

Provide language as a parameter to the Content-Type of the request, like Content-Type: text/html;language=en

I don't want to get into the business of extending HTTP, and I don't feel great about bundling extra metadata into the representation. Neither approach seems friendly to HTTP caches either. So option 3 seems like the best way that I can think of, but even then it's decidedly non-standard to put my own specific parameters on a very well established content type.

Is there any by-the-book way of achieving this?

答:
First of all, let's give your resource a name: let's call it a publication. This is to disambiguate it from another kind of resource your design is implying: the translation.

Second, let's agree to the fact that a collection of resources is also a resource itself. Having said that, a publication looks to me more like a collection of translations.

Third, using PUT to create a translation seems inappropriate to me, because PUT is used to replace a resource with another one. It would make sense if a translation to a specific language was already there, and the translator was updating it. But to create a new one, I think POST suits best.

EDIT: I'm having second thoughts on the above. It appears that, since the id of the new resource is decided by the client, a PUT would actually be appropriate after all. Maybe someone else could provide a more concrete opinion on the matter.

Now, considering the above, a uri structure like /publication/XYZ/en would certainly make sense, because it would refer to the English translation of the publication with id XYZ. This resolves the creating/updating/deleting of translations (using POST/PUT/DELETE resp.), while during a GET request of /publication/XYZ you could examine the Accept-Language header and make the client redirect accordingly.

OTOH, your question clearly states that you want to treat the publication as a single resource. In that case, I guess you must treat translations as separate attributes (i.e. fields) of the same resource. Just as a person resource would have a first name, a last name and an e-mail, a publication could have a publication date, an English translation and a Japanese one.

But then you would have to find a way to partially update the publication when a translation would need to be created/edited. I guess a PATCH request would be appropriate for this scenario.


问:
Entities optional relations: separate classes or single class?
Lets focus on a domain object that is related to more other (different!) entities. Sometimes we need one relation and sometimes the other. Let's be agile and say: we don't know in a front how many other relations there will be.

In other words: we have object A that is related one-to-one to B and one-to-many to C and again one-to-one to D and so on. Now, when developing the presentation tier, it often needs a lot of data to display; like table of A with B, or on other place one A with many C and so on.

How we gonna model these relationships?

Here is an example: Competition. Sometimes it comes and needs to be used with e.g. Venue. Sometimes with e.g. List<Event>. Since you care about performances, let's also say that the related objects (Venue and list of Events) come from the single input/repository method/finder method/one SQL join  (however you call it) - and that they can be injected into Competition using some mapping tool. This way we express the actual relationship between the entities.

Question: should we keep both relations/references in the Competition class and ignore the other when one is used, or we should make many separate classes - one for each relation? (It doesn't matter if it is 1-1 relation or 1-many, the question is the same.)

In other words, should we have:

[A]

Everything in the single class. Getter methods do represents relationships. It's on us to fill the object if relation is needed.

```<code>class Competition {
    ... competition data...

    private Venue venue;
    public Venue getVenue() {
        return venue;
    }

    private List<Event> events;
    public List<Event> getEvents() {
        return events;
    }
}
</code>```

But then, when your application method return a Competition you don't know what relations are populated and you have to figure that out by looking the application methods code or by method name (e.g. findCompetitionWithEvents...()).

[B]

For each relationship we have a type or interface. One way to do so, without interfaces for the simplicity of this example, is:

```<code>class CompetitionVenue extends Competition {
    private Venue venue;
    public Venue getVenue() {
        return venue;
    }
}
</code>```

and

```<code>class CompetitionEvents extends Competition {
    private List<Event> events;
    public List<Event> getEvents() {
        return events;
    }
}
</code>```

Now the type speaks by itself what relationship is returned and therefore application method that returns it guarantees that relation exists. But then each relationship would have its own class or interface;

EDIT:

[C]

Each relationship is represented using a generic class like Tuple<Competition, List<Event>> and Competition does not have the getter for list of events?

答:
I try to follow the "clean code" idea of never returning null (at least as much as I can).  That idea suggests that option B (two subclasses) is the better alternative.

I have an actual case that explains this... our system allows you to log a Ticket against various other entities in the system, but only against one type, so you might log it against a Mill or against a Computer.  In those cases we have a MillTicket and a ComputerTicket.  Only the ComputerTicket has a reference to a Computer.  On the SQL side, they're just nullable foreign keys.

An advantage is that a ComputerTicket can have all kinds of fields that are only applicable when I'm logging a Ticket against a Computer.

What this prevents is the ability to have a Ticket against 2 different entities, so that's a design decision with a pretty significant consequence.  Also, it means that it's relatively difficult to retroactively change a ComputerTicket into a MillTicket if someone changes their mind.  It can be done but it's a pain.


问:
Can we consider a clients interaction with a web server to be stateful if the web server maintains state via session variables or cookies?
A little confused with the notion of stateful/stateless architectures. Forgive me if I'm unclear.

Questions: Can we consider a clients interaction with a web server to be stateful if the web server maintains state via session variables or cookies? What if we assume that any change to this information comes from the client side any way and doesn't depend on other users?

What about amazon's web store? Although state may change and not be reflected automatically to the client... if the client attempts to operate on stale data, the system recognizes this and acts appropriately. Is this purely stateless still? Or somewhere in between?

What if we added a layer of java script that constantly polled the server every second to keep the client side updated? At an abstract level wouldn't this be considered stateful because the client will continuously have an updated state?

Definitions/Models I'm trying to work with:

Stateless architecture of websites: HTTP is a stateless protocol. The client makes an HTTP web request. The server calculates/processes the request and returns back to the client the appropriate information which the current state of the website. While the client has that information, the website can change state and these changes won't be reflected back to the client side until the client makes another web request.

Stateful architecture: The client can simply operate assuming that any data that is seen represents the actual state of the server.

答:
HTTP is a stateless protocol in that each request is an independent transaction.  What came previously or what is expected to come next has no effect on an individual request.

However, this doesn't mean everything you do on the internet is stateless.  Sites like Amazon store states, obviously.  They remember what you have done in the past and know what you are in the middle of doing.  The shopping cart remembers what items you have added across many individual HTTP requests.

Websites get around the stateless nature of HTTP protocol by doing two basic things:

Storing the state of each user on the server, such as your shopping cart, your profile, and the history of what you have purchased.

A method of identifying the same user across multiple requests, such cookies stored on the client side, IP address, and state information embedded in the source of a web page that was served.  In practice, multiple methods of identification are often used together.

Even though each request is independent from the point of the view of the protocol, the application of these methods gives a context to each page that is served to you.  The stateless is made stateful.


问:
How to I write tests for code that's driving Robot and other external features?
I've got some code I use to take regular screenshots of my screen - it's useful to work out how much of any given day I'm spending on various activities. It looks like this:

```<code>/**
 * Code modified from code given in
 * http://whileonefork.blogspot.co.uk/2011/02/java-multi-monitor-screenshots.html following a SE
 * question at
 * http://stackoverflow.com/questions/10042086/screen-capture-in-java-not-capturing-whole-screen and
 * then modified by a code review at
 * http://codereview.stackexchange.com/questions/10783/java-screengrab
 */
package com.tmc.personal;

import java.awt.*;
import java.awt.image.*;
import java.io.File;
import java.io.IOException;

import javax.imageio.ImageIO;

// TODO: improve screencapture tool by having it not take a photo when the mouse hasn't moved...

class ScreenCapture implements Runnable {

  private int minsBetweenScreenshots = 5;
  private String workingDirectory = "";

  public ScreenCapture(String string, int i) {
    workingDirectory = string;
    minsBetweenScreenshots = i;
  }

  private void tryWritingScreenshotToFile(int indexOfPicture) {
    try {
      Image scaledImg = takeScreenshot();
      storeImageToFile(workingDirectory + "ScreenCapture" + indexOfPicture, scaledImg);
    } catch (IOException e1) {
      // skip, move to the next one
    } catch (AWTException e) {
      // photo didn't work skip and move on.
    }
  }

  private Image takeScreenshot() throws AWTException {
    Rectangle allScreenBounds = getAllScreenBounds();
    Robot robot = new Robot();
    BufferedImage img = robot.createScreenCapture(allScreenBounds);
    return scaleImage(img);
  }

  private void storeImageToFile(String filename, Image scaledImg) throws IOException {
    ImageIO.write(toBufferedImage(scaledImg), "jpg",
        new File(filename + ActivityLogger.getDateTime() + ".jpg"));
  }

  // code from
  // http://www.java-forums.org/new-java/2790-how-save-image-jpg.html
  private BufferedImage toBufferedImage(Image src) {
    int w = src.getWidth(null);
    int h = src.getHeight(null);
    int type = BufferedImage.TYPE_INT_RGB; // other options
    BufferedImage dest = new BufferedImage(w, h, type);
    Graphics2D g2 = dest.createGraphics();
    g2.drawImage(src, 0, 0, null);
    g2.dispose();
    return dest;
  }

  private Image scaleImage(BufferedImage img) {
    int scaledWidth = (int) (img.getWidth() * 0.5);
    int scaledHeight = (int) (img.getHeight() * 0.5);
    Image scaledImg =
        img.getScaledInstance(scaledWidth, scaledHeight, BufferedImage.SCALE_AREA_AVERAGING);
    return scaledImg;
  }

  /**
   * Okay so all we have to do here is find the screen with the lowest x, the screen with the lowest
   * y, the screen with the higtest value of X+ width and the screen with the highest value of
   * Y+height
   *
   * @return A rectangle that covers the all screens that might be nearby...
   */
  private Rectangle getAllScreenBounds() {
    Rectangle allScreenBounds = new Rectangle();
    GraphicsEnvironment ge = GraphicsEnvironment.getLocalGraphicsEnvironment();
    GraphicsDevice[] screens = ge.getScreenDevices();

    int farx = 0;
    int fary = 0;
    for (GraphicsDevice screen : screens) {
      Rectangle screenBounds = screen.getDefaultConfiguration().getBounds();
      // finding the one corner
      if (allScreenBounds.x > screenBounds.x) {
        allScreenBounds.x = screenBounds.x;
      }
      if (allScreenBounds.y > screenBounds.y) {
        allScreenBounds.y = screenBounds.y;
      }
      // finding the other corner
      if (farx < (screenBounds.x + screenBounds.width)) {
        farx = screenBounds.x + screenBounds.width;
      }
      if (fary < (screenBounds.y + screenBounds.height)) {
        fary = screenBounds.y + screenBounds.height;
      }
      allScreenBounds.width = farx - allScreenBounds.x;
      allScreenBounds.height = fary - allScreenBounds.y;
    }
    return allScreenBounds;
  }

  @Override
  public void run() {
    int indexOfPicture = 1000;
    while (true) {
      tryWritingScreenshotToFile(indexOfPicture++);
      ActivityLogger.waitForNextSampleTime(minsBetweenScreenshots);
    }
  }

}
</code>```

The expected behavior of the class is that it takes a full-screen (including external monitors) screenshot every five minutes...

I've recently fallen in love with Test Driven Development on other projects and I've come back to this old code. But being honest - I have no idea where I would start with writing tests for it - everything is so tightly coupled to the outside world that simple tests seam impossible - is the a best-practice approach in such situations?

答:
Strictly speaking, you can't. You could mock the APIs, but you'd only be testing that you're calling them a certain way in the implementation. That doesn't prove the implementation is correct - if you make incorrect assumptions in the implementation, you're going to duplicate those mistakes in the tests. Moreover, your tests will be brittle, because you're testing implementation details. When the implementation changes, your tests will have to change too.

You could go the pure functional programming approach and build a new API that outputs IO commands to be executed (rather than actually performing the commands.) For example, you could write functions that return ScreenCapture objects that contain the details of what you're trying to do, e.g. the rectangle of the screen you want to capture. These are just data objects - they don't actually do anything. But you could test that the right command objects are being returned given certain arguments...

...However, at some point some code has to translate those command objects into actual Robot API calls. How do you prove that code is correct? You're back at square one. At the end of the day, you're going to need a proof somewhere. Peer reviews will help expose any details you might've missed.

Testing can expose the presence of bugs, but never their absence.


问:
When using "Github Flow", what if my next feature depends on code from a pending Pull Request?
We are experimenting with "Github Flow", as defined here.

In short, every change starts off as a well-named branch off of master. When it's done, you open a PR for that branch, it gets reviewed, and then gets merged into master. It's a very simple workflow.

However, we have run into this a couple of times: I develop feature X, and open a PR for it. While I'm waiting for the PR for X to be reviewed, I want to start work on another feature Y, but I need the code from PR X.  Should I just start a branch from the feature X branch, or if I've already started feature Y, just merge feature X into the feature Y branch? It seems so, but I wanted to check with other teams that are following this model to see how they handled multiple PRs and features that are dependent upon each other.

答: I start the new work based off branch X. As branch X changes from code reviews, continue to merge it into your new branch Y


问:
Explanation of the code snippet , keyword operator in , in c++ , use of objects in classes
```<code>class Vector {
          public:
           Vector(int s) :elem{new double[s]}, sz{s} { }
           double& operator[](int i) { return elem[i]; } //function 2
           int size() { return sz; }

            private:
                double∗ elem;
                int sz;
         };
</code>```

Code snippet from : the c++ prog. language 4th edition , Bjarne
IDE : Microsoft Visual Studio Professional 2013
My experience : Newbie , have learned a little using turbo c++ before.

I noticed while typing function2 that operator is a keyword(shown in blue color) , but when whole function2 is declared , operator turns white , that is it doesn't remain an keyword anymore.

If i try using any other name other than "operator" , an error pops up , which says
Error: array of function is not allowed

It would be very helpful if someone can explain what is happening in function2, I want to know all that there is about the keyword operator , why,how and when to use this.Ofcourse from a beginner's perspective.

Please refrain from overly complex answers , I am complete newbie

I tried searching on internet , couldn't find anything else apart from operator overloading , which is not my question.

```<code>double read_and_sum(int s) {
                        Vector v(s);                     //line 1
                        for (int i=0; i!=v.size(); ++i)
                        cin>>v[i];                        //line 3
                        double sum = 0;
                        for (int i=0; i!=v.size(); ++i)
                        sum+=v[i];
                         return sum;
                        }
</code>```

Here line1 passes the argument "s" of int type needed by constructor of class vector , that's fine.

But in line3 how can the statement "cin>>v[i]" be valid ? , since the object v isn't declared as an array of objects.
Even if it is valid where does the value go..?

Basically it is out of my knowledge , please explain line3 in simplest possible manner, and at the same time as exhaustively as possible , so that I can learn.

PS: Do not tell me , that i shouldn't be learning c++ , or i shouldn't be using that IDE or anything else like that. If you can , then answer the question, I shall be very thankful.

答:
What this is is called operator overloading. You are overloading the operator [] with a new method. So basically, operator is a conditional keyword here. You can't use it as a method or variable name, but you can reference it for defining an operator overload. So its reserved in some situations, but not others, like the above example.

And to explain operator overloading: You are adding operators to a class so that it can do that functionality when you use the specific syntax associated with that operator.

So, in this case, we're adding the array access operator to the class, so we can use that functionality as if it were an array.

Examples of operators you can overload:

addition (+)

subtraction (-)

multiplication (*)

and so on.

In essence, operator overloading allows a class to act like another type of object. Any sort of operation, like addition, assignment, increment, decrement, comparisons(<, >, !=, ==, etc), and so on all are operators that can be overloaded. This allows you to write a class and be able to use that syntax, such as newObj > oldObj, instead of calling a method, like newObj->IsGreaterThan(oldObj).


问:
Pros and Cons of RESTful architecture
The most common discussion I've seen regarding the pros and cons of REST tends to frame that discussion relative to SOAP. I have no experience in either. I am currently faced with a decision which my lack of experience is making hard for me to evaluate.
I am beginning to develop an application that has several components - primarily an administrative aspect that allows the owner to administer several sites - and a public facing user interface that allows the user to interact with data held on the host.
I need to evaluate the implications of allowing the latter part to be hosted anywhere and communicate with the former via a RESTful architecture - or demanding that both components reside on the same host.
What are the key implications of developing RESTful architecture, particularly with regards to it's capacity in the following areas:

1: Security
2: Performance
3: Interface complexity

EDIT: Looking at some of the answers to this question - I should clarify. I'm not looking for a comparison to SOAP - rather an overview of REST applications vs applications where all components reside on one host. (thanks for those answers though!)

答:
Security: Use HTTPS. This applies to both.

Performance:. REST is less CPU expensive (less parsing, marshalling, unwrapping). Also, caching with REST is piece of cake.

Complexity: REST demands much less in terms of setup, it's just GET/POST after all. SOAP requires much more administration to maintain (wsdl etc), but is a bit easier if your IDE supports it.

I think SOAP is way too bloated when you can do the same thing with REST and some content/mime-types. Also, SOAP brings lots of overhead, due to its wrapping-of-wrappers nature and the fact that it is more general and not limited to HTTP. SOAP is tempting to use if your IDE supports it properly and you don't want to learn HTTP. But for me, REST is much easier to use and much more more web friendly.

Nowadays, there are very good REST APIs to use. If you're into Java, then Jax-RS is really cool. For some folks, this is like porn.

Title: Pros and Cons of RESTful architecture


答:
Your model is clear example of abstraction, but your are approaching it from wrong way. You want to know location of competition, but you don't know what kind of location it is. So you should create an interface or abstract class that defines this location (lets call it Location) and then derive Venue and Event from it.

Also, you are first talking about domain model and then talking about SQL joins. You are mixing the two things together which is never a good thing. Focus either on one or the second, but never on both at the same time.

Title: Entities optional relations: separate classes or single class?

Body:
Lets focus on a domain object that is related to more other (different!) entities. Sometimes we need one relation and sometimes the other. Let's be agile and say: we don't know in a front how many other relations there will be.

In other words: we have object A that is related one-to-one to B and one-to-many to C and again one-to-one to D and so on. Now, when developing the presentation tier, it often needs a lot of data to display; like table of A with B, or on other place one A with many C and so on.

How we gonna model these relationships?

Here is an example: Competition. Sometimes it comes and needs to be used with e.g. Venue. Sometimes with e.g. List<Event>. Since you care about performances, let's also say that the related objects (Venue and list of Events) come from the single input/repository method/finder method/one SQL join  (however you call it) - and that they can be injected into Competition using some mapping tool. This way we express the actual relationship between the entities.

Question: should we keep both relations/references in the Competition class and ignore the other when one is used, or we should make many separate classes - one for each relation? (It doesn't matter if it is 1-1 relation or 1-many, the question is the same.)

In other words, should we have:

[A]

Everything in the single class. Getter methods do represents relationships. It's on us to fill the object if relation is needed.

```<code>class Competition {
    ... competition data...

    private Venue venue;
    public Venue getVenue() {
        return venue;
    }

    private List<Event> events;
    public List<Event> getEvents() {
        return events;
    }
}
</code>```

But then, when your application method return a Competition you don't know what relations are populated and you have to figure that out by looking the application methods code or by method name (e.g. findCompetitionWithEvents...()).

[B]

For each relationship we have a type or interface. One way to do so, without interfaces for the simplicity of this example, is:

```<code>class CompetitionVenue extends Competition {
    private Venue venue;
    public Venue getVenue() {
        return venue;
    }
}
</code>```

and

```<code>class CompetitionEvents extends Competition {
    private List<Event> events;
    public List<Event> getEvents() {
        return events;
    }
}
</code>```

Now the type speaks by itself what relationship is returned and therefore application method that returns it guarantees that relation exists. But then each relationship would have its own class or interface;

EDIT:

[C]

Each relationship is represented using a generic class like Tuple<Competition, List<Event>> and Competition does not have the getter for list of events?


答:
If you only ever need to use either Venue OR Event but never both at the same time, that's pretty much a sum type. I posted an answer a while back showing how to encode them in C#. Unfortunately it's only really practical with lambdas, so unless you're using Java 8, the match method is going to be verbose as hell to use. You could, however, still make use of instanceof to distinguish between the options just as you're already doing in option B. The catch is that using instanceof, if you later add an extra alternative you'll have to find every place you made an if ... else if ... and add the new alternative into the code. Also, this only works for a finite number of possibilities, but that sounds like what you have here.

Using that as a foundation, you could create a class Either that contains a value of either type A or type B, where A and B could be Venue and Event. E.g.

```<code>public class Competition {
    private Either<Venue, Event> venueOrEvent;
    ...
}
</code>```

If instead what you need is a finite number of types of Competition (i.e. there's exactly 5 competition types, each with its own set of data) you could just do what you were already doing in option B, except making them inner classes of the Competition class and giving Competition a private constructor so no one can sneak in additional subclasses.

Body:
If you only ever need to use either Venue OR Event but never both at the same time, that's pretty much a sum type. I posted an answer a while back showing how to encode them in C#. Unfortunately it's only really practical with lambdas, so unless you're using Java 8, the match method is going to be verbose as hell to use. You could, however, still make use of instanceof to distinguish between the options just as you're already doing in option B. The catch is that using instanceof, if you later add an extra alternative you'll have to find every place you made an if ... else if ... and add the new alternative into the code. Also, this only works for a finite number of possibilities, but that sounds like what you have here.

Using that as a foundation, you could create a class Either<A, B> that contains a value of either type A or type B, where A and B could be Venue and Event. E.g.

public class Competition {
    private Either<Venue, Event> venueOrEvent;
    ...
}

If instead what you need is a finite number of types of Competition (i.e. there's exactly 5 competition types, each with its own set of data) you could just do what you were already doing in option B, except making them inner classes of the Competition class and giving Competition a private constructor so no one can sneak in additional subclasses.


问:
Tight Coupling Between Javascript, HTML, and CSS: A More Modern Approach?
It's very common to see Javascript bound to certain selectors to find elements, store data, and listen for events. It's also common to see these same selectors used for styling.

jQuery (and its selector engine Sizzle) support and promote this by referencing elements with CSS-type syntax. As such, this technique is particularly difficult to 'unlearn' (or refactor) when building out projects.

I've come to understand that this is a result of the history of HTML and Javascript development, and that browsers have been built to efficiently consume / parse / and render this sort of coupling. But as websites become increasingly complex, this reality can introduce difficulties in organizing and maintaining these separate layers.

My question is: can and should this be avoided in modern websites?

If I'm new to front-end development, and I wish to learn things 'the right way,' is it worth learning to decouple and avoid such dependencies from the start? Does this mean avoiding jQuery in favor of a library that promotes a more decoupled structure?

答:
If you're willing to forego the interactivity that you get, you can avoid Javascript entirely.  Frameworks like ASP.NET MVC are very good at serving up pages that only contain HTML, CSS, and a SUBMIT button.

OK. Maybe that's a bit extreme.

Decoupling in a web application already occurs at many levels.  REST applications allow you to define your application in terms of "web resources" that are associated with an URL.  View Models allow you to present data to the UI that is decoupled from the domain model, but has the shape that you need to properly display it.  Service layers allow one UI to be swapped for another, and so forth.

Historically, there's always been a tradeoff between interactivity and coupling.  The more interactive your web page is, the more tightly-coupled to the application it's going to be.  But the interactivity logic in the web page is confined to the web page itself; any coupling with the server is going to occur through either POST or AJAX.  So I'm not sure you should be overly concerned with coupling at the Javascript level, other than paying attention to the way data packets are passed between the browser and the server.

The most "modern" approach (i.e. the flavor of the week) is probably SPA applications.


答:
There is no way to avoid that. They are coupled because they interact with each other. If your javascript intends on doing any kind of DOM manipulation, then it needs a way to reference the DOM.

There are various conventions for it.

The Level 2 DOM API provides the getElementById, getElementByTagName, and getElementsByName methods. To this day these are the workhorses of any kind of DOM traversal. All other fancier jQuery selectors resolve into a combination of these eventually, and/or straight up traversal of each DOM node (this was the way to do getByClassName).

There is no other shortcut. Javascript needs to know what to do and where. Typically, if an element has an id or class that is only relevant in scripting, a lot of people will prefix it with js- or some other obvious flag.

Another newer convention is the data-attribute selection.

```<code><ul data-myapp-sortable="true">

jQuery('[data-myapp-sortable]').makeSortable();
</code>```

The data-attribute is generally used for scripting purposes and selecting using that makes some sense. The drawback is that this is slower than using getElementById().

Another approach is the one used by angularJS, which creates a view-model. In this convention any kind of scripting functionality is specified by specially designated attributes like ng-disabled ng-href and many more. You don't add selectors in your javascript. The HTML document becomes the main authority on what is scripted and how, and the javascript works on it abstractly. It's a good approach, but obviously with a higher learning curve than the previous methods. And again, performance has to be considered.

But don't ever think that you can write interactive HTML and javascript, and somehow have both those parts not know about the other. It's more about how can you limit the references to dependencies.

Title: Tight Coupling Between Javascript, HTML, and CSS: A More Modern Approach?

Body:
It's very common to see Javascript bound to certain selectors to find elements, store data, and listen for events. It's also common to see these same selectors used for styling.

jQuery (and its selector engine Sizzle) support and promote this by referencing elements with CSS-type syntax. As such, this technique is particularly difficult to 'unlearn' (or refactor) when building out projects.

I've come to understand that this is a result of the history of HTML and Javascript development, and that browsers have been built to efficiently consume / parse / and render this sort of coupling. But as websites become increasingly complex, this reality can introduce difficulties in organizing and maintaining these separate layers.

My question is: can and should this be avoided in modern websites?

If I'm new to front-end development, and I wish to learn things 'the right way,' is it worth learning to decouple and avoid such dependencies from the start? Does this mean avoiding jQuery in favor of a library that promotes a more decoupled structure?

Body:
There is no way to avoid that. They are coupled because they interact with each other. If your javascript intends on doing any kind of DOM manipulation, then it needs a way to reference the DOM.

There are various conventions for it.

The Level 2 DOM API provides the getElementById, getElementByTagName, and getElementsByName methods. To this day these are the workhorses of any kind of DOM traversal. All other fancier jQuery selectors resolve into a combination of these eventually, and/or straight up traversal of each DOM node (this was the way to do getByClassName).

There is no other shortcut. Javascript needs to know what to do and where. Typically, if an element has an id or class that is only relevant in scripting, a lot of people will prefix it with js- or some other obvious flag.

Another newer convention is the data-attribute selection.

<ul data-myapp-sortable="true">

jQuery('[data-myapp-sortable]').makeSortable();

The data-attribute is generally used for scripting purposes and selecting using that makes some sense. The drawback is that this is slower than using getElementById().

Another approach is the one used by angularJS, which creates a view-model. In this convention any kind of scripting functionality is specified by specially designated attributes like ng-disabled ng-href and many more. You don't add selectors in your javascript. The HTML document becomes the main authority on what is scripted and how, and the javascript works on it abstractly. It's a good approach, but obviously with a higher learning curve than the previous methods. And again, performance has to be considered.

But don't ever think that you can write interactive HTML and javascript, and somehow have both those parts not know about the other. It's more about how can you limit the references to dependencies.


答:
No, using class, element, and ID selectors client-side should not be avoided.  The syntax is used because CSS selectors are very mature and well-established domain language, and having a common design makes it far easier to share a common logical model of a page between program and design, which is a very, very good thing.

While it is possible to mis-use this syntax and create a terrible and unmaintainable application, such is possible regardless of your language or toolset.