答:
Historically, C regarded memory as consisting of a number of groups of numbered slots of type unsigned char (also called "byte", though it need not always be 8 bits).  Any code which used anything stored in memory would need to know which slot or slots the information was stored in, and know what should be done with the information there [e.g. "interpret the four bytes starting at address 123:456 as a 32-bit floating-point value" or "store the lower 16 bits of the most recently computed quantity into two bytes starting at address 345:678].  The memory itself would neither know nor care what the values stored in the memory slots "meant".  If code tried to write memory using one type and read it as another, the bit patterns stored by the write would be interpreted according to the rules of the second type, with whatever consequences might result.

For example, if code were to store 0x12345678 to a 32-bit unsigned int, and then attempt to read two consecutive 16-bit unsigned int values from its address and the one above, then depending upon which half of the unsigned int was stored where, the code might read the values 0x1234 and 0x5678, or 0x5678 and 0x1234.

The C99 Standard, however, no longer requires that memory behave as a bunch of numbered slots that know nothing about what their bit patterns represent.  A compiler is allowed to behave as though memory slots are aware of the types of data that are stored into them, and will only allow data which is written using any type other than unsigned char to be read using either type unsigned char or the same type as it was written with; compilers are further allowed to behave as though memory slots have the power and inclination to arbitrarily corrupt the behavior of any program which tries to access memory in a fashion contrary to those rules.

Given:

```<code>unsigned int a = 0x12345678;
unsigned short p = (unsigned short *)&a;
printf("0x%04X",*p);
</code>```

some implementations might print 0x1234, and others might print 0x5678, but under the C99 Standard it would be legal for an implementation to print "FRINK RULES!" or do anything else, on the theory that it would be legal for the memory locations holding a to include hardware that records what type was used to write them, and for such hardware to respond to an invalid read attempt in any fashion whatsoever, including by causing "FRINK RULES!" to be output.

Note that it doesn't matter if any such hardware actually exists--the fact that such hardware could legally exist makes it legal for compilers to generate code which behaves as though it's running on such a system.  If the compiler can determine that a particular memory location will be written as one type and read as another, it can pretend that it's running on a system whose hardware could make such determination, and could respond with whatever degree of capriciousness the compiler author sees fit.

The purpose of this rule was to allow compilers which knew that a group of bytes holding a value of some type held a particular value at some point in time, and that no value of that same type had been written since, to infer that that group of bytes would still hold that value.  For example, a processor had read a group of bytes into a register, and then later on wanted to use the same information again while it was still in the register, the compiler could use the register contents without having to reread the value from memory.  A useful optimization.  For about the first ten years of the rule, violating it would generally mean that if a variable is written with a type other than one which is used to read it, the write may or may not affect the value read.  Such behavior may in some cases be disastrous, but in other cases may be harmless, especially if the code which is reading the value would be equally happy with the value written or the value held before the write, or even more so if the value written happened to match the value already held.

Around 2009, however, the authors of some compilers like CLANG have determined that since the Standard allows compilers to do anything they like in cases where memory is written using one type and read as another, compilers should infer that programs will never receive input that could cause such a thing to occur.  Since the Standard says the compiler is allowed to do anything it likes when such invalid input is received, code which would only have an effect in cases where the Standard imposes no requirements may (and in the view of some compiler authors, should) be omitted as irrelevant.  This changes the behavior of aliasing violations from being like memory that which, given a read request, may arbitrarily return the last value written using the same type as a read request or any more recent value written using some other type, to being like memory which will capriciously alter program behavior any time the Standard would allow it to do so.

Title: Are data type declarators like "int" and "char" stored in RAM when a C program executes?

Body:
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?

Body:
Historically, C regarded memory as consisting of a number of groups of numbered slots of type unsigned char (also called "byte", though it need not always be 8 bits).  Any code which used anything stored in memory would need to know which slot or slots the information was stored in, and know what should be done with the information there [e.g. "interpret the four bytes starting at address 123:456 as a 32-bit floating-point value" or "store the lower 16 bits of the most recently computed quantity into two bytes starting at address 345:678].  The memory itself would neither know nor care what the values stored in the memory slots "meant".  If code tried to write memory using one type and read it as another, the bit patterns stored by the write would be interpreted according to the rules of the second type, with whatever consequences might result.

For example, if code were to store 0x12345678 to a 32-bit unsigned int, and then attempt to read two consecutive 16-bit unsigned int values from its address and the one above, then depending upon which half of the unsigned int was stored where, the code might read the values 0x1234 and 0x5678, or 0x5678 and 0x1234.

The C99 Standard, however, no longer requires that memory behave as a bunch of numbered slots that know nothing about what their bit patterns represent.  A compiler is allowed to behave as though memory slots are aware of the types of data that are stored into them, and will only allow data which is written using any type other than unsigned char to be read using either type unsigned char or the same type as it was written with; compilers are further allowed to behave as though memory slots have the power and inclination to arbitrarily corrupt the behavior of any program which tries to access memory in a fashion contrary to those rules.

Given:

unsigned int a = 0x12345678;
unsigned short p = (unsigned short *)&a;
printf("0x%04X",*p);

some implementations might print 0x1234, and others might print 0x5678, but under the C99 Standard it would be legal for an implementation to print "FRINK RULES!" or do anything else, on the theory that it would be legal for the memory locations holding a to include hardware that records what type was used to write them, and for such hardware to respond to an invalid read attempt in any fashion whatsoever, including by causing "FRINK RULES!" to be output.

Note that it doesn't matter if any such hardware actually exists--the fact that such hardware could legally exist makes it legal for compilers to generate code which behaves as though it's running on such a system.  If the compiler can determine that a particular memory location will be written as one type and read as another, it can pretend that it's running on a system whose hardware could make such determination, and could respond with whatever degree of capriciousness the compiler author sees fit.

The purpose of this rule was to allow compilers which knew that a group of bytes holding a value of some type held a particular value at some point in time, and that no value of that same type had been written since, to infer that that group of bytes would still hold that value.  For example, a processor had read a group of bytes into a register, and then later on wanted to use the same information again while it was still in the register, the compiler could use the register contents without having to reread the value from memory.  A useful optimization.  For about the first ten years of the rule, violating it would generally mean that if a variable is written with a type other than one which is used to read it, the write may or may not affect the value read.  Such behavior may in some cases be disastrous, but in other cases may be harmless, especially if the code which is reading the value would be equally happy with the value written or the value held before the write, or even more so if the value written happened to match the value already held.

Around 2009, however, the authors of some compilers like CLANG have determined that since the Standard allows compilers to do anything they like in cases where memory is written using one type and read as another, compilers should infer that programs will never receive input that could cause such a thing to occur.  Since the Standard says the compiler is allowed to do anything it likes when such invalid input is received, code which would only have an effect in cases where the Standard imposes no requirements may (and in the view of some compiler authors, should) be omitted as irrelevant.  This changes the behavior of aliasing violations from being like memory that which, given a read request, may arbitrarily return the last value written using the same type as a read request or any more recent value written using some other type, to being like memory which will capriciously alter program behavior any time the Standard would allow it to do so.


问:
Does the issue of battery life for constant polling warrant the extra logic/time to implement a solution with websockets?
I am in the process of designing a chat application with cordova for android devices. I have been researching and have come to the conclusion that there are two ways to go about this that could work.

Websockets. Using websockets the client application could send a message to a webserver, the webserver could lookup the ip address of the recipient within a database and send the message to the recipient. This will require much more logic on the server but will eliminate the need for constant polling. This method would also require a constant loop on the client that would detect network changes and send the updated ip address to the webserver so that the webserver would know where to send the message.

Constant polling. Have client application constantly poll the web server for updates. This would be the easiest method as server logic would be limited. Also there would be no need for logic in the application to handle the case when users switch networks. However the common consensus is to stay away from designs that utilize constant polling as it is a massive drain on device battery life.

My question is then: Does the issue of battery life for constant polling warrant the extra logic/time to implement a solution with websockets?

答:
Web Sockets are the better choice

The problem with constant polling is that, much like sending small bursts of data (which it pretty much amounts to), your device goes into an 'idle' state that it has to 'wake up' from in between polls. There is a high cost associated with making the initial connection and this cost is repeated for every poll you perform. And this adds up. For a chat application where you would need to poll every few seconds to keep it responsive you'd drain the battery in no time.

See also this answer on android.SE

Web sockets are not that hard anyway. There are plenty of libraries out there that can help you, and take care of the issues you list for you.

ContentLicense: CC BY-SA 3.0


问:
Figuring out the mean of a stream of data, disregarding values that are way off bounds
I have a stream of integer data and want to perform some statistical analysis on it. I want to calculate the mean and the standard deviation of it. So far it isn't hard, but keep in mind that I am talking about streams of data, I'd prefer not to store all of the data. There exists both an algorithm for the mean and the deviation to keep the stored data at a minimum - I'd refer to Wikipedia in this matter.

But the problem now is that some of the data will be completely absurd in regards to the rest of the data. For example I will receive

```<code>1 2 2134 7 -2 14 // 2134 is out of line and junk, don't calculate with it
</code>```

I know in what ranges my values will likely be, but only relative to their average value. So I'd like to know if there is a good approach to tackle these kind of noises.

It is even more annoying, as the junk data will most likely be the first to arrive and not in line with the mean value of the rest of the sequence so I can't precalculate the mean value. An example would be something like

```<code>1111 1564 13 1645 12 -4 37 90 ...
</code>```

The junk makes < 5% of the data, so at least there isn't much noise, but I have to keep it out of my calculation.

To distinguish between real and junk data, I know that the real data lies in a bounded interval around the mean value - scaled to the example above, it would be something like +-200. "Groups" of junk data can behave in the same way, only that their mean value differs by at least 1 times the length of the interval from the mean value of the real data.

At the beginning, without any data, I have no idea what the mean value of the real data might be.

I can replay a limited amount/small fraction of data only by first saving it to memory.

Is there a good algorithm that occupies as little as possible space and works when applied iteratively to a sequence?

答: Signal processing is a huge topic, and a lot depends on your application, but a good start for your research would be a Kalman filter.  It's recursive, so it doesn't require storing the entire history, and is commonly used for tasks like filtering outliers out of a sensor signal.  </p>


问:
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?

答:
The other answers are correct in that essentially every consumer device you will encounter doesn't store type information. However, there have been several hardware designs in the past (and the present day, in a research context) that use a tagged architecture -- they store both the data and the type (and possibly other information as well). These would most prominently include the Lisp machines.

I vaguely recall hearing about a hardware architecture designed for object-oriented programming that had something similar, but I can't find it now.


问:
Integer conversion with Console.ReadLine()
To read an integer from user input, you can use:

```<code>int number = Convert.ToInt32(Console.ReadLine());
</code>```

But why won't the following work?

```<code>int number = (int) Console.ReadLine();
</code>```

What's the difference between Convert.ToInt32 and casting with (int)?

答:
This might help understand why this doesn't work.

"Hi " + "there" = "Hi there", right?

1 + 3 = 4

What does "Hi " + 2 = ?

It makes no sense.

Since Console.ReadLine returns a string, the language has no way of knowing whether you're going to enter a number or not.  So it requires you to instead make an explicit statement that you're going to turn the input into a number, and that's what int.Parse does.  Convert calls this method - but like said above it's not as precise as calling Parse.


问:
Code review lags behind the Deliver/Test Cycle
In our Agile process we have 2-week Sprints. Tasks are delivered on a daily basis (daily builds), and the Test Team completes their testing immediately the next day or even the same day.

We also have Dev code reviews, which require some time (1-2 hrs), so they are scheduled 3 times a week: Mon-Weds-Fri. Developers get together and suggest how to improve/refactor code.

Our problem is, by the time Action Items come up after a code review, most of the tasks have already been tested. Testers don't want to re-test what already passed their tests. They don't care about internal dev changes.

Are we misunderstanding the Agile process? Are code reviews incompatible with a daily Release/Test cycle? We can't hold code reviews every day, as they take up everyone's time.

答: Testers don't want to re-test is kind of like saying "coders don't want to refactor."  Its part of the job.  The process can be restated as something like this: Tasks are created. Code is generated. Code is tested.  Code is reviewed. Imperfections are found in the code. New Tasks are created to address these imperfections (e.g. the code is refactored).  These new tasks require new testing.  </p>

OwnerDisplayName: gene b.

OwnerDisplayName: John


问:
Do you actually write 'clean code'?
I have seen some programmers tweaking their code over and over again not only to make it 'work good', but also to make it 'look good'.

IMO, 'clean code' is actually a compliment indicating your code is elegant, perfectly understandable and maintainable. And the difference comes out when you have to choose between an aesthetically appealing code vs. code that's stressful to look at.

So, how many of you actually write 'clean code'? Is it a good practice? What are the other benefits or drawbacks of this?

答:
I would argue that many of us do not write clean code. And generally, that's not our job. Our job as software developers is to deliver a product that works, on time.

I am reminded of Joel Spolsky's blog post: The Duct Tape Programmer.

He quotes from Coders at Work:

At the end of the day, ship the
  f*****g thing! It’s great to rewrite
  your code and make it cleaner and by
  the third time it’ll actually be
  pretty. But that’s not the
  point—you’re not here to write code;
  you’re here to ship products. - Jamie Zawinsky

I am also reminded of Robert Martin's blog response:

So. Be smart. Be clean. Be simple.
  Ship! And keep a small roll of duct
  tape at the ready, and don’t be afraid
  to use it. - Uncle Bob

If the code,a developer writes happens to be clean AND work (is deliverable), so be it, good for everyone. But if a developer is tinkering around trying to make clean and readable code at the expense of being able to deliver it timely, then that's bad. Make it work, use duct tape, and ship it. You can refactor it later and make it super gorgeous and efficient.

Yes, it's good practice to write clean code, but never at the expense of being able to deliver. The benefit of delivering a duct-taped product on time far outweighs the benefits of clean code that was never finished and delivered.

A good chunk of code I've come across isn't clean. Some are downright ugly.  But they were all released and used in production. Some may say that it's unprofessional to write messy code. I disagree. The professional thing is to deliver code that works, whether it's clean or messy. The developer must do the best he/she can, given whatever time that was allocated before delivery. Then, go back to clean up-- that's professional. Hopefully, the code delivered isn't pure duct tape and is 'clean enough'.

Title: Do you actually write 'clean code'?

ContentLicense: CC BY-SA 4.0


问:
In AngularJS - should $resource be used from controller or service?
All the documentation, examples and tutorials I've found on $resource were using it directly in the controller. So far I'm just using $http from services and those services are further used in the controllers. I thought $resource should replace $http and not my whole service. Is my thinking wrong, or were the examples I've found just so trivial that nobody bothered creating a service?

I've heard once the quote

When you want to create a command line interface for your application and you need to copy code out of the controller, than the controller has too much logic and it should be in a service.

Now, obviously this depends on the complexity of a controller, let's assume a simple CRUD view with the corresponding controller. It seems like $resource would be all I need and I can take it also to create a console application without caring about anything else from the controller. But something inside me is just shouting when I want to access the data ($resource) directly in the controller.

Where is the line to be drawn between when a service is necessary when it's overkill?

答:
When you want to create a command line interface for your application and you need to copy code out of the controller, than the controller has too much logic and it should be in a service.

The reason this works is because your UI's are supposed to be independent of the service.  A command line is a UI, and you shouldn't need a Controller to implement it, since you don't need Views, View Models or any of the other things that are part and parcel of an MVVM controller.


答: This depends on the complexity and the long term goals of your app, but in my experience, your best bet is to wrap your $resource calls in a service since at some point in the future you'll find yourself pre/post processing the intput/output of your $resource calls and it's better to simply attach a new function (or parameter to an existing function) to the service that wraps your $resource calls rather than implement the processing code in every controller where you use the $resource. At first it may seem like it's pointless to add a wrapper that simply returns the $resource response immediately, but later on when the complexity grows, you'll be glad you did.</p>

Title: In AngularJS - should $resource be used from controller or service?

Body:
All the documentation, examples and tutorials I've found on $resource were using it directly in the controller. So far I'm just using $http from services and those services are further used in the controllers. I thought $resource should replace $http and not my whole service. Is my thinking wrong, or were the examples I've found just so trivial that nobody bothered creating a service?

I've heard once the quote

When you want to create a command line interface for your application and you need to copy code out of the controller, than the controller has too much logic and it should be in a service.

Now, obviously this depends on the complexity of a controller, let's assume a simple CRUD view with the corresponding controller. It seems like $resource would be all I need and I can take it also to create a console application without caring about anything else from the controller. But something inside me is just shouting when I want to access the data ($resource) directly in the controller.

Where is the line to be drawn between when a service is necessary when it's overkill?


问:
Could a class with only auto properties could be a new language type and act like an interface?
Would it be useful define a type in C# that defines something similar to a data table so it can be instantiated but may not contain logic and also act as an interface?

In addition I'm thinking this could be used in place/in addition to interfaces.

```<code>record A
{
    string S { get; set; }
}
</code>```

could be "syntactic sugar" for

```<code>interface A
{
    string S { get; set; }
}
class A : A
{
    public string S { get; set; }
}
</code>```

Of course there's a name collision here.  That's why it would need to be a language level feature (as opposed to something that could be done with a T4 template for example).

One could instantiate A.  One could implement A.  If there were B and C, then one could implement all three.

My intuition is that this would not be sufficient to bring the down side of multiple inheritance but may open up implementation patterns which would be cleaner and few lines.

Here's one Example of not needing to define the interface and the reason I like the separation of data and functions is because I'm thinking of generic repositories that model the real world and separate libraries of functions that act on them...

```<code>// records exist as pure domain objects, possibly even standardized
record Entity
{
    public string FullName { get; set; }
}
record Dimensions
{
    public float Length { get; set; }
    public float Width { get; set; }
    public float Height { get; set; }
}
class Person : Entity, Dimensions
{
    // tooling is used to generate these members
    // name collisions are resolved using explicit member declaration
    public string FullName { get; set; }
    public float Length { get; set; }
    public float Width { get; set; }
    public float Height { get; set; }
}
static class Extensions
{
    public static void GetNameParts(this Entity target, out string first, out string last)
    {
        first = "todo";
        last = "todo";
    }

    public static float CalculateVolume(this Dimensions target)
    {
        return target.Length * target.Width * target.Height;
    }
}
</code>```

Update:
"Partial-Assignment" might also be useful:

```<code>var entity = new Entity { FullName = "Jim Bob" };
var person = new Person { Entity = entity }; // Entity exists implicitly in this context
</code>```

The implicit property with the same name as the inherited record is also used to easily access members which may have the same names but come from different types.

答:
I think i understand OPs question (it was somewhat vague at first).

Although now, I'm not so sure, after reading it again a few times.

The question (as i understand it) summarized:

Is there room in C# for a interface-like construct (proposed name: record), which may only contain auto-properties, but also has the advantages of an interface in where a class can inherit multiple of these "records" at once.

OPs design example:

Records:

```<code>record Entity
{
    public string FullName { get; set; }
}
record Dimensions
{
    public float Length { get; set; }
    public float Width { get; set; }
    public float Height { get; set; }
}
</code>```

A class implementing the two records

I'm guessing that these properties are actually "not visible" in the class (and are just described by OP)

```<code>class Person : Entity, Dimensions
{
    public string FullName { get; set; }
    public float Length { get; set; }
    public float Width { get; set; }
    public float Height { get; set; }
}
</code>```

Extensions for Entity.

```<code>static class Extensions
{
    public static void GetNameParts(this Entity target, out string first, out string last)
    {
        first = "todo";
        last = "todo";
    }

    public static float CalculateVolume(this Dimensions target)
    {
        return target.Length * target.Width * target.Height;
    }
}
</code>```

Background

At one point i was somewhat annoyed that interface-properties were not "automatic", that you always had to be manually implemented the properties you had already written in your interface, in your then later derived classes.

I was also annoyed that derived classes only could inherit one class at the time.

This created the perfect annoyance where one could no "lazily" implement multiple interfaces or classes.

Solution

This is the solution I have realized, and I find it's working for me. I'm not claiming it's "the correct one".

Grit your teeth, and use more abstraction. Create "common" abstract (or concrete) classes that are "half way there". For instance.

You have the following interfaces

IEntity - base interface for all database-entities

ILinkable- defines that the entity can be visited vi a URL

IInFolder - defines that the entity is in a folder

ILoggedEntity - defines that the entity has creation and edited-dates.

You can then create an abstract class which implements these, as such:

```<code>public abstract class Article : IEntity, ILinkable, IInFolder, ILoggedEntity
{
    public Guid Id { get; set; } // From IEntity
    public DateTime Created { get; set; } // From ILoggedEntity
    public DateTime Edited { get; set; } // From ILoggedEntity
    public string Url { get; set; } // From ILinkable
    public Folder Folder { get; set; } // From IInFolder
}
</code>```

Entities like Page, Product, Picture, File etc... can all inherit Article which saves loads of effort, and is generally considered a good design-pattern.

Usually it doesn't start out with the creation of these abstract half-way-there-classes. It's often a matter of going back through the code and refactoring where "common patterns" occur. — At least that's my experience. I guess it also depends on how your specific company designs your software, if there is an elaborate design phase where class-diagrams and similar are made. Then i guess these things are realized before the coding-phase has begun.

— But back to the question at hand.

Is there room in C# for a "record"-construct?

I'm not a language-designer, these are just my thoughts.

The described record-construct would be kind of nice, I'm not gonna lie.
But the only problem is, it really only solves a "minor annoyance", it doesn't really add much functionality to the language. Interfaces still get the job done nicely.

Ultimately though; isn't programming supposed to be as comfortable as possible? Writing extra lines of code takes time. Time costs money; both for your clients and you.

So it boils down to

- The proposed construct does not add much (if any) functionality

+ The proposed construct could for some purposes save time and effort.

— But it also boils down to how hard it is to implement

Implementation

I honestly don't think it would be very hard to implement.
Most of the implementation could be solved via compiler magic. There's already loads of it in C#. Because there would be no need to create a new construct within the compiler. The compiler could simply treat record as an alias for interface; and the properties (if not defined in the derived class) would be implemented as auto-properties.

Is it worth implementing?

In my opinion? — Absolutely.

But maybe not in the proposed form.

But i think a new keyword, such as auto or concrete would be more suitable within the context of an interface, or even re-use any of the other keywords.

Here's an example:

```<code>public interface ILinkable
{
    auto string Url { get; set; }
}
</code>```

Will it be implemented?

Most likely! I'm not saying it will be implemented in Microsofts "official" C#-compiler (not anytime soon at least). But Roslyn seems to be here to stay. If you have not heard of Roslyn (you have missed out), it's basically an open source C#-compiler written in C#. And is now considered stable.

... Roslyn was RTMed with visual studio 2015.

Which i was unaware of, so start you could attempt to implement something like this yourself.

Even if not you, chances are pretty great that somebody (remember you can be somebody) is going to implement something similar to what both you and I have described.

Body:
I think i understand OPs question (it was somewhat vague at first).

Although now, I'm not so sure, after reading it again a few times.

The question (as i understand it) summarized:

Is there room in C# for a interface-like construct (proposed name: record), which may only contain auto-properties, but also has the advantages of an interface in where a class can inherit multiple of these "records" at once.

OPs design example:

Records:

record Entity
{
    public string FullName { get; set; }
}
record Dimensions
{
    public float Length { get; set; }
    public float Width { get; set; }
    public float Height { get; set; }
}

A class implementing the two records

I'm guessing that these properties are actually "not visible" in the class (and are just described by OP)

class Person : Entity, Dimensions
{
    public string FullName { get; set; }
    public float Length { get; set; }
    public float Width { get; set; }
    public float Height { get; set; }
}

Extensions for Entity.

static class Extensions
{
    public static void GetNameParts(this Entity target, out string first, out string last)
    {
        first = "todo";
        last = "todo";
    }

    public static float CalculateVolume(this Dimensions target)
    {
        return target.Length * target.Width * target.Height;
    }
}

Background

At one point i was somewhat annoyed that interface-properties were not "automatic", that you always had to be manually implemented the properties you had already written in your interface, in your then later derived classes.

I was also annoyed that derived classes only could inherit one class at the time.

This created the perfect annoyance where one could no "lazily" implement multiple interfaces or classes.

Solution

This is the solution I have realized, and I find it's working for me. I'm not claiming it's "the correct one".

Grit your teeth, and use more abstraction. Create "common" abstract (or concrete) classes that are "half way there". For instance.

You have the following interfaces

IEntity - base interface for all database-entities

ILinkable- defines that the entity can be visited vi a URL

IInFolder - defines that the entity is in a folder

ILoggedEntity - defines that the entity has creation and edited-dates.

You can then create an abstract class which implements these, as such:

public abstract class Article : IEntity, ILinkable, IInFolder, ILoggedEntity
{
    public Guid Id { get; set; } // From IEntity
    public DateTime Created { get; set; } // From ILoggedEntity
    public DateTime Edited { get; set; } // From ILoggedEntity
    public string Url { get; set; } // From ILinkable
    public Folder Folder { get; set; } // From IInFolder
}

Entities like Page, Product, Picture, File etc... can all inherit Article which saves loads of effort, and is generally considered a good design-pattern.

Usually it doesn't start out with the creation of these abstract half-way-there-classes. It's often a matter of going back through the code and refactoring where "common patterns" occur. — At least that's my experience. I guess it also depends on how your specific company designs your software, if there is an elaborate design phase where class-diagrams and similar are made. Then i guess these things are realized before the coding-phase has begun.

— But back to the question at hand.

Is there room in C# for a "record"-construct?

I'm not a language-designer, these are just my thoughts.

The described record-construct would be kind of nice, I'm not gonna lie.
But the only problem is, it really only solves a "minor annoyance", it doesn't really add much functionality to the language. Interfaces still get the job done nicely.

Ultimately though; isn't programming supposed to be as comfortable as possible? Writing extra lines of code takes time. Time costs money; both for your clients and you.

So it boils down to

- The proposed construct does not add much (if any) functionality

+ The proposed construct could for some purposes save time and effort.

— But it also boils down to how hard it is to implement

Implementation

I honestly don't think it would be very hard to implement.
Most of the implementation could be solved via compiler magic. There's already loads of it in C#. Because there would be no need to create a new construct within the compiler. The compiler could simply treat record as an alias for interface; and the properties (if not defined in the derived class) would be implemented as auto-properties.

Is it worth implementing?

In my opinion? — Absolutely.

But maybe not in the proposed form.

But i think a new keyword, such as auto or concrete would be more suitable within the context of an interface, or even re-use any of the other keywords.

Here's an example:

public interface ILinkable
{
    auto string Url { get; set; }
}

Will it be implemented?

Most likely! I'm not saying it will be implemented in Microsofts "official" C#-compiler (not anytime soon at least). But Roslyn seems to be here to stay. If you have not heard of Roslyn (you have missed out), it's basically an open source C#-compiler written in C#. And is now considered stable.

... Roslyn was RTMed with visual studio 2015.

Which i was unaware of, so start you could attempt to implement something like this yourself.

Even if not you, chances are pretty great that somebody (remember you can be somebody) is going to implement something similar to what both you and I have described.


问:
Is it a common practice among professional programmers to avoid the use of raw pointers?
C++ tools and libraries have become more powerful than ever.

For instance, we can replace arrays by vectors. We can replace pointers by references. We can use smart-pointers.

Is it a common practice among professional programmers to avoid the use of raw pointers?

答:
If you are starting a new green field project that is at a high enough level (as in you're talking about writing an enterprise Foo rather than a device driver) and has no external dependencies you can probably avoid using pointers entirely.  But most development isn't brand new development, it's leveraging the millions of existing lines of C++ code out there which will undoubtedly include pointers.  And even new applications almost always rely on external libraries and other APIs that will frequently use pointers.  So the set of applications that can be built completely without pointers is pretty small.

It may be possible to minimize how much of your code base needs to use pointers.  You may be able to find different libraries that don't rely on pointers (though this generally comes at a cost in performance or functionality).  You can create your own interface on top of existing code and libraries that depend on pointers and use that new interface in the majority of your new code base.  But you're almost always going to sacrifice some performance and/or flexibility when you start adding in new layers.  Whether those trade-offs are acceptable to you will depend heavily on your application.


问:
Analysis of insertion sort does not equal O(n^2)?
I'm learning more about algorithms and data structures.

According to Wikipedia and other reliable sources, an insertion sort has a worst-case time complexity of O(n2). I'm attempting to measure that complexity in code:

```<code>def swap(n, i, j):
    first, second = n[i], n[j]

    n[i] = second
    n[j] = first

def insertion_sort(n):
    size, steps = len(n), 0

    for i in range(1, len(n)):
        j = i
        steps += 1
        while j > 0 and n[j - 1] > n[j]:
            swap(n, j - 1, j)
            steps += 1
            j = j - 1

    return size, steps

print "size: %d, steps: %d" % insertion_sort([i for i in xrange(1000-1, -1, -1)])
</code>```

Above is Python, a simple swap method for swapping values at given indices, and a simple insertion sort algorithm which also holds a count of how many iterations/operations have been performed.

The final line creates an array which looks like [999, 998, ... 0], 1000 items in the worst possible sorting order: reverse.

When I execute this code, I see that for the array of length 1000, I've taken 500499 steps to sort it properly.

Obviously I'm doing something wrong here. Why am I not seeing 10002 (100000) iterations being required, if this is the expected worst-case behavior?

答:
Since the result of your (fixed) code still confuses you, i try to answer your question:

The O-Notation is not an exact formula notation. Only because something is O(1) doesn't mean it takes one single step, only because it is O(n²) doesn't mean it takes n² steps. The O-Notation is an abstract way to define how complex an algorithm is. Sure, you don't get your 1000² for your O(n²) with n = 1000, but that was expected. There is no O(n²/2 plus a few).

Your algorithm has to iterate over every single element and for every singe element, it needs to iterate again over a part of elements, that is essentially quadratic complexity, therefore O(n²)

See here for a list of possible (or rather, commonly used) O-notations.


答:
If you are going to review the code at some point, it's no more expensive to do the review early. And it seems you have an expensive testing process, so you don't want to test twice. Therefore it is cheaper to review the code before testing. Reviewing the code after testing doesn't make the work go faster. It makes it go slower and tempts you to deliver poorly written but successfully tested code. Over time all this un-reviewed code will make the work go slower and slower. Then a more efficient competitor delivers a better product at less cost and it's game over.

Also, automate the testing. Manual testing is so 1970.

Title: Code review lags behind the Deliver/Test Cycle

Body:
In our Agile process we have 2-week Sprints. Tasks are delivered on a daily basis (daily builds), and the Test Team completes their testing immediately the next day or even the same day.

We also have Dev code reviews, which require some time (1-2 hrs), so they are scheduled 3 times a week: Mon-Weds-Fri. Developers get together and suggest how to improve/refactor code.

Our problem is, by the time Action Items come up after a code review, most of the tasks have already been tested. Testers don't want to re-test what already passed their tests. They don't care about internal dev changes.

Are we misunderstanding the Agile process? Are code reviews incompatible with a daily Release/Test cycle? We can't hold code reviews every day, as they take up everyone's time.


问:
Connect PC application to a group of similar hardware devices, using TCP
Our company has started to design a system where many (typically 4 or 6) force-sensitive platforms, containing load-cells, would stream data to the PC via TCP.

Each platform and the PC shall be connected by network cable to a network switch acting as a hub.

Each platform will be running a microcontrolled device, with a firmware to be developed by our supplier.

So my questions are:

What is the recommended client/server relationship between the software application and each one of the peripherals?

Should the application establish one connection for each platform?

At first I would think the platform should be the server (listener), so that it stays continuously in "standby" (listening) when turned on, waiting for the PC to ask to connect to it (I wonder how to specify the correct IP, though...).

But since the PC is only one and the platforms are many, maybe the PC should be the "server", with each peripheral being one of many "clients"? That got me confused...

答:
From consumer point of view, I want a) easy setup and optionally b) things to be connected to the internet.

For point a) the devices should be able to auto discover the server, either on local network (e.g. Zeroconf) or on the internet.

