答:
Let us keep this discussion to the C language only.

The program you are referring to is written in a high level language like C. The computer understand machine language only.
Higher level languages gives the programmer the ability to express logic in a more human friendly way which is then translated into machine code which the microprocessor can decode and execute.
Now let us discuss the code you mentioned:

```<code>char a = 'A';
int x = 4;
</code>```

Let us try to analyse each part:

char/int are known as data types. These tell the compiler to allocate memory. In the case of char it will be 1 byte and int 2 bytes. ( Please
  note this memory size is again depend upon microprocessor ).

a/x are known as identifiers. Now these are you can say "user friendly" names given to memory locations in RAM.

= tells the compiler to store 'A' at the memory location of a and 4 at memory location x.

So int/char data type identifiers are only used by the compiler and not by the microprocessor during program execution. Hence they are not stored in memory.

Body:
Let us keep this discussion to the C language only.

The program you are referring to is written in a high level language like C. The computer understand machine language only.
Higher level languages gives the programmer the ability to express logic in a more human friendly way which is then translated into machine code which the microprocessor can decode and execute.
Now let us discuss the code you mentioned:

char a = 'A';
int x = 4;

Let us try to analyse each part:

char/int are known as data types. These tell the compiler to allocate memory. In the case of char it will be 1 byte and int 2 bytes. ( Please
  note this memory size is again depend upon microprocessor ).

a/x are known as identifiers. Now these are you can say "user friendly" names given to memory locations in RAM.

= tells the compiler to store 'A' at the memory location of a and 4 at memory location x.

So int/char data type identifiers are only used by the compiler and not by the microprocessor during program execution. Hence they are not stored in memory.


问:
How to handle custom logic for multiple customers
We got a project where we have to process certain requests which the customer sends. The request is either in a generic format or in a customer format (all xml) which is then converted to the generic version.

Then some objects are created which are stored in the clients database to be read at a later moment.

Then the moment comes we have to read this information and do stuff with it. 100% of this will be done in a generic handler class, but each customer will have parts that it would like to have differently handled.
This can be about any of the fields we process.

