问:
Is Default Package included in the Package Level Access?
I would like to know how the default package is defined in Java.I know how public and private access is defined but I don't know whether there is any default package access that is defined in package level access in java.

I'm asking this question because when I compile java file containing two classes since no modifier is given for classes,java compiler would give package level access as the default access modifier for the classes.Since no package is defined,java compiler would use the default package but I couldn't get whether the default package is included in package level access in java.Could anyone help me.

答:
The default package is the package without a name, all classes without a package declaration at the top of the file fall into it.

It is subject to all normal rules of packages except that you can't reference classes of it from a class inside a package.

For example I have 2 java files:

```<code>public class A{
    public static void foo(){System.out.println("fooCalled");}
}
</code>```

and

```<code>package com.example;

public class B{
    public static void main(String[] arg){
        A.foo();//won't compile
    }

}
</code>```

Then B (or in the qualified form com.example.B) can never call the foo of A without reflection magic.

If you ever start making larger programs then you should put all your code in packages. It allows you to segregate your code in a way that makes sense.

The accepted practice is to name you package after a domain the program is part of like com.example

Body:
The default package is the package without a name, all classes without a package declaration at the top of the file fall into it.

It is subject to all normal rules of packages except that you can't reference classes of it from a class inside a package.

For example I have 2 java files:

public class A{
    public static void foo(){System.out.println("fooCalled");}
}

and

package com.example;

public class B{
    public static void main(String[] arg){
        A.foo();//won't compile
    }

}

Then B (or in the qualified form com.example.B) can never call the foo of A without reflection magic.

If you ever start making larger programs then you should put all your code in packages. It allows you to segregate your code in a way that makes sense.

The accepted practice is to name you package after a domain the program is part of like com.example


问:
How much business logic should be allowed to exist in the controller layer?
Sometimes we have some business logic represented in the controller code of our applications. This is usually logic that differentiates what methods to call from the model and/or what arguments to pass them.

Another example of this is a set of utility functions that exist in the controller that may work to format or sanitize data returned from the model, according to a set of business rules.

This works, but I am wondering if its flirting with disaster. If there is business logic shared between controller and model the two layers are no longer separable, and someone inheriting the code may be confused by this unevenness in location of business logic related code.

My question is how much business logic should be allowed in the controller and in what circumstances, if any?

答:
Ideally none

But that's not always possible. I can't give you hard numbers like 20% or 10 lines, that is subjective to the point it can't be answered. I can describe how I use design patterns and circumstances that necessitate bending them slightly.

In my mind it's entirely up to the purpose of the application. Building a simple REST api to post to? Forget about clean separation or even a pattern. You can churn out a working version in under an hour. Building something bigger? Probably best to work on it.

Building individually contained systems is the goal. If you start writing business logic that is specific to how two systems interact that is a problem. Without looking further into it I can't give an opinion.

Design patterns are molds, some like to strictly adhere to them on the basis of principal and well-written code. Strictly adhering to a pattern probably won't give you bad code, but it could take more time and cause you to write much more code.

Design patterns are flexible, adjust them to suit your needs. Bend them too much and they break though. Know what you need and pick a design pattern closest to that.

ContentLicense: CC BY-SA 2.5


问:
Testing vs Don't Repeat Yourself (DRY)
Why is repeating yourself by writing tests so highly encouraged?

It seems that tests basically express the same thing as the code, and hence is a duplicate (in concept, not implementation) of the code. Wouldn't the ultimate target of DRY include elimination of all test code?

答:
Unit tests should not include a duplication of the code under test, as has been noted already.

I would add, though, that unit tests are typically not as DRY as "production" code, because setup tends to be similar (but not identical) across tests ... especially if you have a significant number of dependencies that you're mocking/faking.

It is of course possible to refactor this sort of thing into a common setup method (or set of setup methods) ... but I've found that those setup methods tend to have long parameter lists and be rather brittle.

So be pragmatic.  If you can consolidate setup code without compromising maintainability, by all means do that.  But if the alternative is a complex and brittle set of setup methods, a little bit of repetition in your test methods is OK.

A local TDD/BDD evangelist puts it this way:

"Your production code should be DRY. But it's OK for your tests to be 'moist'."

ContentLicense: CC BY-SA 3.0

Title: Testing vs Don't Repeat Yourself (DRY)


问:
Scrum: Capacity vs Velocity when planning a sprint
We have completed 11 sprints so far in our current project. In most sprints we have not been burning down well and usually finish with our velocity gradient flattening as we approach the end of the sprint. However, having looked back at our last few burn downs it seems we are consistent with how much work we carry over to the next sprint.

Currently we use capacity driven planning where we allocate 50 hours per person in a two week cycle. But I am wondering if it would be better to use the averaged velocities of past sprints as an aid for planning seeing as the velocities are generally consistent?

答:
In my opinion, there are two different types of planning involved here.

Velocity-based planning:
Velocity is usually tracked as completed story points in a sprint. You should have a good idea after 11 sprints of your average story point velocity and should be able to forecast how many 'points' your team can accomplish in an upcoming sprint.

After doing your story estimation, the number of stories you choose to tackle in the upcoming sprint should be based on this historical sprint velocity.

Capacity (hours) planning:
After you have selected your stories, the task planning begins and you start estimating what will be done and how long each task will take. This will let you see how many hours of work you believe you have to do. Based on your average capacity on the team, this will help you validate whether the initial point-based planning is still on track.

My thoughts:
I use capacity mostly to make sure I am tracking actual availability within a given sprint. On average, the team might have about 50 hours per person, but what about a sprint starting on December 15th? Suddenly a lot of folks are taking holidays and vacation time and the sprint capacity is affected. For this reason, I don't believe in using historical capacity's to estimate the current capabilities of the team.

My advice would be to use your story-point velocity that you have established to determine which stories to take on, and then build out the true capacity for the upcoming sprint based on resource availability.


问:
Usage of this keyword in constructor chaining?
I am reading msdn documentation for this keyword. They gave three usages for this keyword as follows

To qualify members hidden by similar names

To pass an object as a parameter to other methods

To declare indexers

and there is no word about the usage of this during constructor chaining.

My question are :

Why they missed out constructor chaining ?

Is in some way that constructor chaining is an application of the above three usages that I am not aware of ?

答:
The article you linked says (emphasis mine):

The following are common uses of this:

The article doesn't say that this doesn't have other uses. In fact, it also explicitly says that it doesn't discuss another use of this:

This article discusses the use of this with class instances. For more information about its use in extension methods, see Extension Methods (C# Programming Guide).

If you think that using this in constructor chaining should be discussed in that article, consider filing a bug.


问:
Are UML class diagrams adequate to design JavaScript systems?
Given that UML is oriented towards a more classic approach to object orientation, is it still usable in a reliable way to design JavaScript systems?

One specific problem that I can see is that class diagrams are, in fact, a structural view of the system, and JavaScript is more behaviour driven, how can you deal with it?

Please keep in mind that I'm not talking about the real world domain here; it's a model for the solution that I'm trying to achieve.

答:
There has been work done to adapt web application to UML, its called the WAE extension and there is a book called Building Web Applications with UML by Jim Conallen explaining it in detail. You can see variables and function of JavaScript in the class diagram.

Why i believe its the best option to model web application ? Because evrybody know how class diagram works and this is the closest thing to it. Its very easy to understand and programmers are too lazy to read documentation in words, but looking at a diagram is not that hard ;). However, if you want to see what happens at the execution, then you should look for a sequence diagram because in web application, sometime files are generated dynamically.


问:
Project implementation details in node.js
I am working as a software engineer turned team leader in a large software company. One of my areas of strength is node.js, and we are in the process of moving a lot of our services to separate node.js services, which is proving to be very successful so far.

However, I am supposed to stop day to day development of small node.js services, and simply lay down a proper specification, so that one of my team members can work on the actual code.

I am aware of tools like UML, but I don't think they apply to a system with apis built with node.js/express. I have made a few flowcharts, but my seniors want me to be very complete with the spec, down to each implementation detail.

How I can achieve this? Should I design objects in UML and make my developers make javascript objects which can be used in express routes?

答:
I created a module that generate class diagram for javascript/node/html/css. Its based on the "WAE" extension of UML. Its called wavi. For javascript, function,variable and use of other modules are automatically recognized. You can use it for documenting your application.

https://www.npmjs.org/package/wavi


问:
Managing multiple JDBC connection
I have an application that connects to databases based on a json string that contains connection information. The json is sent just when the application starts.

How do you manage such connection pools? Because I can get multiple configurations that point to the same database with the same user. I know I cannot create new connection every time since it's an expensive operation so I use connection pools (Apache DBCP2).

But when two pools connect to the same database I sometimes get "too many connections" error since the pool size of two pools is greater than the max allowed connections.

Is holding the connection pools in a HashMap where the connection string is used as the key a bad idea?

Config looks like this (very simplified json):