As for b) as you're already planning to use TCP, going for HTTP probably won't add much effort. It can probably help in designing since you won't need to think about protocol to use, how to add security, etc. Especially helpful because the server part would be very easy.


答: O(n2) means that if you increase n from 1000 to 10000 the number of operations will be around 102=100 times bigger (in your case around 50,000,000 operations).

Title: Analysis of insertion sort does not equal O(n^2)?

Body:
I'm learning more about algorithms and data structures.

According to Wikipedia and other reliable sources, an insertion sort has a worst-case time complexity of O(n2). I'm attempting to measure that complexity in code:

```<code>def swap(n, i, j):
    first, second = n[i], n[j]

    n[i] = second
    n[j] = first

def insertion_sort(n):
    size, steps = len(n), 0

    for i in range(1, len(n)):
        j = i
        steps += 1
        while j > 0 and n[j - 1] > n[j]:
            swap(n, j - 1, j)
            steps += 1
            j = j - 1

    return size, steps

print "size: %d, steps: %d" % insertion_sort([i for i in xrange(1000-1, -1, -1)])
</code>```

Above is Python, a simple swap method for swapping values at given indices, and a simple insertion sort algorithm which also holds a count of how many iterations/operations have been performed.

The final line creates an array which looks like [999, 998, ... 0], 1000 items in the worst possible sorting order: reverse.