Me and my colleague were arguing about the best way to implement this without getting 100+ classes that inherit from the generic version and override those methods that process a certain field the customer wants different. Soon the discussion drifted off to the use of reflection (we program in C#) and dirty configuration files.

I tried searching Google and this site, but couldn't find anything closely related, perhaps I don't know the terms to search for. I already tried these links, but do not cover my case or are actually about something else.

A bit more information about the process:

The custom parts involve certain codes that only that customer uses or certain business rules that only apply to one customer. On top of that it is possible that certain cases should be completely ignored for one or two customers where the base class does not.

The question is:

What is the best way to handle customer specific logic within a generic process?

If this is a duplicate, I'd really like to know how you found it!

If there is more information needed, I'd be happy to supply.

Update:
I created this picture in the hope it would give a better understanding of what I want to achieve. As you can see in the picture, each customer has its own set of overrides of the bigger process.

答:
There are several options you can consider to tackle this problem at the design level.

Pattern-wise, you might want to get yourself a refresher about, including, albeit not limited to:

The abstract factory design pattern

http://www.dofactory.com/net/abstract-factory-design-pattern

which could maybe used in combination with:

The strategy design pattern

http://www.dofactory.com/net/strategy-design-pattern

If statefulness of your implementation is likely to come into play, the state design pattern, in combination with either or both the above, may also help (also presented dofactory).

'Hope this helps,

ContentLicense: CC BY-SA 3.0


问:
How shall I project CQRS command and query services through WCF
I got directed to this site for more conceptual questions. Here is my issue:

Im designing an application that uses CQRS to expose functionality to higher levels in the stack. This looks like below (from Top to down):

WebApi (REST)

WCF Clientside

WCF Serverside

CQRS (Command and Query Services as separeted interfaces)

Domain

At the level of the WebApi I have Dtos that I get from the web client and I have Command objects to call into the CommandServices. I'd like to keep the CQRS related stuff out of the WebApi project.

I was thinking of having a service grouping the command and query part and communicating through this grouped service through WCF. The separated command and query services would then only be on the server side of WCF.

Is this a good design or can anyone recommend a more elegant approach?

答:
My understanding of CQRS here, is it definitely feels like a disciplined implementation strategy for the middle tier more specifically (*) itself a supplier of the service tier (which calls into CQRS) - e.g., WCF, and a consumer of the domain model/data tiers (which is called from CQRS) - e.g., ADO.NET, Entity Framework, or whatnot.

So, unless I missed something, your high level layout overall looks good to me so far, wrt. bridging the gap with the WCF stack.

(*) or if only a part thereof, anyway

'Hope this helps,


问:
Proper way to interpret this dereference operation?
I've seen this example in a text book and am a little confused how to interpret the operator precedence rules. Given this struct:

```<code>   typedef struct {
   char *data;
   size_t start, end;
   } str_wends;
</code>```

Let B be declared as a pointer to this struct,that is.

```<code>   str_wends *B = malloc(sizeof(str_wends));
</code>```

and assume B->start != 0,

then this should be a legal construct:

```<code>   &B->data[B->start]
</code>```

which will return a reference to the string offset by B->start. The question is how to interpret the precedence rules. Since we know that -> and [] have the same precedence and bind left to right, why is B->Start evaluated before B->data[].

答:
Actually, it doesn't matter whether B->start or B->data is "evaluated" first.  The result of interest is address of the referenced element, which is the sum of the base address and the product of the index and the size of the element.  The two addends are independent, meaning that the order of their evaluation is irrelevant.

The result of the addition is an lvalue.  Evaluated on the right-hand side of an assignment expression, it generates a FETCH.  Evaluated on the left-hand side, it generates a STORE.


问:
Is the benefit of the IO monad pattern for handling side effects purely academic?
Sorry for yet another FP + side effects question, but I couldn't find an existing one which quite answered this for me.

My (limited) understanding of functional programming is that state/side effects should be minimised and kept separate from stateless logic.

I also gather Haskell’s approach to this, the IO monad, achieves this by wrapping stateful actions in a container, for later execution, considered outside the scope of the program itself.

I’m trying to understand this pattern, but actually to determine whether to use it in a Python project, so want to avoid Haskell specifics if poss.

Crude example incoming.

If my program converts an XML file to a JSON file:

```<code>def main():
    xml_data = read_file('input.xml')  # impure
    json_data = convert(xml_data)  # pure
    write_file('output.json', json_data) # impure
</code>```

Isn’t the IO monad’s approach effectively to do this:

```<code>steps = list(
    read_file,
    convert,
    write_file,
)
</code>```

then absolve itself of responsibility by not actually calling those steps, but letting the interpreter do it?

Or put another way, it’s like writing:

```<code>def main():  # pure
    def inner():  # impure
        xml_data = read_file('input.xml')
        json_data = convert(xml_data)
        write_file('output.json', json_data)
    return inner
</code>```

then expecting someone else to call inner() and saying your job is done because main() is pure.

The whole program is going to end up contained in the IO monad, basically.

When the code is actually executed, everything after reading the file depends on that file’s state so will still suffer from the same state-related bugs as the imperative implementation, so have you actually gained anything, as a programmer who will maintain this?

I totally appreciate the benefit of reducing and isolating stateful behaviour, which is in fact why I structured the imperative version like that: gather inputs, do pure stuff, spit out outputs. Hopefully convert() can be completely pure and reap the benefits of cachability, threadsafety, etc.

I also appreciate that monadic types can be useful, especially in pipelines operating on comparable types, but don’t see why IO should use monads unless already in such a pipeline.

Is there some additional benefit to dealing with side effects the IO monad pattern brings, which I’m missing?

答:
It's hard to be sure exactly what you mean by "purely academic", but I think the answer is mostly "no".

As explained in Tackling the Awkward Squad by Simon Peyton Jones (strongly recommended reading!), monadic I/O was meant to solve real problems with the way Haskell used to handle I/O. Read the example of the server with Requests and Responses, which I won't copy here; it's very instructive.

Haskell, unlike Python, encourages a style of "pure" computation which can be enforced by its type system. Of course, you can use self-discipline when programming in Python to comply with this style, but what about modules you didn't write? Without much help from the type system (and common libraries), monadic I/O is probably less useful in Python. The philosophy of the language is just not meant to enforce a strict pure/impure separation.

Note that this says more about the different philosophies of Haskell and Python than about how academic monadic I/O is. I wouldn't use it for Python.

One other thing. You say:

The whole program is going to end up contained in the IO monad, basically.

It's true the Haskell main function "lives" in IO, but real Haskell programs are encouraged not to use IO whenever it isn't needed. Almost every function you write that doesn't need to do I/O shouldn't have type IO.

So I'd say in your last example you got it backwards: main is impure (because it reads and writes files) but core functions like convert are pure.


问:
What's an effective threading structure for NIO and server performance in C/C++?
I run into this issue where if I do a read to check for data too often, my CPU skyrockets, and if I don't check often enough, it's slow for client performance. What's an effective way to deal with this & NIO?</p>

答:
You shouldn't need to check for data to be received from a socket. You want to ask the OS to tell you when data is received.

With poll (or select), you can pass it a bunch of sockets at once, and a large (or infinite) timeout. poll will return some data's been received on any of the sockets you passed it. If nothing is received, it will keep waiting without wasting CPU time. If something is received, it will return immediately.


答:
Why is IO impure?  Because it may return different values at different times.  There is a dependency on time that must be accounted for, one way or another.  This is even more crucial with lazy evaluation.  Consider the following program:

```<code>main = do
    putStrLn "Please enter your name"
    name <- getLine
    putStrLn $ "Hello, " ++ name
</code>```

Without an IO monad, why would the first prompt ever get output?  There is nothing depending on it, so lazy evaluation means it will never get demanded.   There is also nothing compelling the prompt to be output before the input is read.  As far as the computer is concerned, without an IO monad, those first two expressions are completely independent of each other.  Fortunately, name imposes an order on the second two.

There are other ways to solve the problem of order dependency, but using an IO monad is probably the simplest way (from the language point of view at least) to allow everything to stay in the lazy functional realm, without little sections of imperative code.  It's also the most flexible.  For example, you can relatively easily build an IO pipeline dynamically at runtime based on user input.

Title: Is the benefit of the IO monad pattern for handling side effects purely academic?

Body:
Sorry for yet another FP + side effects question, but I couldn't find an existing one which quite answered this for me.

My (limited) understanding of functional programming is that state/side effects should be minimised and kept separate from stateless logic.

I also gather Haskell’s approach to this, the IO monad, achieves this by wrapping stateful actions in a container, for later execution, considered outside the scope of the program itself.

I’m trying to understand this pattern, but actually to determine whether to use it in a Python project, so want to avoid Haskell specifics if poss.

Crude example incoming.

If my program converts an XML file to a JSON file:

```<code>def main():
    xml_data = read_file('input.xml')  # impure
    json_data = convert(xml_data)  # pure
    write_file('output.json', json_data) # impure
</code>```

Isn’t the IO monad’s approach effectively to do this:

```<code>steps = list(
    read_file,
    convert,
    write_file,
)
</code>```

then absolve itself of responsibility by not actually calling those steps, but letting the interpreter do it?

Or put another way, it’s like writing:

```<code>def main():  # pure
    def inner():  # impure
        xml_data = read_file('input.xml')
        json_data = convert(xml_data)
        write_file('output.json', json_data)
    return inner
</code>```

then expecting someone else to call inner() and saying your job is done because main() is pure.

The whole program is going to end up contained in the IO monad, basically.

When the code is actually executed, everything after reading the file depends on that file’s state so will still suffer from the same state-related bugs as the imperative implementation, so have you actually gained anything, as a programmer who will maintain this?

I totally appreciate the benefit of reducing and isolating stateful behaviour, which is in fact why I structured the imperative version like that: gather inputs, do pure stuff, spit out outputs. Hopefully convert() can be completely pure and reap the benefits of cachability, threadsafety, etc.

I also appreciate that monadic types can be useful, especially in pipelines operating on comparable types, but don’t see why IO should use monads unless already in such a pipeline.

Is there some additional benefit to dealing with side effects the IO monad pattern brings, which I’m missing?

Body:
Why is IO impure?  Because it may return different values at different times.  There is a dependency on time that must be accounted for, one way or another.  This is even more crucial with lazy evaluation.  Consider the following program:

main = do
    putStrLn "Please enter your name"
    name <- getLine
    putStrLn $ "Hello, " ++ name

Without an IO monad, why would the first prompt ever get output?  There is nothing depending on it, so lazy evaluation means it will never get demanded.   There is also nothing compelling the prompt to be output before the input is read.  As far as the computer is concerned, without an IO monad, those first two expressions are completely independent of each other.  Fortunately, name imposes an order on the second two.

There are other ways to solve the problem of order dependency, but using an IO monad is probably the simplest way (from the language point of view at least) to allow everything to stay in the lazy functional realm, without little sections of imperative code.  It's also the most flexible.  For example, you can relatively easily build an IO pipeline dynamically at runtime based on user input.


问:
General design choices. How do you decide?
I have a project in C that I'm looking to convert to C++.  The project does white box hardware testing of a device (actually many similar devices).  In this case the device has two processors.  Each have unique capabilities and both have some similar features (discrete io and such).  The top level test code is a collection of exported functions from a DLL.

Looking at the code knowing that I'll have to support additional variants of the devices I have the following questions which made me think others would have suggestions on architecture/design and the reasoning behind those design choices will help others:

Do you support a device class with members proc_a and proc_b (has a thinking) with the interface having distinct function names so it's clear to the user what's being manipulated or prefer the interface to have a more generic naming scheme (like setDiscrete which takes an enum encompassing both processors' discrete a (DISCRETE_PROC_A_x and _B_x)?

Knowing that future variants of the device will have updated processor(s) how do I keep the changes to only those features that changed?  I.e. A new processor B adds functionality and the include files for that functionality (from the embedded source) are different then what is used so far.  I'm thinking I make the processor a class and than children of it to handle this concern.  Is there a more maintanable design? What if the interface for that class needs to change but the same functionality is needed?

Tell don't ask is great but when you need setters or getters do you prefer set/get, push/pull, set/clear, etc?  Do you make some communicate with the device and cache the state in your class? If so, is that separate fetch function and you use a state tracking variable or is it another function in the interface?

答:
Looking at your direct questions, I will answer the entire question with a single link to the GoF Design Patterns -

https://en.wikipedia.org/wiki/Design_Patterns

And call out two patterns that I have repeatedly used when designing extendable software with minimal rewrite and that is that of the
Decorator Pattern - https://en.wikipedia.org/wiki/Decorator_pattern
and the Strategy Pattern - https://en.wikipedia.org/wiki/Strategy_pattern

To fully understand the direct answers to the questions you pose, understanding the above patterns will help to inform the following thinking.

You can design your interface to be more generic, build the basic functionality shared by the devices in a concrete implementation, and then decorate the additional functionality on the discrete behaviors that are not shared.

By doing the above, you restrict changes only to the new functionality.  If you find that your interface must change, it likely means that your interface wasn't designed properly in your first use case.  Strategy can come into play as well, if you need two processors to do functionally the same things, but on different types of inputs.

The answer to this depends on how you have decided the implementations of above, with regard to the sharing of data, strategy and how you have done the decorating.  Depending on what you need to share you may be able to make use of the Flyweight pattern - https://en.wikipedia.org/wiki/Flyweight_pattern

Regardless of what you decide, I hope that this drives home the importance of design when you are working with both new and old code with regards to reusable and extensible software.  The is a, has a parent/child subclassing has caused great difficulty when poorly designed!

Happy Patterns!


问:
Are data type declarators like "int" and "char" stored in RAM when a C program executes?
When a C program is running, the data is stored on the heap or the stack. The values are stored in RAM addresses. But what about the type indicators (e.g., int or char)? Are they also stored?

Consider the following code:

```<code>char a = 'A';
int x = 4;
</code>```

I read that A and 4 are stored in RAM addresses here. But what about a and x? Most confusingly, how does the execution know that a is a char and x is an int? I mean, is the int and char mentioned somewhere in RAM?

Let's say a value is stored somewhere in RAM as 10011001; if I am the program which executes the code, how will I know whether this 10011001 is a char or an int?

What I don't understand is how the computer knows, when it reads a variable's value from an address such as 10001, whether it is an int or char. Imagine I click on a program called anyprog.exe. Immediately the code starts executing. Does this executable file include information on whether the variables stored are of the type int or char?

答:
At the lowest level, in the actual physical CPU there are no types at all (ignoring the floating point units). Just patterns of bits. A computer works by manipulating patterns of bits, very, very fast.

That's all the CPU ever does, all it ever can do. There's no such thing as an int, or a char.

```<code>x = 4 + 5
</code>```

Will execute as:

Load  00000100 into register 1

Load  00000101 into register 2

IAdd register 1 to register 2, and store in register 1

The iadd instruction triggers hardware which behaves as if registers 1 and 2 are integers. If they don't actually represent integers, all kinds of things can go wrong later. The best outcome is usually crashing.

It's on the compiler to chose the correct instruction based on the types given in source, but in the actual machine code executed by the CPU, there are no types, anywhere.

edit: Note that the actual machine code does not in fact mention 4, or 5, or integer anywhere. it's just two patterns of bits, and an instruction that takes two bit patterns, assumes they're ints, and adds them together.

Body:
At the lowest level, in the actual physical CPU there are no types at all (ignoring the floating point units). Just patterns of bits. A computer works by manipulating patterns of bits, very, very fast.

That's all the CPU ever does, all it ever can do. There's no such thing as an int, or a char.

x = 4 + 5

Will execute as:

Load  00000100 into register 1

Load  00000101 into register 2

IAdd register 1 to register 2, and store in register 1

The iadd instruction triggers hardware which behaves as if registers 1 and 2 are integers. If they don't actually represent integers, all kinds of things can go wrong later. The best outcome is usually crashing.

It's on the compiler to chose the correct instruction based on the types given in source, but in the actual machine code executed by the CPU, there are no types, anywhere.

edit: Note that the actual machine code does not in fact mention 4, or 5, or integer anywhere. it's just two patterns of bits, and an instruction that takes two bit patterns, assumes they're ints, and adds them together.


问:
Why does Swift not require semicolons?
I normally code in either c# or Objective-C and recently took it upon myself to learn Apple's new programming language - Swift.

The first thing I noticed is that you don't need to add semicolons to end a line in Swift but if you do-at least from what I've tested-it does not interfere with the compiler.

When I write:

```<code>int someNumber = 0;
</code>```

in Objective-C the semicolon tells the program that the line is over and to not fall through to the next line.

With Swift I can declare a variable with

```<code>var someNumber:Int = 5
</code>```

and not add a semicolon and the system knows that this is the end of the line.

What allows the some languages to do this and others to not? Why not keep a uniform system of adding the semicolon to the end?

答:
Line breaks are used instead of semicolons to delimit the end of a statement.

In Language guide: The Basics it says:

Unlike many other languages, Swift does not require you to write a semicolon (;) after each statement in your code, although you can do so if you wish. Semicolons are required, however, if you want to write multiple separate statements on a single line.

Why?  Because that's how the language designers wanted to do it.

The second sentence above hints at why you don't need semicolons; most statements are single line.  Observe this Bubble Sort example; the combination of single-line statements and no semicolons makes for very clean syntax that's VB-like, but less verbose:

```<code>func bubbleSort<T:Comparable>(inout list:[T]) {
    var done = false
    while !done {
        done = true
        for i in 1..<list.count {
            if list[i - 1] > list[i] {
                (list[i], list[i - 1]) = (list[i - 1], list[i])
                done = false
            }
        }
    }
}
</code>```

Because statements in Swift usually end on a line break, the need for semicolons to mark the end of a statement is reduced.  Other languages that use semicolons don't work this way; you can freely write multi-line statements, but the only way the compiler knows that the statement has ended is when you place your semicolon at the end of it.

When statements don't end on a line break, you have to put the line break at a place that the Swift compiler can recognize as a continuation of the previous line:

```<code>let s2 = str
        .lowercaseString
        .replace("hello", withString: "goodbye")
</code>```

Title: Why does Swift not require semicolons?

Body:
Line breaks are used instead of semicolons to delimit the end of a statement.

In Language guide: The Basics it says:

Unlike many other languages, Swift does not require you to write a semicolon (;) after each statement in your code, although you can do so if you wish. Semicolons are required, however, if you want to write multiple separate statements on a single line.

Why?  Because that's how the language designers wanted to do it.

The second sentence above hints at why you don't need semicolons; most statements are single line.  Observe this Bubble Sort example; the combination of single-line statements and no semicolons makes for very clean syntax that's VB-like, but less verbose:

func bubbleSort<T:Comparable>(inout list:[T]) {
    var done = false
    while !done {
        done = true
        for i in 1..<list.count {
            if list[i - 1] > list[i] {
                (list[i], list[i - 1]) = (list[i - 1], list[i])
                done = false
            }
        }
    }
}

Because statements in Swift usually end on a line break, the need for semicolons to mark the end of a statement is reduced.  Other languages that use semicolons don't work this way; you can freely write multi-line statements, but the only way the compiler knows that the statement has ended is when you place your semicolon at the end of it.

When statements don't end on a line break, you have to put the line break at a place that the Swift compiler can recognize as a continuation of the previous line:

let s2 = str
        .lowercaseString
        .replace("hello", withString: "goodbye")


问:
Are SMART goals useful for programmers?
Several organisations I know use SMART goals for their programmers. SMART is an acronym for Specific, Measurable, Achievable, Relevant and Time-Bound. They are fairly common in large corporations.

My own prior experience with SMART goals has not been all that positive. Have other programmers found them an effective way to measure performance? What are some examples of good SMART goals for programmers (if they exist).

答:
As a performance framework, SMART is only as effective as how closely your objectives are aligned with those of your managers. Sometimes your SMART objectives have to DUMB down first, ie. make them:

Doable

Understandable

Manageable

Beneficial

As strange as that might sound.

Title: Are SMART goals useful for programmers?

OwnerDisplayName: AAology


问:
Are "technical user stories" allowed in Scrum?
Are technical user stories allowed in Scrum? If so, what is the standard template for writing technical user stories in Scrum?
Is it the same As a <user> I want to do <task> so that I can <goal> ??

I have read in some blogs that as-a-developer-is-not-a-user-story,
but I have also read that Scrum does not mandate these.  There are few blogs where they have shared user stories with system as user, its like as a <user who is not end user> i want to <system functionality> so that <some techinical thing>. So which one is the standard?

For instance, there are user stories like:

As a reviewer I want to upload photos of any hotel/food so that other users can see and like them

As a user I want to add photo comments so that I can explain my view better

Now for both these user stories, there is a big technical item - Saving and retrieving the image

So can I add a technical story titled "Image storing and retrieving mechanism", with the following description?

As a developer I want to develop a mechanism to store and retrieve images so that users can add/view images wherever required

答:
Technical stories are allowed, but I would advise you to try to avoid them as much as you can.

For example, your story for saving and retrieving images can easily be written as two regular user-stories

As a reviewer, I want my uploaded photos to be stored persistently, so that other users can view them at any time.

(Note that this assumes that in your original upload story, the image will not be persistently stored after the upload. Although this might look strange, it is a valid way of splitting up stories to make them manageable.)

As a user, I want to view uploaded images at a moment that is convenient for me.

(This implies that stored images can be retrieved later.)

Technical stories should be reserved for work that is important for the organization, but not directly visible as a feature/functionality to the users. For example, adding load balancing to handle larger number or requests.


问:
Are Integration Tests Meant to be Redundant?
Here is some fake code under test:

```<code>public void saveItem() {
  try {
    databaseInterface.saveItemToDatabase(item);
  } catch (Exception e) {
      // deal with it
      return;
  }
  itemList.Add(item);
}
</code>```

When writing a unit test, if you were to not stub out that database call, test engineers would say that it is an integration test, not a unit test since it is calling a real database which makes the unit test slow, and a characteristic of a unit test is that it should be fast.

So, you stub out that database call, and test whether the item was saved to the list, ending up with a unit test.

You also create a unit test to test whether the saveItemToDatabase function was actually called, so in this new unit test you decide to mock the call and assert against it.

You are also tasked with unit testing your database interface, to make sure that items are actually being saved to the database, so you do so.

All your tests pass, so now you know that 1) items are being saved to the list 2) your saveItemToDatabase method is actually being called 3) your unit tests covering your database module show that the item is actually being saved to the database.