{
   dbconfig: [
      { database 1 ... },
      { database 2 ... },
      { database 3 ... }
   ],
   otherconfig: { ... }
}
```

The database 1 and 2 config point to the same database, or the same server but a different database

So my application spawns three threads that receive data on a predefined port. I don't know what database connections I will get and how many worker threads will I spawn. And my question is if there is some kind of pooling framework at which I can throw the configs and it will take care of the sharing of connections and I can just request the connection from it.

Currently with my design I would create 3 pools from which 2 pools are accessing the same server and sometimes the same database and that's why I get the "too many connections".

答:
First off, you should be closing connections once you are done using them.  That will help take care of the "too many connections" errors you're seeing.  At an application level, you need to be releasing any shared resources you have as soon as you're done using them.

Second, it sounds like you're trying to duplicate the work that the underlying connection pool manager can provide for you.  Specifically, at the application level, don't worry about the cost involved with opening / closing connections - that's what the pool manager handles for you.  Because you haven't been closing off the connections once done, you're making it harder for the pool manager to be of use to you.

It's not clear if you have multiple, separate applications using separate pool managers or separate applications using the same pool manager.  Regardless, using a HashMap with the connection string is a bad idea.  At a minimum, you'll create inter-application communication issues.  In the worst case, you're going to have to try and coordinate resources (connections) across applications in a web-server which is going to be problematic at best.

Finally, if you need to have multiple pools connecting to the same database server and the total number of connections across those pools is exceeding what the DB server can handle then you need to change that configuration on the DB server.  If you truly need 11 connections and the DB server is only giving you 10, then you need to change the DB server.

To Summarize:

Close the connections already.  You're creating potentially huge headaches in the name of perceived performance savings.

Change the DB server settings if you're still running out of connections.

Title: Managing multiple JDBC connection


问:
Various methods manipulating same member variable versus each takes inputs and provides output
As software design paradigm which is better? to let various methods manipulate a member variable, or define each method or function to take some inputs and provide some outputs?

For example

```<code>   class Test {

       void FooMethod1()
       {
           Foo = ...
       }
       void FooMethod2()
       {
           Foo = ...
       }
       void Method3()
       {
           FooMethod1();
           FooMethod2()
       }
    }
</code>```

versus.

```<code>  class Test {

       var FooMethod1(var input)
       {
           input = ...
           return ...
       }
       var FooMethod2(var input)
       {
           input = ...
           return ...
       }
       void Method3()
       {
           var Foo;
           FooMethod1(Foo);
           FooMethod2(Foo)
       }
    }
</code>```

答:
The first is marginally better, but in general, you should try to avoid unnecessary side effects altogether.

Why? Modifying input parameters is vile. It is unexpected, it is difficult to test, it is difficult to reuse, it creates problems in concurrent environments...

Modifying a class is sometimes fine, that is what classes are for really... but it can be difficult to test, difficult to modify/extend, it creates problems in concurrent environments... And you usage here where Foo is just some placeholder to pass around in Method3 defeats the point of the class.

A better approach would be something like this:

```<code>Foo Method1(Foo x){ ... }
Foo Method2(Foo x){ ... }
Foo Method3(){
    Foo stuff = ...;
    stuff = Method1(stuff);
    stuff = Method2(stuff);
    // and return or just do stuff with stuff...
}
</code>```

Body:
The first is marginally better, but in general, you should try to avoid unnecessary side effects altogether.

Why? Modifying input parameters is vile. It is unexpected, it is difficult to test, it is difficult to reuse, it creates problems in concurrent environments...

Modifying a class is sometimes fine, that is what classes are for really... but it can be difficult to test, difficult to modify/extend, it creates problems in concurrent environments... And you usage here where Foo is just some placeholder to pass around in Method3 defeats the point of the class.

A better approach would be something like this:

Foo Method1(Foo x){ ... }
Foo Method2(Foo x){ ... }
Foo Method3(){
    Foo stuff = ...;
    stuff = Method1(stuff);
    stuff = Method2(stuff);
    // and return or just do stuff with stuff...
}


问:
Creating a sort of 'in-language compiler'
I'm not saying I want to create a whole new compiler that's completely independent. I'm using C# Windows Forms and I want users to be able to write filtering syntax in a textbox withing my managed application in a basic query language, for example:

```<code>inCategory(Animals)
where(animal.age > 40)
take animal;
</code>```

It's basically a simplifed version of LINQ. But I want this logic to be enclosed in some separate class, so I can say something like this:

```<code>var dataQuery = FilterCompiler.Compile(filterTextBox.Text);
dataQuery.Execute();
</code>```

I'm not saying 'gimee the code', but some psuedocode / basic logic structure for this 'compiler' would be nice since I am kind of clueless about this subject. Like for example,

What sort of text analysis would this FilterCompiler need to do?

What would be the type of dataQuery?

Would this require any knowledge of compiler grammar?

Would I need to use any unmanaged code?

How can I keep the compiling as independent as possible so that it does not depend too much on what type of data I have? Currently I have a List, but things change, I might have a database with the information in it soon.

答:
What you are looking at creating is known as a standalone DSL (with a separate syntax and interpreter), as opposed to an embedded one (which shares syntax with a host language).

This will require the skills necessary to build a simple interpreter, at a minimum.

In its simplest form, this entails the following:

Reading in the text.

Performing lexical analysis, which breaks the input text into discrete language-specific entities known as tokens. This step is frequently referred to as lexing.

Performing syntactic analysis, which builds expression trees from the stream of tokens. This step is frequently referred to as parsing.

Interpretation, which accepts the expression trees (in your case, this would be some tree of objects) and then executes the actions indicated by the semantics of your language.

Steps #2-3 are not commonly done through hand-written code, except in the case of full-blown language interpreters. Frameworks or code generators, like lex and yacc for C, are by far the most common method of implementation.

Compilers: Principles, Tools and Techniques (affectionately known as The Dragon Book for the theme of its covers) is a highly regarded source on these sorts of steps.

As an aside, this all seems like a very large amount of work for what it is you really want to accomplish, especially since Microsoft has included a simple expression language on the DataTable structure used by ADO.NET (see here for more information: http://msdn.microsoft.com/en-us/library/system.data.datacolumn.expression(v=vs.110).aspx). Building a user-facing DSL for filtering seems like overkill. If you need complex grids and similar functionality, it would likely be more time efficient to look at a component vendor like DevExpress or Telerik.


问:
Is automatic conversion to collection types from non-collection variable a good idea?
Consider

```<code>public void Do(string[] aBunchOfStrings) { }
</code>```

or

```<code>public void Do(IReadOnlyList<string> aBunchOfStrings) { }
</code>```

Would it be a bad idea to allow the function call

```<code>Do("woei");
</code>```

resolve automatically to an internal call

```<code>Do(new[] { "woei" });
</code>```

to C#?

答:
It weakens your types, meaning the type checker will catch fewer programmer errors.  Whether you consider that a good or bad idea depends where you fall on the weakly/strongly typed spectrum.

I can think of a few situations where it might cause problems, such as if you wanted to override the function to have a separate version that just takes a bare string.  You'd have to have rules to resolve those sorts of conflicts.


答:
What sort of text analysis would this FilterCompiler need to do?

It would need to be able to interpret the input and understand what is good/bad. I would recommend following the standard lexer/parser approach, as it is well known and robust in the face of uncertainty (read: user input).

What would be the type of dataQuery?

Func<T, T> (where T is whatever enumerable you're working against) probably.

Would I need to use any unmanaged code?

Not at all.

.NET has a very nice library to compile delegates on the fly for things specifically like this: Expression Trees. You can even use reflection to know what properties/fields are legal identifiers. Resolving the identifiers to reflection objects and then building the expression trees is about as straight-forward as these things get.

Title: Creating a sort of 'in-language compiler'

Body:
I'm not saying I want to create a whole new compiler that's completely independent. I'm using C# Windows Forms and I want users to be able to write filtering syntax in a textbox withing my managed application in a basic query language, for example:

```<code>inCategory(Animals)
where(animal.age > 40)
take animal;
</code>```

It's basically a simplifed version of LINQ. But I want this logic to be enclosed in some separate class, so I can say something like this:

```<code>var dataQuery = FilterCompiler.Compile(filterTextBox.Text);
dataQuery.Execute();
</code>```

I'm not saying 'gimee the code', but some psuedocode / basic logic structure for this 'compiler' would be nice since I am kind of clueless about this subject. Like for example,

What sort of text analysis would this FilterCompiler need to do?

What would be the type of dataQuery?

Would this require any knowledge of compiler grammar?

Would I need to use any unmanaged code?

How can I keep the compiling as independent as possible so that it does not depend too much on what type of data I have? Currently I have a List, but things change, I might have a database with the information in it soon.


问:
Which are the cases when 'uint' and 'short' datatypes are a better fit than the standard int(32)?
I understand the differences in capacity and values they can represent but it seems as though people always use Int32 regardless of whether it is appropriate. No one ever seems to use the unsigned version (uint) even though a lot of the time it fits better as it describes a value that cannot be negative (perhaps to represent an ID of a database record). Also, no one ever seems to use short/Int16 regardless of the required capacity of the value.

Objectively, are there cases where it's better to use uint or short/Int16 and if so, which are they?

答:
Sure, there are cases where it's better to use uint or short or Int16.  When you know that your data range will fit within the constraints of that variable type, then it's okay to use that type.

In memory constrained environments or when dealing with large amounts of objects, it can make sense to use the smallest size variable.  For example, there is a significant difference in size for a million element array of ints vs. shorts.

Oftentimes, that doesn't happen in actual code for one or more of the following reasons:

Data constraints were not known ahead of time

There was a chance that the data constraints weren't solid or were known to likely be changed

There was a hope of re-using the function with a broader data range

Developer didn't take the time to think through the constraints

Memory savings were insignificant to justify using a smaller variable type

There's a lot more possible reasons, but they boil down to this:  The time involved in deciding upon and using a different variable type didn't provide enough benefit to justify doing so.


答:
Unfortunately its not really that simple, you have a few options...

Coco/R

If you aren't going to do a complex language and only support a few custom keywords, I would suggest something like Coco/R. I have used this several times in the past to create parsers for all kinds of projects.

The jist of it would be that you create a grammar file that describes your language and it allows you to plug in your own functions when certain tokens are found. This may be a little more difficult because it appears that your sample language understands the concepts of Objects and Coco/R actually creates classes that you compile. This means you are going to have to build these sort of things in to the parser and/or use interfaces. You are also doing arithmetic which means you are going to have to write an expression evaluator.

Compile with .NET classes

Another option is to not actually create your own syntax but use something like .NET's built in classes to compile code. This saves you a lot of work (read ton of work) but you lose the flexibility of creating your own simplistic language. More information can be found here.

Reflection.Emit

Another option which would probably be the most complex and not really worth it would be to write IL using reflection and then compile that code to a dynamic function and execute it. You would have a lot of trail and error making sure that you generate valid IL that doesn't just crash and throw up some strange errors that are nearly impossible to track down. There are a lot of benefits from this tho, the user could write complex code that could interact with your own objects (like a real scripting language) and would be easy to extend once the framework was built. More info can be found here

If I personally had to choose one it would come down to what I needed it for. If I was developing this for my company I would probably go with Reflection.Emit and if I just needed something to work right now and fast I would go with using the .NET libraries to just compile C# code to a app domain that I then would just execute. If the language only had a small subset of features I would probably go with Coco/R, but I have a lot of experience with it and there would be no learning curve there for me.

Sorry for the terrible formatting, I'm still rather new to MD.


答:
I suspect you are referring to a perspective colored by your own experiences where you have not worked around folks who use integral types properly. This may well be a common occurrence, but it's been my experience that people commonly do use them correctly as well.

The benefit is memory space and cpu time, possibly IO space as well depending on whether the types are ever sent over the wire or to a disk. Unsigned types give you compiler checks to ensure you won't do certain operations that are impossible, plus extending the available range while maintaining the smaller size for heightened performance where it may be necessary.

The correct use is as you would expect - anytime you know for certain you can use them permanently (do not constrain without certainty or you will regret it later).

If you're trying to represent something that could never reasonably be negative (public uint NumberOfPeople) use an unsigned type.

If you're trying to represent something that could never reasonably be greater than 255 (public byte DamagedToothCount), use a byte.

If you're trying to represent something that could reasonably be greater than 255, but never a significant number of thousands, use a short (public short JimmyHoffasBankBalance).

If you're trying to represent something that could be many hundreds of thousands, millions even, but unlikely to ever reach multiple billions, use an int (public int HoursSinceUnixEpoch).

If you know for certain this number may have an unboundedly large value or you think it may have multiple billions but you're not certain how many billions, long is your best bet. If long's not big enough you have an interesting problem and need to start looking at arbitrary precision numerics (public long MyReallyGreatAppsUserCountThisIsNotWishfulThinkingAtAll).

This reasoning can be used throughout in choosing between signed, unsigned, and varied sizes of types et al, just think about the logical truths of the data you're representing in reality.

Title: Which are the cases when 'uint' and 'short' datatypes are a better fit than the standard int(32)?

Body:
I understand the differences in capacity and values they can represent but it seems as though people always use Int32 regardless of whether it is appropriate. No one ever seems to use the unsigned version (uint) even though a lot of the time it fits better as it describes a value that cannot be negative (perhaps to represent an ID of a database record). Also, no one ever seems to use short/Int16 regardless of the required capacity of the value.

Objectively, are there cases where it's better to use uint or short/Int16 and if so, which are they?


问:
Scrum: Is it ok for the design/UX of user story to occur in the same sprint as implementation
I am currently in a sprint (two weeks) where the designer is tasked with defining the requirements and UX of a particular user story.

In the same sprint, I am to implement this design. During sprint planning, I had to take a wild guess as to how long this undefined user story would take.

Today I finally received the design. Unfortunately, the design is incomplete/vague and is more akin to a client's requirements than a design. However, from this, I can still see that I have not nearly estimated enough.

To make matters worse this is not the first time. In the last sprint, the exact same thing happened. I flagged it in our retrospective and the scrum master did not have an answer of how to solve this, instead of saying "that's just development for you". Ironically he gets annoyed if the burn down is not on target...

Now I am going to have to ask/work with the designer to get his job done. This is going to hold me up as I have completed all my other tasks.

So my question is

 A) <s>how do you handle dependencies in sprint planning?</s> EDIT: Is it ok for the design/UX of user story to occur in the same sprint as implementation

 B) how should I now approach the sprint? Re-estimate the current user story and watch the burndown turn into a burn up and be viewed as incompetent/unproductive? Or add a new task to the current sprint along the lines of "help the designer create a suitable design"

答:
Are the tasks about design expressed as stories and what are your team's definitions of

a story is ready

a story is done

Each story should have his own requirements and conditions of acceptance, but I think it's a good practice to have a set of rules that are applicable to all stories. For instance, a story is ready if (and only if!): the end to end architecture studies are finished, the design is available, the story has been estimated by the team.  Minimal conditions of acceptance could be: the automated test is done, OK and has been integrated to the tests suit, code review is done.

If a story is not ready, don't embed it in your sprint. If condition of acceptance are not meet, then it's not finish.

In your case, the team could decide that to be ready, a development story needs to have a complete design (at least a wireframe, adjust this to your own reality). If so, you can't handle design and dev in the same sprint. The team could also decides that a UX/design story should a least produce a wireframe design. If it's not the case, then the story is not accepted and thus the stories depending on it can't be started.

You should easily convince your managers that having strong rules for ready is a good thing: re-evaluating complexity during sprint is a bad practice. It means the velocity of the team is uncertain and then that they, as managers, have a bad vision of the team's work and of the future.

ContentLicense: CC BY-SA 4.0


答: Sounds like what you want is a script interpreter in your code, to set up a domain-specific language.  As one of the comments notes, there's a book out there about doing this for .NET code, using the Boo language, which can either be used as a compiled language in its own right or as a interpreter on top of an existing CLR program.  Boo isn't really mainstream, but it's open-source and it's got a lot of useful features specifically for metaprogramming and DSL creations, and if you went that route you wouldn't need to build your own parser.</p>


问:
Generate algorithm to solve peg solitaire
I know that with regression it is possible to generate a mathematical function based on experimental data. I was wondering, maybe there is a way to generate something more complex. I have a single player logical game which is hard to solve:

There are 37 glass globes in holes:

```<code>    |o|o|o|
  |o|o|o|o|o|