When I execute this code, I see that for the array of length 1000, I've taken 500499 steps to sort it properly.

Obviously I'm doing something wrong here. Why am I not seeing 10002 (100000) iterations being required, if this is the expected worst-case behavior?


答:
Broadcast: The simplest approach

Given:

Each platform and the PC shall be connected by network cable to a network switch acting as a hub.

It should be safe to assume that the devices are all on the same network. Have each of device toss its data into the broadcast for the network and don't worry about it.  You don't need to configure where the server is, or even if its up at the time (or down, and need to reconnect).  The devices just toss their data and continue on with collecting.

The server is also similarly simple.  It listens for packets that are broadcast to the network, when it gets one, it processes it and continues on with listening for packets.

This is really the simplest thing that you can do, and it will work if everything is on the same network (can get noisy for other things on the network if there are many sensors providing data).

Message queues

If you are willing to invest a bit of time into the devices and what data they are sending out, the use of a message queue can make the architecture easier.  In particular, ZeroMQ which allows for a more formalized structure.

Again, the devices write to a feed and the server reads from it.  Thats the basics of it.  Its a rather flexible approach and there are many architectures that can be applied here depending on the specifics of the need.

If you want to go with something that has guaranteed delivery, look to one that has a more robust message broker.  This then allows for structures that you can reason a bit more about including doing things like having multiple workers/consumers off of the message queue to process the data if the load starts having an issue (but you want to make sure each message only goes to one worker).