If I'm understanding integration test correctly, you would in an integration test, test all of these things, this time using a real database call in one test. So in one integration test your test might do the following:

Create an item.

Call saveItem() (an object method) which will save the item you just created.

Query the database for the item using your database interface.

Check that the item you created and the query result are equal.

Check that the item you saved was added to the itemList.

It seems like the integration test is taking all the unit tests and rechecking what each unit test does, except this time you aren't stubbing or mocking anything out, so it makes it seem like integration tests are a bit redundant.

Am I misunderstanding what an integration test is? It sort of seems like a test that says, "yes, your production code is actually working when you don't stub or mock things out."

答:
It sort of seems like a test that says, "yes, your production code is actually working when you don't stub or mock things out."

That's exactly what it is.

Stubs and mocks isolate the infrastructure from your unit tests, which means that your units get tested, but not the infrastructure that you've stubbed out, nor the connections your units make with that infrastructure.  It's the behavior of your units and the way that behavior interacts  with the actual components that you've stubbed out that is being tested in an integration test.

Remember, stubs and mocks don't represent the actual behavior of a real system; they only simulate a small number of artificially-induced behaviors so that you can run your unit tests.   An integration test not only provides a more realistic exercise of the system, but also a more comprehensive one.


答:
I think you have it backwards - the integration test is the "real" test, testing the system as a whole. But as it is a slow and often difficult to setup, we have unit tests as a stop-gap measure. They test bits in isolation which should give you an indicator that the code will probably work correctly when sent to the integration test.

You can write working systems without unit tests, you cannot do this without integration tests.

Title: Are Integration Tests Meant to be Redundant?

Body:
Here is some fake code under test:

```<code>public void saveItem() {
  try {
    databaseInterface.saveItemToDatabase(item);
  } catch (Exception e) {
      // deal with it
      return;
  }
  itemList.Add(item);
}
</code>```

When writing a unit test, if you were to not stub out that database call, test engineers would say that it is an integration test, not a unit test since it is calling a real database which makes the unit test slow, and a characteristic of a unit test is that it should be fast.

So, you stub out that database call, and test whether the item was saved to the list, ending up with a unit test.

You also create a unit test to test whether the saveItemToDatabase function was actually called, so in this new unit test you decide to mock the call and assert against it.

You are also tasked with unit testing your database interface, to make sure that items are actually being saved to the database, so you do so.

All your tests pass, so now you know that 1) items are being saved to the list 2) your saveItemToDatabase method is actually being called 3) your unit tests covering your database module show that the item is actually being saved to the database.

If I'm understanding integration test correctly, you would in an integration test, test all of these things, this time using a real database call in one test. So in one integration test your test might do the following:

Create an item.

Call saveItem() (an object method) which will save the item you just created.

Query the database for the item using your database interface.

Check that the item you created and the query result are equal.

Check that the item you saved was added to the itemList.

It seems like the integration test is taking all the unit tests and rechecking what each unit test does, except this time you aren't stubbing or mocking anything out, so it makes it seem like integration tests are a bit redundant.

Am I misunderstanding what an integration test is? It sort of seems like a test that says, "yes, your production code is actually working when you don't stub or mock things out."


问:
Will changing published git history on a private repo cause problems when I make it public?
I have a github repo that is currently set to private. I'd like to make it public but before doing so would like to clean it up a little bit by squashing some commits and possibly rebasing so that the history is easier to read and contains less minor commits (version bumps, typo fixes etc.).

I know that changing history on a published repo will create problems for any other users that have pulled from the repo. But will changing history on a repo that only I currently have access to create any issues when I make that repo public?

I'm also curious if others would rather see the full history with warts and all or a cleaned up version though that seems very subjective.

答:
Its problematic if you already work with others, rebase/tidy up your history of a branch where other participants work with and push it afterwards to a public repository. Other participants of your project will have major problems. See -> this explanation

But you work alone so far. There will be no problems if you publish your repository now.
You will get into trouble if you now change the history after publishing via rebase while other people work on that branch.


问:
Why does this use of IEnumerable, List, and Arrays seem to get modified when it shouldn't be?
I have started learning c# and am confused by the following feature.

The following code uses a function Algs.Combinations(n,m) to produce an IEnumerable which contains the combinations of n objects taken from m. Its implementation is exactly as can be found on the Rosetta code page for combinations. For example, applying .toList() to Algs.Combinations(2,3) would produce the list [[0,1],[0,2],[1,2]].