|o|o|o|o|o|o|o|
|o|o|o|o|o|o|o|
|o|o|o|o|o|o|o|
  |o|o|o|o|o|
    |o|o|o|
</code>```

You have to remove one globe at the beginning (I started with the middle one):

```<code>    |o|o|o|
  |o|o|o|o|o|
|o|o|o|o|o|o|o|
|o|o|o| |a|b|o|
|o|o|o|o|o|c|o|
  |o|o|o|o|d|
    |o|o|o|
</code>```

After that you can step over a single globe in horizonatal or vertical direction (I stepped here with "b" over "a", so I removed "a" from the playground):

```<code>    |o|o|o|
  |o|o|o|o|o|
|o|o|o|o|o|o|o|
|o|o|o|b| | |o|
|o|o|o|o|o|c|o|
  |o|o|o|o|d|
    |o|o|o|
</code>```

Now I stepped again (with "d" over "c"):

```<code>    |o|o|o|
  |o|o|o|o|o|
|o|o|o|o|o|o|o|
|o|o|o|b| |d|o|
|o|o|o|o|o| |o|
  |o|o|o|o| |
    |o|o|o|
</code>```

The aim of the game that only a single globe should remain. Now that is extremely hard to achieve, I have less than 1% success rate and I don't have the winning strategy.

Is it possible to generate an algorithm, which can solve the problem by many different scenarios (so which has a strategy)?

I was thinking on genetic algorithms or neural networks, so something which can learn the basics from me and after that develop itself by gaming more, but I have no experience with these methods, so I don't know where to start, and which one would work. I am aware that it is possible to solve the problem manually, but from that I would not learn anything about artificial learning...

答:
It's possible that heuristics exist which improve your success rate, and if they exist, it's possible that you can program something that will find them.

But for a game this small you're almost certainly better off programming a complete search and looking at the solutions that pop up. Then, when you compare what works and what doesn't, your human brain will start to do its thing and pattern-match until you have a better idea of which features of a strategy are relevant to success and which aren't.


问:
What exactly is the meaning of "node" in Document Object Model (DOM)?
I've searched for the definition of a "node" in a programming language and I am still finding it hard to understand.

Could anyone advice me in simple, layman's terms:

What is a node?

答:
The Node object represents a single node in the document tree.

A node can be an element node, an attribute node, a text node, or any other of the node types explained in the Node Types chapter.


答:
In the context of an SGML language where DOM is typically used (i.e. HTML, XML), a node is the smallest piece of text that has semantic meaning. Nodes are arranged in a tree structure, with the document as the root node. Each node can have zero or more children.

There are several types of nodes:

Document: this is the root node of the whole document. It represents the root of the SGML tree, one step above the root element (e.g. the  tag). This is done so it can contain metadata such as the DOCTYPE.

Element: this is a "tag" e.g.
 or <MyXmlElement>. Elements can have subnodes, including attributes and other elements.

Attribute: This is one key/value pair inside an element. For example, the class specifier:

CDATA: "loose" text:
This CDATA is a child of the div element.

Title: What exactly is the meaning of "node" in Document Object Model (DOM)?

Body:
I've searched for the definition of a "node" in a programming language and I am still finding it hard to understand.

Could anyone advice me in simple, layman's terms:

What is a node?

Body:
In the context of an SGML language where DOM is typically used (i.e. HTML, XML), a node is the smallest piece of text that has semantic meaning. Nodes are arranged in a tree structure, with the document as the root node. Each node can have zero or more children.

There are several types of nodes:

Document: this is the root node of the whole document. It represents the root of the SGML tree, one step above the root element (e.g. the <html> tag). This is done so it can contain metadata such as the DOCTYPE.

Element: this is a "tag" e.g. <div> or <MyXmlElement>. Elements can have subnodes, including attributes and other elements.

Attribute: This is one key/value pair inside an element. For example, the class specifier: <div class="SomeCssClass">

CDATA: "loose" text: <div>This CDATA is a child of the div element.</div>


答:
You're confusing global variables for member variables.

Modifying member variables in member functions is fine, when your function is meant to modify the class state. That's kind of why OOP came about in the first place: to logically group state and behavior. If it's getting hard to keep track of whats happening to your member variables, that's not a problem in using them, the problem is your class is too large.

If you are going to be passing variables around non-stop, you might as well not use any OOP features.

Another thing to consider, is that if modifying member variables was considered unwise, then what would be the point of a setter function?

Let's look at an example of a circular buffer, written in C, swiped from Wiki page:

```<code>/* Opaque buffer element type.  This would be defined by the application. */
typedef struct { int value; } ElemType;