Title: Connect PC application to a group of similar hardware devices, using TCP

Body:
Our company has started to design a system where many (typically 4 or 6) force-sensitive platforms, containing load-cells, would stream data to the PC via TCP.

Each platform and the PC shall be connected by network cable to a network switch acting as a hub.

Each platform will be running a microcontrolled device, with a firmware to be developed by our supplier.

So my questions are:

What is the recommended client/server relationship between the software application and each one of the peripherals?

Should the application establish one connection for each platform?

At first I would think the platform should be the server (listener), so that it stays continuously in "standby" (listening) when turned on, waiting for the PC to ask to connect to it (I wonder how to specify the correct IP, though...).

But since the PC is only one and the platforms are many, maybe the PC should be the "server", with each peripheral being one of many "clients"? That got me confused...


答:
If you are finding it hard to get code reviews to happen in the time you currently have before QA, you should consider making code reviews more lightweight, as Code Review in Agile Teams, Part II that @Dukeling posted discusses.

I found that even the simplest thing that could possibly be called a code review gave benefits: before committing code (or pushing in a DVCS), call one other developer over and walk them through your change. This might take five or ten minutes. The goal of this code review is "Does this make sense to the other developer?" The goal was not to nitpick on design implementations or to conform completely to the reviewer's personal ideas about how it should have been written.  It gave these benefits:

Improved shared knowledge of how the code worked

Caught confusing or potentially erroneous code because the act of explaining the code was enough to make the author rethink things

Helped gradually evolve team idioms and style, because it made it easier to explain things

Very little grumbling from the team

Deeper code reviews absolutely work better to find problems. But you have to be able to do them and act on them to get the value. A lightweight process that you can do all the time can be more helpful than a heavyweight process that keeps getting put off, or merely adds things to the backlog.


答:
One solution for this problem is to do do a quick review of the code by another peer once a user story is finished, so that there won't be any basic / obvious mistakes in the code.

But this has to happen before the test cycle. Then there would be less code changes after the test, when you do a larger reviews with all team together.


答:
In this formula O, the time value, is rarely 1.  More importantly, for the time value may be different for different algorithms.  An algorithm which scales linearly, O(n), may be significantly slower than an algorithm that scales quadratically, O(n2).

Knowing the Big O notation relative time values for different algorithms and expected sizes of n can help in picking the appropriate algorithm.  For a small set a fast algorithm that scales non-linearly may be faster, than an alternate algorithm that scales linearly.  If the set will always be small, then the algorithm with the smallest time value may be a better choice.  An algorithm with a larger time value may be a better choice if the set is always going to be large.  Some testing may be required to determine the break-even size.  If the size is likely to vary, then the algorithm choice may be more difficult.

Additionally, algorithms that scale more linearly may be more complex than algorithms that scale less linearly.  The added complexity is likely to increase costs and number of errors.  This may factor in the choice of algorithm.

Consider sorting

The simplest bubble sort implementation has a complexity of O(n2).  However it is simple and fast for small sets.

A common bubble sort be easily optimized by decrementing the size of the outer loop by 1 each iteration requiring with half the comparisons at the cost of a slightly slower outer loop. This can reduce the time value O to almost half that of the simplest bubble sore implementation.  It still has a complexity of O(n2).

Tracking where any moves were done can drop the complexity of a bubble sort to O(n) for sorted input, but increases the time value.

Heap sort has a complexity of O(n log n) depending on the input set.  However the time value is significantly higher that that of a bubble sort.  For small n it will be slower, and is more complex to implement.

Other sort algorithms have different time values and scale differently.  The complexity of implementation also varies.


问:
How to properly handle indefinite generators in Python
Let's say we have a generator that is indefinite, where new elements can arrive at any moment with significant (up to indefinite) delay.

An example of such generator is tail -F command. In python (omitting various edge cases) it could be implemented as the following:

```<code>def tail_follow(file):
    while True:
        line = file.readline()
        if line:
            yield line
        else:
            sleep(1.0)
</code>```

Obvious problem with this generator is that it may cause caller's thread to sleep forever. Therefore it should provide caller's side a way to break iteration.

The solution I came up is the following:

```<code>def tail_follow(file, on_delay_callback):
    while True:
        line = file.readline()
        if line:
            yield line
        else:
            if on_delay_callback():
                break
            else:
                sleep(1.0)
</code>```

Is this the only way to get this behavior with Python? I know that there is a send function that allows 2-way data transfer, can it be used to make solution more pythonic?

答:
I don't see the problem with your approach. I think you are almost there. If you change your generator to yield None when there is nothing to return, then you can simply test for that.

See the following example:

```<code>#!/usr/bin/python

import sys
import time

tailpath = "./tailfile"
fd = open(tailpath)

def tail_follow(file):
    while True:
        line = file.readline()
        if line:
            yield line
        else:
            yield None

if __name__ == "__main__":
    for line in tail_follow(fd):
        if line:
            print ("found: %s" % (line))
        else:
            # do something useful
            time.sleep(1.0)
</code>```

Or alternatively:

```<code>if __name__ == "__main__":
    mytail = tail_follow(fd)
    while True:
        # do something useful
        time.sleep(1.0)
        # anything to tail ?
        line = next(mytail)
        if line:
            print ("found: %s" % (line))
</code>```

Jeff Knupp has a nice post about infinite generators.

Body:
I don't see the problem with your approach. I think you are almost there. If you change your generator to yield None when there is nothing to return, then you can simply test for that.

See the following example:

#!/usr/bin/python

import sys
import time

tailpath = "./tailfile"
fd = open(tailpath)

def tail_follow(file):
    while True:
        line = file.readline()
        if line:
            yield line
        else:
            yield None

if __name__ == "__main__":
    for line in tail_follow(fd):
        if line:
            print ("found: %s" % (line))
        else:
            # do something useful
            time.sleep(1.0)

Or alternatively:

if __name__ == "__main__":
    mytail = tail_follow(fd)
    while True:
        # do something useful
        time.sleep(1.0)
        # anything to tail ?
        line = next(mytail)
        if line:
            print ("found: %s" % (line))

Jeff Knupp has a nice post about infinite generators.


问:
How to filter RSS feed results, according to a DOM element in its page content?
I've a "RSS feed", want to filter its results according to a DOM element in its content!

So, this is the mission I'm looking forward to do:

Monitor a "RSS feed" continuously.

If new RSS elements were added, get its URLs.

Go through every URL's page to check for a specific element.

If the checked element's value was "true", return its page URL back as a result, otherwise ignore it.

Then finally: Print the returned URLs into a new created "RSS feed", to be used in a RSS-reader.

My questions are:

Can that be done only in client-side, or it needs server-side?

What best practices to do it?

Any suggested scenarios?

Thanks in advance!

答:
It could be done client-side, but it wouldn't be a "continuous monitoring" scenario, since client-side code only executes when your user is actually viewing your page. Instead it would be a comparison operation between a local cached version of the RSS feed and the latest RSS feed.

Also, this would only be possible if the user views a page on your site. It can't be done if the user is using any normal RSS client to access the feed. This of course because RSS clients read RSS feeds - they do not parse client-side Javascript.

So while it's (kinda) doable clientside, it's definitely much better doing this server side.

You could create a service which polls the RSS feed every x minutes and performs all the necessary operations you specified: Getting the URLs, retrieving the pages from the URLs, and traversing the DOM of each page, for whatever element you are looking for.

The service then updates a RSS feed file on the same server as the service. The URL to this RSS feed can then be distributed to your users.

As for technology, it can be done in most server side languages. If you are comfortable with JS, look into Node.JS. If you are comfortable with .NET, you could create it as a C# windows service, etc.


问:
In a functional requirements document, is the Assumptions section dangerous?
I am currently a reviewer on a Best Practices document for Developers or Business Analysts in writing a Functional Requirements document.  This document is not necessarily a template for functional requirements documents, but a guide to what elements are necessary, optional, and dangerous to include a Functional Requirements document.

The author of the document states that:

Functional Requirements documents should NEVER have an Assumptions section!  Do not assume anything about what people know about this application or any external issues surrounding it.

I am not sure that I agree with this sentiment but don't really have the words to refute it either.  In a perfect world the analyst will have time to properly analyze every stakeholder input and every possible external issue but inevitably due to time constraints and other issues some assumptions need to be made.

Is this a bad idea because it is too easy for the intellectually lazy to declare assumptions rather than requirements?  If not then why do you think Assumptions are a good idea?

EDIT: To clarify, I am not asking about the Assumptions section of technical documentation but of an Assumptions section in a requirements document written by a non-technical business analyst.

答:
If my requirement is a new report and my assumption is that  - the data required already exist in the application, is that not important? I need to make them aware for when they quote me, just in case they didn't know.

I think assumptions are important. and are not necessarily requirements


问:
How can I manage trash users?
I created a system which hopefully will have many users. We are afraid our user database will be filled by "trash users" which take high-demand usernames, or maybe they just register and never come back.

I know this is common, I do this myself, as I have 3 google accounts, but I only use 1. How can a large website manage trash users or never coming back users like this?

答:
Weirdly, Facebook or Google have so many users that this isn't much of a problem for them.

Whoever picked a really desirable username (e.g. "Frank") probably already did so back in 2008. The many, many users who now come and want to try it, never to come back, will probably have to be content with "Frank32183" instead, and once you accept that, there is no particular reason why you wouldn't accept "Frank32184" just as well (not everyone can be so lucky to have a unique name, like me!).

Another factor is that, famously, big data companies never remove user data unless both public opinion and a court/law really, really urgently tell them to, because their user data is their business model. Being able to say "we have 3,000,000,000 users" is more important than ensuring that they are all live users, because it attracts more new users, plays better with advertising customers, etc. Keeping users happy is important to the company, but not quite as important as keeping them in the first place.

In a smaller, more familiar network the trade-offs may be different. Indeed, actually removing your data without a trace might be a valuable unique selling point of an exclusive online platform. But the really big companies who aim to have everyone on the planet as their customer simply don't operate in that space.

Title: How can I manage trash users?


答:
As humans, we are fallible and prone to making errors. Therefore, we should try to write our programs as safe as possible, and let tools like the compiler or Valgrind help us find problems before they lead to crashes in production.