Now in the foreach loop I add each int[] to a new list. I also print out the values of each array(ie the combination) after turning it to a list and then using the built in ForEach. Everything works as expected.

In the next block I use the built in ForEach on my new list and it seems every int[] has become [2,2]. What is going on here? Presumably in my foreach I am not actually adding the integer array but some kind of pointer?

```<code>using System;
using System.Collections.Generic;
using System.Linq;

namespace Examples
{
    class main
    {
        public static IEnumerable<int[]> Combinations(int m, int n)
        {
            int[] result = new int[m];
            Stack<int> stack = new Stack<int>();
            stack.Push(0);

            while (stack.Count > 0)
            {
                int index = stack.Count - 1;
                int value = stack.Pop();

                while (value < n)
                {
                    result[index++] = value++;
                    stack.Push(value);
                    if (index == m)
                    {
                        yield return result;
                        break;
                    }
                }
            }
        }

        static void Main(String[] args)
        {
            var l = Combinations(2, 3);
            var newL = new List<int[]>();
            foreach (int[] combs in l)
            {
                newL.Add(combs);
                combs.ToList().ForEach(p => Console.Write(p + " ")); // prints 0 1, 0 2, 1 2
                Console.WriteLine();
            }
            newL.ForEach(p =>
            {
                p.ToList().ForEach(q => Console.Write(q + " ")); // prints 2 2, 2 2, 2 2
                Console.WriteLine();
            });
         }

    }
 }
</code>```

Googling hasn't helped so far. Any links to literature I should look at will be appreciated.

答:
This has nothing to do with using an IEnumerable or the yield statement. If you rewrite your "combination" function like this

```<code>    public static List<int[]> Combinations(int m, int n)
    {
        int[] result = new int[m];
        List<int[]> resultList = new List<int[]>();
        Stack<int> stack = new Stack<int>();
        stack.Push(0);

        while (stack.Count > 0)
        {
            int index = stack.Count - 1;
            int value = stack.Pop();

            while (value < n)
            {
                result[index++] = value++;
                stack.Push(value);
                if (index == m)
                {
                    resultList.Add(result); // <-- note what you are adding here
                    break;
                }
            }
        }
        return result;
    }
</code>```

you will face the same problem (well almost the same, because now already your first for-each loop will print out a couple of "2 2" values repeatedly).

This is because each entry in resultList gets a reference to the same array result. And as @Erik correctly wrote, the correct solution here is to make copies of the result array, though I would do this within the combination function, for example by modifying the yieldline in your original code like this:

```<code> yield return result.ToArray();
</code>```

That way, it is not the callers responsibility to make copies, eliminating the drawback Erik was talking of.

Body:
This has nothing to do with using an IEnumerable or the yield statement. If you rewrite your "combination" function like this

    public static List<int[]> Combinations(int m, int n)
    {
        int[] result = new int[m];
        List<int[]> resultList = new List<int[]>();
        Stack<int> stack = new Stack<int>();
        stack.Push(0);

        while (stack.Count > 0)
        {
            int index = stack.Count - 1;
            int value = stack.Pop();

            while (value < n)
            {
                result[index++] = value++;
                stack.Push(value);
                if (index == m)
                {
                    resultList.Add(result); // <-- note what you are adding here
                    break;
                }
            }
        }
        return result;
    }

you will face the same problem (well almost the same, because now already your first for-each loop will print out a couple of "2 2" values repeatedly).

This is because each entry in resultList gets a reference to the same array result. And as @Erik correctly wrote, the correct solution here is to make copies of the result array, though I would do this within the combination function, for example by modifying the yieldline in your original code like this:

 yield return result.ToArray();

That way, it is not the callers responsibility to make copies, eliminating the drawback Erik was talking of.


答:
What allows the some languages to do this and others to not? Why not keep a uniform system of adding the semicolon to the end?

Robert gave a good answer regarding Swift, I'll try to add bit more about parsing in general and why to use or not semicolons.

When you compile the program, there are several steps before your source file is turned into executable code, one of the first being reading and parsing. During parsing your code is transformed from a sequence of characters into a structured representation according to the grammar of the language. For this it's necessary that the elements that compose your code (variables, constants, declarations, etc.) are somehow identified and separated. When you make a declaration like:

```<code>int someNumber = 0;
</code>```

It's just a sequence of characters that somehow needs to be turned unto the concept "create a 'thing' called someNumber of type int and assign 0 to it".

This requires identifying where exactly the statement begins and ends. Imagine if you had this:

```<code>int someNumber = 0;
int otherNumber = 1;
</code>```

You would need to know that those are two different declarations. The ; in C-like languages is used for that, so the parser reads the characters until it finds one, and attempts to understand what was just read as a single statement. This allows, as Robert said, to have several statements in the same line, like:

```<code>int someNumber = 0; int otherNumber = 1;
</code>```

Which has exactly the same effect as writing them in two lines.

In other languages, like Python, you are expected to put each statement in a different line.

```<code>x = 3
if x < 10:
   print 'x smaller than 10'
else:
   print 'x is bigger than 10 or equal'
</code>```

So there is no need to add a ;, because the language itself prevents you from adding statements in the same line!