/* Circular buffer object */
typedef struct {
    int         size;   /* maximum number of elements           */
    int         start;  /* index of oldest element              */
    int         end;    /* index at which to write new element  */
    ElemType   *elems;  /* vector of elements                   */
} CircularBuffer;

void cbInit(CircularBuffer *cb, int size) {
    cb->size  = size + 1; /* include empty elem */
    cb->start = 0;
    cb->end   = 0;
    cb->elems = calloc(cb->size, sizeof(ElemType));
}

void cbFree(CircularBuffer *cb) {
    free(cb->elems); /* OK if null */
}

int cbIsFull(CircularBuffer *cb) {
    return (cb->end + 1) % cb->size == cb->start;
}

int cbIsEmpty(CircularBuffer *cb) {
    return cb->end == cb->start;
}

/* Write an element, overwriting oldest element if buffer is full. App can
   choose to avoid the overwrite by checking cbIsFull(). */
void cbWrite(CircularBuffer *cb, ElemType *elem) {
    cb->elems[cb->end] = *elem;
    cb->end = (cb->end + 1) % cb->size;
    if (cb->end == cb->start)
        cb->start = (cb->start + 1) % cb->size; /* full, overwrite */
}

/* Read oldest element. App must ensure !cbIsEmpty() first. */
void cbRead(CircularBuffer *cb, ElemType *elem) {
    *elem = cb->elems[cb->start];
    cb->start = (cb->start + 1) % cb->size;
}
</code>```

The C example does pass everything in via arguments, transported around via a struct. This is done because C doesn't offer any built-in OOP features, so that's what you have to do.

If we make that in C++, making everything in the struct a member variable and accessing it 'globally' is entirely appropriate:

```<code>class CircularBuffer
{
  private:
    int         size;   // maximum number of elements
    int         start;  // index of oldest element
    int         end;    // index at which to write new element
    ElemType   *elems;  // vector of elements
  public:
    CircularBuffer(int cbSize) {
      size = cbSize + 1; // include empty elem
      start = 0;
      end = 0;
      elems = new ElemType[size];
    }

    ~CircularBuffer() {
      delete[] elems;
    }

    bool IsFull() {
      return (end+1) % size == start;
    }

    bool IsEmpty() {
      return end == start;
    }

    void Write(ElemType *elem) {
      elems[end] = *elem;
      end = (end + 1) % size;
      if (end == start)
        start = (start + 1) % size; //full, overwrite
    }

    //Read oldest element. App must ensure !IsEmpty() first.
    void Read(ElemType *elem) {
        *elem = elems[start];
        start = (start + 1) % size;
    }
}
</code>```

If you instead had methods that did something like this:

```<code>  void Write(ElemType *elem)
  {
    _Write(ElemType *elem, this->start, this->end, this->size);
  }
</code>```

or worse, had to call the member like so:

```<code>  cb.Write(&elem,cb.start,cb.end,cb.size);
</code>```

there would be much rage.

The point is that the variables start, end, size, and elems are part of the internal state of the class, and so those can be manipulated directly inside the classes methods. The user of the class can only manipulate them through the exposed functions, as part of Information Hiding. If you are just going to pass the variables around to all the member functions, like you're writing C, then you might as well use C properly instead of compiling it with a C++ compiler.

Title: Various methods manipulating same member variable versus each takes inputs and provides output

Body:
As software design paradigm which is better? to let various methods manipulate a member variable, or define each method or function to take some inputs and provide some outputs?

For example

```<code>   class Test {

       void FooMethod1()
       {
           Foo = ...
       }
       void FooMethod2()
       {
           Foo = ...
       }
       void Method3()
       {
           FooMethod1();
           FooMethod2()
       }
    }
</code>```

versus.

```<code>  class Test {

       var FooMethod1(var input)
       {
           input = ...
           return ...
       }
       var FooMethod2(var input)
       {
           input = ...
           return ...
       }
       void Method3()
       {
           var Foo;
           FooMethod1(Foo);
           FooMethod2(Foo)
       }
    }
</code>```

Body:
You're confusing global variables for member variables.

Modifying member variables in member functions is fine, when your function is meant to modify the class state. That's kind of why OOP came about in the first place: to logically group state and behavior. If it's getting hard to keep track of whats happening to your member variables, that's not a problem in using them, the problem is your class is too large.

If you are going to be passing variables around non-stop, you might as well not use any OOP features.

Another thing to consider, is that if modifying member variables was considered unwise, then what would be the point of a setter function?

Let's look at an example of a circular buffer, written in C, swiped from Wiki page:

/* Opaque buffer element type.  This would be defined by the application. */
typedef struct { int value; } ElemType;

/* Circular buffer object */
typedef struct {
    int         size;   /* maximum number of elements           */
    int         start;  /* index of oldest element              */
    int         end;    /* index at which to write new element  */
    ElemType   *elems;  /* vector of elements                   */
} CircularBuffer;

void cbInit(CircularBuffer *cb, int size) {
    cb->size  = size + 1; /* include empty elem */
    cb->start = 0;
    cb->end   = 0;
    cb->elems = calloc(cb->size, sizeof(ElemType));
}

void cbFree(CircularBuffer *cb) {
    free(cb->elems); /* OK if null */
}

int cbIsFull(CircularBuffer *cb) {
    return (cb->end + 1) % cb->size == cb->start;
}

int cbIsEmpty(CircularBuffer *cb) {
    return cb->end == cb->start;
}

/* Write an element, overwriting oldest element if buffer is full. App can
   choose to avoid the overwrite by checking cbIsFull(). */
void cbWrite(CircularBuffer *cb, ElemType *elem) {
    cb->elems[cb->end] = *elem;
    cb->end = (cb->end + 1) % cb->size;
    if (cb->end == cb->start)
        cb->start = (cb->start + 1) % cb->size; /* full, overwrite */
}

/* Read oldest element. App must ensure !cbIsEmpty() first. */
void cbRead(CircularBuffer *cb, ElemType *elem) {
    *elem = cb->elems[cb->start];
    cb->start = (cb->start + 1) % cb->size;
}

The C example does pass everything in via arguments, transported around via a struct. This is done because C doesn't offer any built-in OOP features, so that's what you have to do.

If we make that in C++, making everything in the struct a member variable and accessing it 'globally' is entirely appropriate:

class CircularBuffer
{
  private:
    int         size;   // maximum number of elements
    int         start;  // index of oldest element
    int         end;    // index at which to write new element
    ElemType   *elems;  // vector of elements
  public:
    CircularBuffer(int cbSize) {
      size = cbSize + 1; // include empty elem
      start = 0;
      end = 0;
      elems = new ElemType[size];
    }

    ~CircularBuffer() {
      delete[] elems;
    }

    bool IsFull() {
      return (end+1) % size == start;
    }

    bool IsEmpty() {
      return end == start;
    }

    void Write(ElemType *elem) {
      elems[end] = *elem;
      end = (end + 1) % size;
      if (end == start)
        start = (start + 1) % size; //full, overwrite
    }

    //Read oldest element. App must ensure !IsEmpty() first.
    void Read(ElemType *elem) {
        *elem = elems[start];
        start = (start + 1) % size;
    }
}

If you instead had methods that did something like this:

  void Write(ElemType *elem)
  {
    _Write(ElemType *elem, this->start, this->end, this->size);
  }

or worse, had to call the member like so:

  cb.Write(&elem,cb.start,cb.end,cb.size);

there would be much rage.

The point is that the variables start, end, size, and elems are part of the internal state of the class, and so those can be manipulated directly inside the classes methods. The user of the class can only manipulate them through the exposed functions, as part of Information Hiding. If you are just going to pass the variables around to all the member functions, like you're writing C, then you might as well use C properly instead of compiling it with a C++ compiler.


答:
First case is hugely better. BUT only as long as the containing class is cohesive. Using first option when the class has many different responsibilities will introduce unwanted bindings which make understanding the flow of the behavior of the class worse than in second case.

Also, the first approach will have an advantage, when you have many different variables to work with and when different functions might take different variables. This would mean all functions would need to get all variables, even though only few are used by function itself and rest is just passed into other methods.

There is one example, where the case of member variables is end result of refactoring. It is when you have complex and long method, but refactoring it into individual method calls would introduce tons of method parameters being passed around. In this case, you turn the whole method into a single class and turn the method's variables into a classes's members. Then, you can easily divide the one huge method into smaller ones that are all contained inside the class and that don't have to pass around all the variables, because those are contained within the same class.


问:
Why do we have to tell printf() the type of data in C?
Let's consider this C code:

```<code>#include <stdio.h>

