问:
If-Else V.S. Switch end of flow
I was wondering the if if-else statements, is like a switch statement that does have a break statement.

```<code>if( boolean_expression_1 )
  statement_1
else if( boolean_expression_2 )
  statement_2
else
  default_statement
</code>```

Is the same as:

```<code>switch( controlling_expression )
{
case: ( boolean_expression_1 )
{
     statement_1
     break;
}
case: ( boolean_expression_2 )
{
     statement_2
     break;
}
default:
{
     default_statement
}
</code>```

答:
To answer the edited question (with the breaks)

They would evaluate the statements the same, if and only if the conditions to enter each block is the same.

To answer the subjective question, of

gives an angle of thought of preserved similarities and also what they are ( different / alike ) deep down

Comparing the two distracts you from what each was designed to quickly express.

A switch syntactically centralizes the comparison so that you can follow the flow based on its cases.

While an if describes a single condition to enter a block.

Basically the code just "reads" differently.

For example, you have a word in your head and you want to look it up in the dictionary.

A switch would read like: hold the starting letter in your head, and then thumb through the alphabet, then give up if it doesn't start with that letter.

While a bunch of if-else blocks would read like: does word start with letter? repeated many times, then give up.

If you are trying to explain how a switch works to a new programmer (who is familiar with if blocks, it might be easier to explain it as:

```<code>if( boolean_expression_1 ) {
  statement_1;
  return;
}

if( boolean_expression_2 ) {
  statement_2;
  return;
}

default_statement;
return;
</code>```

Now the preceding example breaks what is typically taught in schools, but return early and return often is sometimes easier to read, and just as fast in a stack based vm.

There should be optimizations for switches on primitives, so the choice of which to control block to use should be based on what you are comparing.

Remember that lengthy switch and if statements tend to become very verbose, hard to maintain, and also degrade in performance as more conditions would have to be checked.

You might want to consider a Hash of anonymous classes/functions or a command pattern, instead of lengthy control blocks with many conditions.

Hashes and command pattern allows the code to perform faster, and improves the maintainability of the code.

Title: If-Else V.S. Switch end of flow

Body:
To answer the edited question (with the breaks)

They would evaluate the statements the same, if and only if the conditions to enter each block is the same.

To answer the subjective question, of

gives an angle of thought of preserved similarities and also what they are ( different / alike ) deep down

Comparing the two distracts you from what each was designed to quickly express.

A switch syntactically centralizes the comparison so that you can follow the flow based on its cases.

While an if describes a single condition to enter a block.

Basically the code just "reads" differently.

For example, you have a word in your head and you want to look it up in the dictionary.

A switch would read like: hold the starting letter in your head, and then thumb through the alphabet, then give up if it doesn't start with that letter.

While a bunch of if-else blocks would read like: does word start with letter? repeated many times, then give up.

If you are trying to explain how a switch works to a new programmer (who is familiar with if blocks, it might be easier to explain it as:

if( boolean_expression_1 ) {
  statement_1;
  return;
}

if( boolean_expression_2 ) {
  statement_2;
  return;
}

default_statement;
return;

Now the preceding example breaks what is typically taught in schools, but return early and return often is sometimes easier to read, and just as fast in a stack based vm.

There should be optimizations for switches on primitives, so the choice of which to control block to use should be based on what you are comparing.

Remember that lengthy switch and if statements tend to become very verbose, hard to maintain, and also degrade in performance as more conditions would have to be checked.

You might want to consider a Hash of anonymous classes/functions or a command pattern, instead of lengthy control blocks with many conditions.

Hashes and command pattern allows the code to perform faster, and improves the maintainability of the code.


问:
How effectively "sell" a good design in large meetings
Many times I have witnessed a sad tragedy.  Here's what happens:

A team design review for a new project.

I see a simple design that has quite a few holes.

I casually mention the holes and ways to avoid them.

The warnings are ignored with comments like "that 'never' happen in real life"

Eventually the things that "will 'never' happen" happen

An emergency team design review for a broken project.

So what do I do?  Copping the "I told you so" attitude is not going to win friends and influence people.  Sometimes years go by and the comments from step 3 are forgotten anyway.  I definitely don't want to be the annoying pest reminding the world of the gotchas.  I often sit back and watch the Titanic sail off to Europe.

It's frustrating to see bad designs move forward.  It's also frustrating that I can't seem to convince others of the pending peril of the current path.  I do worst on team meetings where everyone has different ways of understanding different terms.  Also, egos tend to win of reason and thought.  I'm looking for good tactics to convince groups people to use some new and complicated ideas.

答: If you want to influence them, talk to them about it outside of the design meeting. Otherwise they are just going to think you are trying to "score points" off them. A lot of people don't ever want to have real discussions in a meeting with an "audience".</p>

ContentLicense: CC BY-SA 2.5


问:
What is the difference between instantiating and loading a class in Java?
In Java world, there are some scenarios where I see developers used to load the class rather than instantiation. What is the difference between instantiating and loading a class?</p>

答:
Generally, "class loading" refers to loading, and initializing the class definitions -  meaning loading the bytecode from the class file, creating the Class class, running the static initializers, etc.

Once a class is loaded, and initialized, then it would be possible to instantiate an instance of the class -- ie. create an object of that class type.

ContentLicense: CC BY-SA 3.0


问:
Use of keyword "Using" in C# interface
When I'm using C# to write some code and I define an interface using Visual Studio 2010, it always includes a number of "using" statements (as shown in the example)

using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;

namespace TestEngine.TestNameSpace
{
    interface ITest1
    {
        bool testMethod(int xyz);
    }
}
```

I wonder what these are for and if they are really necessary. Can I leave these out? Are they only necessary when I'm using those parts in my interface description?

答:
using in C# used for many ways.. as word keyword using means using.. on start when we used using system; that means there is a DLL of name System in which all main functions are stored and we use it to short our code...

```<code>system.WriteLine("Andy");
</code>```

but when we use system above then we can write it as

```<code>WriteLine("Andy");
</code>```

more over in SQLserver when we use using connection it means after we use data from database by using command connection will itself close. it is very useful for a coder who wants to save its time

Title: Use of keyword "Using" in C# interface

Body:
using in C# used for many ways.. as word keyword using means using.. on start when we used using system; that means there is a DLL of name System in which all main functions are stored and we use it to short our code...

system.WriteLine("Andy");

but when we use system above then we can write it as

WriteLine("Andy");

more over in SQLserver when we use using connection it means after we use data from database by using command connection will itself close. it is very useful for a coder who wants to save its time


问:
Directory structure (file system design)
I was looking at how file systems are designed and noticed that most places say that the directory hierarchy can be implemented using a hash table.

Could someone please explain me how using a hash table to store a directory structure works?

For example, what would happen if I add a file/ directory or move a directory, how does that affect the hash table?

Also, how are paths involved?

答:
The easiest is to have a hash table per directory.  To follow a pathname, just get the root hash table, query it for the first directory in the path.  Then, if it's a directory, get the next hash table and query it with the next part, and so on until the last part.

Since hash tables are unordered structures, you would typically sort them in memory to list a whole directory.  Also, the hash wouldn't help to match wildcards; you have to do a whole directory scan to see which names match a given pattern.  Of course, an ordered structure (like a sorted list or a B*tree) only help if there's a constant prefix.

A different way (used by Mac's HFS system) is to use an ordered structure (a B*tree in HFS case) and index by directory/name.  In HFS, there was a dirID/filename structure that served as the main key for a single B*tree.  Once you had this file handle, a single query returned the directory entry, without having to traverse the whole pathname.  To get a directory list, just read the range [dirID, dirID+1), the resulting interval comprised all the filenames stored in that directory, in binary lexicographical order.


问:
Isn't class scope purely for organization?
Isn't scope just a way to organize classes, preventing outside code from accessing certain things you don't want accessed?

More specifically, is there any functional gain to having public, protected, or private-scoped methods? Is there any advantage to classifying method/property scope rather than to, say, just public-ize everything?

My presumption says no simply because, in binary code, there is no sense of scope (other than r/w/e, which isn't really scope at all, but rather global permissions for a block of memory). Is this correct?

What about in languages like Java and C#[.NET]?

答:
As you point out, the main reason is for organisation.

I see it as a communication channel between coders and maintainers, in order to make the intent of the design clear and to keep the code clean as long as possible.

Of course, this is true not only for OOP but also for any modular design.


答:
By making methods public you define the interface of your class. That way is defined how other code can use it and how it should be tested. So you define in that way how other code can communicate with it. The nice thing is that you can rewrite your internals like private methods without changing the interface.

That generates re-usable code and lowers the amount of cohesion. Using a real interface class abstracts and makes sure even more this interface.

See it maybe as an API, you should not change it and make it very clear to use. Handle the complex internals inside without making them visible.

Title: Isn't class scope purely for organization?

Body:
Isn't scope just a way to organize classes, preventing outside code from accessing certain things you don't want accessed?

More specifically, is there any functional gain to having public, protected, or private-scoped methods? Is there any advantage to classifying method/property scope rather than to, say, just public-ize everything?

My presumption says no simply because, in binary code, there is no sense of scope (other than r/w/e, which isn't really scope at all, but rather global permissions for a block of memory). Is this correct?

What about in languages like Java and C#[.NET]?


问:
Assembly Language being used in Aircraft System
Today my lecturer mentioned the reason why the aircraft system is programmed in assembly language is due to the program being written have less error . Is this statement true ? Because when he asked about our opinion I said assembly can create faster program thus it is a good language for real-time oriented aircraft system program . I search around google but can't seem to find an article clarifying my lecturer's statement . </p>

答:
Your lecturer's statement is provably false. The Joint Strike Fighter's control code is written in C++. The 777 from Boeing uses 99%+ ADA. The JPL uses mostly C to drive spaceships.

I'm sure there are more examples but I suspect many are proprietary or classified.

Here is a paper that goes into some detail on the subject of testing avionics software on a more general level.


答:
I'm writing from a Java perspective (to save me having to put 'from a Java perspective' everywhere).

Carefully designing an API is about more than just "organisation". Many of the public classes I write are used by a lot of clients and by using the lowest access modifier possible I am free to change the inner workings of my classes without breaking their code (and thereby getting nasty phone calls and emails!).

tl;dr: Encapsulation/information hiding, you can change your representation and inner workings without breaking client code, public mutable fields are not thread-safe,  promote immutability.

A module that is well-designed will hide its internal data and implementation details from other modules and cleanly separates its API from its implementation. This means that communication between modules is done only via their APIs and they are oblivious to the inner workings of each other.

The importance of this is that it decouples modules from each other allowing them to be developed, tested, used, optimised and modified in isolation and they can be developed in parallel. It also increases reuse because modules that aren't tightly coupled can potentially be used in other contexts.

In Joshua Bloch's book "Effective Java" he states that the rule of thumb is:

make each class or member as inaccessible as possible. In other words, use the lowest possible access level consistent with the proper functioning of the software that you are writing.

After designing your public API your instinct should be to make everything else private, and only if another class in the same package really needs to access a member should you make it package-private (remove the modifier). The need for protected members in a public class should be relatively rare as a protected member becomes part of the class's exported API.

When you have everything as public it means that the data fields of the class are accessed directly and you cannot change their representation without changing the API. You also generally cannot change the inner workings of your class as you have the potential to break the code of whoever is using your class. This issue/risk is multiplied by the number of your clients as your class may be used all over the place.

If a field is non-final or is a final reference to a mutable object (e.g. Date) and is public then you give up the ability to limit what is stored in the field or enforce invariants on the field. So if you wanted to limit an int to a certain value range, having the field public means that you no longer have control over what is stored in the field. You also lose the ability to take any action when a field is modified, which means that classes with public mutable fields are not thread-safe.

Public final fields with a mutable object in them have all of the disadvantages of a non-final field too. Whilst you cannot change the object reference, the object can still be modified which may break the inner workings of your class and have unintended and disastrous results.

By making fields private you also minimise mutability of your class. Immutable classes are generally easier to design, implement and use than mutable classes are. Private fields prevent clients of your class from obtaining access to mutable objects and modifying the objects directly. You generally also never give a client references to the mutable objects either (you give them copies).

As your class minimises mutability or becomes completely immutable it also becomes inherently thread-safe and requires no synchronisation. They cannot become corrupt by multiple threads accessing them concurrently. A huge functional gain of immutability is it is one of the easiest ways of achieving thread safety.


答:
In Java (and I guess that in .NET too) access modifiers means as much as SecurityManagers says. So if you are in controll of it, you can access private members through reflection.

But if your code runs in other application where SM is set to not allow your code to do reflection magic, you actualy cannot acces private members.

I don't know whether something like this is possible in C++ (and I guess that it isn't).

So above organizational benefits (that are huge), in some languages where it is enforced it provides functional difference.


答:
I mean does having a private method as opposed to a public method give you any sort of advantage as far as how the program works or functions?

Well, no. If you took a working program and elevated all the access modifiers to public, you would still have a working program*. Similarly, if you took a working program and replaced all the for and while loops with equivalent goto constructs, you would also still have a working program. Similarly similarly, if you took a working program and replaced all the string operations with equivalent manual char array manipulations, you would again still have a working program.

But 'Working' isn't the only measure of program goodness. Readability and Maintainability also feature, and for those, access modifiers are useful.

* modulo any Reflection-type stuff that looks for specific access modifiers, etc


答:
Try writing an API

Lets say that you want to write a library to share with the rest of the world. There are two important things to consider.

Will my library conflict with other libraries?

How can I prevent users from depending on code that may change later?

For the first question, classes provide scope to prevent naming collisions. Just try writing code in JavaScript for a while where everything lands in the global namespace by default. Without implementing some form of namespaces or classes, it can ugly very quickly.

The second question is controversial. As a user, I want to be able to see the internal implementation of a classes methods/parameters. As a developer, I want to limit user's accessibility prevent them from changing a classes internal implementation. Many people view the limitations as draconian but they exist for a good reason.

There's a simple saying that embodies the issue, "if it exists, somebody will depend on it."

It's the same reason that Windows still contains applications that were created in the 3.1 days. Libraries, like applications are meant to be used in the long term. The problem is, they are also meant to change and evolve over time.

Stability comes from designing a stable public API. That means, the organization of the class structure shouldn't change and, if it does, measures are taken to provide backwards compatibility.

Flexibility comes from limiting the amount of code that your users can depend on. You want to give them a structure that is named well enough that then can understand what it does but you don't want to show them how you do it. Why, because the method to make it happen may change in the future.

Whether their use outweighs the effort is debatable. In the world of dynamic languages that don't bother with access modifiers it doesn't make a whole lot of difference. If people want to depend on code that is internal to a library then they'll learn the hard way why that's a bad idea. There's still a notion of private/public/global but they're used to classify scope, not policy.


问:
Should I create repositories with special functions like getStaffActive()?
I have seen lots of articles but none really help me. That is because I want to use dapper as a DAL. Should I create repositories with special functions? Like getStaffActive()?

If I use repositories

I can implement with dapper-extension a generic crud

I have no idea how to handle database connection. Where to open the connection? If I do this at every function then how am I supposed to use transaction scope?

Somehow the repositories I work with should share a connection in order transaction to work. But how to do this? Openning connection in BLL?

If I use queries and execute them directly then still the same thing.

答:
(Clarification: this answer was written when the question was on Stack Overflow)

All of these questions are architectural. How you architect your application is complex, and depends on many aspects. There are lots of ways, all valid, of doing this. Some depend each-other, so if one architectural decision is "use transaction scope", then your connection management strategy needs to take that into account.

Dapper, however, is very deliberately not architectural. It is pure implementation detail. It tries very hard not to invade any of your code or force any design decisions upon you. Your architectural decision might be "use dapper", or it might be "get that data from the DB; how we get it is an implementation detail that we don't care about, because it is not tied to any other design components".

Basically: no-one can answer this except you. It might be a reasonable question for programmers.SE, which has a more architectural (rather than implementation) bias. We could migrate the question there if you like.

OwnerDisplayName: Parhs

OwnerDisplayName: Marc Gravell


问:
How to make the switch to C++11?
I've been programming in C++ for a while now, but mostly things centered around the low-level features of C++. By that I mean mostly working with pointers and raw arrays. I think this behavior is known as using C++ as C with classes. Despite this, I only having tried C recently for the first time. I was pleasantly surprised how languages like C# and Java hide these details away in convenient standard library classes like Dictionaries and Lists.

I'm aware that the C++ standard library has many containers like vectors, maps and strings as well and C++11 only adds to this by having std:: array and ranged loops.

How do I best learn to make use of these modern language features and which are suitable for which moments? Is it correct that software engineering in C++ nowadays is mostly free of manual memory management?

Lastly, which compiler should I use to make the most of the new standard? Visual Studio has excellent debugging tools, but even VS2012 seems to have terrible C++11 support.

答:
How do I best learn to make use of these modern language features and which are suitable for which moments?

By programming. Experience is the best way to learn.

C++11 has lots of new features (auto, rvalue, new smart pointers - just to name few). The best start is to just start using them, and read about them whenever you can, and whenever you find an interesting article.

Is it correct that software engineering in C++ nowadays is mostly free of manual memory management?

That depends what you need to do. Most applications can get away with smart pointers, and forget about memory management. There are still applications that can not get away so easily (for example if they need placement new, or a custom memory allocator for whatever reason).

If you need to use Qt, you'll have to use their rules for memory management.

which compiler should I use to make the most of the new standard?

Whatever you have at hand that supports the latest standard :

gcc has good support for c++11 features

vs has list of features

but no compiler supports all features.

Title: How to make the switch to C++11?

ContentLicense: CC BY-SA 4.0


问:
handling a GET error properly
I have a website that takes two primary get strings:

```<code>?type=GAME&id=SomeGameID
?type=SCENARIO&id=SomeScenarioID
</code>```

for reasons unknown, I have recently begun receiving requests for erroneous get strings from both Yandex and Baidu. They are always in the form of:

```<code>?type=GAME&id=SomeScenarioID
</code>```

None of my users are triggering these errors, so I am (sort of) confident that this is not due to an HTML template error somewhere on my part. There is also no HTTP_REFER showing up in the $_SERVER array, so I'm guessing these are direct requests from bad dbase data on their part.

I see two options for dealing with these bad requests, and would like to know which is recommended... or if there are other, better options I have not thought of:

simply 404 the request, since it is incorrect

redirect the request to ?type=SCENARIO&id=SomeScenarioID because the scenario IDs are always valid, the breakage is due to asking for the wrong type.

答:
I concur that 400 is a better response than 404.

When you say "I'm guessing these are direct requests from bad dbase data on their part".  I interpret that as meaning that the requests are coming from web crawlers.  If that is the case, then another alternative would be to configure your site's robots.txt file to tell the Yandex and Baidu crawlers to stay out of the part of your site with the queries.  Or maybe just block them.

Assuming that this is crawler activity, the problem might not be bad data (which would have had to come from somewhere).  It is possible that the engines are trying alternatives in a rather lame fashion in order to harvest stuff that isn't directly linked.  (It sounds like a stupid thing to do, but you never know ...)

On the other hand, if this is not web crawler activity, perhaps it is the result of some users trying to access your site using some custom client rather than using the UI implemented by your web templates.  That would also explain the lack of referrer headers.

Title: handling a GET error properly


问:
Google App Engine: How to be notified when APIs change or become available?
I am thinking about writing a GAE app but am a little hesitant because the EULA gives Google full rights to change their APIs anytime they want, for any reason. Obviously, they'd be out of business quick if they just 'upped and refactored their entire APIs, so I have to imagine they have some kind of notification system, perhaps even an RSS feed, etc. to notify developers well in advance of looming changes, or new features coming out in future releases.

However, for the life of me I can't seem to find any trace of the existence of such a notification system. Perhaps the Google forums is the only place to get such updates?

I guess I'm asking any battle-worn GAE veterans for re-assurance that there are reliable ways of getting notifications about policy or API changes from Google such that I could react and make the necessary app changes without production breaking or impacting any clients.

答:
If you want to be notified when one particular issue or a feature is implemented or something, one good way is to star it in the issues list. Once you do that you will start getting notifications on status changes or new comments regarding a specific issue.

Now for the big changes you don't have to worry about stuff that they are deprecating, since no matter what it's not happening in a day but in a year.

For new up coming features and when they are becoming available for private/public testing I would suggest you to subscribe to the official Google App Engine Blog. For every new version they are posting a detailed description with links to the change logs.


答:
There is no functional benefit.

The most important benefit is that it makes it possible to reason about the behaviour of a program. If any part of a system can call any other part, it becomes too difficult for actual mortal humans to understand the program and deduce how it will behave. It will begin to drown in bugs, and become a big ball of mud. An important milestone in personal improvement is recognising that your brain is finite, and you need to keep things as simple as possible to get the most from it.

It's also beneficial for communication between developers. But that's not the main benefit - otherwise lone developers would develop big programs without organising them at all.


问:
Ways to ensure unique instances of a class?
I'm looking for different ways to ensure that each instance of a given class is a uniquely identifiable instance.

For example, I have a Name class with the field name. Once I have a Name object with name initialised to John Smith I don't want to be able to instantiate a different Name object also with the name as John Smith, or if instantiation does take place I want a reference to the orginal object to be passed back rather than a new object.

I'm aware that one way of doing this is to have a static factory that holds a Map of all the current Name objects and the factory checks that an object with John Smith as the name doesn't already exist before passing back a reference to a Name object.

Another way I could think of off the top of my head is having a static Map in the Name class and when the constructor is called throwing an exception if the value passed in for name is already in use in another object, however I'm aware throwing exceptions in a constructor is generally a bad idea.

Are there other ways of achieving this?

答:
Try following.
You have to keep track of each object you create. For this purpose I'm using List.
And made class constructor private, so that pre-check can be applied before creating an instance</p>

```<code>class UniqueName
    {
        private string Name;
        public int ID;
        private static int Count=0;
        static List<UniqueName> lt=new List<UniqueName>();

        private UniqueName(string Name)
        {
            this.Name = Name;
            ID = ++Count;
        }

        public static UniqueName GetUniqueueInstance(string Name)
        {
            foreach (UniqueName un in lt)
            {
                if ( string.Compare( un.Name,Name,StringComparison.InvariantCultureIgnoreCase)==0)
                    return un;
            }

            UniqueName temp=new UniqueName(Name);
            lt.Add(temp);
            return temp;
        }
    }
</code>```

OwnerDisplayName: Peanut

Body:
Try following.
You have to keep track of each object you create. For this purpose I'm using List.
And made class constructor private, so that pre-check can be applied before creating an instance

class UniqueName
    {
        private string Name;
        public int ID;
        private static int Count=0;
        static List<UniqueName> lt=new List<UniqueName>();

        private UniqueName(string Name)
        {
            this.Name = Name;
            ID = ++Count;
        }

        public static UniqueName GetUniqueueInstance(string Name)
        {
            foreach (UniqueName un in lt)
            {
                if ( string.Compare( un.Name,Name,StringComparison.InvariantCultureIgnoreCase)==0)
                    return un;
            }

            UniqueName temp=new UniqueName(Name);
            lt.Add(temp);
            return temp;
        }
    }


答:
As a starting point:

Stop using char* for strings. Use std::string or std::wstring and just watch your code get shorter, more readable, and safer

Stop using C-style arrays (things declared with [ ]) and use std::vector or some other appropriate container class. The nice things about std::vector are that it knows its own length, it cleans up its contents when it goes out of scope, it is easy to iterate over, and it makes itself bigger when you add more items. But there are other collections that might work even better for your circumstances.

Use std::unique_ptr - and learn std::move almost immediately. Since this may result in some noncopyable objects, laziness may occasionally send you towards std::shared_ptr - and you may have some genuine use cases for std::shared_ptr as well

Use auto when declaring iterators and types that depend on earlier declarations (eg earlier you declared a vector of something, now you're declaring a something, use auto)

Use algorithms and for_each over a "raw for" whenever you can since it spares others from reading your loop carefully to conclude that you're in fact iterating over the whole collection etc. If your compiler supports "range for" then use it over for_each. Learn trivial algorithm calls like iota, generate, accumulate, find_if and so on.

Use lambdas - they are the easy way to leverage algorithms. They also open the door to so much more.

Don't get too worked up about what compiler to use. The "terrible, awful" lack of C++ 11 support in VS2012 is that there isn't variadic templates (yeah right, you were just about to use variadic templates) and the {} initializer isn't there. I want that too but I'm hardly going to stop using a useful development tool over it.

The second thing to do, after embracing std::, is to start thinking RAII. Anytime you have

starting action

series of actions with something you got from starting action

cleanup action that needs to happen even in the case of exceptions

Then what you have is a constructor, a number of member functions, and a destructor. Write a class that takes care of that for you. You might not even have to write the ctor and the dtor. Putting a shared_ptr as a member variable of a class is an example of RAII - you don't write memory management code, but when your instance goes out of scope, the right things will happen. Expand that thinking to cover things like closing files, releasing handles, locks etc and code will just get simpler and smaller (while eliminating leaks) before your eyes.

If you're feeling really confident, purge printf in favour of cout, get rid of macros (#definestuff), and start learn some "advanced idioms" like PIMPL. I have a whole course on this at Pluralsight which you can probably watch using their free trial.

Title: How to make the switch to C++11?

Body:
I've been programming in C++ for a while now, but mostly things centered around the low-level features of C++. By that I mean mostly working with pointers and raw arrays. I think this behavior is known as using C++ as C with classes. Despite this, I only having tried C recently for the first time. I was pleasantly surprised how languages like C# and Java hide these details away in convenient standard library classes like Dictionaries and Lists.

I'm aware that the C++ standard library has many containers like vectors, maps and strings as well and C++11 only adds to this by having std:: array and ranged loops.

How do I best learn to make use of these modern language features and which are suitable for which moments? Is it correct that software engineering in C++ nowadays is mostly free of manual memory management?

Lastly, which compiler should I use to make the most of the new standard? Visual Studio has excellent debugging tools, but even VS2012 seems to have terrible C++11 support.


答:
As far as I know, most C++ compilers strip out the access modifiers when compiling the code.
Also C++ and Java do give you the ability to cross these modifiers (with C++ you really can access any part of the memory you want, and Java's introspection/reflection mechanism can allow you to call code marked as private) although this can quickly become unintuitive and un-performant if abused, not to mention that in both cases you pretty much render compile time checking useless when doing so.

So yes, you can say that access modifiers are just an active way of enforcing the "syntax" of the coded API, things such as encapsulation, implementation hiding etc. You can still say that they have a "functional" role as well, as the compiler will warn you when you're trying to violate the access modifiers (via the "official" channels) and also throw an error. This is a functional advantage over, for example, C, where you can't really tell the compiler "this part of the code here should NOT be accessible to that part over there".


问:
Are there any additional considerations to make when designing a site structure if you plan to use persistent connection technologies?
As the title states, I'm thinking of making a simple-card-game based website, using persistent connection technology (Something like signalR) for the actual game part of it.

I've never planned a site to use this technology, and wondering for those who have, are there any additional things that need to be taken into consideration for the site structure?

I'm planning on using the asp MVC framework for the whole thing, and starting off with some simple game (e.g. card based Rock/Paper/Scissors) for proof of concept (to see if I can get it working how I think it would in my head).

答:
You need take into account the browser compatibility issues when working with technologies that do/don't use web-sockets. This is very important point.

Another thing is exploring advantages of Modernizr library with ASP.NET MVC architecture.


问:
How to define a code snippet in Java
I know about static final equivalent to #define , But I am not looking for it

I have used #define REP(i,n) for(__typeof(n) i=0; i<(n); i++) in C++ and after that I can use REP(i,10) instead of for(i=0; i<10; i++) in the whole program.

But is there a way to do this in Java? I want a version of #define REP(i,n) for(__typeof(n) i=0; i<(n); i++) in Java.

I try it with static final but can't figure out.

答:
First of all, static final is not the same as #define. define uses the C preprocessor and goes around your code making text substitutions before the compiler even sees the code. Java has no mechanism like this.

Instead static final is really just equivalent to static const in C++. It simply means

There is only one instance of this field between every instance of this class

This field won't change ever.

So to answer your question, in java, there are no macros and thus no direct way to do what you're asking.

If it's really that much of a bother, you could use higher order functions to do what you're asking. Your function would look like:

```<code>void looper(int times, SomeInterface action){
    for(int i = 0; i<times; ++i)
        action.act(i);
    }
 }
</code>```

However I think you'll find that this is overkill. Additionally this loses several important features you'd want in a for loop, such as the ability to break out of it on demand. The ability to modify the loop counter or any variables surrounding the loop.

You'd be better served to stick to iterating over collections and for situations where you actually need to use numbers, try using a Range class.

Java 8 (whenever that gets released) will have closures, making many of these things possible. But in the meantime, I'm afraid you'll just have to type it out.

Title: How to define a code snippet in Java

Body:
First of all, static final is not the same as #define. define uses the C preprocessor and goes around your code making text substitutions before the compiler even sees the code. Java has no mechanism like this.

Instead static final is really just equivalent to static const in C++. It simply means

There is only one instance of this field between every instance of this class

This field won't change ever.

So to answer your question, in java, there are no macros and thus no direct way to do what you're asking.

If it's really that much of a bother, you could use higher order functions to do what you're asking. Your function would look like:

void looper(int times, SomeInterface action){
    for(int i = 0; i<times; ++i)
        action.act(i);
    }
 }

However I think you'll find that this is overkill. Additionally this loses several important features you'd want in a for loop, such as the ability to break out of it on demand. The ability to modify the loop counter or any variables surrounding the loop.

You'd be better served to stick to iterating over collections and for situations where you actually need to use numbers, try using a Range class.

Java 8 (whenever that gets released) will have closures, making many of these things possible. But in the meantime, I'm afraid you'll just have to type it out.


答:
It looks like you are missing the concept of Unit of Work pattern in your DAL design.

There are nice posts that explaining this concepts here:

Unit of Work pattern - managing parent child relationships

The Unit Of Work Pattern And Persistence Ignorance

Unit of Work Pattern

Title: Should I create repositories with special functions like getStaffActive()?

Body:
I have seen lots of articles but none really help me. That is because I want to use dapper as a DAL. Should I create repositories with special functions? Like getStaffActive()?

If I use repositories

I can implement with dapper-extension a generic crud

I have no idea how to handle database connection. Where to open the connection? If I do this at every function then how am I supposed to use transaction scope?

Somehow the repositories I work with should share a connection in order transaction to work. But how to do this? Openning connection in BLL?

If I use queries and execute them directly then still the same thing.


问:
Language agnostic programming books
Are there any great programming or software development books that are language agnostic?  Why should I read it?</p>

答:
Code Complete: A Practical Handbook of Software Construction by Steve McConnell

This book is probably the definitive book on software construction. It discusses topics such as the foundations for construction (requirements, architecture, and design), choosing a programming language, choosing a development methodology, designing classes and objects, writing high-quality functions and methods, defensive programming, the use and naming of variables, data types, organizing and formatting statements, collaborative programming, testing, debugging, refactoring, and development tools.

This is a must have on every software engineer's shelf, even if you aren't explicitly writing code.

Title: Language agnostic programming books


答:
No, it's not possible. However in your particular case it's not needed either.

Java is intentionally designed so that you can't redefine anything. That makes it easier for less experienced programmers to understand code and easier for others to understand the code they write, because things can't be redefined.

The downside is that it makes the language much less flexible, so where good programmer can make advanced code still short and readable in C++, it will inevitably be verbose in Java.

In your particular case, though:

You should almost never iterate over range of numbers. Iterate over collections. That's true in any language. C, C++, Java, Python, whatever.

Java has a range-based for loop: for(ItemType i: collection)

You can create a Range class to iterate over range of integers like: for(int i: new Range(0, 10)). There does not seem to be one in standard library, but you can try one of the many samples laying around the net.

Title: How to define a code snippet in Java

Body:
I know about static final equivalent to #define , But I am not looking for it

I have used #define REP(i,n) for(__typeof(n) i=0; i<(n); i++) in C++ and after that I can use REP(i,10) instead of for(i=0; i<10; i++) in the whole program.

But is there a way to do this in Java? I want a version of #define REP(i,n) for(__typeof(n) i=0; i<(n); i++) in Java.

I try it with static final but can't figure out.


答:
If you are a novice with a language, you should learn the idioms of that language, not invent your own.

As pointed out by @jozefg, Java static final functions are not equivalent to #define macros in C/C++. They work in different ways and serve completely different purposes.

Introducing arbitrary new syntax is guaranteed to trip up any developer not familiar with your codebase. If I see something like

```<code>for(int i = 0; i < 10; i++) {
  doSomethingNthTime(i);
}
</code>```

then I know exactly what it means. If I see:

```<code>REP(i, 10) { doSomethingNthTime(i); }
</code>```

it isn't anywhere near as obvious. Who is this representative that you are talking about? And even if I know that by REP you mean "repeat", what exact range will i cover? I will have to look at the macro declaration to know, whereas with the plain for loop the answer is in plain sight.

Also, plain for allows things that your REP macro has no way to express. How about the following?

```<code>short i;
long j, k = 0;
for(i = 0, j = 16; i < 10; i++, j <<= 2) {
  doSomethingNthTime(i, j, &k);
}
</code>```

or

```<code>int i;
for(i = 0; i < 16; i++) { ... }
i += values[z];
for(; i < 1024; i++) { ... }
</code>```

Such complex for expressions (although obviously with a meatier loop body) are not entirely unusual in production code, and can be extremely useful in some situations.

Title: How to define a code snippet in Java

Body:
If you are a novice with a language, you should learn the idioms of that language, not invent your own.

As pointed out by @jozefg, Java static final functions are not equivalent to #define macros in C/C++. They work in different ways and serve completely different purposes.

Introducing arbitrary new syntax is guaranteed to trip up any developer not familiar with your codebase. If I see something like

for(int i = 0; i < 10; i++) {
  doSomethingNthTime(i);
}

then I know exactly what it means. If I see:

REP(i, 10) { doSomethingNthTime(i); }

it isn't anywhere near as obvious. Who is this representative that you are talking about? And even if I know that by REP you mean "repeat", what exact range will i cover? I will have to look at the macro declaration to know, whereas with the plain for loop the answer is in plain sight.

Also, plain for allows things that your REP macro has no way to express. How about the following?

short i;
long j, k = 0;
for(i = 0, j = 16; i < 10; i++, j <<= 2) {
  doSomethingNthTime(i, j, &k);
}

or

int i;
for(i = 0; i < 16; i++) { ... }
i += values[z];
for(; i < 1024; i++) { ... }

Such complex for expressions (although obviously with a meatier loop body) are not entirely unusual in production code, and can be extremely useful in some situations.


问:
Alternatives to type casting in your domain
In my Domain I have an entity Activity which has a list of ITasks. Each implementation of this task has it's own properties beside the implementation of ITask itself. Now each operation of the Activity entity (e.g. Execute()) only needs to loop over this list and call an ITask method (e.g. ExecuteTask()).

Where I'm having trouble is when a specific tasks' properties needs to be updated, as in configuring the task (not as part of the execute method). How do I get an instance of that task? The options I see are:

Get the Activity by Id and cast the task I need. This'll either sprinkle my code with:

Tasks.OfType<SpecificTask>().Single(t => t.Id == taskId)

or Tasks.Single(t => t.Id == taskId) as SpecificTask

Make each task unique in the whole system (make each task an entity), and create a new repository for each ITask implementation

I don't like either option, the first because I don't like casting: I'm using NHibernate and I'm sure this'll come back and bite me when I start using Lazy Loading (NHibernate currently uses proxies to implement this). I don't like the second option because there are/will be dozens of different kind of tasks. Which would mean I'd have to create as many repositories.

Am I missing a third option here? Or are any of my objections to the two options not justified? How have you solved this problem in the past?

答:
It is true that casting is bad when it introduces coupling. But that doesn't mean it's always bad. There's not a lot wrong with

```<code>ITask task = Tasks.Single(t => t.Id == taskId);
IArduousTask arduous = task as IArduousTask;

if (arduous != null)
{
    arduous.HaveLunchBreak();
}

task.DoTask();
</code>```

This way, we're not tied to an implementation of ITask or IArduousTask. And any task can implement IArduousTask (with a different implementation of HaveLunchBreak(), if you choose) and HaveLunchBreak will automatically get called. But tasks that don't implement IArduousTask will not break.

However, in your case, you should probably also reconsider whether your Task objects should be mutable. It might be better to do this:

```<code>ITask updated = task.GetUpdated(someData);
activity.UpdateTask(updated);
</code>```

Where GetUpdated is a new method on ITask and activity.UpdateTask matches on updated.ID and replaces the entire object in the array. This leaves the implementation of GetUpdated to the task type itself.

someData can either be all the data that could possibly be required to perform an update of any type of task, or it could be a dictionary (or dynamic object) containing data from a task-specific UI, passed into a specific task.

Body:
It is true that casting is bad when it introduces coupling. But that doesn't mean it's always bad. There's not a lot wrong with

ITask task = Tasks.Single(t => t.Id == taskId);
IArduousTask arduous = task as IArduousTask;

if (arduous != null)
{
    arduous.HaveLunchBreak();
}

task.DoTask();

This way, we're not tied to an implementation of ITask or IArduousTask. And any task can implement IArduousTask (with a different implementation of HaveLunchBreak(), if you choose) and HaveLunchBreak will automatically get called. But tasks that don't implement IArduousTask will not break.

However, in your case, you should probably also reconsider whether your Task objects should be mutable. It might be better to do this:

ITask updated = task.GetUpdated(someData);
activity.UpdateTask(updated);

Where GetUpdated is a new method on ITask and activity.UpdateTask matches on updated.ID and replaces the entire object in the array. This leaves the implementation of GetUpdated to the task type itself.

someData can either be all the data that could possibly be required to perform an update of any type of task, or it could be a dictionary (or dynamic object) containing data from a task-specific UI, passed into a specific task.


答:
Activity should not know about the special property.

This knowledge belongs to a virtual method in the task class like this:

```<code>public class MyTask
{
    public virtual void ExecuteTask()
    {
        // ....
    }
}

public class MyTaskWithSpecialProperty : MyTask
{
    public int MySpecialProperty {get;set}
    public override void ExecuteTask()
    {
        CalculateSpecialProperty();
        base.ExecuteTask();
    }
    private void CalculateSpecialProperty()
    {
            MySpecialProperty++;
    }
}
</code>```

Activity does not need to know about MySpecialProperty  when executing

```<code>public class Activity
{
    public void ExecuteTasks()
    {
        foreach(var task in this.Tasks)
            task.ExecuteTask();
    }
}
</code>```

Title: Alternatives to type casting in your domain

Body:
In my Domain I have an entity Activity which has a list of ITasks. Each implementation of this task has it's own properties beside the implementation of ITask itself. Now each operation of the Activity entity (e.g. Execute()) only needs to loop over this list and call an ITask method (e.g. ExecuteTask()).

Where I'm having trouble is when a specific tasks' properties needs to be updated, as in configuring the task (not as part of the execute method). How do I get an instance of that task? The options I see are:

Get the Activity by Id and cast the task I need. This'll either sprinkle my code with:

Tasks.OfType<SpecificTask>().Single(t => t.Id == taskId)

or Tasks.Single(t => t.Id == taskId) as SpecificTask

Make each task unique in the whole system (make each task an entity), and create a new repository for each ITask implementation

I don't like either option, the first because I don't like casting: I'm using NHibernate and I'm sure this'll come back and bite me when I start using Lazy Loading (NHibernate currently uses proxies to implement this). I don't like the second option because there are/will be dozens of different kind of tasks. Which would mean I'd have to create as many repositories.

Am I missing a third option here? Or are any of my objections to the two options not justified? How have you solved this problem in the past?

Body:
Activity should not know about the special property.

This knowledge belongs to a virtual method in the task class like this:

public class MyTask
{
    public virtual void ExecuteTask()
    {
        // ....
    }
}

public class MyTaskWithSpecialProperty : MyTask
{
    public int MySpecialProperty {get;set}
    public override void ExecuteTask()
    {
        CalculateSpecialProperty();
        base.ExecuteTask();
    }
    private void CalculateSpecialProperty()
    {
            MySpecialProperty++;
    }
}

Activity does not need to know about MySpecialProperty  when executing

public class Activity
{
    public void ExecuteTasks()
    {
        foreach(var task in this.Tasks)
            task.ExecuteTask();
    }
}


答:
I wonder why nobody has mentioned it, but there is a possible gain. As someone pointed out,  it makes it possible to reason about the behaviour of a program. Which allow tools for static analysis to tell you a function or variable is not needed at all (so you can scrap it) or not written from anywhere (so you probably do not need it either). You might consider this organisation only, though.

But it also allows the compiler to optimise. Throw out unneeded functions and variables (smaller program), or analyse the flow of the program so that a known value can be cached.


问:
Why didn't "cloud computing" offer appear earlier?
Cloud computing is a model of renting resources - servers and data storage. Both servers and data storage have been around for much more than a decade so far. Yet cloud computing offers only appeared several years ago.

What's the deal here? What was the critical change that triggered massive adoption and massive marketing of cloud computing offers?

答:
There are two answers. The first is that it didn't really take off until high-speed internet access became ubiquitous. Cloud computing doesn't work well unless you can be reasonably sure that you will always have high-speed access to your cloud resources.

The second answer is that it's not really a new idea. Before PCs became affordable it was the norm to have many people connecting to one computer using dumb terminals. The machine you would be sitting in front of wouldn't have any storage or processing abilities beyond what was necessary to send your input and display output.


答:
It has appeared earlier. In fact, this was the original model of getting access to computing resources back in the 1950s till well into the 1980s, when it was called "time sharing", then in the early 1990s it re-appeared under the name "Client/Server", then in the late 1990s again under the name "Thin Client", then "Application Service Provider".

However, in the exact form we see it today it requires high quality, high reliability, high throughput, low latency, low price, ubiquitous Internet access, which didn't exist until a few years ago, and in fact, still doesn't exist for the vast majority of people (e.g. almost all of Africa, much of Asia, parts of Eastern Europe and South America).

Title: Why didn't "cloud computing" offer appear earlier?

Body:
Cloud computing is a model of renting resources - servers and data storage. Both servers and data storage have been around for much more than a decade so far. Yet cloud computing offers only appeared several years ago.

What's the deal here? What was the critical change that triggered massive adoption and massive marketing of cloud computing offers?


答:
People have been renting time on remote computers for decades. In fact, "timesharing" was the original model for selling computing services back before computers were small enough and affordable enough that individual businesses could afford to own their own machines. The large information services of the 80's (Compuserve, AOL, etc.) were another way to rent computing power/space. Next, as the Internet developed, people needed ways to maintain a 24/7 presence on the network and hosting companies popped up.

Cloud computing is just another version of the same idea. It took some time for data centers to become so developed, standardized, and scalable that cloud services could sell general purpose computing on virtual machines as a commodity and manage it all in a way that was both affordable and profitable, but it's really just the latest generation of the same idea.


问:
Why are there no package management systems for C and C++?
There are some programming languages for which exist a package management system:

CTAN for TeX

CPAN for Perl

Pip & Eggs for Python

Maven for Java

cabal for Haskell

Gems for Ruby

npm for NodeJS

bower for frontend Javascript & CSS

nuget for C#

composer for PHP

Is there any other languages with such systems? What about C and C++? (that's the main question!) Why there are no such systems for them? And isn't creating packages for yum, apt-get or other general package management systems better?

答:
I think that a problem with C and even more with C++ is that they are more heterogeneous languages: even though these languages are standardized there exist different compilers with different options or different sets of supported features. E.g., I remember posting a question about C++ on stack overflow with an example that was working perfectly on GCC / Linux and someone immediately posted an answer saying that my code was non-standard.

Having a package system like the ones mentioned in the question would imply having a common language and libraries that are supported uniformly by all major compilers on all common operating systems. E.g., you do not want to download a C++ package and discover that it won't compile on your version of compiler X because it was developed on compiler Y on another operating system.

I could imagine that a system based on make and configure scripts (as commonly found on Linux, cygwin and other Unix flavors) could work. But why should Visual Studio users adopt it? The same is valid if one started a package system based on Microsoft Compilers (and libraries).

The fact that C++ is a fast evolving language and its standards always take some time before being fully supported by all compilers does not alleviate the problem.


问:
Why was dependency injection pattern not included in the Gang of four?
Why was the dependency injection pattern not incluided in the gang of four? Did GOF pre-date widespread automated testing? Is dependency injection now considered a core pattern?</p>

答:
I think Dependency Injection is more relevant when separating implementation in tiers. Another area where we think about dependency injection is unit testing. And your pre-date suggestion seems to be correct. If the gang were to collect and segregate patterns in 2012, definitely dependency injection will be there.

Strategy could come up in discussions but Strategy does not talk about dependency injection. But when using strategy pattern in a single project or dll(all classes and interfaces remain in one project) it appears that we are doing dependency injection. In fact we are not.

Now, if the classes and interfaces mentioned in strategy pattern are separated in different projects or tiers then WE will have to use dependency injection techniques. We could use unity configuration files(no runtime change possible though). But Strategy pattern does not say how to inject a dependency.

If there is a pattern that resembles closely to Dependency injection then it is Abstract Factory Method pattern. This pattern could be used inside a strategy pattern to inject dependency.


答:
I work on OBOGS, which is a component that gets plugged into various aircraft. We typically use C for the devices that fly, but looking through the historical files, there are a couple of assembly projects in there.

It's fashion, honestly. Languages rise and fall. The reasons people use one or the other vary all over the place and are mostly subjective. I find it completely plausible that someone at some point argued that assembly was the right choice for some project somewhere entirely because it would have less errors than in any other language. And he was probably right, but that's because the guy didn't know how to code in C worth a damn. By and far the best language for the job is the one you know.  (And the best language for your personal growth is one you don't.)

You can objectively say that assembly is closer to the hardware, less abstracted, more direct, with more instructions to the same thing in other languages. You can even say that it's in the realm of possibility that assembly can be written to cut out overhead and be smoking fast. If you know what you're doing. But as for error-prone-ness, speed of development, readability, and the ability to cure cancer? All that depends on the ability of the programmer and what they've worked in for the last 20 years. Measurements of which projects with which language have X amount of bugs are subject to sociological factors, largely making them worthless metrics. No, it's all just so much fashion.

It's good to know what your code boils down to, so I'm going to say that it's important to learn assembly. If only a little. But I wouldn't write any avionics in it.

Title: Assembly Language being used in Aircraft System

Body: Today my lecturer mentioned the reason why the aircraft system is programmed in assembly language is due to the program being written have less error . Is this statement true ? Because when he asked about our opinion I said assembly can create faster program thus it is a good language for real-time oriented aircraft system program . I search around google but can't seem to find an article clarifying my lecturer's statement . </p>


问:
Clarify the Single Responsibility Principle
The Single Responsibility Principle states that a class should do one and only one thing.  Some cases are pretty clear cut.  Others, though, are difficult because what looks like "one thing" when viewed at a given level of abstraction may be multiple things when viewed at a lower level.  I also fear that if the Single Responsibility Principle is honored at the lower levels, excessively decoupled, verbose ravioli code, where more lines are spent creating tiny classes for everything and plumbing information around than actually solving the problem at hand, can result.

How would you describe what "one thing" means?  What are some concrete signs that a class really does more than "one thing"?

答: I don't know if there is an objective scale to it but what would give this away would be the methods - not so much the number of them but the variety of their function. I agree you can take decomposition too far but I wouldn't follow any hard and fast rules about it.</p>


问:
Is it required to start a business to sell Android Apps (US)?
I know you can sell apps using your own personal tax information, but what if there are several people working on the app? Our plan is to just have one of us register for the Google Merchant account and then we'll privately divide up any revenue that comes to the PayPal account.

Is this legal? Or do we need to actually create an LLC and have a payroll, etc?

答:
In short, yes your plans is good to go with a simple agreement between partners.
You may consider that agreement to define basic rights of each of you in the project.

However, if you are planning to grow the business and hit some point of substantial sale/revenue then you may probably want to consider registering business as LLC or Inc.

The rule of thumb is - when your revenue is the main source of the income, at that point you better register a business. This was advice of an accountant that makes my taxes in USA.


答:
I would say it depended on virtualization technology on commodity hardware. Time sharing and mainframe/client access has always existed, but required expensive special hardware to securely portion resources. Client/server access has always existed on commodity hardware since the internet. However, it required a dedicated server and you couldn't just replicate that server with the push of a button. In order to maintain security, you had to maintain the security on that server yourself. Shared servers were susceptible to attack, unless they were locked down, and that limited options if you needed something custom.

With ubiquitous, cheap virtualization, you can create an entire server with full access, and that can be shared on a larger commodity platform. It can be copied, moved, replicated, and deleted on a whim. It required INTEL and AMD chips to support the virtual machines and time slicing that goes with servers, along with easy software to maintain multiple operating systems running at once.


答:
Its not required, but it is a good idea.

By not creating a separate company whoever registers to put apps on the app store assumes 100% of the liability and is also not required to actually divide any revenue you get unless you create a separate contract stating those requirements.

Creating a simple LLC is quick and cheap, the potential headaches in the future when it comes time to distribute revenue or worst case legal action is taken against you are more of a pain than the ~$100 it takes to avoid them entirely.

Title: Is it required to start a business to sell Android Apps (US)?

Body:
I know you can sell apps using your own personal tax information, but what if there are several people working on the app? Our plan is to just have one of us register for the Google Merchant account and then we'll privately divide up any revenue that comes to the PayPal account.

Is this legal? Or do we need to actually create an LLC and have a payroll, etc?


问:
"Never do in code what you can get the SQL server to do well for you" - Is this a recipe for a bad design?
It's an idea I've heard repeated in a handful of places. Some more or less acknowledging that once trying to solve a problem purely in SQL exceeds a certain level of complexity you should indeed be handling it in code.

The logic behind the idea is that for the large majority of cases, the database engine will do a better job at finding the most efficient way of completing your task than you could in code. Especially when it comes to things like making the results conditional on operations performed on the data. Arguably with modern engines effectively JIT'ing + caching the compiled version of your query it'd make sense on the surface.

The question is whether or not leveraging your database engine in this way is inherently bad design practice (and why). The lines become blurred further when all the logic exists inside the database and you're just hitting it via an ORM.

答:
I would rephrase that to "Never do in code what SQL Server can do for you well".

Things like string manipulation, regex work and such I would not do in SQL Server (barring SQL CLR).

The above tends to talk about things like - joins, set operations and queries. The intention behind it is to delegate much of the heavy lifting to SQL Server (at things it is good at) and reduce the amount of IO as much as possible (so let SQL do the joins and filter down with a WHERE clause, returning a much smaller data set than otherwise).


答:
In short, it would be correct to say that: "Never perform database specific operations in your code base" as they are better addressed in your database.

Look at example of the set base operations. As you may know, RDBMS  are build to handle a common data storage and manipulation operations.

In addition, the project choice of database plays important role. Having a RDBMS (MS SQL, Oracle, etc..) is different than NoSQL databases like RavenDB.

Title: "Never do in code what you can get the SQL server to do well for you" - Is this a recipe for a bad design?

Body:
It's an idea I've heard repeated in a handful of places. Some more or less acknowledging that once trying to solve a problem purely in SQL exceeds a certain level of complexity you should indeed be handling it in code.

The logic behind the idea is that for the large majority of cases, the database engine will do a better job at finding the most efficient way of completing your task than you could in code. Especially when it comes to things like making the results conditional on operations performed on the data. Arguably with modern engines effectively JIT'ing + caching the compiled version of your query it'd make sense on the surface.

The question is whether or not leveraging your database engine in this way is inherently bad design practice (and why). The lines become blurred further when all the logic exists inside the database and you're just hitting it via an ORM.


问:
Generic rule parser for RPG board game rules - how to do it?
I want to build a generic rule parser for pen and paper style RPG systems. A rule can involve usually 1 to N entities 1 to N roles of a dice and calculating values based on multiple attributes of an entity.

For example:

Player has STR 18, his currently equipped weapon gives him a bonus of +1 STR but a malus of DEX -1. He attacks a monster entity and the game logic now is required to run a set of rules or actions:

Player rolls the dice, if he gets for example 8 or more (base attack value he needs to pass is one of his base attributes!) his attack is successfull. The monster then rolls the dice to calculate if the attack goes through it's armor. If yes the damage is taken if not the attack was blocked.

Besides simple math rules can also have constraints like applying only to a certain class of user (warrior vs wizard for example) or any other attribute. So this is not just limited to mathematical operations.

If you're familiar with RPG systems like Dungeon and Dragons you'll know what I'm up to.

My issue is now that I have no clue how to exactly build this the best possible way. I want people to be able to set up any kind of rule and later simply do an action like selecting a player and a monster and run an action (set of rules like an attack).

I'm asking less for help with the database side of things but more about how to come up with a structure and a parser for it to keep my rules flexible. The language of choice for this is php by the way.

Edit I:

Let me refine my goal: I want to create a user friendly interface (that does not require somebody to learn a programming language) to build more or less complex game rules. The simple reason: Personal use to not need to remember all the rules all the time, we simply do not play that often and it's a stopper to look them up each time. Also: Looks like a fun task to do and learn something. :)

What I've tried so far: Just thinking about a concept instead of wasting time building a wrong architecture. So far I have the idea to allow a user to create as many attributes as they want and then assign as many attributes as they want to any kind of entity. An entity can be a player, a monster, an item, anything. Now when calculating something the data is made available to the rule parser so that the rule parser should be able to do things like if Player.base_attack + dice(1x6) > Monster.armor_check then Monster.health - 1; The question here is about how to create that parser.

Edit II:

Here is an example of pretty basic value but to calculate it properly there are lots of different things and variables to take into account:

Base Attack Bonus (Term) Your base attack bonus (commonly referred to
  as BAB by the d20 community) is an attack roll bonus derived from
  character class and level. Base attack bonuses increase at different
  rates for different character classes. A character gains a second
  attack per round when his base attack bonus reaches +6, a third with a
  base attack bonus of +11 or higher, and a fourth with a base attack
  bonus of +16 or higher. Base attack bonuses gained from different
  classes, such as for a multiclass character, stack. A character’s base
  attack bonus does not grant any more attacks after reaching +16,
  cannot be less than +0, and does not increase due to class levels
  after character level reaches 20th. A minimum base attack bonus is
  required for certain feats.

You can read it here http://www.dandwiki.com/wiki/Base_Attack_Bonus_(Term) including the links to classes and feats which have again their own rules to calculate the values that are required for the base attack.

I began to think that keeping it as generic as possible will also make it pretty hard to get a good rule parser done.

答:
I'd take a look at maptool specifically Rumble's 4th ed framework. It's the best system I've seen for setting up what you're talking about. Unfortunately the best is still horribly crufty. Their "macro" system has... let's say... evolved over time.

As for a "rules parser" I'd just stick with whatever programming language you're comfortable with, even if that's PHP. There's not going to be any good way around encoding all the rules of your system.

Now, if you want your users to be able to write THEIR OWN ruleset, then you're looking at implementing your own scripting language. Users script their own high-level actions, your php interprets that into something that actually affect database values, and then it throws a bunch of errors because it's a horribly crufty system that's been shoe-horned into place over the years. Really, Jon Purdy's answer is right on the ball.


答:
I like to look at it as SQL should only deal with the data itself. The business rules that decide what the query may look like can happen in code. The regex or validation of the informaiton should be done in code. SQL should be left to just join your table, query your data, insert clean data, etc.

What gets passed into SQL should be clean data and SQL should not really need to know anything more than it needs to store it, update it, delete it or retrieve something. I have seen way too many developers want to throw their business logic and coding in SQL because they think of the data as their business. Decouple your logic from your data and you will find your code gets cleaner and easier to manage.

Just my $0.02 though.


答:
Never do in code what you can get the SQL server to do well for you (emphasis is mine)

The key to the answer is you need to look for SQL doing something well, as opposed to simply doing something, for you. SQL is an amazingly powerful language. Coupled with built-in functions, it can potentially do a lot of things. However, the fact that you can do something in SQL should not be an excuse for actually doing it in SQL.

My specific criteria to make a decision is to look at the amount of data that you get back and the number of round-trips: if you can cut the amount of data by shipping a task to the server, without increasing the number of round-trips, then the task belongs on the server; if the amount of data remains the same or increases without a simultaneous drop in the number of round-trips, the task belongs in your code.

Consider these examples:

You store a birth date, and you need to calculate the age for a group of users. You can have SQL server do the subtraction, or you can do it in your code. The number of round-trips stays the same, and the amount of data sent back to you goes up. Therefore, a code-based solution wins

You store a birth date, and you need to find users of ages between 20 and 30. You can load all users back on the client, do the subtraction to find the age, and then do the filtering, but shipping the logic to SQL Server would reduce the amount of data without requiring a additional round-trips; therefore, SQL-based solution wins.


答:
Generally I agree that the code should control the business logic and the DB should be a logic free hash. But here are some counter points:

Primary, foreign key, and required (not null) constraints could be enforced by code. Constraints are business logic. Should they be left out of the database since they duplicate what code can do?

Do other parties outside of your control touch the database? If so having constraints enforced close to the data is nice. Access could be restricted to a web-service which implements logic, but this assumes you were there "first" and have the power to enforce the use of the service on the other parties.

Does your ORM perform a separate insert/update for each object? If yes, then you will have severe performance problems when batch processing large data sets. Set operations is the way to go. An ORM will have trouble accurately modeling all the possible joined sets which you could perform operations on.

Do you consider a "layer" to be a physical split by servers, or a logical split? Running logic on any server could theoretically still fall under it's logical layer. You might organize the split by compiling into different DLL's rather than splitting servers exclusively. This can dramatically increase response time (but sacrificing througput) while maintaining separation of concerns. A split DLL could later be moved to other servers without a new build to increase throughput (at the cost of response time).


问:
What did programmers do before variable scope, where everything is global?
So, I am having to deal with seemingly archiac language (called PowerOn) where I have a main method, a few datatypes to define variables with, and has the ability to have sub-procedures (essentially void methods) that does not return a type nor accepts any arguements.  The problem here is that EVERYTHING is global.  I've read of these type of languages, but most books take the aproach "Ok, we use to use a horse and cariage, but now, here's a car so let's learn how to work on THAT!" We will NEVER relive those days".  I have to admit, the mind is struggling to think outside of scope and extent.

Well here I am.  I am trying to figure out how to best manage nothing but global variables across several open methods.  Yep, even iterators for for loops have to be defined globaly, which I find myself recycling in different parts of my code.

My Question:  for those that have this type experience, how did programmers deal with a large amount of variables in a global playing field?  I have feeling it just became a mental juggling trick, but I would be interested to know if there were any known aproaches.

答:
My gosh, that is many years ago (bubbling memories :)).

I don't know the language you refer to, but in general we adapted to what we had. It wasn't really a huge issue. You needed to pay more attention to var names which often contained (in short form, in those days number of bytes was precious) reference to sub or function, like mIORead1 if you had a handler to read data from a file 1, or you had various counter vars like i, j, k etc. which by your own system you knew what they were for, if they could be reused and so forth. It was more hardcore (no helmets or gloves back then) :-)


答:
You'll need some kind of mental bookkeeping tricks (naming conventions, etc) in order to keep it straight. Also, document, document, document. Since all variables are globals, have a single document with all of them listed, if you can.

Try to have a small number of variables that you always use for temporaries, and remember that THEY ARE TEMPORARY. By constantly re-using the same ones, you'll get into the habit of keeping track of where they are valid or not.

Also, you want to look at the documentation and make sure you know how long variable names can be, and how many characters are actually unique. I know NOTHING about PowerOn, but if it's archaic enough to have only global scope, then it's possible that it's got a limited uniqueness length on identifiers.

I've seen things before with long identifiers, but whose identifiers were only unique in the first 8 characters. So you could have RonnyRayGun and RonnyRayBlaster and they are actually the SAME variable. In such cases I recommend keeping variable names under the 'unique' limit so that you're less likely to accidentally collide.

Title: What did programmers do before variable scope, where everything is global?

Body:
So, I am having to deal with seemingly archiac language (called PowerOn) where I have a main method, a few datatypes to define variables with, and has the ability to have sub-procedures (essentially void methods) that does not return a type nor accepts any arguements.  The problem here is that EVERYTHING is global.  I've read of these type of languages, but most books take the aproach "Ok, we use to use a horse and cariage, but now, here's a car so let's learn how to work on THAT!" We will NEVER relive those days".  I have to admit, the mind is struggling to think outside of scope and extent.

Well here I am.  I am trying to figure out how to best manage nothing but global variables across several open methods.  Yep, even iterators for for loops have to be defined globaly, which I find myself recycling in different parts of my code.

My Question:  for those that have this type experience, how did programmers deal with a large amount of variables in a global playing field?  I have feeling it just became a mental juggling trick, but I would be interested to know if there were any known aproaches.


答:
The rise of programming languages with block scope coincided with the advent of faster, larger machines, and that is no coincidence. Early computers had RAM measured in MB, kB or even in bytes; there was simply no opportunity to even have so many variables that they would be confused when the program got large, because programs never got that large. Advances in programming languages were usually made when people recognized that their old programming habits didn't scale up when the arena got much larger; block scope was invented as a mechanism of defense for programmers against their own limited memory.

Computing was also a much more rarefied and exotic activity when comoputers were fantastically expensive, and it may well be that only particularly mathematically inclined and ingenious individuals became programmers in the first place (although such comparisons are impractical to test, and certainly politically incendiary). In the early days, software was usually shipped for free with a computer in order to convince people to buy it in the first place; the thought that institutional users would even attempt to write their own programs was unknown at first.


答:
In layman's words:

These are things that SQL is made to do and, believe it or not, I've seen done in code:

joins - codewise it'd require complex array manipulation

filtering data (where) - codewise it'd require heavy inserting and deleting  of items in lists

selecting  columns - codewise it'd require heavy list or array manipulation

aggregate functions - codewise it'd require arrays to hold values and complex switch cases

foreign key integrity - codewise it'd require queries prior to insert and assumes nobody will use the data outside app

primary key integrity - codewise it'd require queries prior to insert and assumes nobody will use the data outside app

Doing these things instead of relying in SQL or the RDBMS leads to writing tons of code with no added value, meaning more code to debug and maintain. And it dangerously assumes the database will only be accessed via the application.


答:
This is pretty similar to PLC programming, though modern PLCs now allow you to have "tags" (aka variables) that are local to a program.  Still, a lot of people just program using all global tags.

I've found, if you're going to do that, you need to use a structured naming convention.  For instance: Motor1_DriveContactor_Run.  If your language happens to support structures (sometimes known as user-defined types) then you can also use those to create a structured data hierarchy, such as: Motor[1].DriveContactor.Run.

That keeps everything organized, and usually the intellisense is decent enough to help you along.


答:
Data dictionary.

In a central repository (usually the lead programmer's office), there was a looseleaf binder, that contained one page for each and every global variable.  The page gave the name, its definition, its purpose, and which routines set or used it.

Early embedded systems with microscopic RAM had a similar problem, and a similar solution.  The lead programmer maintained the master RAM map, down to the individual bytes, showing what RAM was used by which modules for which purposes.  Programmers who needed a dedicated RAM allocation went to the lead programmer, who, after discussing the matter, made the appropriate notebook entry and gave the guy his RAM.  (You did not want to be in the shoes of the programmer who took a RAM byte without clearing it with the lead programmer.  Trust me on this.)

This problem also showed up when programmers had to build large systems in early versions of BASIC.  It showed up for me personally while using a very primitive "database" manager called Info (product of Henco, Inc. of New Jersey - HOPEFULLY now long gone!).  Both of those languages had a very limited variable name vocabulary.


问:
How to turn on/off code modules?
I am trying to run multiple sites using single code base and code base consist of the following module (i.e. classes)

User module

Q & A module

Faq module

and each class works on MVC pattern i.e. it consist of

Entity class

Helper class (i.e. static class)

View (i.e. pages and controls)

and let's say I have 2 sites site1.com and site2.com. And I am trying to achieve following functionality

site1.com can have User, Q & A and Faq module up and running

site2.com can have User and Q & A module live while Faq module is switched off but it can be turned-on if needed, so my query here is what is the best way to achieve such functionality

Do I introduce a flag bit that I check on every page and control belonging to that module? It's more like CMS where you can turn on/off different features. I am trying to get my head around it, please provide me with an example or point out if I am taking the wrong approach.

答:
To me the simplest approach would be to set up a permissions table and give each module an identifier. An integer would do and the have some way to identify which site is loaded and check against that table to see if they are set up for it. Where I work now, we do that in the pages since we have multiple users with permissions and multiple countries to contend with. Any one user can have different modules and can use those modules in different countries.

We basically declare a variable on the page and look up the users permissions (that part is done in the master page so we only do it once and save it for the session). Now we need only check the in-memory object to see if they have the permission for that page which is again in a variable.

HTH

Title: How to turn on/off code modules?


答:
"Premature optimization is the root of all evil (most of it, anyway) in computer programming" - Donald Knuth

The database is exactly that; the data layer of your application. Its job is to provide your application with the data asked for, and store the data given to it. Your application is the place to put code that actually works with the data; displaying it, validating it, etc.

While the sentiment in the title line is admirable, and accurate to a point (the nitty-gritty of filtering, projecting, grouping etc should in the overwhelming number of cases be left to the DB), a definition of "well" might be in order. The tasks that SQL Server can execute with a high level of performance are many, but the tasks that you can demonstrate that SQL Server does correctly in an isolated, repeatable manner are very few. SQL Management Studio is a great database IDE (especially given the other options I've worked with like TOAD), but it has its limitations, first among them being that pretty much anything you use it to do (or any procedural code you execute in the DB underneath) is by definition a "side effect" (altering state lying outside the domain of your process's memory space). In addition, procedural code within SQL Server is only just now, with the latest IDEs and tools, able to be measured the way managed code can using coverage metrics and path analysis (so you can demonstrate that this particular if statement is encountered by tests X, Y, and Z, and test X is designed to make the condition true and execute that half while Y and Z execute the "else". That, in turn, assumes you have a test that can set the database up with a particular starting state, execute the database procedural code through some action, and assert the expected results.

All of this is much more difficult and involved than the solution provided by most data access layers; assume the data layer (and, for that matter, the DAL) know how to do their job when given the correct input, and then test that your code provides correct input. By keeping procedural code like SPs and triggers out of the DB and instead doing those types of things in application code, said application code is much easier to exercise.


问:
MVC Can the model know ANYTHING about the view?
I'm working on a game, and without getting into any details I am using MVC "patterns", "rules" or whatever you want to call it to make the game.

The view includes everything needed to draw things on the screen, the controller passes input to the model. And the Model contains game logic.

Here's my problem, the game is being made for mobile devices that vary in screen sizes. I feel my model needs to know the view size so it can appropriately adjust for it.

I've thought about it for a while I could put all the adjustments in the view, but it just seems inefficient to translate the model positioning to the view's needed positioning every time. If the model knows the size it only needed to adjust itself once.

So my question is can I pass the view size to the model without 'breaking' MVC? I feel personally they are still decoupled this way because a size is just a number, I could still change the view any time as long as it has a size. But I wanted to get a community response on this because I haven't seen many discussions of MVC being used in a game.

(And to be clear I don't want an answer of why I shouldn't use it in a game, but do I break MVC by letting it know the view's size)

EDIT - More details on the game's needs and why I wanted to pass the view.

Some objects positions need to be set relative to the edge of the screen (such as UI elements) so that they appear relatively in the same place. Sprite sizes are not stretched if the window size is wider such as an IPhone 5 screen. They will just be placed relatively to the screen edge. .If I gave it to the view to handle this, I will need a flag saying that this element is positioned say x number of pixels from TOP BOTTOM RIGHT LEFT. Then allow the view to draw it with that information. Its acceptable, I just wanted to know if there was a better way while still being MVC because it seems this way will be repeating a logic over and over, where as if I knew the view size in the model, I could convert all the relative positions into absolute positions in one run, but with this I have to convert on every update to the screen.

答:
You might be trying to do too much in the model. If the model has to care about screen size, I would say the design is breaking some rules of MVC. Instead, why can't the controller (or "presenter") know the screen size and adapt the model data to match? The Controller is technically the correct place for any logic requiring knowledge of both the view and the model.

You didn't give many specifics (like why screen size is important); it's fair enough for you to want to keep secrets about your game, but if you can at least tell us what basic function is being performed that requires screen size, we may be able to better tell you how best to implement MVC patterns in your code.


答:
As usual, the answer is it depends.

If you use an abstraction for the screen size in the model, they could live together. For example, the model could know about the size of the universe or visible universe. This would be different depending on the device type or screen size ... or simply put depending on the hardware.

If you put it this way, your model depends on information from the hardware (lowest level) and does it's job. You view will take whatever the model gives to it and do the rendering job on the screen.

On the other hand, you may also use another approach. You may ask yourself, should the Model know about coordinates? I don't know the answer to this, it depends on your application. Maybe you could use view helpers to adjust for coordinates where needed.

Also keep in mind, many times optimization is the reverse of refactoring or making thing right. If it's a performance hit you can't live with, sacrifice the design and make your program do what it needs to do.

Title: MVC Can the model know ANYTHING about the view?

Body:
I'm working on a game, and without getting into any details I am using MVC "patterns", "rules" or whatever you want to call it to make the game.

The view includes everything needed to draw things on the screen, the controller passes input to the model. And the Model contains game logic.

Here's my problem, the game is being made for mobile devices that vary in screen sizes. I feel my model needs to know the view size so it can appropriately adjust for it.

I've thought about it for a while I could put all the adjustments in the view, but it just seems inefficient to translate the model positioning to the view's needed positioning every time. If the model knows the size it only needed to adjust itself once.

So my question is can I pass the view size to the model without 'breaking' MVC? I feel personally they are still decoupled this way because a size is just a number, I could still change the view any time as long as it has a size. But I wanted to get a community response on this because I haven't seen many discussions of MVC being used in a game.

(And to be clear I don't want an answer of why I shouldn't use it in a game, but do I break MVC by letting it know the view's size)

EDIT - More details on the game's needs and why I wanted to pass the view.

Some objects positions need to be set relative to the edge of the screen (such as UI elements) so that they appear relatively in the same place. Sprite sizes are not stretched if the window size is wider such as an IPhone 5 screen. They will just be placed relatively to the screen edge. .If I gave it to the view to handle this, I will need a flag saying that this element is positioned say x number of pixels from TOP BOTTOM RIGHT LEFT. Then allow the view to draw it with that information. Its acceptable, I just wanted to know if there was a better way while still being MVC because it seems this way will be repeating a logic over and over, where as if I knew the view size in the model, I could convert all the relative positions into absolute positions in one run, but with this I have to convert on every update to the screen.


答:
It is good to look at MV* pattern with more views existing in parallel on the same model (that is how proper separation of domain and presentation should work, seamlessly). From this point of view, how could you put screen size into the model, when there could be more screen sizes?

That is, MVP / MVVM provides slightly better structure to solve this - presenter (or view model) are parts which know of the screen size. They are the parts responsible of delivering data to show into the view. But not the model.

OTOH, there is other view (especially when it is a game), where screen size actually should be part of a model - that is when the game logic really depends on that screen size.

So, I would ask myself if the screen size is the necessary part of game logic. If yes, it is part of the model (and any screen-type views are restricted to only that one screen). If not, it is the matter of presenter/viewmodel to take care of this (and lots of other, like skinning/themes for example) presentation detail.


答:
I think it would be poor design to not use the database for the things it is meant for. I have never seen any database where the rules were enforced outside the database that had good data. And I have looked at hundreds of databases.

So things that must be done in a database:

Auditing (application only auditing will not track all changes to the
database and thus is worthless).

Data ingerity constrainsts including default values, foreign key
constraints and rules which must always be applied to all data. All
data is not always changed or inserted through an application, there
are one-time data fixes especially of large data sets that are no
practical to do one record at a time (please update these 100,000
records that got mismarked as status 1 when they should be 2 due to
an application code bug or please update all records from client A to
client B because company B bought company A) and data imports and
other applications which might touch the same database.

JOINS and where clause filtering (to reduce the number of records
sent across the network)