Yet other languages, like LISP or Scheme, have a very different way of grouping statements (ok, they are not really statements, but let's ignore that for now). So you have just parenthesis for everything:

```<code>(define (do-stuff x)
  (begin
    (display (format "value: ~a" x))
    x))
</code>```

Again, you don't need the ; just because you use the same symbols (), () for things that in other languages are {, }, :, etc. Someone who only knows Lisp syntax might ask you: Why do you need ; at the end of your statements?

Just to add a stranger example: OCaml not only has a semicolon at the end of statements... it has two!

```<code>let rec fact x =
    if x <= 1 then 1 else x * fact (x - 1);;
</code>```

Why? I don't know. :)

Different languages are designed with different purposes and different philosophies. If all languages shared the same syntax and conventions, they would probably only allow you to do the same things in the same way.

Title: Why does Swift not require semicolons?

Body:
I normally code in either c# or Objective-C and recently took it upon myself to learn Apple's new programming language - Swift.

The first thing I noticed is that you don't need to add semicolons to end a line in Swift but if you do-at least from what I've tested-it does not interfere with the compiler.

When I write:

```<code>int someNumber = 0;
</code>```

in Objective-C the semicolon tells the program that the line is over and to not fall through to the next line.

With Swift I can declare a variable with

```<code>var someNumber:Int = 5
</code>```

and not add a semicolon and the system knows that this is the end of the line.

What allows the some languages to do this and others to not? Why not keep a uniform system of adding the semicolon to the end?

Body:
What allows the some languages to do this and others to not? Why not keep a uniform system of adding the semicolon to the end?

Robert gave a good answer regarding Swift, I'll try to add bit more about parsing in general and why to use or not semicolons.

When you compile the program, there are several steps before your source file is turned into executable code, one of the first being reading and parsing. During parsing your code is transformed from a sequence of characters into a structured representation according to the grammar of the language. For this it's necessary that the elements that compose your code (variables, constants, declarations, etc.) are somehow identified and separated. When you make a declaration like:

int someNumber = 0;

It's just a sequence of characters that somehow needs to be turned unto the concept "create a 'thing' called someNumber of type int and assign 0 to it".

This requires identifying where exactly the statement begins and ends. Imagine if you had this:

int someNumber = 0;
int otherNumber = 1;

You would need to know that those are two different declarations. The ; in C-like languages is used for that, so the parser reads the characters until it finds one, and attempts to understand what was just read as a single statement. This allows, as Robert said, to have several statements in the same line, like:

int someNumber = 0; int otherNumber = 1;

Which has exactly the same effect as writing them in two lines.

In other languages, like Python, you are expected to put each statement in a different line.

x = 3
if x < 10:
   print 'x smaller than 10'
else:
   print 'x is bigger than 10 or equal'

So there is no need to add a ;, because the language itself prevents you from adding statements in the same line!

Yet other languages, like LISP or Scheme, have a very different way of grouping statements (ok, they are not really statements, but let's ignore that for now). So you have just parenthesis for everything:

(define (do-stuff x)
  (begin
    (display (format "value: ~a" x))
    x))

Again, you don't need the ; just because you use the same symbols (), () for things that in other languages are {, }, :, etc. Someone who only knows Lisp syntax might ask you: Why do you need ; at the end of your statements?

Just to add a stranger example: OCaml not only has a semicolon at the end of statements... it has two!

let rec fact x =
    if x <= 1 then 1 else x * fact (x - 1);;

Why? I don't know. :)

Different languages are designed with different purposes and different philosophies. If all languages shared the same syntax and conventions, they would probably only allow you to do the same things in the same way.


问:
Separate interface for mutation methods
I've been working on refactoring some code, and I think I may have taken the first step down the rabbit hole. I'm writing the example in Java, but I suppose it could be agnostic.

I have an interface Foo defined as

```<code>public interface Foo {

    int getX();

    int getY();

    int getZ();
}
</code>```

And an implementation as

```<code>public final class DefaultFoo implements Foo {

    public DefaultFoo(int x, int y, int z) {
        this.x = x;
        this.y = y;
        this.z = z;
    }

    public int getX() {
        return x;
    }

    public int getY() {
        return y;
    }

    public int getZ() {
        return z;
    }

    private final int x;
    private final int y;
    private final int z;
}
</code>```

I also have an interface MutableFoo that provides matching mutators

```<code>/**
 * This class extends Foo, because a 'write-only' instance should not
 * be possible and a bit counter-intuitive.
 */
public interface MutableFoo extends Foo {

    void setX(int newX);

    void setY(int newY);

    void setZ(int newZ);
}
</code>```

There are a couple of implementations of MutableFoo that could exist (I haven't implemented them yet). One of them is

```<code>public final class DefaultMutableFoo implements MutableFoo {

    /**
     * A DefaultMutableFoo is not conceptually constructed
     * without all values being set.
     */
    public DefaultMutableFoo(int x, int y, int z) {
        this.x = x;
        this.y = y;
        this.z = z;
    }

    public int getX() {
        return x;
    }

    public void setX(int newX) {
        this.x = newX;
    }

    public int getY() {
        return y;
    }

    public void setY(int newY) {
        this.y = newY;
    }

    public int getZ() {
        return z;
    }

    public void setZ(int newZ) {
        this.z = newZ;
    }

    private int x;
    private int y;
    private int z;
}
</code>```

The reason I have split these is because it is equally likely for each to be used. Meaning, it is equally likely that someone using these classes will want an immutable instance, as it is they will want a mutable one.

The primary use-case that I have is an interface called StatSet that represents certain combat details for a game (hitpoints, attack, defense). However, the "effective" stats, or the actual stats, are a result of the base stats, that can never be changed, and the trained stats, which can be increased. These two are related by

```<code>/**
 * The EffectiveStats can never be modified independently of either the baseStats
 * or trained stats. As such, this StatSet must never provide mutators.
 */
public StatSet calculateEffectiveStats() {
    int effectiveHitpoints =
        baseStats.getHitpoints() + (trainedStats.getHitpoints() / 4);
    int effectiveAttack =
        baseStats.getAttack() + (trainedStats.getAttack() / 4);
    int effectiveDefense =
        baseStats.getDefense() + (trainedStats.getDefense() / 4);

    return StatSetFactory.createImmutableStatSet(effectiveHitpoints, effectiveAttack, effectiveDefense);
}
</code>```

the trainedStats are increased after every battle like

```<code>public void grantExperience() {
    int hitpointsReward = 0;
    int attackReward = 0;
    int defenseReward = 0;

    final StatSet enemyStats = enemy.getEffectiveStats();
    final StatSet currentStats = player.getEffectiveStats();
    if (enemyStats.getHitpoints() >= currentStats.getHitpoints()) {
        hitpointsReward++;
    }
    if (enemyStats.getAttack() >= currentStats.getAttack()) {
        attackReward++;
    }
    if (enemyStats.getDefense() >= currentStats.getDefense()) {
        defenseReward++;
    }

    final MutableStatSet trainedStats = player.getTrainedStats();
    trainedStats.increaseHitpoints(hitpointsReward);
    trainedStats.increaseAttack(attackReward);
    trainedStats.increaseDefense(defenseReward);
}
</code>```

but they aren't increased just after battle. Using certain items, employing certain tactics, clever use of the battlefield all can grant different experience.

Now for my questions:

Is there a name for splitting interfaces by accessors and mutators into separate interfaces?

Is splitting them in this way the 'right' approach if they are equally likely to be used, or is there a different, more accepted pattern that I should use instead (eg. Foo foo = FooFactory.createImmutableFoo(); which could return DefaultFoo or DefaultMutableFoo but is hidden because createImmutableFoo returns Foo)?

Are there any immediately foreseeable downsides to using this pattern, save for complicating the interface hierarchy?

The reason I started designing it this way is because I'm of the mindset that all implementers of an interface should adhere to the simplest interface possible, and provide nothing more. By adding setters to the interface, now the effective stats can be modified independently of its parts.

Making a new class for the EffectiveStatSet does not make much sense as we're not extending the functionality in any way. We could change the implementation, and make an EffectiveStatSet a composite of two different StatSets, but I feel that is not the right solution;

```<code>public class EffectiveStatSet implements StatSet {

    public EffectiveStatSet(StatSet baseStats, StatSet trainedStats) {
        // ...
    }

    public int getHitpoints() {
        return baseStats.getHitpoints() + (trainedStats.getHitpoints() / 4);
    }
}
</code>```

答:
There's a big problem here: just because a data structure is immutable doesn't mean we don't need modified versions of it. The real immutable version of a data structure does provide setX, setY, and setZ methods - they just return a new structure instead of modifying the object you called them on.

```<code>// Mutates mutableFoo
mutableFoo.setX(...)
// Creates a new updated immutableFoo, existing immutableFoo is unchanged
newFoo = immutableFoo.setX(...)
</code>```

So how do you give one part of your system the ability to change it while restricting other parts? With a mutable object containing a reference to an instance of the immutable structure. Basically, instead of your player class being able to mutate its stats object while giving every other class an immutable view of its stats, its stats are immutable and the player is mutable. Instead of:

```<code>// Stats are mutable, mutates self.stats
self.stats.setX(...)
</code>```

You'd have:

```<code>// Stats are immutable, mutates self, setX() returns new updated stats
self.stats = self.stats.setX(...)
</code>```

See the difference? The stats object is completely immutable, but the player's current stats is a mutable reference to the immutable object. No need to make two interfaces at all - simply make the data structure completely immutable and manage a mutable reference to it where you happen to be using it to store state.

This means other objects in your system can't rely on a reference to the stats object - the stats object they have won't be the same stats object the player has after the player updates their stats.

This makes more sense anyway, since conceptually it's not really the stats that are changing, it's the player's current stats. Not the stats object. The reference to the stats object the player object has. So other parts of your system depending on that reference should all be explicitly referencing player.currentStats() or some such instead of getting ahold of the player's underlying stats object, storing it somewhere, and relying on it updating through mutations.

Title: Separate interface for mutation methods

Body:
There's a big problem here: just because a data structure is immutable doesn't mean we don't need modified versions of it. The real immutable version of a data structure does provide setX, setY, and setZ methods - they just return a new structure instead of modifying the object you called them on.

// Mutates mutableFoo
mutableFoo.setX(...)
// Creates a new updated immutableFoo, existing immutableFoo is unchanged
newFoo = immutableFoo.setX(...)

So how do you give one part of your system the ability to change it while restricting other parts? With a mutable object containing a reference to an instance of the immutable structure. Basically, instead of your player class being able to mutate its stats object while giving every other class an immutable view of its stats, its stats are immutable and the player is mutable. Instead of:

// Stats are mutable, mutates self.stats
self.stats.setX(...)

You'd have:

// Stats are immutable, mutates self, setX() returns new updated stats
self.stats = self.stats.setX(...)

See the difference? The stats object is completely immutable, but the player's current stats is a mutable reference to the immutable object. No need to make two interfaces at all - simply make the data structure completely immutable and manage a mutable reference to it where you happen to be using it to store state.

This means other objects in your system can't rely on a reference to the stats object - the stats object they have won't be the same stats object the player has after the player updates their stats.

This makes more sense anyway, since conceptually it's not really the stats that are changing, it's the player's current stats. Not the stats object. The reference to the stats object the player object has. So other parts of your system depending on that reference should all be explicitly referencing player.currentStats() or some such instead of getting ahold of the player's underlying stats object, storing it somewhere, and relying on it updating through mutations.


问:
The Programmers Bill of Responsibilities
So, we've all heard of The Programmers Bill of Rights and XP has a similar concept.

It's a common complaint these days that we hear a lot about people's rights but not so much about their responsibilities, so what should be on the programmers bill of responsibilities.  That is things that they should do, which they may find unpalatable, but that which separate programmers acting professionally and responsibly, from those who do not.

I'm primarily interested in the unpalatable ones and the ones which tend not to happen.  That is the ones that programmers tend to shirk and avoid, rather than the ones which 90% of programmers actually want to do (such as always refactor and use source control).

So, what should be on the Programmers Bill of Responsibilities?

答:
A programmer has the responsibility to push back poor requirements instead of blindly implementing them. This includes telling clients that what they want is more expensive than other options or has a particular set of risks. It also includes communicating bad news in a professional way - not screaming, calling people stupid, implying they are stupid or other childish behavior. If he pushes back, he should have a set of reasons (more than, "I don't like SQL Server and won't use it") and an alternative plan to present.

However, the programmer also has the responsibility  of accepting decisions and using tools or designs they may not like if their pushback was not accepted. If a report was requested in SSRS, delivering it in Crystal Reports (which the client may not have) is unacceptable. If a .net solution was required, delivering it in Haskell is unacceptable. If no one else on the team uses a tool or language that you want to use, it is unprofessional to use it if management doesn't agree that it is the best tool for the particular job.

A programmer has the responsibility to test his work. (This shouldn't be the only test, but no professional programmer should send out code he has not tested.) This includes testing even the branches of the code you don't expect to hit very often. If you have a set of nested IFs, test all possible routes.

A programmer has the responsibility to handle errors and exceptions gracefully and to write error messages that the user will see that are professional and neutral not jokes or insulting.

A programmer has the responsibility to protect private data, protect the proprietary code he writes for the company and to protect the users from catastrophe (even self inflicted catastrophe) from their use of the application.

A programmer has the responsibility to make sure his code is maintainable and is in source control.

A programmer has the responsibility to coordinate with others to make sure his changes do not adversely affect what they are doing.

A programmer has the responsibility to recommend the best choice for the client of tools or languages in the design phase not the tool/language he wants to play with and learn.

A programmer has the responsibility to work with all the appropriate personnel for a project including the ones he does not like. It is not your job to like people, it is your job to work with them and be polite.

A programmer has the responsibility to produce a product that does what was specified in a reasonable time-frame. If the time-frame is not going to be met, he or she has the responsibility to inform management of that as soon as it is known.

A programmer has the responsibility to let project management know about impediments to getting the job done. They can't fix what they don't know about.

A programmer has the responsibility to do the whole task not just the fun, interesting parts. Every job has some boring parts, they still need to be done. This includes things like timesheets and adding discussion items to project management software. It includes things like documentation, code review, etc.

A programmer has the responsibility to learn the business domain he is supporting not just programming concepts.

A programmer has the responsibility to keep his skills up-to-date.

When a programmer messes up, he has the responsibility to do all in his power to fix the problems as soon as humanly possible. This may include bearing the bad news to management rather than trying to hide that you just deleted a critical table in the production database.

A programmer has the same responsibilities of any other worker - to show up on time, to work the hours contracted, to request vacation time in advance, to answer phone and email messages (heck to read their emails), to fill in required forms for HR, etc.

ContentLicense: CC BY-SA 2.5


问:
Should you ever mix scalar and list contexts anyway?
I have decided to learn Perl as my next language and I am currently reading about the scalar and list contexts, although this question is not specifically Perl-related, I will just put it in a Perl context (hah, get it?!)

So, the basic idea is that operators expect either a scalar or a list value, and if they get an argument that is of a different type than the one they are expecting, they will convert it to the appropriate context.

A couple of examples of the correct contexts being used:

# Scalar context
$first_number = 2;
$second_number = 3;
say 3+2; # This obviously prints 5

# List context
@array = qw (one two three);
@array = reverse @array;
say @array; # Prints threetwoone
```

<p>Now, if you mix contexts, you can get something like this:</p>

<pre class="lang-perl prettyprint-override"><code>$first_number = 2;
@array = qw (one two three);
$result = 2 + @array;
say $result; # This prints 5
</code>```

This is because using an array in a mathematical operation returns the length of the array instead.

Now, the question is: why would you ever want to do this unless you are an evil person and you want to make people reading your code miserable? Would it be too mainstream to use something like 2 + $#array instead?

In general, is it good programming practice to let the language take care of this type of scenario? Wouldn't it be better if the programmer took care of the variables and prepared data so that all operators received the correct argument type in the first place?

答:
Larry designed Perl to DWIM (Do What I Mean). If you're using an array in scalar context, meaning that you are using the array in a context where there is exactly one value that represents it, that one value you most likely want is its length. Thus, when you do that, that's what you get. If the situation were different, perhaps the single value that most people would want most of the time was the index of the last inserted element (which might be somewhere in the middle), an array in scalar context would do that.

$#array, which is the index of the last element, is wrong if you want the length. It's one less than that. It's also not the most common single value you'd want to know about an array because Perl handles list extending for you. You don't need to know the last element to add another element. You don't even need to know the last element to get it since Perl can count backward: $array[-1] is always the last element. This bit of knowledge is much less likely to be the single value you'd want in scalar context.

A better illustration of this philosophy are the getpw* functions, such as getpwnam. In list context, it returns a list of the elements for the user entry from the password table for the named user. In scalar context, it returns the one value of that list that you probably want if you only want one value. That's the UID of the named user. There's no rule that governs what a particular thing will do in scalar context other than giving you the value that most people probably want.

This is Perl handling some of the mundane details for you so you can get on with the task instead of fiddling with moving things around. If you're coming from a simpler language and are used to having to do much more work to do common things, this might seem odd. After spending some time with Perl, you might come to appreciate how much Perl does for you so you don't have to do the boring stuff.

Note that you had the tag "type-conversion", but that's not what's going on here. Perl isn't casting or coercing anything. An array is always an array. The variables and values can respond to context, but that doesn't change what they are. It's not using the same bit pattern to mean something different like you can do in C, for instance.


问:
How should I structure these Python classes?
Base Class

I have a class called Remote. This class represents a remote machine and has properties such as ip, hostname, username, and password, as well as methods for transferring files to/from the machine and running code on the machines command line.

Classes Based on Specific VM Providers

I have multiple subclasses of Remote, such as SLRemote, for remote machines running on SoftLayer, VBRemote for machines running in Virtual Box, and potentially in the future I might create other subclasses like an AWSRemote for remote machines running on Amazon Web Services, for example.

These classes have the __init__ method set so that they can take in a few arguments specific to the VM provider and properly find an existing VM, or provision a new VM. Since this may take awhile (IE, SoftLayer takes 2-20 minutes to set up a new VM, depending on image size and network conditions), the __init__ method runs these tasks on a separate thread, and I define a __getattribute__ method which joins the creation thread if it requires that the VM be finished (IE, how can you transfer files to/from the machine if it hasn't finished provisioning?)

Classes Based on Specific Software

I also have classes like DB2Server, WASServer, and FTPServer, which represent remote machines which have specific software installed on them. It seems to me that these classes should also somehow inherit from Remote. Just like Remote, they have an ip, a hostname, a username, and a password. Just like you want to transfer files to a Remote, you want to transfer files to these classes.

Solutions I've Considered

1 - So I want to subclass Remote, right? Well, no, not really, because DB2Server could be installed on a SLRemote or a VBRemote or a AWSRemote, in addition to the generic Remote.

2 - What about multiple inheritance? Again, no, not really, because then I have to write a set of classes for inheriting from each specific VM Provider with the specific software. Plus what if you install multiple things on the same server?

3 - Currently, the design I'm going with is that the classes based on specific software being installed inherit from object (I'm using Python 2), and the __init__ method takes in a remote argument. I've written __getattribute__ and __setattr__ so that in addition to querying the object directly for attributes, it also checks the remote object for those same attributes.

But this is annoying because it requires me to write the exact same __getattribute__ and __setattr__ method in each of my specific software classes, and as my team is growing and more people are having to write classes like these, they're having to come to understand that I'm using these methods and they need to replicate that code, too. It has a bad code smell in it.

4 - As I was writing up what I'm currently doing, this just came to me (the benefits of writing out your problem on Stack Exchange... or a sticky note... or an email... or telling it to someone who knows nothing at all about the problem you're talking about). I could write a base Software class which just takes in a  Remote instance and defines the __getattribute__ and __setattr__ methods. Then DB2Server, WASServer, and FTPServer would inherit from that instead.

Other Things that I'm vaguely aware of that might help?

Metaclasses? Aspect Oriented Programming? Mix-ins? These are all concepts that I'm vaguely aware of... would any of these help me with my problem?

What is the right way of doing this? What is the standard and correct design to apply to my situation?

Getting meta with these questions now:

How can I better summarize this problem and make a helpful title for the question with it?

Is this even the right place to ask? The question doesn't involve a single full line of code, so CodeReview is definitely not the right place, and StackOverflow doesn't seem right, either.

答:
I would leave them completely separate. Services and servers (notice I carefully separate the abstracted hardware and the abstracted software) are separate things.

I would let each Service object have one Remote (or VMInstance or whatever you want to call it) property, possibly passed in a contructor, that could potentially be changeable (service migration...).

At that point, it may well be that you decide that while it's convenient to have an accessor for some property that (strictly speaking) probably depends solely on the Remote on your Service instance, you can implement it as a simple pass-through (at least for a get-type operation).


答:
The question, given your particular example, would be why does a developer want to develop a mechanism to store and retrieve images so that users can add/view images wherever required, unless a user wants to add or view images?

That is, while your question is a good one, the example isn't. This is a user feature and should have a user story. And if the user doesn't really need that functionality then the developer shouldn't want to do it.

A technical story is more "As a developer, I want to reduce duplication in the data-archiving modules, so that I don't have to make every change in 6 places."

The question of whether these should be included in the sprint is a difficult one, and it depends somewhat who you consider to be your customer. Is it the end user, or the business who employs you, or the business who employs the business who employs you?

A lot of industry opinion-guiding is done by people who work for consultancy companies. From that perspective, I can see the argument that developer stories are bad. They should just be a part of what you do, day-to-day, invisible to the company that's paying for it. Those companies instinctively know that running up the bills too high ensures that your work dries up, so every developer works on a principle of doing only technical development that improves your development time, or improves your ability to release bug-free software.

My experience is more with working on in-house teams, providing software directly to the company who pays my wages. In many of those companies, there is a trust barrier between the business and the technical wing of the business. In all of them, there is a different mentality, where decreasing costs are every bit as increasing income.

In those environments, it can be good to define significant developer stories. It increases visibility, engendering trust, and encourages developers and management alike to think about the value of such tasks to the business and prioritise accordingly.

Ultimately, I suggest you try it. And, if it doesn't offer value, stop doing it.

But my instinct says that if you were considering the value of this development to the business, you wouldn't even have tried to make it a developer story. It's either good for the end user or it isn't. If it isn't then there's no value to the business.

Title: Are "technical user stories" allowed in Scrum?

Body:
Are technical user stories allowed in Scrum? If so, what is the standard template for writing technical user stories in Scrum?
Is it the same As a <user> I want to do <task> so that I can <goal> ??

I have read in some blogs that as-a-developer-is-not-a-user-story,
but I have also read that Scrum does not mandate these.  There are few blogs where they have shared user stories with system as user, its like as a <user who is not end user> i want to <system functionality> so that <some techinical thing>. So which one is the standard?

For instance, there are user stories like:

As a reviewer I want to upload photos of any hotel/food so that other users can see and like them

As a user I want to add photo comments so that I can explain my view better

Now for both these user stories, there is a big technical item - Saving and retrieving the image

So can I add a technical story titled "Image storing and retrieving mechanism", with the following description?

As a developer I want to develop a mechanism to store and retrieve images so that users can add/view images wherever required


问:
How to share data members between classes in C++ without violating encapsulation too much
In C++ let's say I have some class A:

```<code>Class A
      {
      int a1, a2, a3;

      void foo();
      }
</code>```

and I need to use a subset of members (a1, a2) in a member function for a second class B.

What I'm wondering is whether I should define the arguments of B's member function by passing a pointer to A as an argument, or whether I should pass the members of A as arguments. e.g.,

```<code>Class B
      {
      int b1, b2;

      void bar(A &a);
      }
</code>```

or should this be

```<code>Class B
      {
      int b1, b2;

      void bar(int a1, int a2);
      }
</code>```

The latter would seem to minimize having to violate encapsulation, because B can then be largely agnostic about the constituents of A; whereas, in the former case, B would have to know something about the members of A. So it would seem the second implementation would be preferable.

Another reason the first implementation seems problematic to me is that, ideally, I'd like to keep the members (a1, a2, a3) of A protected rather than public. Normally I'd be tempted to make B a friend class of A, but the problem here is that A and B will both each have several derived classes, and since friendship doesn't inherit in C++ that wouldn't seem to be a good solution.

So these reasons would argue for using something like the second definition of B. However, in the actual code I'm dealing with, there are quite a few (about 6 or more) members of A that B will require, so this could get unwieldy. Being able to just pass a pointer to A would seem preferable from a readability standpoint and hide the details of what B.bar() requires from other parts of the code that deal with B.

Perhaps one work around would be to have methods inside A that do something like:A::get_a1() {return this->a1} or something, but I'm also not sure if that's really the correct design solution here.

答:
If you want to avoid an extra "data transfer class" like suggested by @Robert Harvey, you need to access your member variables by getter and setter functions.

Thus your approach described in your last paragraph

Perhaps one work around would be to have methods inside A that do something like:A::get_a1() {return this->a1} or something, but I'm also not sure if that's really the correct design solution here.

would be the right solution to me.

However, I have created dozens of classes (in C# though, but the underlying problem was the same) with a bunch of member variables in each. I also needed to access these member variables, like you do. You only need to read as far as I can see. I am writing them, too.

My solution was not a pair of get/set function for each member (which means for n members you gotta create 2*n functions), but having only 1 get-function and 1 set-function (or 1 of get/set for each variable type). The choice which variable has to be set is done by passing an integer variable (an Enum, to be exact: PID, parameter ID) with those functions:

```<code>int GetValue (EnumPID i_enPID, out int    o_iValue);
int GetValue (EnumPID i_enPID, out double o_dValue);
int GetValue (EnumPID i_enPID, out String o_sValue);  // C#
...
int SetValue (EnumPID i_enPID, int    i_iValue);
int SetValue (EnumPID i_enPID, double i_dValue);
int SetValue (EnumPID i_enPID, String i_sValue);  // C#
...
// the int return value is the result of the function: SUCCESS (=1), failure (= 1001 upwards).
// Actually, it's an Enum in my case, too, (EnumResult)...
</code>```

The credits for this solution go to my former boss, who showed me this kind of design.

It has been working perfectly in C# since.

Body:
If you want to avoid an extra "data transfer class" like suggested by @Robert Harvey, you need to access your member variables by getter and setter functions.

Thus your approach described in your last paragraph

Perhaps one work around would be to have methods inside A that do something like:A::get_a1() {return this->a1} or something, but I'm also not sure if that's really the correct design solution here.

would be the right solution to me.

However, I have created dozens of classes (in C# though, but the underlying problem was the same) with a bunch of member variables in each. I also needed to access these member variables, like you do. You only need to read as far as I can see. I am writing them, too.

My solution was not a pair of get/set function for each member (which means for n members you gotta create 2*n functions), but having only 1 get-function and 1 set-function (or 1 of get/set for each variable type). The choice which variable has to be set is done by passing an integer variable (an Enum, to be exact: PID, parameter ID) with those functions:

int GetValue (EnumPID i_enPID, out int    o_iValue);
int GetValue (EnumPID i_enPID, out double o_dValue);
int GetValue (EnumPID i_enPID, out String o_sValue);  // C#
...
int SetValue (EnumPID i_enPID, int    i_iValue);
int SetValue (EnumPID i_enPID, double i_dValue);
int SetValue (EnumPID i_enPID, String i_sValue);  // C#
...
// the int return value is the result of the function: SUCCESS (=1), failure (= 1001 upwards).
// Actually, it's an Enum in my case, too, (EnumResult)...

The credits for this solution go to my former boss, who showed me this kind of design.

It has been working perfectly in C# since.


问:
Handle multiple data writings per second
I am planning a website with an html/javascript frontend input and a php backend. The user has to input data which will be saved in a database. Now I want to inform the other users of my site accordingly about the changes made on the database.

Is this possible in any way (at this point of planning I cannot say how many people will use this in the end so it has to be a user friendly option).

The concept I have is following:
I type in a message like Hello then the other user should be informed about the fact that the last word was Hello so that they can add a new word like World. But the fact that some user are faster than others the word will be fastly outdated. So i have to find a solution for that.

Any suggestions or is my question unclear?

答: Your best bet for this if your intended clients have sufficiently modern web browsers is Web Sockets. There are plenty of libraries out there that you can use and can look into. The one I have used most recently for PHP projects is Pusher, but searching for 'PHP websockets' turns up plenty of libraries and code samples you could use.</p>


答:
I recommend abstracting this up a level, especially if you find you need a1 and a2 in multiple locations. The steps go something like this:

Identify what data the function requires.

Conceptually group the data together into its own unit.

Describe the data. What does this data represent?

Create an interface1 named after the description of the data.

Now you inherit from the interface in class A, and class B's function takes a reference to the new interface.

Benefits:

Loose coupling: you decouple the two classes. If B needs to know about data that A has but it is not appropriate for them to be tightly coupled, the interface adds a layer of abstraction that keeps the design clean (even if a little larger).

Code reuse: if the data in the interface is applicable other places, you can reuse the interface.

If a particular use of the interface lends itself more toward Robert Harvey's suggestion of using a Data Transfer class, you can create a bare-bones implementation of the interface (pure virtual class) and use it. The two classes would then be interchangeable as far as users of the interface are concerned, which adds flexibility.

Code example:

```<code>class Foo {
public:
  int getA1() const = 0;
  int getA2() const = 0;
};

class A : public Foo {
  int a1, a2, a3;
public:
  // C++11 adds the "override" keyword.
  int getA1() const override { return a1; }
  int getA2() const override { return a2; }
  int getA3() const { return a3; }
}

class B {
public:
  void foo(const Foo& foo) {
    foo.getA1();
    foo.getA2();
  }
}

b.foo(a);
</code>```

Note: it may also be valid to have class A contain a Foo via composition rather than implement it via inheritance. This is probably the better solution, but based on the wording of your question I felt the above solution was more appropriate. Here is a code example for completeness:

```<code>class Foo {
  int a1, a2;
public:
  int getA1() const { return a1; }
  int getA2() const { return a2; }
};

class A {
  int a3;
  Foo foo;
public:
  const Foo& getFoo() const { return foo; }
  int getA3() const { return a3; }
}

class B {
public:
  void foo(const Foo& foo) {
    foo.getA1();
    foo.getA2();
  }
}

b.foo(a.getFoo());
</code>```

1 C++ has no interface keyword like certain other languages do. Nor does it have a concept of an abstract or pure virtual class: these concepts only apply to functions in classes. In this context, a C++ interface means a class where all functions are pure virtual. The only exceptions are constructors and the destructor, which cannot be virtual and must exist even if the compiler generates them for you. Also note that the destructor must be declared virtual for any class designed to have subclasses.

Title: How to share data members between classes in C++ without violating encapsulation too much

Body:
In C++ let's say I have some class A:

```<code>Class A
      {
      int a1, a2, a3;

      void foo();
      }
</code>```

and I need to use a subset of members (a1, a2) in a member function for a second class B.

What I'm wondering is whether I should define the arguments of B's member function by passing a pointer to A as an argument, or whether I should pass the members of A as arguments. e.g.,

```<code>Class B
      {
      int b1, b2;

      void bar(A &a);
      }
</code>```

or should this be

```<code>Class B
      {
      int b1, b2;

      void bar(int a1, int a2);
      }
</code>```

The latter would seem to minimize having to violate encapsulation, because B can then be largely agnostic about the constituents of A; whereas, in the former case, B would have to know something about the members of A. So it would seem the second implementation would be preferable.

Another reason the first implementation seems problematic to me is that, ideally, I'd like to keep the members (a1, a2, a3) of A protected rather than public. Normally I'd be tempted to make B a friend class of A, but the problem here is that A and B will both each have several derived classes, and since friendship doesn't inherit in C++ that wouldn't seem to be a good solution.

So these reasons would argue for using something like the second definition of B. However, in the actual code I'm dealing with, there are quite a few (about 6 or more) members of A that B will require, so this could get unwieldy. Being able to just pass a pointer to A would seem preferable from a readability standpoint and hide the details of what B.bar() requires from other parts of the code that deal with B.

Perhaps one work around would be to have methods inside A that do something like:A::get_a1() {return this->a1} or something, but I'm also not sure if that's really the correct design solution here.

Body:
I recommend abstracting this up a level, especially if you find you need a1 and a2 in multiple locations. The steps go something like this:

Identify what data the function requires.

Conceptually group the data together into its own unit.

Describe the data. What does this data represent?

Create an interface1 named after the description of the data.

Now you inherit from the interface in class A, and class B's function takes a reference to the new interface.

Benefits:

Loose coupling: you decouple the two classes. If B needs to know about data that A has but it is not appropriate for them to be tightly coupled, the interface adds a layer of abstraction that keeps the design clean (even if a little larger).

Code reuse: if the data in the interface is applicable other places, you can reuse the interface.

If a particular use of the interface lends itself more toward Robert Harvey's suggestion of using a Data Transfer class, you can create a bare-bones implementation of the interface (pure virtual class) and use it. The two classes would then be interchangeable as far as users of the interface are concerned, which adds flexibility.

Code example:

class Foo {
public:
  int getA1() const = 0;
  int getA2() const = 0;
};

class A : public Foo {
  int a1, a2, a3;
public:
  // C++11 adds the "override" keyword.
  int getA1() const override { return a1; }
  int getA2() const override { return a2; }
  int getA3() const { return a3; }
}

class B {
public:
  void foo(const Foo& foo) {
    foo.getA1();
    foo.getA2();
  }
}

b.foo(a);

Note: it may also be valid to have class A contain a Foo via composition rather than implement it via inheritance. This is probably the better solution, but based on the wording of your question I felt the above solution was more appropriate. Here is a code example for completeness:

class Foo {
  int a1, a2;
public:
  int getA1() const { return a1; }
  int getA2() const { return a2; }
};

class A {
  int a3;
  Foo foo;
public:
  const Foo& getFoo() const { return foo; }
  int getA3() const { return a3; }
}

class B {
public:
  void foo(const Foo& foo) {
    foo.getA1();
    foo.getA2();
  }
}

b.foo(a.getFoo());

1 C++ has no interface keyword like certain other languages do. Nor does it have a concept of an abstract or pure virtual class: these concepts only apply to functions in classes. In this context, a C++ interface means a class where all functions are pure virtual. The only exceptions are constructors and the destructor, which cannot be virtual and must exist even if the compiler generates them for you. Also note that the destructor must be declared virtual for any class designed to have subclasses.


问:
How to handle the default time when user is selecting dates to filter on?
We have an ASP.NET application which allows users to report on their data. We have a number of reports that the user selects the start and end date from a datepicker and then we returned the filtered result.

By default the time from the datepicker is 00:00:00

In translating the query for the database, we have always queried as such:

```<code>WHERE Date >= @DateMin and Date < @DateMax
</code>```

So if we the developers wanted to return a months worth of data (such as June) we would naturally choose 1st June as our start date and 1st July as the end date. Its only in watching some users work that we realised that they would be searching for a months worth of data by using 1st June and 30th June as start/end dates. Therefore losing a whole day's worth of data from their report.

I've been trying to find out if there are any best practices for handling the time when a user selects only the date. Should we be defaulting the end date time to 23:59:59? Is that what other products do?

Reporting on data and allowing users to select the date range seems such a common occurrence that I'm surprised my internet searches haven't returned anything. So how is it best to handle the time portion when a user is selecting a date range?

答: Time on a date-only object is usually midnight.   So if you add one to your ending day, you'll get the correct range; it will include the entire last day, up to midnight.</p>


问:
Proper way to interpret this dereference operation?
I've seen this example in a text book and am a little confused how to interpret the operator precedence rules. Given this struct:

```<code>   typedef struct {
   char *data;
   size_t start, end;
   } str_wends;
</code>```

Let B be declared as a pointer to this struct,that is.

```<code>   str_wends *B = malloc(sizeof(str_wends));
</code>```

and assume B->start != 0,

then this should be a legal construct:

```<code>   &B->data[B->start]
</code>```

which will return a reference to the string offset by B->start. The question is how to interpret the precedence rules. Since we know that -> and [] have the same precedence and bind left to right, why is B->Start evaluated before B->data[].

答:
Concerning this:

```<code>&B->data[B->start]
</code>```

you assert in comments that:

If I read the tokens from left to right, the operators are ->, [], ->

But those are not the operators reading left to right: you're including the closing ] with the opening [, even though the -> comes between them. That doesn't make any sense. When you see [expression], the inner expression doesn't have a precedence with respect to [] at all - it's an argument to it.

The code tokenizes as:

```<code>& B -> data [ B -> start ]
</code>```

and the grammar rule for [] is approximately:

```<code>lvalue [ rvalue ]
</code>```

This must reduce to lvalue:(B->data) [ rvalue:(B->start) ].
It cannot reduce to something like B -> (data [ B) -> (start ]), it simply isn't well-formed. This is an issue of grammar, not precedence.

Body:
Concerning this:

&B->data[B->start]

you assert in comments that:

If I read the tokens from left to right, the operators are ->, [], ->

But those are not the operators reading left to right: you're including the closing ] with the opening [, even though the -> comes between them. That doesn't make any sense. When you see [expression], the inner expression doesn't have a precedence with respect to [] at all - it's an argument to it.

The code tokenizes as:

& B -> data [ B -> start ]

and the grammar rule for [] is approximately:

lvalue [ rvalue ]

This must reduce to lvalue:(B->data) [ rvalue:(B->start) ].
It cannot reduce to something like B -> (data [ B) -> (start ]), it simply isn't well-formed. This is an issue of grammar, not precedence.


问:
How to find a programming mentor?
I decided to learn programming. I've been reading SO for few days, and I think I will start with C++, as I read some articles. I am aware of loops, arrays, program logic and objects a little and I need someone to look me over and help me with small questions I get when doing my first projects.

So here is the question - where do I find such guy? I don't got any friends who program and all.

EDIT: 2 years later, I am still looking for mentor. I did not actively code just started 3 months again. I work on Objective-C and iOS programming and game programming with Cocos2d. If you want to become my mentor, drop me a or comment.

答:
Open source projects are great at getting feedback on specific code you've added and potentially new ways to do things, but as you figured out, that probably won't amount to a mentor relationship.

I'd suggest what you've already mentioned and that is user groups.  User groups usually gather fairly frequently so you can get actual face time with potential mentors.  This face time can allow for a quicker, easier flow of communication.  Will it guarantee that everyone is in the same domain? No, but you have to start somewhere.  If you find someone who has a lot of experience, they may still be able to help you with your domain, just based on other experiences they've had.

Title: How to find a programming mentor?


问:
How much effort should I put into the functional specification?
I've spent six full days so far working on a spec for a web-app component. Apart from personally wanting some task that doesn't involve Word, I'm wondering if there is a point at which I know that the spec I'm working on is finished (but isn't a spec a constant work-in-progress?). I feel that the spec still doesn't explain a good solution for all the requirements I have, so I'm still on it.

Is there any good heuristic or red flag that says I should stop working on a spec?

Note:
As opposed to this question and it's answers, I am looking for a completion metric specific to the design, rather than how to decide when code quality is good enough to know that the implementation is complete.

答:
What you are looking for is traceability.

Whether you use old-school waterfall or more modern iterative approaches, a unit of functionality necessarily follows a simple process:

Define business requirements.

Define functional requirements.

Define technical requirements.

Design the software. <-- You are here

Implement the software.

Test the software.

At each step of the process, you should be able to trace your requirements back and forth between steps.

Each functional requirement (the system shall have function X) must be traceable to a business requirement (we need a system to do X). Note that a business requirement is normally high level and spawns many functional requirements.

Each design element traces back to a functional requirement. E.g. the form elements on this screen all support functional requirement X. All of the data requirements in this functional or technical requirement are satisfied by this screen or interface.

When you have 100% coverage throughout the whole process, you know your design is functionally complete.

But wait! Can the design be implemented reasonably? The key here is collaboration. This is where design reviews come into play. Get the key players involved: customer, project management, developers, and QA. Can the design be implemented? Can it be tested? Does it really satisfy the requirements? Once the team comes to a consensus, you are likely done with the design.


问:
Are data type declarators like "int" and "char" stored in RAM when a C program executes?
When a C program is running, the data is stored on the heap or the stack. The values are stored in RAM addresses. But what about the type indicators (e.g., int or char)? Are they also stored?

Consider the following code:

```<code>char a = 'A';
int x = 4;
</code>```

I read that A and 4 are stored in RAM addresses here. But what about a and x? Most confusingly, how does the execution know that a is a char and x is an int? I mean, is the int and char mentioned somewhere in RAM?

Let's say a value is stored somewhere in RAM as 10011001; if I am the program which executes the code, how will I know whether this 10011001 is a char or an int?

What I don't understand is how the computer knows, when it reads a variable's value from an address such as 10001, whether it is an int or char. Imagine I click on a program called anyprog.exe. Immediately the code starts executing. Does this executable file include information on whether the variables stored are of the type int or char?

答:
My answer here is somewhat simplified and will refer only to C.

No, type information does not get stored in the program.

int or char are not type indicators to the CPU; only to the compiler.

The exe created by the compiler will have instructions to manipulate ints if the variable was declared as an int. Likewise, if the variable was declared as a char, the exe will contain instructions to manipulate a char.

In C:

```<code>int main()
{
    int a = 65;
    char b = 'A';
    if(a == b)
    {
        printf("Well, what do you know. A char can equal an int.\n");
    }
    return 0;
}
</code>```

This program will print its message, since the char and the int have the same values in RAM.

Now, if you are wondering how printf manages to output 65 for an int and A for a char, that is because you have to specify in the "format string" how printf should treat the value.

(For example, %c means to treat the value as a char, and %d means to treat the value as an integer; same value either way, though.)

Body:
My answer here is somewhat simplified and will refer only to C.

No, type information does not get stored in the program.

int or char are not type indicators to the CPU; only to the compiler.

The exe created by the compiler will have instructions to manipulate ints if the variable was declared as an int. Likewise, if the variable was declared as a char, the exe will contain instructions to manipulate a char.

In C:

int main()
{
    int a = 65;
    char b = 'A';
    if(a == b)
    {
        printf("Well, what do you know. A char can equal an int.\n");
    }
    return 0;
}

This program will print its message, since the char and the int have the same values in RAM.

Now, if you are wondering how printf manages to output 65 for an int and A for a char, that is because you have to specify in the "format string" how printf should treat the value.

(For example, %c means to treat the value as a char, and %d means to treat the value as an integer; same value either way, though.)