main()
{
  int x=5;
  printf("x is ");
  printf("%d",5);
}
</code>```

In this, when we wrote int x=5; we told the computer that x is an integer. The computer must remember that x is an integer. But when we output the value of x in printf() we have to again tell the computer that x is an integer. Why is that?

Why does the computer forget that x was an integer?

答:
There are two issues at play here:

Issue #1: C is a statically typed language; all type information is determined at compile time.  No type information is stored with any object in memory such that its type and size can be determined at run time1.  If you examine the memory at any particular address while the program is running, all you'll see is a sludge of bytes; there's nothing to tell you whether that particular address actually contains an object, what the type or size of that object is, or how to interpret those bytes (as an integer, or floating point type, or sequence of characters in a string, etc.).  All that information is baked into the machine code when the code is compiled, based on type information specified in the source code; for example, the function definition

```<code>void foo( int x, double y, char *z )
{
  ...
}
</code>```

tells the compiler to generate the appropriate machine code to handle x as an integer, y as a floating-point value, and z as a pointer to char.  Note that any mismatches in the number or type of arguments between a function call and a function definition are only detected when the code is being compiled2; it's only during the compilation phase that any type information is associated with an object.

Issue #2: printf is a variadic function; it takes one fixed parameter of type const char * restrict (the format string), along with zero or more additional parameters, the number and type of which are not known at compile time:

```<code>int printf( const char * restrict fmt, ... );
</code>```

The printf function has no way of knowing what the number and types of additional arguments are from the passed arguments themselves; it has to rely on the format string to tell it how to interpret the sludge of bytes on the stack (or in the registers).  Even better, because it's a variadic function, arguments with certain types are promoted to a limited set of default types (e.g., short is promoted to int, float is promoted to double, etc.).

Again, there's no information associated with the additional arguments themselves to give printf any clues on how to interpret or format them.  Hence the need for the conversion specifiers in the format string.

Note that in addition to telling printf the number and type of additional arguments, conversion specifiers also tell printf how to format the output (field widths, precision, padding, justification, base (decimal, octal, or hex for integer types), etc.).

Edit

To avoid extensive discussion in the comments (and because the chat page is blocked from my work system - yes I'm being a bad boy), I'm going to address the last two questions here.

IF I do this: ```<code>float b;
float c;
b=3.1;
c=(5.0/9.0)*(b);</code>```

In the last statement how does the compiler know that b is of type float?

During translation, the compiler maintains a table (often called a symbol table) that stores information about an object's name, type, storage duration, scope, etc.  You declared b and c as float, so any time the compiler sees an expression with b or c in it, it will generate the machine code to handle a floating-point value.

I took your code above and wrapped a full program around it:

```<code>/**
 * c1.c
 */
#include <stdio.h>
int main( void )
{
  float b;
  float c;
  b = 3.1;
  c = (5.0 / 9.0) * b;

  printf( "c = %f\n", c );
  return 0;
}
</code>```

I used the -g and -Wa,-aldh options with gcc to create a listing of the generated machine code interleaved with the C source code3:

```<code>GAS LISTING /tmp/ccmGgGG2.s                     page 1

   1                            .file   "c1.c"
   9                    .Ltext0:
  10                            .section        .rodata
  11                    .LC2:
  12 0000 63203D20              .string "c = %f\n"
  12      25660A00
  13                            .align 8
  14                    .LC1:
  15 0008 721CC771              .long   1908874354
  16 000c 1CC7E13F              .long   1071761180
  17                            .text
  18                    .globl main
  20                    main:
  21                    .LFB2:
  22                            .file 1 "c1.c"
   1:c1.c          **** #include <stdio.h>
   2:c1.c          **** int main( void )
   3:c1.c          **** {
  23                            .loc 1 3 0
  24 0000 55                    pushq   %rbp
  25                    .LCFI0:
  26 0001 4889E5                movq    %rsp, %rbp
  27                    .LCFI1:
  28 0004 4883EC10              subq    $16, %rsp
  29                    .LCFI2:
   4:c1.c          ****   float b;
   5:c1.c          ****   float c;
   6:c1.c          ****   b = 3.1;
  30                            .loc 1 6 0
  31 0008 B8666646              movl    $0x40466666, %eax
  31      40
  32 000d 8945F8                movl    %eax, -8(%rbp)
   7:c1.c          ****   c = (5.0 / 9.0) * b;
  33                            .loc 1 7 0
  34 0010 F30F5A4D              cvtss2sd        -8(%rbp), %xmm1
  34      F8
  35 0015 F20F1005              movsd   .LC1(%rip), %xmm0
  35      00000000
  36 001d F20F59C1              mulsd   %xmm1, %xmm0
  37 0021 F20F5AC0              cvtsd2ss        %xmm0, %xmm0
  38 0025 F30F1145              movss   %xmm0, -4(%rbp)
  38      FC
   8:c1.c          ****
   9:c1.c          ****   printf( "c = %f\n", c );
  39                            .loc 1 9 0
  40 002a F30F5A45              cvtss2sd        -4(%rbp), %xmm0
  40      FC
  41 002f BF000000              movl    $.LC2, %edi
  41      00
  42 0034 B8010000              movl    $1, %eax
  42      00
  43 0039 E8000000              call    printf
  43      00
  10:c1.c          ****   return 0;
  44                            .loc 1 10 0
  45 003e B8000000              movl    $0, %eax

GAS LISTING /tmp/ccmGgGG2.s                     page 2

  11:c1.c          **** }
  46                            .loc 1 11 0
  47 0043 C9                    leave
  48 0044 C3                    ret
</code>```

Here's how to read the assembly listing:

```<code>  40 002a F30F5A45              cvtss2sd        -4(%rbp), %xmm0
  40      FC
  ^  ^    ^                     ^               ^
  |  |    |                     |               |
  |  |    |                     |               +-- Instruction operands
  |  |    |                     +------------------ Instruction mnemonic
  |  |    +---------------------------------------- Actual machine code (instruction and operands)
  |  +--------------------------------------------- Byte offset of instruction from subroutine entry point
  +------------------------------------------------ Line number of assembly listing
</code>```

One thing to note here.  In the generated assembly code, there are no symbols for b or c; they only exist in the source code listing.  When main executes at runtime, space for b and c (along with some other stuff) is allocated from the stack by adjusting the stack pointer:

```<code>subq    $16, %rsp
</code>```

The code refers to those objects by their offset from the frame pointer4, with b being -8 bytes from the address stored in the frame pointer and c being -4 bytes from it, as follows:

```<code>   7:c1.c          ****   c = (5.0 / 9.0) * b;
  .loc 1 7 0
  cvtss2sd        -8(%rbp), %xmm1  ;; converts contents of b from single- to double-
                                   ;; precision float, stores result to floating-
                                   ;; point register xmm1
  movsd   .LC1(%rip), %xmm0        ;; writes the pre-computed value of 5.0/9.0
                                   ;; to floating point register xmm0
  mulsd   %xmm1, %xmm0             ;; multiply contents of xmm1 by xmm0, store result
                                   ;; in xmm0
  cvtsd2ss        %xmm0, %xmm0     ;; convert result in xmm0 from double- to single-
                                   ;; precision float
  movss   %xmm0, -4(%rbp)          ;; save result to c
</code>```

Since you declared b and c as floats, the compiler generated machine code to specifically handle floating-point values; the movsd, mulsd, cvtss2sd instructions are all specific to floating-point operations, and the registers %xmm0 and %xmm1 are used to store double-precision floating point values.

If I change the source code so that b and c are integers instead of floats, the compiler generates different machine code:

```<code>/**
 * c2.c
 */
#include <stdio.h>
int main( void )
{
  int b;
  int c;
  b = 3;
  c = (9 / 4) * b; // changed these values since integer 5/9 == 0, making for
                   // some really boring machine code.

  printf( "c = %d\n", c );
  return 0;
}
</code>```

Compiling with gcc -o c2 -g -std=c99 -pedantic -Wall -Werror -Wa,-aldh=c2.lst c2.c gives:

```<code>GAS LISTING /tmp/ccyxHwid.s                     page 1

   1                            .file   "c2.c"
   9                    .Ltext0:
  10                            .section        .rodata
  11                    .LC0:
  12 0000 63203D20              .string "c = %d\n"
  12      25640A00
  13                            .text
  14                    .globl main
  16                    main:
  17                    .LFB2:
  18                            .file 1 "c2.c"
   1:c2.c          **** #include <stdio.h>
   2:c2.c          **** int main( void )
   3:c2.c          **** {
  19                            .loc 1 3 0
  20 0000 55                    pushq   %rbp
  21                    .LCFI0:
  22 0001 4889E5                movq    %rsp, %rbp
  23                    .LCFI1:
  24 0004 4883EC10              subq    $16, %rsp
  25                    .LCFI2:
   4:c2.c          ****   int b;
   5:c2.c          ****   int c;
   6:c2.c          ****   b = 3;
  26                            .loc 1 6 0
  27 0008 C745F803              movl    $3, -8(%rbp)
  27      000000
   7:c2.c          ****   c = (9 / 4) * b;
  28                            .loc 1 7 0
  29 000f 8B45F8                movl    -8(%rbp), %eax
  30 0012 01C0                  addl    %eax, %eax
  31 0014 8945FC                movl    %eax, -4(%rbp)
   8:c2.c          ****
   9:c2.c          ****   printf( "c = %d\n", c );
  32                            .loc 1 9 0
  33 0017 8B75FC                movl    -4(%rbp), %esi
  34 001a BF000000              movl    $.LC0, %edi
  34      00
  35 001f B8000000              movl    $0, %eax
  35      00
  36 0024 E8000000              call    printf
  36      00
  10:c2.c          ****   return 0;
  37                            .loc 1 10 0
  38 0029 B8000000              movl    $0, %eax
  38      00
  11:c2.c          **** }
  39                            .loc 1 11 0
  40 002e C9                    leave
  41 002f C3                    ret
</code>```

Here's the same operation, but with b and c declared as integers:

```<code>   7:c2.c          ****   c = (9 / 4) * b;
  .loc 1 7 0
  movl    -8(%rbp), %eax  ;; copy value of b to register eax
  addl    %eax, %eax      ;; since 9/4 == 2 (integer arithmetic), double the
                          ;; value in eax
  movl    %eax, -4(%rbp)  ;; write result to c