It is clear that it is impossible to avoid pointers at all levels – they provide a mechanism for indirection that is invaluable for complex architectures – “all problems in computer science can be solved by another level of indirection, except of course for the problem of too many indirections” (Wheeler's law). However, raw pointers are too powerful for either us or the compiler to efficiently reason about.

Pointers might be NULL.

Pointers might reference invalid memory, freed memory, or unallocated memory. Hello, segfault!

A pointer might point to a single value, or be array-like and point to a sequence of values. In the latter case, there might not be a clear length associated with the array-like pointer, which encourages buffer overruns.

Pointers are difficult for the compiler to optimize.

The lifetime of pointed-to values is difficult to manage: Who is responsible for deleting the value? What happens with other pointers referencing that memory?

C++ offers a number of mechanism that allows a programmer to more precisely indicate why they are using a pointer-like thing.

References are guaranteed to be non-null, but can still have problems regarding lifetime. They are best used for function parameters, and effectively subsume the C patterns of pass-by-pointer (in contrast to the default pass-by-value) and out-parameters.

Iterators are an array-like pointer that points to some element in a collection. Whenever you are tempted to increment a pointer, you actually wanted an Iterator. In practice, Iterators have no or only few problems regarding null pointers, lifetime, or buffer overruns.

Smart Pointers solve the problems regarding lifetime, by explicitly specifying lifetime semantics for the value. It is impossible to write exception-safe code with raw pointers in some circumstances, but smart pointers make this trivial. In other respects, they retain the full flexibility of raw pointers – importantly, they can be NULL. Also note that std::unique_ptr is a zero-cost abstraction, so whenever your pointer has a clear owner, using the smart pointer is a clear win in safety.

STL types such as std::vector or std::string replace most uses of array-like pointers, and introduce proper lifetime management, proper copying, make buffer overruns less likely with correct use, and aren't even terribly inefficient. Unfortunately, they have an unsafe operator[], but you always have the option to use the bounds-checked .at() instead.

These solutions are not perfect, but they make it way more difficult to write dangerously wrong code. Unless you are optimizing for C compatibility or (in case of shared pointers, some usage scenarios of vectors) object size, there is no reason to forgo this safety. I have yet to see a good example where references, iterators, smart pointers, or collections were not a better, more self-documenting, and more correct solution to a problem than raw pointers.

Is it professional to use these safety features? Yes: it is professional to solve our problems correctly and efficiently. Debugging segfaults, buffer overruns, and memory leaks is not an efficient use of my time, so I'd rather avoid them from the start. With any half-decent IDE or editor (and C++11's auto), this isn't even much more code to type.

Body:
C++ tools and libraries have become more powerful than ever.

For instance, we can replace arrays by vectors. We can replace pointers by references. We can use smart-pointers.

Is it a common practice among professional programmers to avoid the use of raw pointers?


问:
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.

答:
What are you expecting from a mentor?  The suggestions of an open source project or local user group are designed to be more about networking and finding someone that is a few steps further along what you want to be so that they can help guide you in a way.  Think of it as trying to learn to cook from Jamie Oliver or Gordon Ramsay, it may be quite entertaining and useful at the end of the day.

Depending on your expectations it may be easy or amazingly hard to find a mentor.  If you are expecting someone that can read your mind and give you step by step the secrets to being awesome in a year or less then that may not be realistic.  At the same time, if you want to find someone that can do some things better than you this may not be so hard to do possibly.  So first figure out what are your expectations.

Second, now that you know what you want, you have to find it.  This may well be quite hard as it isn't like there are many places devoted to showcasing developers using their skills like we have the arts in Canada and the U.S. which is why the suggestion was given I'd imagine.  MentorNet would be an example of a program that may work though I haven't tried it, I did research it a while back and didn't think it was for me and what I wanted.  Another thought here is how well do your friends and family know of what you want here?  They may know someone or some place that may assist you if you ask.  While this isn't a comprehensive answer, what you ask is kind of vague and so hopefully you can add more to this and then I'll follow-up once you give some more details of what you want and how you want it as this isn't Burger King but we could try to work it that way.

C++ server side component experts may be rather hard to find.  Are there any nearby post-secondary institutions?  Those may have someone that has those skills that may be shifting into something else as a possible idea.  Good luck on finding that mentor.

Title: How to find a programming mentor?

ContentLicense: CC BY-SA 2.5


问:
Is it possible to avoid a lot of using statements?
Lets say I have a simple code like this (fiddleLink):

```<code>using System;

public class Program
{
    public static void Main()
    {
        //Dependency register logic here
        var service = new DataServiceAdapter();
        var client = new Client(service);
        Foo(client);
    }

    //Work class
    public static void Foo(Client client)
    {
        client.ClientMethod();
    }
}

public class Client
{
    private readonly IDataService _service;
    public Client(IDataService service)
    {
        _service = service;
    }

    public void ClientMethod()
    {
        Console.WriteLine(_service.Method());
        Console.WriteLine(_service.Method2("Hello"));
    }
}

internal class DataServiceAdapter : IDataService
{
    public bool Method()
    {
        using (var something = new SpecifiDataService())
        {
            return something.Method();
        }
    }

    public int Method2(string arg)
    {
        using (var something = new SpecifiDataService())
        {
            return something.Method2(arg);
        }
    }
}

public class SpecifiDataService : IDataService, IDisposable
{
    public bool Method()
    {
        return true;
    }

    public int Method2(string arg)
    {
        return arg.Length;
    }

    public void Dispose()
    {
        //Dispose logic here
    }
}

public interface IDataService
{
    bool Method();
    int Method2(string arg);
}
</code>```

Goal I want to achieve is to encapsulate using logic from client somewhere else (specifically in DataServiceAdapter class).

Is there any way to write using statement only once and not repeat it in every single method?

P.S. SpecifiDataService may be WCF client service or DbContext of EntityFramework. Both should have short lifespans so I cant just open connection once and work with it.

P.P.S I can't reuse SpecificDataService because in real case it will be WCF proxy-client or EntityFramework DbContext implementation. Both cases contains dozens of method calls, so I have to write using statements everywhere. First of all I want to free my client class from implementation of service. It should work both with short living services and long living ones. Another thing I tried to achieve - write methods without using because its boring copy-paste in every single method

答:
C#3+:

```<code>internal class DataServiceAdapter : IDataService
{
    public bool Method()
    {
        return Using(s => s.Method());
    }

    public int Method2(string arg)
    {
        return Using(s => s.Method2(arg));
    }

    private static TRes Using<TRes>(Func<SpecifiDataService, TRes> func)
    {
        using (var something = new SpecifiDataService())
        {
            return func(something);
        }
    }
}
</code>```

C#6:

```<code>internal class DataServiceAdapter : IDataService
{
    public bool Method() => Using(s => s.Method());

    public int Method2(string arg) => Using(s => s.Method2(arg));

    private static TRes Using<TRes>(Func<SpecifiDataService, TRes> func)
    {
        using (var something = new SpecifiDataService())
            return func(something);
    }
}
</code>```

Explanation: extract a command-pattern-like function and then reduce its arity via partial application.

http://codeblog.jonskeet.uk/2012/01/30/currying-vs-partial-function-application

https://stackoverflow.com/questions/327955/does-functional-programming-replace-gof-design-patterns

Body:
C#3+:

internal class DataServiceAdapter : IDataService
{
    public bool Method()
    {
        return Using(s => s.Method());
    }

    public int Method2(string arg)
    {
        return Using(s => s.Method2(arg));
    }

    private static TRes Using<TRes>(Func<SpecifiDataService, TRes> func)
    {
        using (var something = new SpecifiDataService())
        {
            return func(something);
        }
    }
}

C#6:

internal class DataServiceAdapter : IDataService
{
    public bool Method() => Using(s => s.Method());

    public int Method2(string arg) => Using(s => s.Method2(arg));

    private static TRes Using<TRes>(Func<SpecifiDataService, TRes> func)
    {
        using (var something = new SpecifiDataService())
            return func(something);
    }
}

Explanation: extract a command-pattern-like function and then reduce its arity via partial application.

http://codeblog.jonskeet.uk/2012/01/30/currying-vs-partial-function-application

https://stackoverflow.com/questions/327955/does-functional-programming-replace-gof-design-patterns


问:
What's the difference between stateful and stateless?
The books and documentation on the MVC just heap on using the Stateful and Stateless terms. To be honest, i am just unable to grab the idea of it, what the books are talking about. They don't give an example to understand any of the either state, rather than just telling that HTTP is stateless and with ASP.NET MVC microsoft is going along with it. Am I missing some fundamental knowledge, as i can't understand what is stateful and why is stateful and same goes for stateless.

A simple and short example that talks about a control like button or textbox can be simplify the understanding i suppose.

答:
Addition to @coder exact answer.

The idea of state is to remember previous data.

For example, you have a list control on the server with values "A,B,C" and "A" is selected. The list goes to the client browser. You select "B". And post back to the server. How would you know that the value is changed?

ASP.NET

Microsoft uses term ViewState in ASP.NET. There is a huge misunderstanding among developers about it.

ViewState holds all initial state of the list in <input type="hidden" value="base64 encoded" />: values "A,B,C" and mark "A is selected".

Then with post back browser sends ViewState and "B is selected" to the server. ASP.NET restores initial state of the list and applies new "B" selection.
This was done to lure WinForms developers (mentioned by @Ronald). On the web server you can subscribe to list changes listObject.Changed += OnChanged.