</code>```

This is what I meant earlier when I said that type information was "baked in" to the machine code.  When the program runs, it doesn't examine b or c to determine their type; it already knows what their type should be based on the generated machine code.

If the compiler determines the type and size at run time then why doesn't the following program works:
```<code>float b='H';
printf(" value of b is %c \n",b);
</code>```

It doesn't work because you're lying to the compiler. You tell it that b is a float, so it will generate machine code to handle floating-point values. When you initialize it, the bit pattern corresponding to the constant 'H' will be interpreted as a floating-point value, not a character value.

You lie to the compiler again when you use the %c conversion specifier, which expects a value of type char, for the argument b. Because of this, printf won't interpret the contents of b correctly, and you'll wind up with garbage output5.  Again, printf can't know the number or types of any additional arguments based on the arguments themselves; all it sees is an address on the stack (or a bunch of registers).  It needs the format string to tell it what additional arguments have been passed, and what their types are.

1.  The one exception being variable-length arrays; since their size isn't established until runtime, there's no way to evaluate sizeof on a VLA at compile time.

2.  As of C89, anyway. Prior to that, the compiler could only catch mismatches in the function return type; it couldn't detect mismatches in the function parameter lists.

3.  This code is generated on a 64-bit SuSE Linux Enterprise 10 system using gcc 4.1.2. If you're on a different implementation (compiler/OS/chip architecture), then the exact machine instructions will be different, but the general point will still hold; the compiler will generate different instructions to handle floats vs. ints vs. strings, etc.

4.  When you call a function in a running program, a stack frame is created to store the function arguments, local variables, and the address of the instruction following the function call.  A special register called the frame pointer is used to keep track of the current frame.

5.  For example, assume a big-endian system where the high-order byte is the addressed byte.  The bit pattern for H will be stored to b as 0x00000048.  However, because the %c conversion specifier indicates that the argument should be a char, only the first byte will be read, so printf will try to write the character corresponding to the encoding 0x00.

Body:
There are two issues at play here:

Issue #1: C is a statically typed language; all type information is determined at compile time.  No type information is stored with any object in memory such that its type and size can be determined at run time1.  If you examine the memory at any particular address while the program is running, all you'll see is a sludge of bytes; there's nothing to tell you whether that particular address actually contains an object, what the type or size of that object is, or how to interpret those bytes (as an integer, or floating point type, or sequence of characters in a string, etc.).  All that information is baked into the machine code when the code is compiled, based on type information specified in the source code; for example, the function definition

void foo( int x, double y, char *z )
{
  ...
}

tells the compiler to generate the appropriate machine code to handle x as an integer, y as a floating-point value, and z as a pointer to char.  Note that any mismatches in the number or type of arguments between a function call and a function definition are only detected when the code is being compiled2; it's only during the compilation phase that any type information is associated with an object.

Issue #2: printf is a variadic function; it takes one fixed parameter of type const char * restrict (the format string), along with zero or more additional parameters, the number and type of which are not known at compile time:

int printf( const char * restrict fmt, ... );

The printf function has no way of knowing what the number and types of additional arguments are from the passed arguments themselves; it has to rely on the format string to tell it how to interpret the sludge of bytes on the stack (or in the registers).  Even better, because it's a variadic function, arguments with certain types are promoted to a limited set of default types (e.g., short is promoted to int, float is promoted to double, etc.).

Again, there's no information associated with the additional arguments themselves to give printf any clues on how to interpret or format them.  Hence the need for the conversion specifiers in the format string.

Note that in addition to telling printf the number and type of additional arguments, conversion specifiers also tell printf how to format the output (field widths, precision, padding, justification, base (decimal, octal, or hex for integer types), etc.).

Edit

To avoid extensive discussion in the comments (and because the chat page is blocked from my work system - yes I'm being a bad boy), I'm going to address the last two questions here.

IF I do this:
float b;
float c;
b=3.1;
c=(5.0/9.0)*(b);

In the last statement how does the compiler know that b is of type float?

During translation, the compiler maintains a table (often called a symbol table) that stores information about an object's name, type, storage duration, scope, etc.  You declared b and c as float, so any time the compiler sees an expression with b or c in it, it will generate the machine code to handle a floating-point value.

I took your code above and wrapped a full program around it:

/**
 * c1.c
 */
#include <stdio.h>
int main( void )
{
  float b;
  float c;
  b = 3.1;
  c = (5.0 / 9.0) * b;

  printf( "c = %f\n", c );
  return 0;
}

I used the -g and -Wa,-aldh options with gcc to create a listing of the generated machine code interleaved with the C source code3:

GAS LISTING /tmp/ccmGgGG2.s                     page 1

   1                            .file   "c1.c"
   9                    .Ltext0:
  10                            .section        .rodata
  11                    .LC2:
  12 0000 63203D20              .string "c = %f\n"
  12      25660A00
  13                            .align 8
  14                    .LC1:
  15 0008 721CC771              .long   1908874354
  16 000c 1CC7E13F              .long   1071761180
  17                            .text
  18                    .globl main
  20                    main:
  21                    .LFB2:
  22                            .file 1 "c1.c"
   1:c1.c          **** #include <stdio.h>
   2:c1.c          **** int main( void )
   3:c1.c          **** {
  23                            .loc 1 3 0
  24 0000 55                    pushq   %rbp
  25                    .LCFI0:
  26 0001 4889E5                movq    %rsp, %rbp
  27                    .LCFI1:
  28 0004 4883EC10              subq    $16, %rsp
  29                    .LCFI2:
   4:c1.c          ****   float b;
   5:c1.c          ****   float c;
   6:c1.c          ****   b = 3.1;
  30                            .loc 1 6 0
  31 0008 B8666646              movl    $0x40466666, %eax
  31      40
  32 000d 8945F8                movl    %eax, -8(%rbp)
   7:c1.c          ****   c = (5.0 / 9.0) * b;
  33                            .loc 1 7 0
  34 0010 F30F5A4D              cvtss2sd        -8(%rbp), %xmm1
  34      F8
  35 0015 F20F1005              movsd   .LC1(%rip), %xmm0
  35      00000000
  36 001d F20F59C1              mulsd   %xmm1, %xmm0
  37 0021 F20F5AC0              cvtsd2ss        %xmm0, %xmm0
  38 0025 F30F1145              movss   %xmm0, -4(%rbp)
  38      FC
   8:c1.c          ****
   9:c1.c          ****   printf( "c = %f\n", c );
  39                            .loc 1 9 0
  40 002a F30F5A45              cvtss2sd        -4(%rbp), %xmm0
  40      FC
  41 002f BF000000              movl    $.LC2, %edi
  41      00
  42 0034 B8010000              movl    $1, %eax
  42      00
  43 0039 E8000000              call    printf
  43      00
  10:c1.c          ****   return 0;
  44                            .loc 1 10 0
  45 003e B8000000              movl    $0, %eax

GAS LISTING /tmp/ccmGgGG2.s                     page 2

  11:c1.c          **** }
  46                            .loc 1 11 0
  47 0043 C9                    leave
  48 0044 C3                    ret

Here's how to read the assembly listing:

  40 002a F30F5A45              cvtss2sd        -4(%rbp), %xmm0
  40      FC
  ^  ^    ^                     ^               ^
  |  |    |                     |               |
  |  |    |                     |               +-- Instruction operands
  |  |    |                     +------------------ Instruction mnemonic
  |  |    +---------------------------------------- Actual machine code (instruction and operands)
  |  +--------------------------------------------- Byte offset of instruction from subroutine entry point
  +------------------------------------------------ Line number of assembly listing

One thing to note here.  In the generated assembly code, there are no symbols for b or c; they only exist in the source code listing.  When main executes at runtime, space for b and c (along with some other stuff) is allocated from the stack by adjusting the stack pointer:

subq    $16, %rsp

The code refers to those objects by their offset from the frame pointer4, with b being -8 bytes from the address stored in the frame pointer and c being -4 bytes from it, as follows:

   7:c1.c          ****   c = (5.0 / 9.0) * b;
  .loc 1 7 0
  cvtss2sd        -8(%rbp), %xmm1  ;; converts contents of b from single- to double-
                                   ;; precision float, stores result to floating-
                                   ;; point register xmm1
  movsd   .LC1(%rip), %xmm0        ;; writes the pre-computed value of 5.0/9.0
                                   ;; to floating point register xmm0
  mulsd   %xmm1, %xmm0             ;; multiply contents of xmm1 by xmm0, store result
                                   ;; in xmm0
  cvtsd2ss        %xmm0, %xmm0     ;; convert result in xmm0 from double- to single-
                                   ;; precision float
  movss   %xmm0, -4(%rbp)          ;; save result to c

Since you declared b and c as floats, the compiler generated machine code to specifically handle floating-point values; the movsd, mulsd, cvtss2sd instructions are all specific to floating-point operations, and the registers %xmm0 and %xmm1 are used to store double-precision floating point values.

If I change the source code so that b and c are integers instead of floats, the compiler generates different machine code:

/**
 * c2.c
 */
#include <stdio.h>
int main( void )
{
  int b;
  int c;
  b = 3;
  c = (9 / 4) * b; // changed these values since integer 5/9 == 0, making for
                   // some really boring machine code.

  printf( "c = %d\n", c );
  return 0;
}

Compiling with gcc -o c2 -g -std=c99 -pedantic -Wall -Werror -Wa,-aldh=c2.lst c2.c gives:

GAS LISTING /tmp/ccyxHwid.s                     page 1

   1                            .file   "c2.c"
   9                    .Ltext0:
  10                            .section        .rodata
  11                    .LC0:
  12 0000 63203D20              .string "c = %d\n"
  12      25640A00
  13                            .text
  14                    .globl main
  16                    main:
  17                    .LFB2:
  18                            .file 1 "c2.c"
   1:c2.c          **** #include <stdio.h>
   2:c2.c          **** int main( void )
   3:c2.c          **** {
  19                            .loc 1 3 0
  20 0000 55                    pushq   %rbp
  21                    .LCFI0:
  22 0001 4889E5                movq    %rsp, %rbp
  23                    .LCFI1:
  24 0004 4883EC10              subq    $16, %rsp
  25                    .LCFI2:
   4:c2.c          ****   int b;
   5:c2.c          ****   int c;
   6:c2.c          ****   b = 3;
  26                            .loc 1 6 0
  27 0008 C745F803              movl    $3, -8(%rbp)
  27      000000
   7:c2.c          ****   c = (9 / 4) * b;
  28                            .loc 1 7 0
  29 000f 8B45F8                movl    -8(%rbp), %eax
  30 0012 01C0                  addl    %eax, %eax
  31 0014 8945FC                movl    %eax, -4(%rbp)
   8:c2.c          ****
   9:c2.c          ****   printf( "c = %d\n", c );
  32                            .loc 1 9 0
  33 0017 8B75FC                movl    -4(%rbp), %esi
  34 001a BF000000              movl    $.LC0, %edi
  34      00
  35 001f B8000000              movl    $0, %eax
  35      00
  36 0024 E8000000              call    printf
  36      00
  10:c2.c          ****   return 0;
  37                            .loc 1 10 0
  38 0029 B8000000              movl    $0, %eax
  38      00
  11:c2.c          **** }
  39                            .loc 1 11 0
  40 002e C9                    leave
  41 002f C3                    ret

Here's the same operation, but with b and c declared as integers:

   7:c2.c          ****   c = (9 / 4) * b;
  .loc 1 7 0
  movl    -8(%rbp), %eax  ;; copy value of b to register eax
  addl    %eax, %eax      ;; since 9/4 == 2 (integer arithmetic), double the
                          ;; value in eax
  movl    %eax, -4(%rbp)  ;; write result to c

This is what I meant earlier when I said that type information was "baked in" to the machine code.  When the program runs, it doesn't examine b or c to determine their type; it already knows what their type should be based on the generated machine code.

If the compiler determines the type and size at run time then why doesn't the following program works:

float b='H';
printf(" value of b is %c \n",b);

It doesn't work because you're lying to the compiler. You tell it that b is a float, so it will generate machine code to handle floating-point values. When you initialize it, the bit pattern corresponding to the constant 'H' will be interpreted as a floating-point value, not a character value.

You lie to the compiler again when you use the %c conversion specifier, which expects a value of type char, for the argument b. Because of this, printf won't interpret the contents of b correctly, and you'll wind up with garbage output5.  Again, printf can't know the number or types of any additional arguments based on the arguments themselves; all it sees is an address on the stack (or a bunch of registers).  It needs the format string to tell it what additional arguments have been passed, and what their types are.

1.  The one exception being variable-length arrays; since their size isn't established until runtime, there's no way to evaluate sizeof on a VLA at compile time.

2.  As of C89, anyway. Prior to that, the compiler could only catch mismatches in the function return type; it couldn't detect mismatches in the function parameter lists.

3.  This code is generated on a 64-bit SuSE Linux Enterprise 10 system using gcc 4.1.2. If you're on a different implementation (compiler/OS/chip architecture), then the exact machine instructions will be different, but the general point will still hold; the compiler will generate different instructions to handle floats vs. ints vs. strings, etc.

4.  When you call a function in a running program, a stack frame is created to store the function arguments, local variables, and the address of the instruction following the function call.  A special register called the frame pointer is used to keep track of the current frame.

5.  For example, assume a big-endian system where the high-order byte is the addressed byte.  The bit pattern for H will be stored to b as 0x00000048.  However, because the %c conversion specifier indicates that the argument should be a char, only the first byte will be read, so printf will try to write the character corresponding to the encoding 0x00.


答:
It is generally a bad idea to use unsigned types because they overflow in unpleasant ways.x = 5-6 is suddenly a timebomb in your code. Meanwhile the benefits of unsigned types boil down to a single extra bit of precision, and if that bit is worth it for you, you should almost certainly be using a bigger type instead.

There are use cases where a smaller type could make sense but unless you're concerned about memory usage or need to pack data for transmission or cache efficiency or a handful of other concerns it's usually the case that there is no benefit to using a smaller type. Moreover, on many architectures, it's actually slower to use these types so they can actually impose a small cost.


问:
Changing method signature while keeping backwards compatibility
I've inherited an API to maintain.

Users can pass a callback function to the class which gets called on some event. The callback function is currently passed in a single argument.

I need to change the expected signature of the callback function to accept additional arguments.

This would be fine if everyones' callback function took in *args and **kwargs, but unfortunately they don't and it's too much work to get everyone to change them.

What is the cleanest way for me to make the change in the API while keeping the callback backwards compatible?

I have this as a shoe-in but it's not very future proof, nor is it very elegant:

```<code>...
if self._callback.func_code.co_argcount > 1:
    self._callback( data, additional_arg )