ASP.NET MVC

The problem with ViewState is the size. For years .NET developers forced to transfer kilobytes of useless information, like states of 20 controls for every roundtrip.

The new approach is to send only new and small "B" value.

Or if you want to track the change from "A" to "B" then implement it by your own. Using javascript and sending "Was A, Now B". Or save and retrieve state by ID in SQL Server.

ASP.NET MVC and ASP.NET implements state for Authentication and Cashing.  So it is not correct to say that ASP.NET MVC fully stateless.

Memory mentioned in the answers means "remembering", not computer memory.
State can be implemented by storing data in File system, SQL server or Computer Memory.

OwnerDisplayName: Pankaj Upadhyay


问:
Testing private methods as protected
I was reading this answer about testing private methods and it mentioned several possibilities:

extract methods as public to another class

make them public

separate the env of test and production so that methods are only public in the test env

I am currently coding in Java and I was wondering  what does the community think about a kind of intermediary possibility provided by Java and maybe some other languages. With Java you can make your methods Protected or Package access so it is neither private not public but something between the two that make it testable by JUnit.

The Google Guava library even provide an annotation just for that called "VisibleForTesting" which doesn't do anything apart from explicitly saying that it is protected or public for testing purpose.

Since there is even annotations dedicated to this usage surely it is an accepted strategy among part of the community at least?

Is it an acceptable strategy or should I stick to the 3 options mentioned above and consider it the same as the "make public" strategy?

答:
Generally, one would better be judicious about using protected access at all. The reasons for that are laid out in answers to prior questions over here: Why is Clean Code suggesting avoiding protected variables?

As for using it the way you think of here - weakening access limitation because it feels like more comfortable to test - it looks like a terribly bad idea.

The "right option" when you test functionality covered by private method is to leave its modifier alone and figure testing approach based on assumption that method is and will stay private.

There could be many cases and reasons when one needs to redesign code for testability. Various difficulties in writing unit tests often serve as good indication for such a need. But, "oh, that method is private" is not one of those indicative difficulties.

I wrote an explanation for this in an answer to prior question as a side note because that other question and answer were focused on different matters. But for the question you asked, it seems to apply fully and directly, so I will simply copy that part over here.

<rant "I think I heard enough whining. Guess it's about time to say loud and clear...">

Private methods are beneficial to unit testing.

Note below assumes that you are familiar with code coverage. If not, take a time to learn, since it's quite useful to those interested in unit testing and in testing at all.

All right, so I've got that private method and unit tests, and coverage analysis telling me that there's a gap, my private method isn't covered by tests. Now...

What do I gain from keeping it private

Since method is private, the only way to proceed is to study the code to learn how it is used through non-private API. Typically, such a study reveals that reason for the gap is that particular usage scenario is missing in tests.

```<code>    void nonPrivateMethod(boolean condition) {
        if (condition) {
            privateMethod();
        }
        // other code...
    }

    // unit tests don't invoke nonPrivateMethod(true)
    //   => privateMethod isn't covered.
</code>```

For the sake of completeness, other (less frequent) reasons for such coverage gaps could be bugs in specification / design. I won't dive deep into these here, to keep things simple; suffice to say that if you weaken access limitation "just to make method testable", you'll miss a chance to learn that these bugs exist at all.

Fine, to fix the gap, I add a unit test for missing scenario, repeat coverage analysis and verify that gap is gone. What do I have now? I've got as new unit test for specific usage of non-private API.

New test ensures that expected behavior for this usage won't change without a notice since if it changes, test will fail.