else:
    self._callback( data )
...
</code>```

答:
An explicit check of the callback's ability to handle parameters is about the best you're going to be able to do. Python may be loosie-goosie in its duck typing, but it will complain and raise a TypeError exception if you feed a function the wrong number of parameters. No ifs, ands, or buts about that.

You have existing functions in the field that you don't feel you can change--and probably for good reason. So having an inspection that asks, "what can this callback function accept?" or "what does this callback function expect?"--it may be inelegant, but that's what's available to you.

The other choices involve:

Having some form of object-relative state (such as an additional instance value or method) or even global state (whether a true global variable, a class variable, a singleton reporting object, or whathaveyou) which callbacks can reference to get the extended information you're now offering them. This is how C, Unix, and many other codebases handle exceptional and additional information. It is, unfortunately, not especially elegant--and it can be quite problematic/unworkable for multithreaded apps.

On the off chance that your data parameter is an extensible type, you might be able to add fields to it. If it's a dict or similar structure you're golden, as long as the callbacks play by duck typing rules and don't strictly check that they got only the fields back they expected. This is a trick that often works in dynamic languages, even though it would fall flat on its face in statically typed languages/data passing environments. But, you have to get lucky to have this work. If data is a more static type, you're back to choice 1 or your inspection-based approach ("choice 0").

Update

As an aside, your code will run fine in Python 2. But Python 3 changes the place the code is stored. To encompass both your current Python 2 and future moves to Python 3, here's a shim that works in both:

```<code>import sys
_PY2 = sys.version_info[0] == 2

def arg_count(f):
    code = f.func_code if _PY2 else f.__code__
    return code.co_argcount
</code>```

Then:

```<code>if arg_count(self._callback) > 1:
    ....