An outside reader may look into this test and learn how it is supposed to use and behave (here, outside reader includes my future self, since I tend to forget the code a month or two after I'm done with it).

New test is tolerant to refactoring (do I refactor private methods? you bet!) Whatever I do to privateMethod, I'll always want to test nonPrivateMethod(true). No matter what I do to privateMethod, there will be no need to modify test because method isn't directly invoked.

Not bad? You bet.

What do I loose from weakening access limitation

Now imagine that instead of above, I simply weaken access limitation. I skip the study of the code that uses the method and proceed straight with test that invokes my exPrivateMethod. Great? Not!

Do I gain a test for specific usage of non-private API mentioned above? No: there was no test for nonPrivateMethod(true) before, and there is no such test now.

Do outside readers get a chance to better understand usage of the class? No. "- Hey what's the purpose of the method tested here? - Forget it, it's strictly for internal use. - Oops."

Is it tolerant to refactoring? No way: whatever I change in exPrivateMethod, will likely break the test. Rename, merge into some other method, change arguments and test will just stop compiling. Headache? You bet!

Summing up, sticking with private method brings me a useful, reliable enhancement in unit tests. In contrast, weakening access limitations "for testability" only gives me an obscure, hard to understand piece of test code, which is additionally at permanent risk of being broken by any minor refactoring; frankly what I get looks suspiciously like technical debt.

</rant>

Title: Testing private methods as protected

Body:
Generally, one would better be judicious about using protected access at all. The reasons for that are laid out in answers to prior questions over here: Why is Clean Code suggesting avoiding protected variables?

As for using it the way you think of here - weakening access limitation because it feels like more comfortable to test - it looks like a terribly bad idea.

The "right option" when you test functionality covered by private method is to leave its modifier alone and figure testing approach based on assumption that method is and will stay private.

There could be many cases and reasons when one needs to redesign code for testability. Various difficulties in writing unit tests often serve as good indication for such a need. But, "oh, that method is private" is not one of those indicative difficulties.

I wrote an explanation for this in an answer to prior question as a side note because that other question and answer were focused on different matters. But for the question you asked, it seems to apply fully and directly, so I will simply copy that part over here.

<rant "I think I heard enough whining. Guess it's about time to say loud and clear...">

Private methods are beneficial to unit testing.

Note below assumes that you are familiar with code coverage. If not, take a time to learn, since it's quite useful to those interested in unit testing and in testing at all.

All right, so I've got that private method and unit tests, and coverage analysis telling me that there's a gap, my private method isn't covered by tests. Now...

What do I gain from keeping it private

Since method is private, the only way to proceed is to study the code to learn how it is used through non-private API. Typically, such a study reveals that reason for the gap is that particular usage scenario is missing in tests.

    void nonPrivateMethod(boolean condition) {
        if (condition) {
            privateMethod();
        }
        // other code...
    }

    // unit tests don't invoke nonPrivateMethod(true)
    //   => privateMethod isn't covered.

For the sake of completeness, other (less frequent) reasons for such coverage gaps could be bugs in specification / design. I won't dive deep into these here, to keep things simple; suffice to say that if you weaken access limitation "just to make method testable", you'll miss a chance to learn that these bugs exist at all.

Fine, to fix the gap, I add a unit test for missing scenario, repeat coverage analysis and verify that gap is gone. What do I have now? I've got as new unit test for specific usage of non-private API.

New test ensures that expected behavior for this usage won't change without a notice since if it changes, test will fail.

An outside reader may look into this test and learn how it is supposed to use and behave (here, outside reader includes my future self, since I tend to forget the code a month or two after I'm done with it).

New test is tolerant to refactoring (do I refactor private methods? you bet!) Whatever I do to privateMethod, I'll always want to test nonPrivateMethod(true). No matter what I do to privateMethod, there will be no need to modify test because method isn't directly invoked.

Not bad? You bet.

What do I loose from weakening access limitation

Now imagine that instead of above, I simply weaken access limitation. I skip the study of the code that uses the method and proceed straight with test that invokes my exPrivateMethod. Great? Not!

Do I gain a test for specific usage of non-private API mentioned above? No: there was no test for nonPrivateMethod(true) before, and there is no such test now.

Do outside readers get a chance to better understand usage of the class? No. "- Hey what's the purpose of the method tested here? - Forget it, it's strictly for internal use. - Oops."

Is it tolerant to refactoring? No way: whatever I change in exPrivateMethod, will likely break the test. Rename, merge into some other method, change arguments and test will just stop compiling. Headache? You bet!

Summing up, sticking with private method brings me a useful, reliable enhancement in unit tests. In contrast, weakening access limitations "for testability" only gives me an obscure, hard to understand piece of test code, which is additionally at permanent risk of being broken by any minor refactoring; frankly what I get looks suspiciously like technical debt.

</rant>


问:
Designing CRUD part of an HTTP API
This question is in the context of web based applications. A web server
exposing an HTTP api for clients (e.g. running in a browser but not
necessarily). Usually the web server would be connected to somekind of
datastorage.

My concern is the API exposed by the HTTP server, and how to design it.

I find that, often, a big part of api exposed to the client is just a
CRUD interface to the datastorage. For example, the api almost always
contains things like:

```<code>- get_all_users()
- get_this_user(id)
- create_new_user(name, email, phone, password)
- update_user(id, name?, email?, phone?, password?)
- delete_user(id)
</code>```

This is not all the API does, but it something that is common to a lot
of APIs I've worked with.

Depending on what the client needs, I often end up with more and more
things in the API such as these:

```<code>- get_user_by_email(email)
- get_all_users_along_with_number_of_lincenses_for_each()
- delete_all_these_users_at_once(array [])
- get_users_whose_profile_is(profile_name)
- get_names_of_users_who_are_admin_profiles()
- .... etc
</code>```

In other words, the client often needs to do joins, filter, and sort the
data in all kinds of ways.

Which has led me to overly bloated APIs (just like the one above)
supporting all kinds of options for filtering, sorting, and joining with
data from other tables.

The resulting API is too complex for both the client to use and learn
and for the server to maintain and test.

(IMO the Zabbix HTTP api suffers from this syndrom).

Questions:

Do you have similar experience?

Do you have some pointers as to how to strike a good balance between
API completeness and complexity.

PS. I'm aware of REST, but I don't find it resolves the problem, the api
provided is still very basic, and doesn't solve the
get_users_along_with_number_of_licenses() or the
get_names_of_users_which_are_admin() api calls.;

答:
I have done such things as REST, which, as you say, doesn't solve all problems, though at least a few of them possibly.

Basically search features I have implemented using URL params instead having a single URL for each of them. So your get_user_by_email would just be

```<code>/user?email=joe.doe@something.net
</code>```

Similar you can handle the returned data for things like get_all_users_along_with_number_of_lincenses_for_each

```<code>/users?fields=number_licenses
</code>```

Or even return nested data like

```<code>/users?includes=licenses
</code>```

Can even be several includes:

```<code>/users?includes=licenses,orders
</code>```

which would return a nested JSON object with users and all the license records.

or for your get_names_of_users_who_are_admin_profiles like this:

```<code>/users?admin=true&fields=id,name
</code>```

The method get_users_whose_profile_is would be a simple nested route:

```<code>/profiles/{profile_id}/users
</code>```

Of course this doesn't fully solve the complexity problem, but at least reduces the amount of endpoints the user has to access and learn. Still he needs to know which fields exist and how to query them (we even have some full text search features for some resources).

Another problem here could be the permissions, since some users may be allowed to search and request different types of data. Especially which fields he is allowed to request can be problematic. Still at least with the reduced endpoints the first level of permissions is easier (user can request /users/ or he can not.

How easy this is to implement may depend on your technology stack. We use Ruby on Rails that allows to write a few generic methods that make it easy to process things like fields=name,id,street,city or includes=orders,licenses (though be careful, this again needs to ensure that permissions are handled properly)

Title: Designing CRUD part of an HTTP API

Body:
I have done such things as REST, which, as you say, doesn't solve all problems, though at least a few of them possibly.

Basically search features I have implemented using URL params instead having a single URL for each of them. So your get_user_by_email would just be

/user?email=joe.doe@something.net

Similar you can handle the returned data for things like get_all_users_along_with_number_of_lincenses_for_each

/users?fields=number_licenses

Or even return nested data like

/users?includes=licenses

Can even be several includes:

/users?includes=licenses,orders

which would return a nested JSON object with users and all the license records.

or for your get_names_of_users_who_are_admin_profiles like this:

/users?admin=true&fields=id,name

The method get_users_whose_profile_is would be a simple nested route:

/profiles/{profile_id}/users

Of course this doesn't fully solve the complexity problem, but at least reduces the amount of endpoints the user has to access and learn. Still he needs to know which fields exist and how to query them (we even have some full text search features for some resources).

Another problem here could be the permissions, since some users may be allowed to search and request different types of data. Especially which fields he is allowed to request can be problematic. Still at least with the reduced endpoints the first level of permissions is easier (user can request /users/ or he can not.

How easy this is to implement may depend on your technology stack. We use Ruby on Rails that allows to write a few generic methods that make it easy to process things like fields=name,id,street,city or includes=orders,licenses (though be careful, this again needs to ensure that permissions are handled properly)


答:
No, they are not avoided per se.

Use "raw" pointers as appropriate, with a long list of things where they are not appropriate.

To keep this short:

Do not use raw pointers to model ownership (avoid naked deleteand possibly also naked new -> make_sharedor make_uniqueare your friends)

Do not use raw pointers to "pass around" a conceptual non-owning reference iff a C++ reference suffices.

C++ references do have some restrictions where using raw pointers is OK and often the easier way (to write, read and reason about).

I don't see anything wrong with modelling optional function parameters by using raw pointer arguments, e.g. f(int* pOptValue) where the user can pass nullptr to indicate no-value. (Although I'm sure a lengthy discussing of using optional<int> instead could be started.)

Title: Is it a common practice among professional programmers to avoid the use of raw pointers?


答:
This is a classic API design dilemma, regardless of whether it's provided by a web service, or by linking a library, or by just being part of a code base that gets built along with everything else. It boils down to whether you prefer many functions that each do one specific thing, or whether you have fewer, more parameterized functions.

Since web calls are more "expensive" in terms of time, many web API designers opt for the fewer, richer, calls. A CRUD interface over HTTP would provide Read (GET), Write/Create (PUT/POST), and Delete (DELETE) operations, with all necessary parameters being provided in the request body or encoded as parameters in the URL (QueryString).

To address your ever-growing list of ways to filter and organize your Read operations, you should define a richer set of inputs, which can be as complex and structured as you want, since HTTP will deliver anything you ask it to. Most folks design their parameters as name/value pairs, or as Json objects, or as xml documents. Your parameters can include filtering criteria, and options indicating what data you would like the call to return.

Atlassian does this with their REST APIs for JIRA and Confluence (and others). They provide URLs (calls) to get all issues, or one issue, or some issues based on a filter or query. Each GET call supports a parameter (in this case, called expand, which allows the caller to ask that certain optional return data be included in the response.

As for sorting, if your service will be returning lots of data, or chunked (paged) data, it is nice of you design the call with a sort parameter to make life simpler for the caller. For smaller lists of data, it might be easier to just provide the data in one ordering, and let the client sort it however they like.

REST is currently popular because it is highly decoupled between caller and provider, which offers extreme flexibility. You may prefer something like XMLRPC, which looks more like function calls to client code. You can still provide a call that accepts many parameters, or one large object-like parameter. It's still up to you.

Do yourself, and your users a favor, and make sure you document your API thoroughly, and make it readily available. The trend in web services lately is to move away from tight bindings (as in SOAP and XMLRPC), which makes it harder for compilers and IDEs to help you know how to make a call. Thorough, accessible documentation will be your friend.

Title: Designing CRUD part of an HTTP API

Body:
This question is in the context of web based applications. A web server
exposing an HTTP api for clients (e.g. running in a browser but not
necessarily). Usually the web server would be connected to somekind of
datastorage.

My concern is the API exposed by the HTTP server, and how to design it.

I find that, often, a big part of api exposed to the client is just a
CRUD interface to the datastorage. For example, the api almost always
contains things like:

```<code>- get_all_users()
- get_this_user(id)
- create_new_user(name, email, phone, password)
- update_user(id, name?, email?, phone?, password?)
- delete_user(id)
</code>```

This is not all the API does, but it something that is common to a lot
of APIs I've worked with.

Depending on what the client needs, I often end up with more and more
things in the API such as these:

```<code>- get_user_by_email(email)
- get_all_users_along_with_number_of_lincenses_for_each()
- delete_all_these_users_at_once(array [])
- get_users_whose_profile_is(profile_name)
- get_names_of_users_who_are_admin_profiles()
- .... etc
</code>```

In other words, the client often needs to do joins, filter, and sort the
data in all kinds of ways.

Which has led me to overly bloated APIs (just like the one above)
supporting all kinds of options for filtering, sorting, and joining with
data from other tables.

The resulting API is too complex for both the client to use and learn
and for the server to maintain and test.

(IMO the Zabbix HTTP api suffers from this syndrom).

Questions:

Do you have similar experience?

Do you have some pointers as to how to strike a good balance between
API completeness and complexity.

PS. I'm aware of REST, but I don't find it resolves the problem, the api
provided is still very basic, and doesn't solve the
get_users_along_with_number_of_licenses() or the
get_names_of_users_which_are_admin() api calls.;


答:
Some services remove accounts that have not seen any activity in a certain amount of time, say, a year.

Others don't bother, on the ground that keeping a user record in their system is a trivial amount of data and who knows, they may come back.

Of course if you're keeping track of what users actually do with your service removing them is rather tricky. Either you're going to have to remove everything they contributed to as well or find some way to unlink all that from their account (which may not be a good thing to do for a variety of reasons, attribution, legal hassles, etc.).

And if the users actually had to pay for content that's accessible through that inactive account, removing the account is not a good thing at all as you're now depriving people of things they actually spent good money on (Linden Lab had to change their policy regarding Second Life users because of that, they used to remove inactive accounts after a period but had to stop doing so when people complained that they were being deprived of their investment, and rightly so, when some people returned after prolonged absences due to for example temporary placement overseas (expats, military, etc. etc.).

Best you can probably do is not to bother. Second best would be to only remove accounts that not only have seen no activity for a long time but also have contributed nothing and have nothing linked to them at all.

Title: How can I manage trash users?

Body:
I created a system which hopefully will have many users. We are afraid our user database will be filled by "trash users" which take high-demand usernames, or maybe they just register and never come back.

I know this is common, I do this myself, as I have 3 google accounts, but I only use 1. How can a large website manage trash users or never coming back users like this?