</code>```

Body:
An explicit check of the callback's ability to handle parameters is about the best you're going to be able to do. Python may be loosie-goosie in its duck typing, but it will complain and raise a TypeError exception if you feed a function the wrong number of parameters. No ifs, ands, or buts about that.

You have existing functions in the field that you don't feel you can change--and probably for good reason. So having an inspection that asks, "what can this callback function accept?" or "what does this callback function expect?"--it may be inelegant, but that's what's available to you.

The other choices involve:

Having some form of object-relative state (such as an additional instance value or method) or even global state (whether a true global variable, a class variable, a singleton reporting object, or whathaveyou) which callbacks can reference to get the extended information you're now offering them. This is how C, Unix, and many other codebases handle exceptional and additional information. It is, unfortunately, not especially elegant--and it can be quite problematic/unworkable for multithreaded apps.

On the off chance that your data parameter is an extensible type, you might be able to add fields to it. If it's a dict or similar structure you're golden, as long as the callbacks play by duck typing rules and don't strictly check that they got only the fields back they expected. This is a trick that often works in dynamic languages, even though it would fall flat on its face in statically typed languages/data passing environments. But, you have to get lucky to have this work. If data is a more static type, you're back to choice 1 or your inspection-based approach ("choice 0").

Update

As an aside, your code will run fine in Python 2. But Python 3 changes the place the code is stored. To encompass both your current Python 2 and future moves to Python 3, here's a shim that works in both:

import sys
_PY2 = sys.version_info[0] == 2

def arg_count(f):
    code = f.func_code if _PY2 else f.__code__
    return code.co_argcount

Then:

if arg_count(self._callback) > 1:
    ....


问:
Member variables vs. State Varaibels? Are they the same?
I am learning that member variables are to hold the state of an object? Is it their recommended usage? Are all member variables state variables too? or state variables have specific definition and  are defined according to a class? In general what is the definition of an state variable?

In fact, I look for the best usage of member variables and how to avoid declaring unnecessary variables and using alternative approaches for example passing parameters to the methods of a class. As I think too many state variables may bring complexity to the state of class.

答:
A member variable is any variable that is scoped to the class.  That means that any code within the class can access the variable. How the variable is used or how it is accessed doesn't matter, with respect to it's member status.  Member variables and class/object state are the same thing.

Example:

```<code>public class MyClass
{
   // Not a member variable; never changes.
   private const pi = 3.14159;

   // class state; member variable, but shared with all object instances.
   private static object locker;

   // member variable.
   private List<double> list;

   // member variable.
   private int counter;

   // member variable, but properties are preferred.
   public bool IsSingleton;

   // not a member variable; part of the class's external API.
   public int Counter
   {
       get { return counter; }
   }

   public double CalculateAverage
   {
       // not a member variable; scoped to method.
       double sum;

       for (int i=0; i< list.Length; i++)
       {
           sum += list[i];
       }
       return sum / list.Length;
   }
}
</code>```

Body:
A member variable is any variable that is scoped to the class.  That means that any code within the class can access the variable. How the variable is used or how it is accessed doesn't matter, with respect to it's member status.  Member variables and class/object state are the same thing.

Example:

public class MyClass
{
   // Not a member variable; never changes.
   private const pi = 3.14159;

   // class state; member variable, but shared with all object instances.
   private static object locker;

   // member variable.
   private List<double> list;

   // member variable.
   private int counter;

   // member variable, but properties are preferred.
   public bool IsSingleton;

   // not a member variable; part of the class's external API.
   public int Counter
   {
       get { return counter; }
   }

   public double CalculateAverage
   {
       // not a member variable; scoped to method.
       double sum;

       for (int i=0; i< list.Length; i++)
       {
           sum += list[i];
       }
       return sum / list.Length;
   }
}


答:
You can safely compare it to a map of a subway system, e.g. the London Underground:

(http://it.wikipedia.org/wiki/Mappa_della_metropolitana_di_Londra)

A node is a stop, an edge is the connection between stations. That's about it with general graphs. However, there are special graphs with more, interesting properties, like Trees:

(https://hbfs.wordpress.com/2013/05/14/average-node-depth-in-a-full-tree/)

Nodes in a tree are either (a) the root (think ) or (b) have exactly one parent. They may also have one or many children nodes, which have them as a parent, so we get exactly one path to the root for every node in the graph.

The DOM is a tree.

Body:
You can safely compare it to a map of a subway system, e.g. the London Underground:

(http://it.wikipedia.org/wiki/Mappa_della_metropolitana_di_Londra)

A node is a stop, an edge is the connection between stations. That's about it with general graphs. However, there are special graphs with more, interesting properties, like Trees:

(https://hbfs.wordpress.com/2013/05/14/average-node-depth-in-a-full-tree/)

Nodes in a tree are either (a) the root (think <html>) or (b) have exactly one parent. They may also have one or many children nodes, which have them as a parent, so we get exactly one path to the root for every node in the graph.

The DOM is a tree.


答:
One use of "declaring variables as members" is for attributes. Them being things that describe the thing you are modeling that, maybe, some external consumer would want to ask. For example the name and age of a person are examples of attributes. These atributes are usually modified using a setter method and read using a getter method.

Attributes are part of the "state" of an object. But other variables besides the attributes are part of the state also.

The second possible use is for those kinds of variables. Such variables contain information that are usually read from and written to by several of the class method.

Examples:

an internal counter ( not the counters in for loops )

an open database connection

a list of processed items

a flag indicating the object is in certain state (waiting, closed, open, available, etc.)

These variables are candidates to be member variables even when no one outside the class need to know them.

What you say about just passing everything as parameters to the methods indicates that such methods are not cohesive to the class and that they should be static.

Maybe you are not modelling real world concepts in a OO way and you are just using classes as applications, i.e, the application is the class, and that's why you don't find it natural to declare member variables.

One additional tip is that if you find you are constantly passing the same parameter between several methods, chances are that method should be a member.

Recomendation:

Use classes to model real life entities, like BankAccount, Player, Chessman, etc. Don't make a giant class with a giant main method and a lot of helper functions.

Title: Member variables vs. State Varaibels? Are they the same?

Body:
I am learning that member variables are to hold the state of an object? Is it their recommended usage? Are all member variables state variables too? or state variables have specific definition and  are defined according to a class? In general what is the definition of an state variable?

In fact, I look for the best usage of member variables and how to avoid declaring unnecessary variables and using alternative approaches for example passing parameters to the methods of a class. As I think too many state variables may bring complexity to the state of class.


答:
It's really hard to give good advice on such a broad topic. The honest answer is: it depends on what you want to accomplish.

1) Member variables could represent state of an object. This might or might not be, what you intended to do. If your object lives in a web- / concurrency-context, then that is most of the time not, what you want. In these contexts, most of the time you want statelessness / immutability. If an object is shared and reads and writes are permitted, there is trouble. Of course there are ways to avoid such problems (e.g. locks etc.) but it is not a good idea to have mutable objects.

2) Another usecase for member variables is to hold dependencies for the object: e.g. dependencies to repositories, services, etc. These are most of the time injected once; sometimes via constructor-injection or via setter-injection. It would make no sense to avoid using membervariables for these dependencies; on the other hand you would have to inject needed dependencies with each function call. This pollutes the method signature unnecessary and makes using your api complicated.

3) And there is the space in between. If an object is not shared and the membervariable does not represent a dependency you are free to do, what you like. It is wrong to think of them as global variables since they are not global - they are limited to the object. And one pillar of object oriented design is encapsulation or information hiding. It's like dancing naked in your living room: as long as nobody sees it - who cares?


答:
Your problem is no programming problem, it's a configuration problem.

1) Configure your database (server) according to your needs, e.g. see MySql documentation. You could use two different users for one database, you want to access with two different datasources. Then configure quota in the DB and in your application; say 200 Connections each user. So there should be no problem of running out of connections.

The same goes for the third connection pool.

2) Change your Connection Pool to something different Tomcat (There are reasons for why you want to change on the page or read this) or C3PO.

Is holding the connection pools in a HashMap where the connection string is used as the key a bad idea?

I see no reason for that. You define 3 independend Datasources. Done. What is the usecase for the hashmap?

3) Think of using a framework which does the dirty work for you: e.g. Spring Data JPA. See further Spring JDBC for the lowlevel work JdbcTemplate leaves near to no wishes open. There is no need to get your hands dirty. Without a framework there is too much boilerplate to write and the work is error prone.

Title: Managing multiple JDBC connection

Body:
I have an application that connects to databases based on a json string that contains connection information. The json is sent just when the application starts.

How do you manage such connection pools? Because I can get multiple configurations that point to the same database with the same user. I know I cannot create new connection every time since it's an expensive operation so I use connection pools (Apache DBCP2).

But when two pools connect to the same database I sometimes get "too many connections" error since the pool size of two pools is greater than the max allowed connections.

Is holding the connection pools in a HashMap where the connection string is used as the key a bad idea?

Config looks like this (very simplified json):

{
   dbconfig: [
      { database 1 ... },
      { database 2 ... },
      { database 3 ... }
   ],
   otherconfig: { ... }
}
```

The database 1 and 2 config point to the same database, or the same server but a different database

So my application spawns three threads that receive data on a predefined port. I don't know what database connections I will get and how many worker threads will I spawn. And my question is if there is some kind of pooling framework at which I can throw the configs and it will take care of the sharing of connections and I can just request the connection from it.

Currently with my design I would create 3 pools from which 2 pools are accessing the same server and sometimes the same database and that's why I get the "too many connections".


答:
It seems that tests basically express the same thing as the code, and
  hence is a duplicate (in concept, not implementation) of the code.

This is not true, tests describe the use cases, while the code describes an algorithm which pass the use cases, so which is more general. By TDD you begin with writing use cases (probably based on the user story) and after that you implement the code necessary to pass these use cases. So you write a small test, a small chunk of code, and after that you refactor if necessary to get rid of the repetitions. That's how it works.

By tests there can be repetitions as well. For example you can reuse fixtures, fixture generating code, complicated assertions, etc... I usually do this, to prevent bugs in the tests, but I usually forget to test first whether a test really fails, and it can really ruin the day, when you are looking for the bug in the code for half an hour and the test is wrong... xD

Title: Testing vs Don't Repeat Yourself (DRY)

Body:
Why is repeating yourself by writing tests so highly encouraged?

It seems that tests basically express the same thing as the code, and hence is a duplicate (in concept, not implementation) of the code. Wouldn't the ultimate target of DRY include elimination of all test code?


答:
In C, in contexts not involving integer promotion, unsigned values were specified to behave as members of a "wrapping" abstract algebraic ring (so for any X and Y, X-Y will yield a unique value which, when added to Y, will yield X), while signed integer types were specified as behaving like integers when computations stayed within a certain range, and allowed to do anything at all when computations went beyond that.  Numerical semantics in C#, however, are totally different.  When within a checked numerical context, both signed and unsigned types behave like integers provided computations stay in range, and throw OverflowException when they don't; in an unchecked context, they both behave like algebraic rings.

The only time it's generally worthwhile to use any data type smaller than Int32 is when it's necessary to packing or unpacking things for compact storage or transport.  If one needs to store half a billion positive numbers, and they'll all be in the range 0 to 100, using one byte each rather than four will save 1.5 gigabytes of storage.  That's a big savings.  If a piece of code needs to store a total of a couple hundred values, however, making each of them one byte rather than four would save about 600 bytes.  Probably not worth bothering with.

With regard to unsigned types, the only times they're really useful are when performing information interchange, or when subdividing numbers into pieces.  If, for example, one needs to do math on 96-bit integers, it will likely be much easier to perform the computations on groups of three unsigned 32 bit integers, than on groups of signed integers.  Otherwise, there aren't a whole lot of situations where the range of a signed 32- or 64-bit value would be inadequate, but the same size of unsigned value would suffice.


问:
Which design pattern restricts limits class creation to certain classes
I have a fairly simple application that is divided into two classes. The first class is the Manager class and the second class is the employee class. These are simple classes and do not inherit from any other class. Now what I want is to keep others from instantiating the employee class.The Manager class has an instantiated pointer to the employee class and controls all the methods of the employee class from there.My first idea is to keep the constructor of the employee as private and putting the manager as its friend. Such as this:

```<code>class employee
{
 friend class manager;
 private:
  employee()
  {
  }
}

class manager
{
  private:
  boost::shared_ptr<employee> emp;
  public:
  bar()
  {
    emp = boost::shared_ptr<employee>(new employee());
    //Now manager uses this pointer to control employee
  }
}
</code>```

This is something i came up with but wanted to know if there was a design pattern or a better approach to accomplish this . My objective is to prevent others from creating or using the employee class the only drawback i see to this is exposing the private variables of employee class to the manager class

答: I guess the way you have solved the problem of having a private Constructor might just serve your need. I don't see any creational design pattern fit this requirement, but you should be fine without one here. </p>


答: Etymologically, a "node" is a "knot": think of a fisherman's net as "holes tied together with string", and then nodes are where the string is knotted. The term comes from graph theory in mathematics. If you think of a graph as a collection of points connected to each other by lines ("arcs"), then the points are called nodes. A tree is a special case of a graph in which a node can only have one "upwards" arc (to its "parent"). The DOM models a document as a tree: documents have a hierarchic structure in which sections contains sections contain sections, and a tree is a graph-theoretic representation of a hierarchy. So the parts of a document - the sections - are represented by nodes in the tree.</p>